repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/qBraid/qBraid
qBraid
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/qBraid/qBraid
qBraid
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. """ Benchmarking accuracy of qiskit to braket conversions """ import qiskit from qiskit_braket_provider.providers.adapter import to_braket from qbraid.interface import circuits_allclose from qbraid.transpiler import transpile from ..fixtures.qiskit.gates import get_qiskit_gates def execute_test(conversion_function, input_circuit): """Execute conversion, test equality, and return 1 if it fails, 0 otherwise""" try: output_circuit = conversion_function(input_circuit) if not circuits_allclose(input_circuit, output_circuit, strict_gphase=False): return 1 except Exception: # pylint: disable=broad-exception-caught return 1 return 0 qiskit_gates = get_qiskit_gates(seed=0) qbraid_failed, qiskit_failed = 0, 0 for gate_name, gate in qiskit_gates.items(): if gate_name == "GlobalPhaseGate": continue qiskit_circuit = qiskit.QuantumCircuit(gate.num_qubits) qiskit_circuit.compose(gate, inplace=True) qiskit_failed += execute_test(to_braket, qiskit_circuit) qbraid_failed += execute_test(lambda circuit: transpile(circuit, "braket"), qiskit_circuit) total_tests = len(qiskit_gates) qbraid_passed, qiskit_passed = total_tests - qbraid_failed, total_tests - qiskit_failed qbraid_percentage, qiskit_percentage = round((qbraid_passed / total_tests) * 100, 2), round( (qiskit_passed / total_tests) * 100, 2 ) print("Qiskit to Braket standard gate conversion tests\n") print(f"qbraid: {qbraid_passed}/{total_tests} ~= {qbraid_percentage}%") # 58/58 print(f"qiskit-braket-provider: {qiskit_passed}/{total_tests} ~= {qiskit_percentage}%") # 31/58
https://github.com/qBraid/qBraid
qBraid
from qiskit import * from oracle_generation import generate_oracle get_bin = lambda x, n: format(x, 'b').zfill(n) def gen_circuits(min,max,size): circuits = [] secrets = [] ORACLE_SIZE = size for i in range(min,max+1): cur_str = get_bin(i,ORACLE_SIZE-1) (circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str) circuits.append(circuit) secrets.append(secret) return (circuits, secrets)
https://github.com/qBraid/qBraid
qBraid
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. """ Unit tests for qbraid.programs.qiskit.QiskitCircuit """ import pytest from qiskit import QuantumCircuit from qbraid.programs.circuits.qiskit import QiskitCircuit from qbraid.programs.exceptions import ProgramTypeError def test_reverse_qubit_order(): """Test reversing ordering of qubits in qiskit circuit""" circ = QuantumCircuit(3) circ.h(0) circ.cx(0, 2) qprogram = QiskitCircuit(circ) qprogram.reverse_qubit_order() reversed_circ = qprogram.program expected_circ = QuantumCircuit(3) expected_circ.h(2) expected_circ.cx(2, 0) assert ( reversed_circ == expected_circ ), "The reversed circuit does not match the expected output." def test_remove_idle_qubits_qiskit(): """Test convert_to_contigious on qiskit circuit""" circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0, 1) qprogram = QiskitCircuit(circuit) qprogram.remove_idle_qubits() contig_circuit = qprogram.program assert contig_circuit.num_qubits == 2 def test_raise_program_type_error(): """Test raising ProgramTypeError""" with pytest.raises(ProgramTypeError): QiskitCircuit("OPENQASM 2.0;qreg q[2];h q[0];cx q[0],q[1];") def test_circuit_properties(): """Test properties of QiskitCircuit""" circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) qprogram = QiskitCircuit(circuit) assert len(qprogram.qubits) == 2 assert qprogram.num_qubits == 2 assert qprogram.num_clbits == 0 assert qprogram.depth == 2
https://github.com/qBraid/qBraid
qBraid
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. """ Unit tests for transpiling ciruits with idle qubits """ import braket.circuits import cirq import pytest import qiskit from qbraid.interface.circuit_equality import assert_allclose_up_to_global_phase, circuits_allclose from qbraid.programs import load_program from qbraid.transpiler import transpile # pylint: disable=redefined-outer-name @pytest.fixture def braket_circuit() -> braket.circuits.Circuit: """Returns Braket bell circuit with idle qubits""" return braket.circuits.Circuit().h(4).cnot(4, 8) @pytest.fixture def cirq_circuit() -> cirq.Circuit: """Returns Cirq bell circuit with idle qubits""" q4, q8 = cirq.LineQubit(4), cirq.LineQubit(8) circuit = cirq.Circuit(cirq.ops.H(q4), cirq.ops.CNOT(q4, q8)) return circuit @pytest.fixture def qiskit_circuit() -> qiskit.QuantumCircuit: """Returns Qiskit bell circuit with idle qubits""" circuit = qiskit.QuantumCircuit(9) circuit.h(4) circuit.cx(4, 8) return circuit def test_braket_to_cirq(braket_circuit): """Tests Braket conversions""" cirq_test = transpile(braket_circuit, "cirq", require_native=True) assert circuits_allclose(cirq_test, braket_circuit) def test_braket_to_qiskit(braket_circuit): """Tests Braket conversions""" qiskit_test = transpile(braket_circuit, "qiskit", require_native=True) qprogram_qiskit = load_program(qiskit_test) qprogram_braket = load_program(braket_circuit) qprogram_braket.populate_idle_qubits() qiskit_u = qprogram_qiskit.unitary() braket_u = qprogram_braket.unitary() assert_allclose_up_to_global_phase(qiskit_u, braket_u, atol=1e-7) def test_cirq_to_braket(cirq_circuit): """Tests Cirq conversions""" braket_test = transpile(cirq_circuit, "braket", require_native=True) assert circuits_allclose(braket_test, cirq_circuit) def test_cirq_to_qiskit(cirq_circuit): """Tests Cirq conversions""" qiskit_test = transpile(cirq_circuit, "qiskit", require_native=True) assert circuits_allclose(qiskit_test, cirq_circuit) def test_qiskit_to_cirq(qiskit_circuit): """Tests Qiskit conversions""" cirq_test = transpile(qiskit_circuit, "cirq", require_native=True) qprogram_qiskit = load_program(qiskit_circuit) qprogram_cirq = load_program(cirq_test) qprogram_cirq.populate_idle_qubits() qiskit_u = qprogram_qiskit.unitary() cirq_u = qprogram_cirq.unitary() assert_allclose_up_to_global_phase(qiskit_u, cirq_u, atol=1e-7) def test_qiskit_to_braket(qiskit_circuit): """Tests Qiskit conversions""" braket_test = transpile(qiskit_circuit, "braket", require_native=True) qprogram_qiskit = load_program(qiskit_circuit) qprogram_braket = load_program(braket_test) qprogram_braket.populate_idle_qubits() qiskit_u = qprogram_qiskit.unitary() braket_u = qprogram_braket.unitary() assert_allclose_up_to_global_phase(qiskit_u, braket_u, atol=1e-7)
https://github.com/qBraid/qBraid
qBraid
import contextlib import pathlib import uuid import sys from typing import Iterable import pytest from qiskit.circuit import QuantumCircuit, Parameter import qiskit_qasm2.parse if sys.version_info >= (3, 8): def _unlink(path: pathlib.Path): path.unlink(missing_ok=True) else: def _unlink(path: pathlib.Path): try: path.unlink() except FileNotFoundError: pass def gate_builder(name: str, parameters: Iterable[Parameter], definition: QuantumCircuit): """Get a builder for a custom gate. Ideally we would just use an eagerly defined `Gate` instance here, but limitations in how `QuantumCircuit.__eq__` and `Instruction.__eq__` work mean that we have to ensure we're using the same class as the parser for equality checks to work.""" # Ideally we wouldn't have this at all, but hiding it away in one function is likely the safest # and easiest to update if the Python component of the library changes. # pylint: disable=protected-access def definer(*arguments): # We can supply empty lists for the gates and the bytecode, because we're going to override # the definition manually ourselves. gate = qiskit_qasm2.parse._DefinedGate(name, definition.num_qubits, arguments, (), ()) gate._definition = definition.assign_parameters(dict(zip(parameters, arguments))) return gate return definer class _TemporaryFilePathFactory: def __init__(self, basedir): self._basedir = basedir @contextlib.contextmanager def __call__(self): path = self._basedir / str(uuid.uuid4()) path.touch() try: yield path finally: _unlink(path) @pytest.fixture(scope="session") def tmp_file_path_factory(tmp_path_factory): """Get a path to a unique read/writeable temporary file that already exists on disk (with no content), has a valid file name, and can be opened for both reading and writing in any mode. The file will cleaned up after the function, if it still exists.""" return _TemporaryFilePathFactory(tmp_path_factory.getbasetemp())
https://github.com/qBraid/qBraid
qBraid
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. # pylint: disable=redefined-outer-name """ Unit tests for BraketProvider class """ import datetime import json import warnings from unittest.mock import MagicMock, Mock, patch import numpy as np import pytest from braket.aws.aws_session import AwsSession from braket.aws.queue_information import QueueDepthInfo, QueueType from braket.circuits import Circuit from braket.device_schema import ExecutionDay from braket.devices import Devices, LocalSimulator from qiskit import QuantumCircuit as QiskitCircuit from qbraid.exceptions import QbraidError from qbraid.interface import circuits_allclose from qbraid.programs import ProgramSpec from qbraid.runtime import ( DeviceActionType, DeviceProgramTypeMismatchError, DeviceStatus, DeviceType, TargetProfile, ) from qbraid.runtime.braket.availability import _calculate_future_time from qbraid.runtime.braket.device import BraketDevice from qbraid.runtime.braket.job import AmazonBraketVersionError, BraketQuantumTask from qbraid.runtime.braket.provider import BraketProvider from qbraid.runtime.braket.result import BraketGateModelJobResult from qbraid.runtime.exceptions import JobStateError, ProgramValidationError from ..fixtures.braket.gates import get_braket_gates braket_gates = get_braket_gates() SV1_ARN = Devices.Amazon.SV1 @pytest.fixture def braket_provider(): """Return a BraketProvider instance.""" return BraketProvider() @pytest.fixture def sv1_profile(): """Target profile for AWS SV1 device.""" return TargetProfile( device_type=DeviceType.SIMULATOR, num_qubits=34, program_spec=ProgramSpec(Circuit), provider_name="Amazon Braket", device_id=SV1_ARN, action_type=DeviceActionType.OPENQASM, ) class TestAwsSession: """Test class for AWS session.""" def __init__(self): self.region = "us-east-1" def get_device(self, arn): # pylint: disable=unused-argument """Returns metadata for a device.""" capabilities = { "action": { "braket.ir.openqasm.program": "literally anything", "paradigm": {"qubitCount": 2}, } } cap_json = json.dumps(capabilities) metadata = { "deviceType": "SIMULATOR", "providerName": "Amazon Braket", "deviceCapabilities": cap_json, } return metadata def cancel_quantum_task(self, arn): # pylint: disable=unused-argument """Cancel a quantum task.""" return None class ExecutionWindow: """Test class for execution window.""" def __init__(self): self.windowStartHour = datetime.time(0) self.windowEndHour = datetime.time(23, 59, 59) self.executionDay = ExecutionDay.EVERYDAY class Service: """Test class for braket device service.""" def __init__(self): self.executionWindows = [ExecutionWindow()] class TestProperties: """Test class for braket device properties.""" def __init__(self): self.service = Service() class TestAwsDevice: """Test class for braket device.""" def __init__(self, arn, aws_session=None): self.arn = arn self.name = "SV1" self.aws_session = aws_session or TestAwsSession() self.status = "ONLINE" self.properties = TestProperties() self.is_available = True @staticmethod def get_device_region(arn): # pylint: disable=unused-argument """Returns the region of a device.""" return "us-east-1" class MockTask: """Mock task class.""" def __init__(self, arg): self.id = arg self.arn = arg self._aws_session = TestAwsSession() def result(self): """Mock result method.""" return "not a result" def state(self): """Mock state method.""" return "COMPLETED" if self.id == "task1" else "RUNNING" def cancel(self): """Mock cancel method.""" raise RuntimeError @pytest.fixture def mock_sv1(): """Return a mock SV1 device.""" return TestAwsDevice(SV1_ARN) @pytest.fixture def mock_aws_configure(): """Mock aws_conifugre function.""" with patch("qbraid.runtime.braket.provider.aws_configure") as mock: yield mock @pytest.mark.parametrize( "input_keys, expected_calls", [ ( {"aws_access_key_id": "AKIA...", "aws_secret_access_key": "secret"}, {"aws_access_key_id": "AKIA...", "aws_secret_access_key": "secret"}, ), ({}, {"aws_access_key_id": "default_key", "aws_secret_access_key": "default_secret"}), ( {"aws_access_key_id": "AKIA..."}, {"aws_access_key_id": "AKIA...", "aws_secret_access_key": "default_secret"}, ), ], ) def test_save_config(mock_aws_configure, input_keys, expected_calls): """Test save_config method of BraketProvider class.""" instance = BraketProvider() instance.aws_access_key_id = "default_key" instance.aws_secret_access_key = "default_secret" instance.save_config(**input_keys) mock_aws_configure.assert_called_once_with(**expected_calls) def test_provider_get_aws_session(): """Test getting an AWS session.""" with patch("boto3.session.Session") as mock_boto_session: mock_boto_session.aws_access_key_id.return_value = "aws_access_key_id" mock_boto_session.aws_secret_access_key.return_value = "aws_secret_access_key" aws_session = BraketProvider()._get_aws_session() assert aws_session.boto_session.region_name == "us-east-1" assert isinstance(aws_session, AwsSession) def test_provider_get_devices_raises(braket_provider): """Test raising device wrapper error due to invalid device ID.""" with pytest.raises(ValueError): braket_provider.get_device("Id123") def test_provider_build_runtime_profile(mock_sv1): """Test building a runtime profile.""" provider = BraketProvider() profile = provider._build_runtime_profile(device=mock_sv1, extra="data") assert profile.get("device_type") == DeviceType.SIMULATOR.name assert profile.get("provider_name") == "Amazon Braket" assert profile.get("device_id") == SV1_ARN assert profile.get("extra") == "data" @pytest.mark.parametrize( "region_names, key, values, expected", [(["us-west-1"], "Project", ["X"], ["arn:aws:resource1", "arn:aws:resource2"])], ) @patch("boto3.client") def test_provider_get_tasks_by_tag(mock_boto_client, region_names, key, values, expected): """Test fetching tagged resources from AWS.""" mock_client = MagicMock() mock_boto_client.return_value = mock_client mock_client.get_resources.return_value = { "ResourceTagMappingList": [ {"ResourceARN": "arn:aws:resource1"}, {"ResourceARN": "arn:aws:resource2"}, ] } provider = BraketProvider() result = provider.get_tasks_by_tag(key, values, region_names) # Assert the results mock_boto_client.assert_called_with("resourcegroupstaggingapi", region_name="us-west-1") mock_client.get_resources.assert_called_once_with(TagFilters=[{"Key": key, "Values": values}]) assert result == expected def test_provider_get_device(mock_sv1): """Test getting a Braket device.""" provider = BraketProvider() with ( patch("qbraid.runtime.braket.provider.AwsDevice") as mock_aws_device, patch("qbraid.runtime.braket.device.AwsDevice") as mock_aws_device_2, ): mock_aws_device.return_value = mock_sv1 mock_aws_device_2.return_value = mock_sv1 device = provider.get_device(SV1_ARN) assert device.id == SV1_ARN assert device.name == "SV1" assert str(device) == "BraketDevice('Amazon Braket SV1')" assert device.status() == DeviceStatus.ONLINE assert isinstance(device, BraketDevice) def test_provider_get_devices(mock_sv1): """Test getting list of Braket devices.""" with ( patch("qbraid.runtime.braket.provider.AwsDevice.get_devices", return_value=[mock_sv1]), patch("qbraid.runtime.braket.device.AwsDevice") as mock_aws_device_2, ): provider = BraketProvider() mock_aws_device_2.return_value = mock_sv1 devices = provider.get_devices() assert len(devices) == 1 assert devices[0].id == SV1_ARN @patch("qbraid.runtime.braket.device.AwsDevice") def test_device_profile_attributes(mock_aws_device, sv1_profile): """Test that device profile attributes are correctly set.""" mock_aws_device.return_value = Mock() device = BraketDevice(sv1_profile) assert device.id == sv1_profile.get("device_id") assert device.num_qubits == sv1_profile.get("num_qubits") assert device._target_spec == sv1_profile.get("program_spec") assert device.device_type == DeviceType(sv1_profile.get("device_type")) assert device.profile.get("action_type") == "OpenQASM" @patch("qbraid.runtime.braket.device.AwsDevice") def test_device_queue_depth(mock_aws_device, sv1_profile): """Test getting queue_depth BraketDevice""" mock_aws_device.queue_depth.return_value = QueueDepthInfo( quantum_tasks={QueueType.NORMAL: "19", QueueType.PRIORITY: "3"}, jobs="0 (3 prioritized job(s) running)", ) device = BraketDevice(sv1_profile) queue_depth = device.queue_depth() assert isinstance(queue_depth, int) @patch("qbraid.runtime.braket.device.AwsDevice") def test_device_run_circuit_too_many_qubits(mock_aws_device, sv1_profile): """Test that run method raises exception when input circuit num qubits exceeds that of wrapped AWS device.""" mock_aws_device.return_value = Mock() device = BraketDevice(sv1_profile) num_qubits = device.num_qubits + 10 circuit = QiskitCircuit(num_qubits) circuit.h([0, 1]) circuit.cx(0, num_qubits - 1) with pytest.raises(ProgramValidationError): with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) device.run(circuit) @patch("qbraid.runtime.braket.device.AwsDevice") def test_batch_run(mock_aws_device, sv1_profile): """Test batch run method of BraketDevice.""" mock_aws_device.return_value = MagicMock() mock_aws_device.return_value.__iter__.return_value = [MockTask("task1"), MockTask("task2")] mock_aws_device.return_value.status = "ONLINE" device = BraketDevice(sv1_profile) circuits = [Circuit().h(0).cnot(0, 1), Circuit().h(0).cnot(0, 1)] tasks = device.run(circuits, shots=10) assert isinstance(tasks, list) @pytest.mark.parametrize( "available_time, expected", [ (3600, "2024-01-01T01:00:00Z"), (1800, "2024-01-01T00:30:00Z"), (45, "2024-01-01T00:00:45Z"), ], ) def test_availability_future_utc_datetime(available_time, expected): """Test calculating future utc datetime""" current_utc_datime = datetime.datetime(2024, 1, 1, 0, 0, 0) _, datetime_str = _calculate_future_time(available_time, current_utc_datime) assert datetime_str == expected def test_device_availability_window(braket_provider, mock_sv1): """Test BraketDeviceWrapper avaliable output identical""" with ( patch("qbraid.runtime.braket.provider.AwsDevice") as mock_aws_device, patch("qbraid.runtime.braket.device.AwsDevice") as mock_aws_device_2, ): mock_device = mock_sv1 mock_device.is_available = False mock_aws_device.return_value = mock_device mock_aws_device_2.return_value = mock_device device = braket_provider.get_device(SV1_ARN) _, is_available_time, iso_str = device.availability_window() assert len(is_available_time.split(":")) == 3 assert isinstance(iso_str, str) try: datetime.datetime.strptime(iso_str, "%Y-%m-%dT%H:%M:%SZ") except ValueError: pytest.fail("iso_str not in expected format") @patch("qbraid.runtime.braket.BraketProvider") def test_device_is_available(mock_provider): """Test device availability function.""" provider = mock_provider.return_value mock_device_0 = Mock() mock_device_0.availability_window.return_value = (True, 0, 0) mock_device_0._device.is_available = True mock_device_1 = Mock() mock_device_1.availability_window.return_value = (False, 0, 0) mock_device_1._device.is_available = False provider.get_devices.return_value = [mock_device_0, mock_device_1] devices = provider.get_devices() for device in devices: is_available_bool, _, _ = device.availability_window() assert device._device.is_available == is_available_bool @patch("qbraid.runtime.braket.device.AwsDevice") def test_device_transform_circuit_sv1(mock_aws_device, sv1_profile): """Test transform method for device with OpenQASM action type.""" mock_aws_device.return_value = Mock() device = BraketDevice(sv1_profile) circuit = Circuit().h(0).cnot(0, 2) transformed_expected = Circuit().h(0).cnot(0, 1) transformed_circuit = device.transform(circuit) assert transformed_circuit == transformed_expected @patch("qbraid.runtime.braket.device.AwsDevice") def test_device_transform_raises_for_mismatch(mock_aws_device, braket_circuit): """Test raising exception for mismatched action type AHS and program type circuit.""" mock_aws_device.return_value = Mock() profile = TargetProfile( device_type=DeviceType.SIMULATOR, num_qubits=34, program_spec=ProgramSpec(Circuit), provider_name="Amazon Braket", device_id=SV1_ARN, action_type=DeviceActionType.AHS, ) device = BraketDevice(profile) with pytest.raises(DeviceProgramTypeMismatchError): device.transform(braket_circuit) @patch("qbraid.runtime.braket.device.AwsDevice") def test_device_ionq_transform(mock_aws_device): """Test converting Amazon Braket circuit to use only IonQ supprted gates""" mock_aws_device.return_value = Mock() profile = TargetProfile( device_type=DeviceType.QPU, num_qubits=11, program_spec=ProgramSpec(Circuit), provider_name="IonQ", device_id="arn:aws:braket:us-east-1::device/qpu/ionq/Harmony", action_type=DeviceActionType.OPENQASM, ) device = BraketDevice(profile) toffoli_circuit = Circuit().ccnot(0, 1, 2) transformed_circuit = device.transform(toffoli_circuit) assert isinstance(transformed_circuit, Circuit) assert toffoli_circuit.depth == 1 assert transformed_circuit.depth == 11 assert circuits_allclose(transformed_circuit, toffoli_circuit) @patch("qbraid.runtime.braket.BraketProvider") def test_device_submit_task_with_tags(mock_provider): """Test getting tagged quantum tasks.""" provider = mock_provider.return_value provider.REGIONS = ["us-east-1", "us-west-1"] provider._get_default_region.return_value = "us-east-1" alt_regions = ["us-west-1"] mock_device = Mock() provider.get_device.return_value = mock_device mock_task_1 = Mock() mock_task_1.id = "task1" mock_task_2 = Mock() mock_task_2.id = "task2" circuit = Circuit().h(0).cnot(0, 1) mock_device.run.side_effect = [mock_task_1, mock_task_2] key, value1, value2 = "abc123", "val1", "val2" mock_task_1.tags = {key: value1} mock_task_2.tags = {key: value2} provider.get_tasks_by_tag.side_effect = [ [mock_task_1.id, mock_task_2.id], [mock_task_1.id], [], ] task1 = mock_device.run(circuit, shots=2, tags={key: value1}) task2 = mock_device.run(circuit, shots=2, tags={key: value2}) assert set([task1.id, task2.id]) == set(provider.get_tasks_by_tag(key)) assert len(provider.get_tasks_by_tag(key, values=[value1], region_names=["us-east-1"])) == 1 assert len(provider.get_tasks_by_tag(key, region_names=alt_regions)) == 0 @patch("qbraid.runtime.braket.job.AwsQuantumTask") def test_job_load_completed(mock_aws_quantum_task): """Test is terminal state method for BraketQuantumTask.""" circuit = Circuit().h(0).cnot(0, 1) mock_device = LocalSimulator() mock_job = mock_device.run(circuit, shots=10) mock_aws_quantum_task.return_value = mock_job job = BraketQuantumTask(mock_job.id) assert job.metadata()["job_id"] == mock_job.id assert job.is_terminal_state() res = job.result() assert res.measurements() is not None @pytest.mark.parametrize("position,expected", [(10, 10), (">2000", 2000)]) @patch("qbraid.runtime.braket.job.AwsQuantumTask") def test_job_queue_position(mock_aws_quantum_task, position, expected): """Test getting queue_depth BraketDevice""" mock_queue_position_return = MagicMock() mock_queue_position_return.queue_position = position mock_aws_quantum_task.return_value.queue_position.return_value = mock_queue_position_return job = BraketQuantumTask("job_id") assert job.queue_position() == expected @patch("qbraid.runtime.braket.job.AwsQuantumTask") def test_job_queue_position_raises_version_error(mock_aws_quantum_task): """Test handling of AttributeError leads to raising AmazonBraketVersionError.""" mock_aws_quantum_task.return_value.queue_position.side_effect = AttributeError job = BraketQuantumTask("job_id") with pytest.raises(AmazonBraketVersionError) as excinfo: job.queue_position() assert "Queue visibility is only available for amazon-braket-sdk>=1.56.0" in str(excinfo.value) def test_job_raise_for_cancel_terminal(): """Test raising an error when trying to cancel a completed/failed job.""" with patch("qbraid.runtime.job.QuantumJob.is_terminal_state", return_value=True): job = BraketQuantumTask(SV1_ARN, task=Mock()) with pytest.raises(JobStateError): job.cancel() def test_result_measurements(): """Test measurements method of BraketGateModelJobResult class.""" mock_measurements = np.array([[0, 1, 1], [1, 0, 1]]) mock_result = MagicMock() mock_result.measurements = mock_measurements result = BraketGateModelJobResult(mock_result) expected_output = np.array([[1, 1, 0], [1, 0, 1]]) np.testing.assert_array_equal(result.measurements(), expected_output) def test_result_raw_counts(): """Test raw_counts method of BraketGateModelJobResult class.""" mock_measurement_counts = {(0, 1, 1): 10, (1, 0, 1): 5} mock_result = MagicMock() mock_result.measurement_counts = mock_measurement_counts result = BraketGateModelJobResult(mock_result) expected_output = {"110": 10, "101": 5} assert result.raw_counts() == expected_output def test_get_default_region_error(): """Test getting default region when an exception is raised.""" with patch("qbraid.runtime.braket.provider.Session") as mock_boto_session: mock_boto_session.side_effect = Exception mock_boto_session.region_name.return_value = "not us-east-1" assert BraketProvider()._get_default_region() == "us-east-1" def test_get_s3_default_bucket(): """Test getting default S3 bucket.""" with patch("qbraid.runtime.braket.provider.AwsSession") as mock_aws_session: mock_instance = mock_aws_session.return_value mock_instance.default_bucket.return_value = "default bucket" assert BraketProvider()._get_s3_default_bucket() == "default bucket" mock_instance.default_bucket.side_effect = Exception assert BraketProvider()._get_s3_default_bucket() == "amazon-braket-qbraid-jobs" def test_get_quantum_task_cost(): """Test getting quantum task cost.""" task_mock = Mock() task_mock.arn = "fake_arn" task_mock.state.return_value = "COMPLETED" job = BraketQuantumTask("task_arn", task_mock) with patch("qbraid.runtime.braket.job.get_quantum_task_cost", return_value=0.1): assert job.get_cost() == 0.1 def test_built_runtime_profile_fail(): """Test building a runtime profile with invalid device.""" class FakeSession: """Fake Session for testing.""" def __init__(self): self.region = "us-east-1" def get_device(self, arn): # pylint: disable=unused-argument """Fake get_device method.""" return { "deviceType": "SIMULATOR", "providerName": "Amazon Braket", "deviceCapabilities": "{}", } class FakeDevice: """Fake AWS Device for testing.""" def __init__(self, arn, aws_session=None): self.arn = arn self.aws_session = aws_session or FakeSession() self.status = "ONLINE" self.properties = TestProperties() self.is_available = True @staticmethod def get_device_region(arn): # pylint: disable=unused-argument """Fake get_device_region method.""" return "us-east-1" provider = BraketProvider( aws_access_key_id="aws_access_key_id", aws_secret_access_key="aws_secret_access_key", ) device = FakeDevice(arn=SV1_ARN, aws_session=FakeSession()) with pytest.raises(QbraidError): assert provider._build_runtime_profile(device=device) def test_braket_result_error(): """Test Braket result decoding error.""" task = MockTask("task1") braket_task = BraketQuantumTask("task1", task) with pytest.raises(ValueError): braket_task.result() def test_braket_job_cancel(): """Test Braket job cancel method.""" task = MockTask("task2") braket_task = BraketQuantumTask("task2", task) assert braket_task.cancel() is None def test_get_tasks_by_tag_value_error(): """Test getting tagged quantum tasks with invalid values.""" with patch("qbraid.runtime.braket.provider.quantum_lib_proxy_state") as mock_proxy_state: mock_proxy_state.side_effect = ValueError provider = BraketProvider() result = provider.get_tasks_by_tag("key", ["value1", "value2"]) assert isinstance(result, list) def test_get_tasks_by_tag_qbraid_error(): """Test getting tagged quantum tasks with jobs enabled.""" with patch("qbraid.runtime.braket.provider.quantum_lib_proxy_state") as mock_proxy_state: mock_proxy_state.return_value = {"enabled": True} provider = BraketProvider() with pytest.raises(QbraidError): provider.get_tasks_by_tag("key", ["value1", "value2"])
https://github.com/qBraid/qBraid
qBraid
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. # pylint: disable=redefined-outer-name """ Unit tests for QiskitProvider class """ import random import warnings from types import SimpleNamespace from unittest.mock import MagicMock, Mock, patch import numpy as np import pytest from qiskit import QuantumCircuit from qiskit.providers import Job from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.providers.models import QasmBackendConfiguration from qiskit_ibm_runtime import QiskitRuntimeService, RuntimeJob from qiskit_ibm_runtime.exceptions import IBMNotAuthorizedError, RuntimeInvalidStateError from qiskit_ibm_runtime.qiskit_runtime_service import QiskitBackendNotFoundError from qbraid.programs import NATIVE_REGISTRY, ProgramSpec from qbraid.runtime import DeviceActionType, DeviceStatus, DeviceType, JobStateError, TargetProfile from qbraid.runtime.exceptions import QbraidRuntimeError from qbraid.runtime.qiskit import QiskitBackend, QiskitJob, QiskitResult, QiskitRuntimeProvider FIXTURE_COUNT = sum(key in NATIVE_REGISTRY for key in ["qiskit", "braket", "cirq"]) class FakeDevice(GenericBackendV2): """A test Qiskit device.""" # pylint: disable-next=too-many-arguments def __init__( self, num_qubits, local=True, simulator=True, operational=True, status_msg="active", **kwargs, ): super().__init__(num_qubits) self._num_qubits = num_qubits self._operational = operational self._status_msg = status_msg self._local = local self._simulator = simulator self._instance = kwargs.get("instance", None) def status(self): """Return the status of the backend.""" status_obj = SimpleNamespace() status_obj.operational = self._operational status_obj.status_msg = self._status_msg # dummy value proportional to num_qubits status_obj.pending_jobs = 0 if self._local else random.randint(1, 100) return status_obj def configuration(self): """Return the configuration of the backend.""" return QasmBackendConfiguration( backend_name="fake_backend", backend_version="1.0", n_qubits=self._num_qubits, basis_gates=["u1", "u2", "u3", "cx"], gates=[], local=self._local, simulator=self._simulator, conditional=False, open_pulse=False, memory=True, max_shots=8192, coupling_map=None, ) class FakeService: """Fake Qiskit runtime service for testing.""" def backend(self, backend_name, instance=None): """Return fake backend.""" for backend in self.backends(instance=instance): if backend_name == backend.name: return backend raise QiskitBackendNotFoundError("No backend matches the criteria.") def backends(self, **kwargs): # pylint: disable=unused-argument """Return fake Qiskit backend.""" return [FakeDevice(num_qubits=n, **kwargs) for n in [5, 20]] def backend_names(self, **kwargs): """Return fake backend names.""" return [backend.name for backend in self.backends(**kwargs)] def least_busy(self, **kwargs): """Return the least busy backend based on the number of pending jobs.""" backends = self.backends(**kwargs) return min(backends, key=lambda backend: backend.status().pending_jobs) def job(self, job_id): # pylint: disable=unused-argument """Return fake job.""" return MagicMock(spec=RuntimeJob) def _create_backend_fixture(service: FakeService, local: bool, simulator: bool) -> QiskitBackend: """Create a Qiskit backend fixture.""" backend = service.backends(local=local, simulator=simulator)[0] program_spec = ProgramSpec(QuantumCircuit) if local: device_type = DeviceType.LOCAL_SIMULATOR elif simulator: device_type = DeviceType.SIMULATOR else: device_type = DeviceType.QPU profile = TargetProfile( device_id=backend.name, device_type=device_type, action_type=DeviceActionType.OPENQASM, num_qubits=backend.num_qubits, program_spec=program_spec, provider_name="IBM", ) return QiskitBackend(profile, service) @pytest.fixture def fake_service(): """Return a fake Qiskit runtime service.""" return FakeService() @pytest.fixture def fake_device(fake_service): """Return a fake local simulator backend.""" return _create_backend_fixture(fake_service, local=True, simulator=True) def test_provider_initialize_service(): """Test getting IBMQ provider using qiskit_ibm_provider package.""" with patch("qbraid.runtime.qiskit.provider.QiskitRuntimeService") as mock_runtime_service: mock_runtime_service.return_value = Mock(spec=QiskitRuntimeService) provider = QiskitRuntimeProvider(token="test_token", channel="test_channel") assert isinstance(provider.runtime_service, QiskitRuntimeService) assert provider.token == "test_token" assert provider.channel == "test_channel" assert provider.runtime_service == mock_runtime_service.return_value def test_provider_save_config(fake_service): """Test saving the IBM account configuration to disk.""" with patch("qbraid.runtime.qiskit.provider.QiskitRuntimeService") as mock_runtime_service: mock_runtime_service.return_value = fake_service provider = QiskitRuntimeProvider(token="fake_token", channel="fake_channel") provider.save_config(token="fake_token", channel="fake_channel", overwrite=False) mock_runtime_service.save_account.assert_called_once_with( token="fake_token", channel="fake_channel", overwrite=False ) provider.save_config() mock_runtime_service.save_account.assert_called_with( token="fake_token", channel="fake_channel", overwrite=True ) @pytest.mark.parametrize( "local,simulator,num_qubits,device_type", [ (True, True, 20, DeviceType.LOCAL_SIMULATOR), (False, True, 5, DeviceType.SIMULATOR), (False, False, 5, DeviceType.QPU), ], ) def test_provider_build_runtime_profile(local, simulator, num_qubits, device_type): """Test building runtime profile for Qiskit backend.""" with patch("qbraid.runtime.qiskit.provider.QiskitRuntimeService") as mock_runtime_service: mock_runtime_service.return_value = FakeService() backend = FakeDevice(num_qubits, local=local, simulator=simulator) provider = QiskitRuntimeProvider(token="test_token", channel="test_channel") profile = provider._build_runtime_profile(backend) assert profile["device_id"] == f"generic_backend_{num_qubits}q" assert profile["device_type"] == device_type.name assert profile["num_qubits"] == num_qubits assert profile["max_shots"] == 8192 qiskit_backend = QiskitBackend(profile, mock_runtime_service()) assert isinstance(qiskit_backend, QiskitBackend) assert qiskit_backend.profile == profile def test_provider_get_devices(fake_service): """Test getting a backend from the runtime service.""" with patch("qbraid.runtime.qiskit.provider.QiskitRuntimeService") as mock_runtime_service: mock_runtime_service.return_value = fake_service provider = QiskitRuntimeProvider(token="test_token", channel="test_channel") devices = provider.get_devices() assert len(devices) == 2 assert all(isinstance(device, QiskitBackend) for device in devices) device = devices[0] device_copy = provider.get_device(device.id) assert device.id == device_copy.id assert str(device) == f"QiskitBackend('{device.id}')" @pytest.mark.parametrize("local", [True, False]) def test_provider_least_busy(fake_service, local): """Test getting a backend from the runtime service, both local and non-local.""" with patch("qbraid.runtime.qiskit.provider.QiskitRuntimeService") as mock_provider_service: mock_provider_service.return_value = fake_service provider = QiskitRuntimeProvider(token="test_token", channel="test_channel") least_busy = provider.least_busy(local=local) least_busy._backend = FakeDevice(5, local=local) assert least_busy.queue_depth() == 0 if local else least_busy.queue_depth() > 0 @pytest.mark.parametrize( "operational,local,status_msg,expected_status", [ (True, True, "active", DeviceStatus.ONLINE), (True, False, "active", DeviceStatus.ONLINE), (True, False, "not active", DeviceStatus.UNAVAILABLE), (False, False, None, DeviceStatus.OFFLINE), ], ) def test_device_status(fake_service, operational, local, status_msg, expected_status): """Test getting a backend from the runtime service, both local and non-local.""" with patch("qbraid.runtime.qiskit.provider.QiskitRuntimeService") as mock_provider_service: mock_provider_service.return_value = fake_service provider = QiskitRuntimeProvider(token="test_token", channel="test_channel") params = {"operational": operational, "local": local, "status_msg": status_msg} device = provider.get_devices(**params)[0] device._backend = FakeDevice(device.num_qubits, **params) assert device.status() == expected_status @pytest.mark.parametrize("circuit", range(FIXTURE_COUNT), indirect=True) def test_device_run(fake_device, circuit): """Test run method from wrapped fake Qiskit backends""" with warnings.catch_warnings(): warnings.simplefilter(action="ignore", category=RuntimeWarning) qbraid_job = fake_device.run(circuit, shots=10) vendor_job = qbraid_job._job assert isinstance(qbraid_job, QiskitJob) assert isinstance(vendor_job, Job) def test_device_run_batch(fake_device, run_inputs): """Test run method from wrapped fake Qiskit backends""" with warnings.catch_warnings(): warnings.simplefilter(action="ignore", category=RuntimeWarning) qbraid_job = fake_device.run(run_inputs, shots=10) vendor_job = qbraid_job._job assert isinstance(qbraid_job, QiskitJob) assert isinstance(vendor_job, Job) @pytest.fixture def mock_service(): """Fixture to create a mock QiskitRuntimeService.""" service = MagicMock(spec=QiskitRuntimeService) service.job.return_value = MagicMock(spec=RuntimeJob) return service def test_job_initialize_from_service(mock_service): """Test successful job retrieval with a provided service. Args: mock_service (MagicMock): A mocked service passed as a fixture. Tests that QiskitJob retrieves a job using a provided mock service and verifies that the job method is called exactly once with the correct job ID. """ job_id = "test_job_id" job = QiskitJob(job_id, service=mock_service) assert job._job is not None mock_service.job.assert_called_once_with(job_id) def test_job_initialize_service_from_device(mock_service): """Test job retrieval when service is provided via the device attribute.""" mock_device = MagicMock() mock_device._service = mock_service job_id = "test_job_id" job = QiskitJob(job_id, device=mock_device) assert job._job is not None mock_service.job.assert_called_once_with(job_id) def test_job_service_initialization(): """Test job retrieval when initializing a new service.""" with patch("qbraid.runtime.qiskit.job.QiskitRuntimeService") as mock_service_class: mock_service = MagicMock(spec=QiskitRuntimeService) mock_service.job.return_value = MagicMock(spec=RuntimeJob) mock_service_class.return_value = mock_service job_id = "test_job_id" job = QiskitJob(job_id) assert job._job is not None mock_service.job.assert_called_once_with(job_id) def test_job_service_initialization_failure(): """Test handling of service initialization failure.""" with patch("qbraid.runtime.qiskit.job.QiskitRuntimeService", side_effect=IBMNotAuthorizedError): job_id = "test_job_id" with pytest.raises(QbraidRuntimeError) as exc_info: QiskitJob(job_id) assert "Failed to initialize the quantum service." in str(exc_info.value) def test_job_retrieval_failure(mock_service): """Test handling of job retrieval failure.""" mock_service.job.side_effect = ConnectionError job_id = "test_job_id" with pytest.raises(QbraidRuntimeError) as exc_info: QiskitJob(job_id, service=mock_service) assert "Error retrieving job test_job_id" in str(exc_info.value) @pytest.fixture def mock_runtime_job(): """Fixture to create a mock QiskitRuntimeJob object.""" return MagicMock() def test_job_queue_position(mock_runtime_job): """Test that the queue position of the job is correctly returned.""" queue_position = 5 mock_runtime_job.queue_position.return_value = queue_position job = QiskitJob(job_id="123", job=mock_runtime_job) assert job.queue_position() == queue_position def test_cancel_job_in_terminal_state(mock_runtime_job): """Test attempting to cancel a job in a terminal state raises JobStateError.""" job = QiskitJob(job_id="123", job=mock_runtime_job) job.is_terminal_state = MagicMock(return_value=True) # Simulate terminal state with pytest.raises(JobStateError, match="Cannot cancel quantum job in non-terminal state."): job.cancel() def test_cancel_job_success(mock_runtime_job): """Test successful cancellation of a non-terminal job.""" job = QiskitJob(job_id="123", job=mock_runtime_job) job.is_terminal_state = MagicMock(return_value=False) mock_runtime_job.cancel.return_value = None assert job.cancel() is None def test_cancel_job_fails_due_to_runtime_error(mock_runtime_job): """Test that cancellation fails with a RuntimeInvalidStateError and raises JobStateError.""" mock_job = mock_runtime_job mock_job.cancel.side_effect = RuntimeInvalidStateError job = QiskitJob(job_id="123", job=mock_job) job.is_terminal_state = MagicMock(return_value=False) with pytest.raises(JobStateError): job.cancel() @pytest.fixture def mock_runtime_result(): """Return a mock Qiskit result.""" mock_result = Mock() mock_result.results = [Mock(), Mock()] meas1 = ["01"] * 9 + ["10"] + ["11"] * 4 + ["00"] * 6 meas2 = ["0"] * 8 + ["1"] * 12 mock_result.get_memory.side_effect = [meas1, meas2] mock_result.get_counts.side_effect = [{"01": 9, "10": 1, "11": 4, "00": 6}, {"0": 8, "1": 12}] return mock_result def test_result_from_job(mock_runtime_job, mock_runtime_result): """Test that result returns QiskitResult when the job is in a terminal state.""" mock_job = QiskitJob(job_id="123", job=mock_runtime_job) mock_runtime_job.result.return_value = mock_runtime_result result = mock_job.result() assert isinstance(result, QiskitResult) assert isinstance(result.raw_counts(), dict) assert isinstance(result.measurements(), np.ndarray) def test_result_raw_counts(mock_runtime_result): """Test getting raw counts from a Qiskit result.""" qr = QiskitResult() qr._result = mock_runtime_result expected = {"01": 9, "10": 1, "11": 4, "00": 6} assert qr.raw_counts() == expected def test_result_format_measurements(): """Test formatting measurements into integers.""" qr = QiskitResult() memory_list = ["010", "111"] expected = [[0, 1, 0], [1, 1, 1]] assert qr._format_measurements(memory_list) == expected def test_result_measurements_single_circuit(mock_runtime_result): """Test getting measurements from a single circuit.""" qr = QiskitResult() qr._result = mock_runtime_result mock_runtime_result.results = [Mock()] expected = np.array([[0, 1]] * 9 + [[1, 0]] + [[1, 1]] * 4 + [[0, 0]] * 6) assert np.array_equal(qr.measurements(), expected) def test_result_measurements_multiple_circuits(mock_runtime_result): """Test getting measurements from multiple circuits.""" qr = QiskitResult() qr._result = mock_runtime_result expected_meas1 = np.array([[0, 1]] * 9 + [[1, 0]] + [[1, 1]] * 4 + [[0, 0]] * 6) expected_meas2 = np.array([[0, 0]] * 8 + [[0, 1]] * 12) expected = np.array([expected_meas1, expected_meas2]) assert np.array_equal(qr.measurements(), expected)
https://github.com/qBraid/qBraid
qBraid
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests basic functionality of the transpile function""" import copy import io import math import os import sys import unittest from logging import StreamHandler, getLogger from test import combine # pylint: disable=wrong-import-order from unittest.mock import patch import numpy as np import rustworkx as rx from ddt import data, ddt, unpack from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister, pulse, qasm3, qpy from qiskit.circuit import ( Clbit, ControlFlowOp, ForLoopOp, Gate, IfElseOp, Parameter, Qubit, Reset, SwitchCaseOp, WhileLoopOp, ) from qiskit.circuit.classical import expr from qiskit.circuit.delay import Delay from qiskit.circuit.library import ( CXGate, CZGate, HGate, RXGate, RYGate, RZGate, SXGate, U1Gate, U2Gate, UGate, XGate, ) from qiskit.circuit.measure import Measure from qiskit.compiler import transpile from qiskit.converters import circuit_to_dag from qiskit.dagcircuit import DAGOpNode, DAGOutNode from qiskit.exceptions import QiskitError from qiskit.providers.backend import BackendV2 from qiskit.providers.fake_provider import ( FakeBoeblingen, FakeMelbourne, FakeMumbaiV2, FakeNairobiV2, FakeRueschlikon, FakeSherbrooke, FakeVigo, ) from qiskit.providers.options import Options from qiskit.pulse import InstructionScheduleMap from qiskit.quantum_info import Operator, random_unitary from qiskit.test import QiskitTestCase, slow_test from qiskit.tools import parallel from qiskit.transpiler import CouplingMap, Layout, PassManager, TransformationPass from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements, GateDirection, VF2PostLayout from qiskit.transpiler.passmanager_config import PassManagerConfig from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager, level_0_pass_manager from qiskit.transpiler.target import InstructionProperties, Target class CustomCX(Gate): """Custom CX gate representation.""" def __init__(self): super().__init__("custom_cx", 2, []) def _define(self): self._definition = QuantumCircuit(2) self._definition.cx(0, 1) def connected_qubits(physical: int, coupling_map: CouplingMap) -> set: """Get the physical qubits that have a connection to this one in the coupling map.""" for component in coupling_map.connected_components(): if physical in (qubits := set(component.graph.nodes())): return qubits raise ValueError(f"physical qubit {physical} is not in the coupling map") @ddt class TestTranspile(QiskitTestCase): """Test transpile function.""" def test_empty_transpilation(self): """Test that transpiling an empty list is a no-op. Regression test of gh-7287.""" self.assertEqual(transpile([]), []) def test_pass_manager_none(self): """Test passing the default (None) pass manager to the transpiler. It should perform the default qiskit flow: unroll, swap_mapper, cx_direction, cx_cancellation, optimize_1q_gates and should be equivalent to using tools.compile """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) coupling_map = [[1, 0]] basis_gates = ["u1", "u2", "u3", "cx", "id"] backend = BasicAer.get_backend("qasm_simulator") circuit2 = transpile( circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates, ) circuit3 = transpile( circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates ) self.assertEqual(circuit2, circuit3) def test_transpile_basis_gates_no_backend_no_coupling_map(self): """Verify transpile() works with no coupling_map or backend.""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) basis_gates = ["u1", "u2", "u3", "cx", "id"] circuit2 = transpile(circuit, basis_gates=basis_gates, optimization_level=0) resources_after = circuit2.count_ops() self.assertEqual({"u2": 2, "cx": 4}, resources_after) def test_transpile_non_adjacent_layout(self): """Transpile pipeline can handle manual layout on non-adjacent qubits. circuit: .. parsed-literal:: ┌───┐ qr_0: ┤ H ├──■──────────── -> 1 └───┘┌─┴─┐ qr_1: ─────┤ X ├──■─────── -> 2 └───┘┌─┴─┐ qr_2: ──────────┤ X ├──■── -> 3 └───┘┌─┴─┐ qr_3: ───────────────┤ X ├ -> 5 └───┘ device: 0 - 1 - 2 - 3 - 4 - 5 - 6 | | | | | | 13 - 12 - 11 - 10 - 9 - 8 - 7 """ qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) coupling_map = FakeMelbourne().configuration().coupling_map basis_gates = FakeMelbourne().configuration().basis_gates initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] new_circuit = transpile( circuit, basis_gates=basis_gates, coupling_map=coupling_map, initial_layout=initial_layout, ) qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)} for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map) def test_transpile_qft_grid(self): """Transpile pipeline can handle 8-qubit QFT on 14-qubit grid.""" qr = QuantumRegister(8) circuit = QuantumCircuit(qr) for i, _ in enumerate(qr): for j in range(i): circuit.cp(math.pi / float(2 ** (i - j)), qr[i], qr[j]) circuit.h(qr[i]) coupling_map = FakeMelbourne().configuration().coupling_map basis_gates = FakeMelbourne().configuration().basis_gates new_circuit = transpile(circuit, basis_gates=basis_gates, coupling_map=coupling_map) qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)} for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map) def test_already_mapped_1(self): """Circuit not remapped if matches topology. See: https://github.com/Qiskit/qiskit-terra/issues/342 """ backend = FakeRueschlikon() coupling_map = backend.configuration().coupling_map basis_gates = backend.configuration().basis_gates qr = QuantumRegister(16, "qr") cr = ClassicalRegister(16, "cr") qc = QuantumCircuit(qr, cr) qc.cx(qr[3], qr[14]) qc.cx(qr[5], qr[4]) qc.h(qr[9]) qc.cx(qr[9], qr[8]) qc.x(qr[11]) qc.cx(qr[3], qr[4]) qc.cx(qr[12], qr[11]) qc.cx(qr[13], qr[4]) qc.measure(qr, cr) new_qc = transpile( qc, coupling_map=coupling_map, basis_gates=basis_gates, initial_layout=Layout.generate_trivial_layout(qr), ) qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)} cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"] cx_qubits_physical = [ [qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits ] self.assertEqual( sorted(cx_qubits_physical), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]] ) def test_already_mapped_via_layout(self): """Test that a manual layout that satisfies a coupling map does not get altered. See: https://github.com/Qiskit/qiskit-terra/issues/2036 circuit: .. parsed-literal:: ┌───┐ ┌───┐ ░ ┌─┐ qn_0: ┤ H ├──■────────────■──┤ H ├─░─┤M├─── -> 9 └───┘ │ │ └───┘ ░ └╥┘ qn_1: ───────┼────────────┼────────░──╫──── -> 6 │ │ ░ ║ qn_2: ───────┼────────────┼────────░──╫──── -> 5 │ │ ░ ║ qn_3: ───────┼────────────┼────────░──╫──── -> 0 │ │ ░ ║ qn_4: ───────┼────────────┼────────░──╫──── -> 1 ┌───┐┌─┴─┐┌──────┐┌─┴─┐┌───┐ ░ ║ ┌─┐ qn_5: ┤ H ├┤ X ├┤ P(2) ├┤ X ├┤ H ├─░──╫─┤M├ -> 4 └───┘└───┘└──────┘└───┘└───┘ ░ ║ └╥┘ cn: 2/════════════════════════════════╩══╩═ 0 1 device: 0 -- 1 -- 2 -- 3 -- 4 | | 5 -- 6 -- 7 -- 8 -- 9 | | 10 - 11 - 12 - 13 - 14 | | 15 - 16 - 17 - 18 - 19 """ basis_gates = ["u1", "u2", "u3", "cx", "id"] coupling_map = [ [0, 1], [0, 5], [1, 0], [1, 2], [2, 1], [2, 3], [3, 2], [3, 4], [4, 3], [4, 9], [5, 0], [5, 6], [5, 10], [6, 5], [6, 7], [7, 6], [7, 8], [7, 12], [8, 7], [8, 9], [9, 4], [9, 8], [9, 14], [10, 5], [10, 11], [10, 15], [11, 10], [11, 12], [12, 7], [12, 11], [12, 13], [13, 12], [13, 14], [14, 9], [14, 13], [14, 19], [15, 10], [15, 16], [16, 15], [16, 17], [17, 16], [17, 18], [18, 17], [18, 19], [19, 14], [19, 18], ] q = QuantumRegister(6, name="qn") c = ClassicalRegister(2, name="cn") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[5]) qc.cx(q[0], q[5]) qc.p(2, q[5]) qc.cx(q[0], q[5]) qc.h(q[0]) qc.h(q[5]) qc.barrier(q) qc.measure(q[0], c[0]) qc.measure(q[5], c[1]) initial_layout = [ q[3], q[4], None, None, q[5], q[2], q[1], None, None, q[0], None, None, None, None, None, None, None, None, None, None, ] new_qc = transpile( qc, coupling_map=coupling_map, basis_gates=basis_gates, initial_layout=initial_layout ) qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)} cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"] cx_qubits_physical = [ [qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits ] self.assertEqual(sorted(cx_qubits_physical), [[9, 4], [9, 4]]) def test_transpile_bell(self): """Test Transpile Bell. If all correct some should exists. """ backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) circuits = transpile(qc, backend) self.assertIsInstance(circuits, QuantumCircuit) def test_transpile_one(self): """Test transpile a single circuit. Check that the top-level `transpile` function returns a single circuit.""" backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) circuit = transpile(qc, backend) self.assertIsInstance(circuit, QuantumCircuit) def test_transpile_two(self): """Test transpile two circuits. Check that the transpiler returns a list of two circuits. """ backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qubit_reg2 = QuantumRegister(2) clbit_reg2 = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qc_extra = QuantumCircuit(qubit_reg, qubit_reg2, clbit_reg, clbit_reg2, name="extra") qc_extra.measure(qubit_reg, clbit_reg) circuits = transpile([qc, qc_extra], backend) self.assertIsInstance(circuits, list) self.assertEqual(len(circuits), 2) for circuit in circuits: self.assertIsInstance(circuit, QuantumCircuit) def test_transpile_singleton(self): """Test transpile a single-element list with a circuit. Check that `transpile` returns a single-element list. See https://github.com/Qiskit/qiskit-terra/issues/5260 """ backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) circuits = transpile([qc], backend) self.assertIsInstance(circuits, list) self.assertEqual(len(circuits), 1) self.assertIsInstance(circuits[0], QuantumCircuit) def test_mapping_correction(self): """Test mapping works in previous failed case.""" backend = FakeRueschlikon() qr = QuantumRegister(name="qr", size=11) cr = ClassicalRegister(name="qc", size=11) circuit = QuantumCircuit(qr, cr) circuit.u(1.564784764685993, -1.2378965763410095, 2.9746763177861713, qr[3]) circuit.u(1.2269835563676523, 1.1932982847014162, -1.5597357740824318, qr[5]) circuit.cx(qr[5], qr[3]) circuit.p(0.856768317675967, qr[3]) circuit.u(-3.3911273825190915, 0.0, 0.0, qr[5]) circuit.cx(qr[3], qr[5]) circuit.u(2.159209321625547, 0.0, 0.0, qr[5]) circuit.cx(qr[5], qr[3]) circuit.u(0.30949966910232335, 1.1706201763833217, 1.738408691990081, qr[3]) circuit.u(1.9630571407274755, -0.6818742967975088, 1.8336534616728195, qr[5]) circuit.u(1.330181833806101, 0.6003162754946363, -3.181264980452862, qr[7]) circuit.u(0.4885914820775024, 3.133297443244865, -2.794457469189904, qr[8]) circuit.cx(qr[8], qr[7]) circuit.p(2.2196187596178616, qr[7]) circuit.u(-3.152367609631023, 0.0, 0.0, qr[8]) circuit.cx(qr[7], qr[8]) circuit.u(1.2646005789809263, 0.0, 0.0, qr[8]) circuit.cx(qr[8], qr[7]) circuit.u(0.7517780502091939, 1.2828514296564781, 1.6781179605443775, qr[7]) circuit.u(0.9267400575390405, 2.0526277839695153, 2.034202361069533, qr[8]) circuit.u(2.550304293455634, 3.8250017126569698, -2.1351609599720054, qr[1]) circuit.u(0.9566260876600556, -1.1147561503064538, 2.0571590492298797, qr[4]) circuit.cx(qr[4], qr[1]) circuit.p(2.1899329069137394, qr[1]) circuit.u(-1.8371715243173294, 0.0, 0.0, qr[4]) circuit.cx(qr[1], qr[4]) circuit.u(0.4717053496327104, 0.0, 0.0, qr[4]) circuit.cx(qr[4], qr[1]) circuit.u(2.3167620677708145, -1.2337330260253256, -0.5671322899563955, qr[1]) circuit.u(1.0468499525240678, 0.8680750644809365, -1.4083720073192485, qr[4]) circuit.u(2.4204244021892807, -2.211701932616922, 3.8297006565735883, qr[10]) circuit.u(0.36660280497727255, 3.273119149343493, -1.8003362351299388, qr[6]) circuit.cx(qr[6], qr[10]) circuit.p(1.067395863586385, qr[10]) circuit.u(-0.7044917541291232, 0.0, 0.0, qr[6]) circuit.cx(qr[10], qr[6]) circuit.u(2.1830003849921527, 0.0, 0.0, qr[6]) circuit.cx(qr[6], qr[10]) circuit.u(2.1538343756723917, 2.2653381826084606, -3.550087952059485, qr[10]) circuit.u(1.307627685019188, -0.44686656993522567, -2.3238098554327418, qr[6]) circuit.u(2.2046797998462906, 0.9732961754855436, 1.8527865921467421, qr[9]) circuit.u(2.1665254613904126, -1.281337664694577, -1.2424905413631209, qr[0]) circuit.cx(qr[0], qr[9]) circuit.p(2.6209599970201007, qr[9]) circuit.u(0.04680566321901303, 0.0, 0.0, qr[0]) circuit.cx(qr[9], qr[0]) circuit.u(1.7728411151289603, 0.0, 0.0, qr[0]) circuit.cx(qr[0], qr[9]) circuit.u(2.4866395967434443, 0.48684511243566697, -3.0069186877854728, qr[9]) circuit.u(1.7369112924273789, -4.239660866163805, 1.0623389015296005, qr[0]) circuit.barrier(qr) circuit.measure(qr, cr) circuits = transpile(circuit, backend) self.assertIsInstance(circuits, QuantumCircuit) def test_transpiler_layout_from_intlist(self): """A list of ints gives layout to correctly map circuit. virtual physical q1_0 - 4 ---[H]--- q2_0 - 5 q2_1 - 6 ---[H]--- q3_0 - 8 q3_1 - 9 q3_2 - 10 ---[H]--- """ qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") qr3 = QuantumRegister(3, "qr3") qc = QuantumCircuit(qr1, qr2, qr3) qc.h(qr1[0]) qc.h(qr2[1]) qc.h(qr3[2]) layout = [4, 5, 6, 8, 9, 10] cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] new_circ = transpile( qc, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout ) qubit_indices = {bit: idx for idx, bit in enumerate(new_circ.qubits)} mapped_qubits = [] for instruction in new_circ.data: mapped_qubits.append(qubit_indices[instruction.qubits[0]]) self.assertEqual(mapped_qubits, [4, 6, 10]) def test_mapping_multi_qreg(self): """Test mapping works for multiple qregs.""" backend = FakeRueschlikon() qr = QuantumRegister(3, name="qr") qr2 = QuantumRegister(1, name="qr2") qr3 = QuantumRegister(4, name="qr3") cr = ClassicalRegister(3, name="cr") qc = QuantumCircuit(qr, qr2, qr3, cr) qc.h(qr[0]) qc.cx(qr[0], qr2[0]) qc.cx(qr[1], qr3[2]) qc.measure(qr, cr) circuits = transpile(qc, backend) self.assertIsInstance(circuits, QuantumCircuit) def test_transpile_circuits_diff_registers(self): """Transpile list of circuits with different qreg names.""" backend = FakeRueschlikon() circuits = [] for _ in range(2): qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.measure(qr, cr) circuits.append(circuit) circuits = transpile(circuits, backend) self.assertIsInstance(circuits[0], QuantumCircuit) def test_wrong_initial_layout(self): """Test transpile with a bad initial layout.""" backend = FakeMelbourne() qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) bad_initial_layout = [ QuantumRegister(3, "q")[0], QuantumRegister(3, "q")[1], QuantumRegister(3, "q")[2], ] with self.assertRaises(TranspilerError): transpile(qc, backend, initial_layout=bad_initial_layout) def test_parameterized_circuit_for_simulator(self): """Verify that a parameterized circuit can be transpiled for a simulator backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") qc.rz(theta, qr[0]) transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator")) expected_qc = QuantumCircuit(qr) expected_qc.append(RZGate(theta), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_parameterized_circuit_for_device(self): """Verify that a parameterized circuit can be transpiled for a device backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") qc.rz(theta, qr[0]) transpiled_qc = transpile( qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr) ) qr = QuantumRegister(14, "q") expected_qc = QuantumCircuit(qr, global_phase=-1 * theta / 2.0) expected_qc.append(U1Gate(theta), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_parameter_expression_circuit_for_simulator(self): """Verify that a circuit including expressions of parameters can be transpiled for a simulator backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") square = theta * theta qc.rz(square, qr[0]) transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator")) expected_qc = QuantumCircuit(qr) expected_qc.append(RZGate(square), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_parameter_expression_circuit_for_device(self): """Verify that a circuit including expressions of parameters can be transpiled for a device backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") square = theta * theta qc.rz(square, qr[0]) transpiled_qc = transpile( qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr) ) qr = QuantumRegister(14, "q") expected_qc = QuantumCircuit(qr, global_phase=-1 * square / 2.0) expected_qc.append(U1Gate(square), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_final_measurement_barrier_for_devices(self): """Verify BarrierBeforeFinalMeasurements pass is called in default pipeline for devices.""" qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm")) layout = Layout.generate_trivial_layout(*circ.qregs) orig_pass = BarrierBeforeFinalMeasurements() with patch.object(BarrierBeforeFinalMeasurements, "run", wraps=orig_pass.run) as mock_pass: transpile( circ, coupling_map=FakeRueschlikon().configuration().coupling_map, initial_layout=layout, ) self.assertTrue(mock_pass.called) def test_do_not_run_gatedirection_with_symmetric_cm(self): """When the coupling map is symmetric, do not run GateDirection.""" qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm")) layout = Layout.generate_trivial_layout(*circ.qregs) coupling_map = [] for node1, node2 in FakeRueschlikon().configuration().coupling_map: coupling_map.append([node1, node2]) coupling_map.append([node2, node1]) orig_pass = GateDirection(CouplingMap(coupling_map)) with patch.object(GateDirection, "run", wraps=orig_pass.run) as mock_pass: transpile(circ, coupling_map=coupling_map, initial_layout=layout) self.assertFalse(mock_pass.called) def test_optimize_to_nothing(self): """Optimize gates up to fixed point in the default pipeline See https://github.com/Qiskit/qiskit-terra/issues/2035 """ # ┌───┐ ┌───┐┌───┐┌───┐ ┌───┐ # q0_0: ┤ H ├──■──┤ X ├┤ Y ├┤ Z ├──■──┤ H ├──■────■── # └───┘┌─┴─┐└───┘└───┘└───┘┌─┴─┐└───┘┌─┴─┐┌─┴─┐ # q0_1: ─────┤ X ├───────────────┤ X ├─────┤ X ├┤ X ├ # └───┘ └───┘ └───┘└───┘ qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.x(qr[0]) circ.y(qr[0]) circ.z(qr[0]) circ.cx(qr[0], qr[1]) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.cx(qr[0], qr[1]) after = transpile(circ, coupling_map=[[0, 1], [1, 0]], basis_gates=["u3", "u2", "u1", "cx"]) expected = QuantumCircuit(QuantumRegister(2, "q"), global_phase=-np.pi / 2) msg = f"after:\n{after}\nexpected:\n{expected}" self.assertEqual(after, expected, msg=msg) def test_pass_manager_empty(self): """Test passing an empty PassManager() to the transpiler. It should perform no transformations on the circuit. """ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) resources_before = circuit.count_ops() pass_manager = PassManager() out_circuit = pass_manager.run(circuit) resources_after = out_circuit.count_ops() self.assertDictEqual(resources_before, resources_after) def test_move_measurements(self): """Measurements applied AFTER swap mapping.""" backend = FakeRueschlikon() cmap = backend.configuration().coupling_map qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "move_measurements.qasm")) lay = [0, 1, 15, 2, 14, 3, 13, 4, 12, 5, 11, 6] out = transpile(circ, initial_layout=lay, coupling_map=cmap, routing_method="stochastic") out_dag = circuit_to_dag(out) meas_nodes = out_dag.named_nodes("measure") for meas_node in meas_nodes: is_last_measure = all( isinstance(after_measure, DAGOutNode) for after_measure in out_dag.quantum_successors(meas_node) ) self.assertTrue(is_last_measure) @data(0, 1, 2, 3) def test_init_resets_kept_preset_passmanagers(self, optimization_level): """Test initial resets kept at all preset transpilation levels""" num_qubits = 5 qc = QuantumCircuit(num_qubits) qc.reset(range(num_qubits)) num_resets = transpile(qc, optimization_level=optimization_level).count_ops()["reset"] self.assertEqual(num_resets, num_qubits) @data(0, 1, 2, 3) def test_initialize_reset_is_not_removed(self, optimization_level): """The reset in front of initializer should NOT be removed at beginning""" qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) qc.initialize([1.0 / math.sqrt(2), 1.0 / math.sqrt(2)], [qr[0]]) qc.initialize([1.0 / math.sqrt(2), -1.0 / math.sqrt(2)], [qr[0]]) after = transpile(qc, basis_gates=["reset", "u3"], optimization_level=optimization_level) self.assertEqual(after.count_ops()["reset"], 2, msg=f"{after}\n does not have 2 resets.") def test_initialize_FakeMelbourne(self): """Test that the zero-state resets are remove in a device not supporting them.""" desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2]]) out = transpile(qc, backend=FakeMelbourne()) out_dag = circuit_to_dag(out) reset_nodes = out_dag.named_nodes("reset") self.assertEqual(len(reset_nodes), 3) def test_non_standard_basis(self): """Test a transpilation with a non-standard basis""" qr1 = QuantumRegister(1, "q1") qr2 = QuantumRegister(2, "q2") qr3 = QuantumRegister(3, "q3") qc = QuantumCircuit(qr1, qr2, qr3) qc.h(qr1[0]) qc.h(qr2[1]) qc.h(qr3[2]) layout = [4, 5, 6, 8, 9, 10] cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit = transpile( qc, backend=None, coupling_map=cmap, basis_gates=["h"], initial_layout=layout ) dag_circuit = circuit_to_dag(circuit) resources_after = dag_circuit.count_ops() self.assertEqual({"h": 3}, resources_after) def test_hadamard_to_rot_gates(self): """Test a transpilation from H to Rx, Ry gates""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.h(0) expected = QuantumCircuit(qr, global_phase=np.pi / 2) expected.append(RYGate(theta=np.pi / 2), [0]) expected.append(RXGate(theta=np.pi), [0]) circuit = transpile(qc, basis_gates=["rx", "ry"], optimization_level=0) self.assertEqual(circuit, expected) def test_basis_subset(self): """Test a transpilation with a basis subset of the standard basis""" qr = QuantumRegister(1, "q1") qc = QuantumCircuit(qr) qc.h(qr[0]) qc.x(qr[0]) qc.t(qr[0]) layout = [4] cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit = transpile( qc, backend=None, coupling_map=cmap, basis_gates=["u3"], initial_layout=layout ) dag_circuit = circuit_to_dag(circuit) resources_after = dag_circuit.count_ops() self.assertEqual({"u3": 1}, resources_after) def test_check_circuit_width(self): """Verify transpilation of circuit with virtual qubits greater than physical qubits raises error""" cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] qc = QuantumCircuit(15, 15) with self.assertRaises(TranspilerError): transpile(qc, coupling_map=cmap) @data(0, 1, 2, 3) def test_ccx_routing_method_none(self, optimization_level): """CCX without routing method.""" qc = QuantumCircuit(3) qc.cx(0, 1) qc.cx(1, 2) out = transpile( qc, routing_method="none", basis_gates=["u", "cx"], initial_layout=[0, 1, 2], seed_transpiler=0, coupling_map=[[0, 1], [1, 2]], optimization_level=optimization_level, ) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_ccx_routing_method_none_failed(self, optimization_level): """CCX without routing method cannot be routed.""" qc = QuantumCircuit(3) qc.ccx(0, 1, 2) with self.assertRaises(TranspilerError): transpile( qc, routing_method="none", basis_gates=["u", "cx"], initial_layout=[0, 1, 2], seed_transpiler=0, coupling_map=[[0, 1], [1, 2]], optimization_level=optimization_level, ) @data(0, 1, 2, 3) def test_ms_unrolls_to_cx(self, optimization_level): """Verify a Rx,Ry,Rxx circuit transpile to a U3,CX target.""" qc = QuantumCircuit(2) qc.rx(math.pi / 2, 0) qc.ry(math.pi / 4, 1) qc.rxx(math.pi / 4, 0, 1) out = transpile(qc, basis_gates=["u3", "cx"], optimization_level=optimization_level) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_ms_can_target_ms(self, optimization_level): """Verify a Rx,Ry,Rxx circuit can transpile to an Rx,Ry,Rxx target.""" qc = QuantumCircuit(2) qc.rx(math.pi / 2, 0) qc.ry(math.pi / 4, 1) qc.rxx(math.pi / 4, 0, 1) out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_cx_can_target_ms(self, optimization_level): """Verify a U3,CX circuit can transpiler to a Rx,Ry,Rxx target.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.rz(math.pi / 4, [0, 1]) out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_measure_doesnt_unroll_ms(self, optimization_level): """Verify a measure doesn't cause an Rx,Ry,Rxx circuit to unroll to U3,CX.""" qc = QuantumCircuit(2, 2) qc.rx(math.pi / 2, 0) qc.ry(math.pi / 4, 1) qc.rxx(math.pi / 4, 0, 1) qc.measure([0, 1], [0, 1]) out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level) self.assertEqual(qc, out) @data( ["cx", "u3"], ["cz", "u3"], ["cz", "rx", "rz"], ["rxx", "rx", "ry"], ["iswap", "rx", "rz"], ) def test_block_collection_runs_for_non_cx_bases(self, basis_gates): """Verify block collection is run when a single two qubit gate is in the basis.""" twoq_gate, *_ = basis_gates qc = QuantumCircuit(2) qc.cx(0, 1) qc.cx(1, 0) qc.cx(0, 1) qc.cx(0, 1) out = transpile(qc, basis_gates=basis_gates, optimization_level=3) self.assertLessEqual(out.count_ops()[twoq_gate], 2) @unpack @data( (["u3", "cx"], {"u3": 1, "cx": 1}), (["rx", "rz", "iswap"], {"rx": 6, "rz": 12, "iswap": 2}), (["rx", "ry", "rxx"], {"rx": 6, "ry": 5, "rxx": 1}), ) def test_block_collection_reduces_1q_gate(self, basis_gates, gate_counts): """For synthesis to non-U3 bases, verify we minimize 1q gates.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) out = transpile(qc, basis_gates=basis_gates, optimization_level=3) self.assertTrue(Operator(out).equiv(qc)) self.assertTrue(set(out.count_ops()).issubset(basis_gates)) for basis_gate in basis_gates: self.assertLessEqual(out.count_ops()[basis_gate], gate_counts[basis_gate]) @combine( optimization_level=[0, 1, 2, 3], basis_gates=[ ["u3", "cx"], ["rx", "rz", "iswap"], ["rx", "ry", "rxx"], ], ) def test_translation_method_synthesis(self, optimization_level, basis_gates): """Verify translation_method='synthesis' gets to the basis.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) out = transpile( qc, translation_method="synthesis", basis_gates=basis_gates, optimization_level=optimization_level, ) self.assertTrue(Operator(out).equiv(qc)) self.assertTrue(set(out.count_ops()).issubset(basis_gates)) def test_transpiled_custom_gates_calibration(self): """Test if transpiled calibrations is equal to custom gates circuit calibrations.""" custom_180 = Gate("mycustom", 1, [3.14]) custom_90 = Gate("mycustom", 1, [1.57]) circ = QuantumCircuit(2) circ.append(custom_180, [0]) circ.append(custom_90, [1]) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) with pulse.build() as q1_y90: pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1)) # Add calibration circ.add_calibration(custom_180, [0], q0_x180) circ.add_calibration(custom_90, [1], q1_y90) backend = FakeBoeblingen() transpiled_circuit = transpile( circ, backend=backend, layout_method="trivial", ) self.assertEqual(transpiled_circuit.calibrations, circ.calibrations) self.assertEqual(list(transpiled_circuit.count_ops().keys()), ["mycustom"]) self.assertEqual(list(transpiled_circuit.count_ops().values()), [2]) def test_transpiled_basis_gates_calibrations(self): """Test if the transpiled calibrations is equal to basis gates circuit calibrations.""" circ = QuantumCircuit(2) circ.h(0) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibration circ.add_calibration("h", [0], q0_x180) backend = FakeBoeblingen() transpiled_circuit = transpile( circ, backend=backend, ) self.assertEqual(transpiled_circuit.calibrations, circ.calibrations) def test_transpile_calibrated_custom_gate_on_diff_qubit(self): """Test if the custom, non calibrated gate raises QiskitError.""" custom_180 = Gate("mycustom", 1, [3.14]) circ = QuantumCircuit(2) circ.append(custom_180, [0]) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibration circ.add_calibration(custom_180, [1], q0_x180) backend = FakeBoeblingen() with self.assertRaises(QiskitError): transpile(circ, backend=backend, layout_method="trivial") def test_transpile_calibrated_nonbasis_gate_on_diff_qubit(self): """Test if the non-basis gates are transpiled if they are on different qubit that is not calibrated.""" circ = QuantumCircuit(2) circ.h(0) circ.h(1) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibration circ.add_calibration("h", [1], q0_x180) backend = FakeBoeblingen() transpiled_circuit = transpile( circ, backend=backend, ) self.assertEqual(transpiled_circuit.calibrations, circ.calibrations) self.assertEqual(set(transpiled_circuit.count_ops().keys()), {"u2", "h"}) def test_transpile_subset_of_calibrated_gates(self): """Test transpiling a circuit with both basis gate (not-calibrated) and a calibrated gate on different qubits.""" x_180 = Gate("mycustom", 1, [3.14]) circ = QuantumCircuit(2) circ.h(0) circ.append(x_180, [0]) circ.h(1) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) circ.add_calibration(x_180, [0], q0_x180) circ.add_calibration("h", [1], q0_x180) # 'h' is calibrated on qubit 1 transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial") self.assertEqual(set(transpiled_circ.count_ops().keys()), {"u2", "mycustom", "h"}) def test_parameterized_calibrations_transpile(self): """Check that gates can be matched to their calibrations before and after parameter assignment.""" tau = Parameter("tau") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [2 * 3.14 * tau]), [0]) def q0_rxt(tau): with pulse.build() as q0_rxt: pulse.play(pulse.library.Gaussian(20, 0.4 * tau, 3.0), pulse.DriveChannel(0)) return q0_rxt circ.add_calibration("rxt", [0], q0_rxt(tau), [2 * 3.14 * tau]) transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial") self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"}) circ = circ.assign_parameters({tau: 1}) transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial") self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"}) def test_inst_durations_from_calibrations(self): """Test that circuit calibrations can be used instead of explicitly supplying inst_durations. """ qc = QuantumCircuit(2) qc.append(Gate("custom", 1, []), [0]) with pulse.build() as cal: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("custom", [0], cal) out = transpile(qc, scheduling_method="alap") self.assertEqual(out.duration, cal.duration) @data(0, 1, 2, 3) def test_multiqubit_gates_calibrations(self, opt_level): """Test multiqubit gate > 2q with calibrations works Adapted from issue description in https://github.com/Qiskit/qiskit-terra/issues/6572 """ circ = QuantumCircuit(5) custom_gate = Gate("my_custom_gate", 5, []) circ.append(custom_gate, [0, 1, 2, 3, 4]) circ.measure_all() backend = FakeBoeblingen() with pulse.build(backend, name="custom") as my_schedule: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(1) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(2) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(3) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(4) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(1) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(2) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(3) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(4) ) circ.add_calibration("my_custom_gate", [0, 1, 2, 3, 4], my_schedule, []) trans_circ = transpile(circ, backend, optimization_level=opt_level, layout_method="trivial") self.assertEqual({"measure": 5, "my_custom_gate": 1, "barrier": 1}, trans_circ.count_ops()) @data(0, 1, 2, 3) def test_circuit_with_delay(self, optimization_level): """Verify a circuit with delay can transpile to a scheduled circuit.""" qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) out = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", 0, 200), ("cx", [0, 1], 700)], optimization_level=optimization_level, ) self.assertEqual(out.duration, 1200) def test_delay_converts_to_dt(self): """Test that a delay instruction is converted to units of dt given a backend.""" qc = QuantumCircuit(2) qc.delay(1000, [0], unit="us") backend = FakeRueschlikon() backend.configuration().dt = 0.5e-6 out = transpile([qc, qc], backend) self.assertEqual(out[0].data[0].operation.unit, "dt") self.assertEqual(out[1].data[0].operation.unit, "dt") out = transpile(qc, dt=1e-9) self.assertEqual(out.data[0].operation.unit, "dt") def test_scheduling_backend_v2(self): """Test that scheduling method works with Backendv2.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() backend = FakeMumbaiV2() out = transpile([qc, qc], backend, scheduling_method="alap") self.assertIn("delay", out[0].count_ops()) self.assertIn("delay", out[1].count_ops()) @data(1, 2, 3) def test_no_infinite_loop(self, optimization_level): """Verify circuit cost always descends and optimization does not flip flop indefinitely.""" qc = QuantumCircuit(1) qc.ry(0.2, 0) out = transpile( qc, basis_gates=["id", "p", "sx", "cx"], optimization_level=optimization_level ) # Expect a -pi/2 global phase for the U3 to RZ/SX conversion, and # a -0.5 * theta phase for RZ to P twice, once at theta, and once at 3 pi # for the second and third RZ gates in the U3 decomposition. expected = QuantumCircuit( 1, global_phase=-np.pi / 2 - 0.5 * (-0.2 + np.pi) - 0.5 * 3 * np.pi ) expected.p(-np.pi, 0) expected.sx(0) expected.p(np.pi - 0.2, 0) expected.sx(0) error_message = ( f"\nOutput circuit:\n{out!s}\n{Operator(out).data}\n" f"Expected circuit:\n{expected!s}\n{Operator(expected).data}" ) self.assertEqual(out, expected, error_message) @data(0, 1, 2, 3) def test_transpile_preserves_circuit_metadata(self, optimization_level): """Verify that transpile preserves circuit metadata in the output.""" circuit = QuantumCircuit(2, metadata={"experiment_id": "1234", "execution_number": 4}) circuit.h(0) circuit.cx(0, 1) cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] res = transpile( circuit, basis_gates=["id", "p", "sx", "cx"], coupling_map=cmap, optimization_level=optimization_level, ) self.assertEqual(circuit.metadata, res.metadata) @data(0, 1, 2, 3) def test_transpile_optional_registers(self, optimization_level): """Verify transpile accepts circuits without registers end-to-end.""" qubits = [Qubit() for _ in range(3)] clbits = [Clbit() for _ in range(3)] qc = QuantumCircuit(qubits, clbits) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) qc.measure(qubits, clbits) out = transpile(qc, FakeBoeblingen(), optimization_level=optimization_level) self.assertEqual(len(out.qubits), FakeBoeblingen().configuration().num_qubits) self.assertEqual(len(out.clbits), len(clbits)) @data(0, 1, 2, 3) def test_translate_ecr_basis(self, optimization_level): """Verify that rewriting in ECR basis is efficient.""" circuit = QuantumCircuit(2) circuit.append(random_unitary(4, seed=1), [0, 1]) circuit.barrier() circuit.cx(0, 1) circuit.barrier() circuit.swap(0, 1) circuit.barrier() circuit.iswap(0, 1) res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=optimization_level) self.assertEqual(res.count_ops()["ecr"], 9) self.assertTrue(Operator(res).equiv(circuit)) def test_optimize_ecr_basis(self): """Test highest optimization level can optimize over ECR.""" circuit = QuantumCircuit(2) circuit.swap(1, 0) circuit.iswap(0, 1) res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=3) self.assertEqual(res.count_ops()["ecr"], 1) self.assertTrue(Operator(res).equiv(circuit)) def test_approximation_degree_invalid(self): """Test invalid approximation degree raises.""" circuit = QuantumCircuit(2) circuit.swap(0, 1) with self.assertRaises(QiskitError): transpile(circuit, basis_gates=["u", "cz"], approximation_degree=1.1) def test_approximation_degree(self): """Test more approximation gives lower-cost circuit.""" circuit = QuantumCircuit(2) circuit.swap(0, 1) circuit.h(0) circ_10 = transpile( circuit, basis_gates=["u", "cx"], translation_method="synthesis", approximation_degree=0.1, ) circ_90 = transpile( circuit, basis_gates=["u", "cx"], translation_method="synthesis", approximation_degree=0.9, ) self.assertLess(circ_10.depth(), circ_90.depth()) @data(0, 1, 2, 3) def test_synthesis_translation_method_with_single_qubit_gates(self, optimization_level): """Test that synthesis basis translation works for solely 1q circuit""" qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.h(2) res = transpile( qc, basis_gates=["id", "rz", "x", "sx", "cx"], translation_method="synthesis", optimization_level=optimization_level, ) expected = QuantumCircuit(3, global_phase=3 * np.pi / 4) expected.rz(np.pi / 2, 0) expected.rz(np.pi / 2, 1) expected.rz(np.pi / 2, 2) expected.sx(0) expected.sx(1) expected.sx(2) expected.rz(np.pi / 2, 0) expected.rz(np.pi / 2, 1) expected.rz(np.pi / 2, 2) self.assertEqual(res, expected) @data(0, 1, 2, 3) def test_synthesis_translation_method_with_gates_outside_basis(self, optimization_level): """Test that synthesis translation works for circuits with single gates outside bassis""" qc = QuantumCircuit(2) qc.swap(0, 1) res = transpile( qc, basis_gates=["id", "rz", "x", "sx", "cx"], translation_method="synthesis", optimization_level=optimization_level, ) if optimization_level != 3: self.assertTrue(Operator(qc).equiv(res)) self.assertNotIn("swap", res.count_ops()) else: # Optimization level 3 eliminates the pointless swap self.assertEqual(res, QuantumCircuit(2)) @data(0, 1, 2, 3) def test_target_ideal_gates(self, opt_level): """Test that transpile() with a custom ideal sim target works.""" theta = Parameter("θ") phi = Parameter("ϕ") lam = Parameter("λ") target = Target(num_qubits=2) target.add_instruction(UGate(theta, phi, lam), {(0,): None, (1,): None}) target.add_instruction(CXGate(), {(0, 1): None}) target.add_instruction(Measure(), {(0,): None, (1,): None}) qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) result = transpile(qc, target=target, optimization_level=opt_level) self.assertEqual(Operator.from_circuit(result), Operator.from_circuit(qc)) @data(0, 1, 2, 3) def test_transpile_with_custom_control_flow_target(self, opt_level): """Test transpile() with a target and constrol flow ops.""" target = FakeMumbaiV2().target target.add_instruction(ForLoopOp, name="for_loop") target.add_instruction(WhileLoopOp, name="while_loop") target.add_instruction(IfElseOp, name="if_else") target.add_instruction(SwitchCaseOp, name="switch_case") circuit = QuantumCircuit(6, 1) circuit.h(0) circuit.measure(0, 0) circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with circuit.for_loop((1,)): circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with else_: circuit.cx(3, 4) circuit.cz(3, 5) circuit.append(CustomCX(), [4, 5], []) with circuit.while_loop((circuit.clbits[0], True)): circuit.cx(3, 4) circuit.cz(3, 5) circuit.append(CustomCX(), [4, 5], []) with circuit.switch(circuit.cregs[0]) as case_: with case_(0): circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with case_(1): circuit.cx(1, 2) circuit.cz(1, 3) circuit.append(CustomCX(), [2, 3], []) transpiled = transpile( circuit, optimization_level=opt_level, target=target, seed_transpiler=12434 ) # Tests of the complete validity of a circuit are mostly done at the indiviual pass level; # here we're just checking that various passes do appear to have run. self.assertIsInstance(transpiled, QuantumCircuit) # Assert layout ran. self.assertIsNot(getattr(transpiled, "_layout", None), None) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue(target.instruction_supported(instruction.operation.name, qargs)) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) # Assert unrolling ran. self.assertNotIsInstance(instruction.operation, CustomCX) # Assert translation ran. self.assertNotIsInstance(instruction.operation, CZGate) # Assert routing ran. _visit_block( transpiled, qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)}, ) @data(1, 2, 3) def test_transpile_identity_circuit_no_target(self, opt_level): """Test circuit equivalent to identity is optimized away for all optimization levels >0. Reproduce taken from https://github.com/Qiskit/qiskit-terra/issues/9217 """ qr1 = QuantumRegister(3, "state") qr2 = QuantumRegister(2, "ancilla") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr1, qr2, cr) qc.h(qr1[0]) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr1[2]) qc.cx(qr1[1], qr1[2]) qc.cx(qr1[0], qr1[1]) qc.h(qr1[0]) empty_qc = QuantumCircuit(qr1, qr2, cr) result = transpile(qc, optimization_level=opt_level) self.assertEqual(empty_qc, result) @data(0, 1, 2, 3) def test_initial_layout_with_loose_qubits(self, opt_level): """Regression test of gh-10125.""" qc = QuantumCircuit([Qubit(), Qubit()]) qc.cx(0, 1) transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level) self.assertIsNotNone(transpiled.layout) self.assertEqual( transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]}) ) @data(0, 1, 2, 3) def test_initial_layout_with_overlapping_qubits(self, opt_level): """Regression test of gh-10125.""" qr1 = QuantumRegister(2, "qr1") qr2 = QuantumRegister(bits=qr1[:]) qc = QuantumCircuit(qr1, qr2) qc.cx(0, 1) transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level) self.assertIsNotNone(transpiled.layout) self.assertEqual( transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]}) ) @combine(opt_level=[0, 1, 2, 3], basis=[["rz", "x"], ["rx", "z"], ["rz", "y"], ["ry", "x"]]) def test_paulis_to_constrained_1q_basis(self, opt_level, basis): """Test that Pauli-gate circuits can be transpiled to constrained 1q bases that do not contain any root-Pauli gates.""" qc = QuantumCircuit(1) qc.x(0) qc.barrier() qc.y(0) qc.barrier() qc.z(0) transpiled = transpile(qc, basis_gates=basis, optimization_level=opt_level) self.assertGreaterEqual(set(basis) | {"barrier"}, transpiled.count_ops().keys()) self.assertEqual(Operator(qc), Operator(transpiled)) @ddt class TestPostTranspileIntegration(QiskitTestCase): """Test that the output of `transpile` is usable in various other integration contexts.""" def _regular_circuit(self): a = Parameter("a") regs = [ QuantumRegister(2, name="q0"), QuantumRegister(3, name="q1"), ClassicalRegister(2, name="c0"), ] bits = [Qubit(), Qubit(), Clbit()] base = QuantumCircuit(*regs, bits) base.h(0) base.measure(0, 0) base.cx(0, 1) base.cz(0, 2) base.cz(0, 3) base.cz(1, 4) base.cx(1, 5) base.measure(1, 1) base.append(CustomCX(), [3, 6]) base.append(CustomCX(), [5, 4]) base.append(CustomCX(), [5, 3]) base.append(CustomCX(), [2, 4]).c_if(base.cregs[0], 3) base.ry(a, 4) base.measure(4, 2) return base def _control_flow_circuit(self): a = Parameter("a") regs = [ QuantumRegister(2, name="q0"), QuantumRegister(3, name="q1"), ClassicalRegister(2, name="c0"), ] bits = [Qubit(), Qubit(), Clbit()] base = QuantumCircuit(*regs, bits) base.h(0) base.measure(0, 0) with base.if_test((base.cregs[0], 1)) as else_: base.cx(0, 1) base.cz(0, 2) base.cz(0, 3) with else_: base.cz(1, 4) with base.for_loop((1, 2)): base.cx(1, 5) base.measure(2, 2) with base.while_loop((2, False)): base.append(CustomCX(), [3, 6]) base.append(CustomCX(), [5, 4]) base.append(CustomCX(), [5, 3]) base.append(CustomCX(), [2, 4]) base.ry(a, 4) base.measure(4, 2) with base.switch(base.cregs[0]) as case_: with case_(0, 1): base.cz(3, 5) with case_(case_.DEFAULT): base.cz(1, 4) base.append(CustomCX(), [2, 4]) base.append(CustomCX(), [3, 4]) return base def _control_flow_expr_circuit(self): a = Parameter("a") regs = [ QuantumRegister(2, name="q0"), QuantumRegister(3, name="q1"), ClassicalRegister(2, name="c0"), ] bits = [Qubit(), Qubit(), Clbit()] base = QuantumCircuit(*regs, bits) base.h(0) base.measure(0, 0) with base.if_test(expr.equal(base.cregs[0], 1)) as else_: base.cx(0, 1) base.cz(0, 2) base.cz(0, 3) with else_: base.cz(1, 4) with base.for_loop((1, 2)): base.cx(1, 5) base.measure(2, 2) with base.while_loop(expr.logic_not(bits[2])): base.append(CustomCX(), [3, 6]) base.append(CustomCX(), [5, 4]) base.append(CustomCX(), [5, 3]) base.append(CustomCX(), [2, 4]) base.ry(a, 4) base.measure(4, 2) with base.switch(expr.bit_and(base.cregs[0], 2)) as case_: with case_(0, 1): base.cz(3, 5) with case_(case_.DEFAULT): base.cz(1, 4) base.append(CustomCX(), [2, 4]) base.append(CustomCX(), [3, 4]) return base @data(0, 1, 2, 3) def test_qpy_roundtrip(self, optimization_level): """Test that the output of a transpiled circuit can be round-tripped through QPY.""" transpiled = transpile( self._regular_circuit(), backend=FakeMelbourne(), optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_backendv2(self, optimization_level): """Test that the output of a transpiled circuit can be round-tripped through QPY.""" transpiled = transpile( self._regular_circuit(), backend=FakeMumbaiV2(), optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow(self, optimization_level): """Test that the output of a transpiled circuit with control flow can be round-tripped through QPY.""" if optimization_level == 3 and sys.platform == "win32": self.skipTest( "This test case triggers a bug in the eigensolver routine on windows. " "See #10345 for more details." ) backend = FakeMelbourne() transpiled = transpile( self._control_flow_circuit(), backend=backend, basis_gates=backend.configuration().basis_gates + ["if_else", "for_loop", "while_loop", "switch_case"], optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow_backendv2(self, optimization_level): """Test that the output of a transpiled circuit with control flow can be round-tripped through QPY.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow_expr(self, optimization_level): """Test that the output of a transpiled circuit with control flow including `Expr` nodes can be round-tripped through QPY.""" if optimization_level == 3 and sys.platform == "win32": self.skipTest( "This test case triggers a bug in the eigensolver routine on windows. " "See #10345 for more details." ) backend = FakeMelbourne() transpiled = transpile( self._control_flow_expr_circuit(), backend=backend, basis_gates=backend.configuration().basis_gates + ["if_else", "for_loop", "while_loop", "switch_case"], optimization_level=optimization_level, seed_transpiler=2023_07_26, ) buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow_expr_backendv2(self, optimization_level): """Test that the output of a transpiled circuit with control flow including `Expr` nodes can be round-tripped through QPY.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2023_07_26, ) buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qasm3_output(self, optimization_level): """Test that the output of a transpiled circuit can be dumped into OpenQASM 3.""" transpiled = transpile( self._regular_circuit(), backend=FakeMelbourne(), optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # TODO: There's not a huge amount we can sensibly test for the output here until we can # round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump # itself doesn't throw an error, though. self.assertIsInstance(qasm3.dumps(transpiled).strip(), str) @data(0, 1, 2, 3) def test_qasm3_output_control_flow(self, optimization_level): """Test that the output of a transpiled circuit with control flow can be dumped into OpenQASM 3.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # TODO: There's not a huge amount we can sensibly test for the output here until we can # round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump # itself doesn't throw an error, though. self.assertIsInstance( qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(), str, ) @data(0, 1, 2, 3) def test_qasm3_output_control_flow_expr(self, optimization_level): """Test that the output of a transpiled circuit with control flow and `Expr` nodes can be dumped into OpenQASM 3.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2023_07_26, ) # TODO: There's not a huge amount we can sensibly test for the output here until we can # round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump # itself doesn't throw an error, though. self.assertIsInstance( qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(), str, ) @data(0, 1, 2, 3) def test_transpile_target_no_measurement_error(self, opt_level): """Test that transpile with a target which contains ideal measurement works Reproduce from https://github.com/Qiskit/qiskit-terra/issues/8969 """ target = Target() target.add_instruction(Measure(), {(0,): None}) qc = QuantumCircuit(1, 1) qc.measure(0, 0) res = transpile(qc, target=target, optimization_level=opt_level) self.assertEqual(qc, res) def test_transpile_final_layout_updated_with_post_layout(self): """Test that the final layout is correctly set when vf2postlayout runs. Reproduce from #10457 """ def _get_index_layout(transpiled_circuit: QuantumCircuit, num_source_qubits: int): """Return the index layout of a transpiled circuit""" layout = transpiled_circuit.layout if layout is None: return list(range(num_source_qubits)) pos_to_virt = {v: k for k, v in layout.input_qubit_mapping.items()} qubit_indices = [] for index in range(num_source_qubits): qubit_idx = layout.initial_layout[pos_to_virt[index]] if layout.final_layout is not None: qubit_idx = layout.final_layout[transpiled_circuit.qubits[qubit_idx]] qubit_indices.append(qubit_idx) return qubit_indices vf2_post_layout_called = False def callback(**kwargs): nonlocal vf2_post_layout_called if isinstance(kwargs["pass_"], VF2PostLayout): vf2_post_layout_called = True self.assertIsNotNone(kwargs["property_set"]["post_layout"]) backend = FakeVigo() qubits = 3 qc = QuantumCircuit(qubits) for i in range(5): qc.cx(i % qubits, int(i + qubits / 2) % qubits) tqc = transpile(qc, backend=backend, seed_transpiler=4242, callback=callback) self.assertTrue(vf2_post_layout_called) self.assertEqual([3, 2, 1], _get_index_layout(tqc, qubits)) class StreamHandlerRaiseException(StreamHandler): """Handler class that will raise an exception on formatting errors.""" def handleError(self, record): raise sys.exc_info() class TestLogTranspile(QiskitTestCase): """Testing the log_transpile option.""" def setUp(self): super().setUp() logger = getLogger() self.addCleanup(logger.setLevel, logger.level) logger.setLevel("DEBUG") self.output = io.StringIO() logger.addHandler(StreamHandlerRaiseException(self.output)) self.circuit = QuantumCircuit(QuantumRegister(1)) def assertTranspileLog(self, log_msg): """Runs the transpiler and check for logs containing specified message""" transpile(self.circuit) self.output.seek(0) # Filter unrelated log lines output_lines = self.output.readlines() transpile_log_lines = [x for x in output_lines if log_msg in x] self.assertTrue(len(transpile_log_lines) > 0) def test_transpile_log_time(self): """Check Total Transpile Time is logged""" self.assertTranspileLog("Total Transpile Time") class TestTranspileCustomPM(QiskitTestCase): """Test transpile function with custom pass manager""" def test_custom_multiple_circuits(self): """Test transpiling with custom pass manager and multiple circuits. This tests created a deadlock, so it needs to be monitored for timeout. See: https://github.com/Qiskit/qiskit-terra/issues/3925 """ qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) pm_conf = PassManagerConfig( initial_layout=None, basis_gates=["u1", "u2", "u3", "cx"], coupling_map=CouplingMap([[0, 1]]), backend_properties=None, seed_transpiler=1, ) passmanager = level_0_pass_manager(pm_conf) transpiled = passmanager.run([qc, qc]) expected = QuantumCircuit(QuantumRegister(2, "q")) expected.append(U2Gate(0, 3.141592653589793), [0]) expected.cx(0, 1) self.assertEqual(len(transpiled), 2) self.assertEqual(transpiled[0], expected) self.assertEqual(transpiled[1], expected) @ddt class TestTranspileParallel(QiskitTestCase): """Test transpile() in parallel.""" def setUp(self): super().setUp() # Force parallel execution to True to test multiprocessing for this class original_val = parallel.PARALLEL_DEFAULT def restore_default(): parallel.PARALLEL_DEFAULT = original_val self.addCleanup(restore_default) parallel.PARALLEL_DEFAULT = True @data(0, 1, 2, 3) def test_parallel_multiprocessing(self, opt_level): """Test parallel dispatch works with multiprocessing.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() backend = FakeMumbaiV2() pm = generate_preset_pass_manager(opt_level, backend) res = pm.run([qc, qc]) for circ in res: self.assertIsInstance(circ, QuantumCircuit) @data(0, 1, 2, 3) def test_parallel_with_target(self, opt_level): """Test that parallel dispatch works with a manual target.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() target = FakeMumbaiV2().target res = transpile([qc] * 3, target=target, optimization_level=opt_level) self.assertIsInstance(res, list) for circ in res: self.assertIsInstance(circ, QuantumCircuit) @data(0, 1, 2, 3) def test_parallel_dispatch(self, opt_level): """Test that transpile in parallel works for all optimization levels.""" backend = FakeRueschlikon() qr = QuantumRegister(16) cr = ClassicalRegister(16) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) for k in range(1, 15): qc.cx(qr[0], qr[k]) qc.measure(qr, cr) qlist = [qc for k in range(15)] tqc = transpile( qlist, backend=backend, optimization_level=opt_level, seed_transpiler=424242 ) result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result() counts = result.get_counts() for count in counts: self.assertTrue(math.isclose(count["0000000000000000"], 500, rel_tol=0.1)) self.assertTrue(math.isclose(count["0111111111111111"], 500, rel_tol=0.1)) def test_parallel_dispatch_lazy_cal_loading(self): """Test adding calibration by lazy loading in parallel environment.""" class TestAddCalibration(TransformationPass): """A fake pass to test lazy pulse qobj loading in parallel environment.""" def __init__(self, target): """Instantiate with target.""" super().__init__() self.target = target def run(self, dag): """Run test pass that adds calibration of SX gate of qubit 0.""" dag.add_calibration( "sx", qubits=(0,), schedule=self.target["sx"][(0,)].calibration, # PulseQobj is parsed here ) return dag backend = FakeMumbaiV2() # This target has PulseQobj entries that provides a serialized schedule data pass_ = TestAddCalibration(backend.target) pm = PassManager(passes=[pass_]) self.assertIsNone(backend.target["sx"][(0,)]._calibration._definition) qc = QuantumCircuit(1) qc.sx(0) qc_copied = [qc for _ in range(10)] qcs_cal_added = pm.run(qc_copied) ref_cal = backend.target["sx"][(0,)].calibration for qc_test in qcs_cal_added: added_cal = qc_test.calibrations["sx"][((0,), ())] self.assertEqual(added_cal, ref_cal) @data(0, 1, 2, 3) def test_backendv2_and_basis_gates(self, opt_level): """Test transpile() with BackendV2 and basis_gates set.""" backend = FakeNairobiV2() qc = QuantumCircuit(5) qc.h(0) qc.cz(0, 1) qc.cz(0, 2) qc.cz(0, 3) qc.cz(0, 4) qc.measure_all() tqc = transpile( qc, backend=backend, basis_gates=["u", "cz"], optimization_level=opt_level, seed_transpiler=12345678942, ) op_count = set(tqc.count_ops()) self.assertEqual({"u", "cz", "measure", "barrier"}, op_count) for inst in tqc.data: if inst.operation.name not in {"u", "cz"}: continue qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) self.assertIn(qubits, backend.target.qargs) @data(0, 1, 2, 3) def test_backendv2_and_coupling_map(self, opt_level): """Test transpile() with custom coupling map.""" backend = FakeNairobiV2() qc = QuantumCircuit(5) qc.h(0) qc.cz(0, 1) qc.cz(0, 2) qc.cz(0, 3) qc.cz(0, 4) qc.measure_all() cmap = CouplingMap.from_line(5, bidirectional=False) tqc = transpile( qc, backend=backend, coupling_map=cmap, optimization_level=opt_level, seed_transpiler=12345678942, ) op_count = set(tqc.count_ops()) self.assertTrue({"rz", "sx", "x", "cx", "measure", "barrier"}.issuperset(op_count)) for inst in tqc.data: if len(inst.qubits) == 2: qubit_0 = tqc.find_bit(inst.qubits[0]).index qubit_1 = tqc.find_bit(inst.qubits[1]).index self.assertEqual(qubit_1, qubit_0 + 1) def test_transpile_with_multiple_coupling_maps(self): """Test passing a different coupling map for every circuit""" backend = FakeNairobiV2() qc = QuantumCircuit(3) qc.cx(0, 2) # Add a connection between 0 and 2 so that transpile does not change # the gates cmap = CouplingMap.from_line(7) cmap.add_edge(0, 2) with self.assertRaisesRegex(TranspilerError, "Only a single input coupling"): # Initial layout needed to prevent transpiler from relabeling # qubits to avoid doing the swap transpile( [qc] * 2, backend, coupling_map=[backend.coupling_map, cmap], initial_layout=(0, 1, 2), ) @data(0, 1, 2, 3) def test_backend_and_custom_gate(self, opt_level): """Test transpile() with BackendV2, custom basis pulse gate.""" backend = FakeNairobiV2() inst_map = InstructionScheduleMap() inst_map.add("newgate", [0, 1], pulse.ScheduleBlock()) newgate = Gate("newgate", 2, []) circ = QuantumCircuit(2) circ.append(newgate, [0, 1]) tqc = transpile( circ, backend, inst_map=inst_map, basis_gates=["newgate"], optimization_level=opt_level ) self.assertEqual(len(tqc.data), 1) self.assertEqual(tqc.data[0].operation, newgate) qubits = tuple(tqc.find_bit(x).index for x in tqc.data[0].qubits) self.assertIn(qubits, backend.target.qargs) @ddt class TestTranspileMultiChipTarget(QiskitTestCase): """Test transpile() with a disjoint coupling map.""" def setUp(self): super().setUp() class FakeMultiChip(BackendV2): """Fake multi chip backend.""" def __init__(self): super().__init__() graph = rx.generators.directed_heavy_hex_graph(3) num_qubits = len(graph) * 3 rng = np.random.default_rng(seed=12345678942) rz_props = {} x_props = {} sx_props = {} measure_props = {} delay_props = {} self._target = Target("Fake multi-chip backend", num_qubits=num_qubits) for i in range(num_qubits): qarg = (i,) rz_props[qarg] = InstructionProperties(error=0.0, duration=0.0) x_props[qarg] = InstructionProperties( error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7) ) sx_props[qarg] = InstructionProperties( error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7) ) measure_props[qarg] = InstructionProperties( error=rng.uniform(1e-3, 1e-1), duration=rng.uniform(1e-8, 9e-7) ) delay_props[qarg] = None self._target.add_instruction(XGate(), x_props) self._target.add_instruction(SXGate(), sx_props) self._target.add_instruction(RZGate(Parameter("theta")), rz_props) self._target.add_instruction(Measure(), measure_props) self._target.add_instruction(Delay(Parameter("t")), delay_props) cz_props = {} for i in range(3): for root_edge in graph.edge_list(): offset = i * len(graph) edge = (root_edge[0] + offset, root_edge[1] + offset) cz_props[edge] = InstructionProperties( error=rng.uniform(1e-5, 5e-3), duration=rng.uniform(1e-8, 9e-7) ) self._target.add_instruction(CZGate(), cz_props) @property def target(self): return self._target @property def max_circuits(self): return None @classmethod def _default_options(cls): return Options(shots=1024) def run(self, circuit, **kwargs): raise NotImplementedError self.backend = FakeMultiChip() @data(0, 1, 2, 3) def test_basic_connected_circuit(self, opt_level): """Test basic connected circuit on disjoint backend""" qc = QuantumCircuit(5) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.measure_all() tqc = transpile(qc, self.backend, optimization_level=opt_level) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data(0, 1, 2, 3) def test_triple_circuit(self, opt_level): """Test a split circuit with one circuit component per chip.""" qc = QuantumCircuit(30) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.measure_all() if opt_level == 0: with self.assertRaises(TranspilerError): tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) return tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) def test_disjoint_control_flow(self): """Test control flow circuit on disjoint coupling map.""" qc = QuantumCircuit(6, 1) qc.h(0) qc.ecr(0, 1) qc.cx(0, 2) qc.measure(0, 0) with qc.if_test((qc.clbits[0], True)): qc.reset(0) qc.cz(1, 0) qc.h(3) qc.cz(3, 4) qc.cz(3, 5) target = self.backend.target target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)}) target.add_instruction(IfElseOp, name="if_else") tqc = transpile(qc, target=target) edges = set(target.build_coupling_map().graph.edge_list()) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue(target.instruction_supported(instruction.operation.name, qargs)) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) elif len(qargs) == 2: self.assertIn(qargs, edges) self.assertIn(instruction.operation.name, target) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) def test_disjoint_control_flow_shared_classical(self): """Test circuit with classical data dependency between connected components.""" creg = ClassicalRegister(19) qc = QuantumCircuit(25) qc.add_register(creg) qc.h(0) for i in range(18): qc.cx(0, i + 1) for i in range(18): qc.measure(i, creg[i]) with qc.if_test((creg, 0)): qc.h(20) qc.ecr(20, 21) qc.ecr(20, 22) qc.ecr(20, 23) qc.ecr(20, 24) target = self.backend.target target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)}) target.add_instruction(IfElseOp, name="if_else") tqc = transpile(qc, target=target) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue(target.instruction_supported(instruction.operation.name, qargs)) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) @slow_test @data(2, 3) def test_six_component_circuit(self, opt_level): """Test input circuit with more than 1 component per backend component.""" qc = QuantumCircuit(42) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.h(30) qc.cx(30, 31) qc.cx(30, 32) qc.cx(30, 33) qc.h(34) qc.cx(34, 35) qc.cx(34, 36) qc.cx(34, 37) qc.h(38) qc.cx(38, 39) qc.cx(39, 40) qc.cx(39, 41) qc.measure_all() tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) def test_six_component_circuit_level_1(self): """Test input circuit with more than 1 component per backend component.""" opt_level = 1 qc = QuantumCircuit(42) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.h(30) qc.cx(30, 31) qc.cx(30, 32) qc.cx(30, 33) qc.h(34) qc.cx(34, 35) qc.cx(34, 36) qc.cx(34, 37) qc.h(38) qc.cx(38, 39) qc.cx(39, 40) qc.cx(39, 41) qc.measure_all() tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data(0, 1, 2, 3) def test_shared_classical_between_components_condition(self, opt_level): """Test a condition sharing classical bits between components.""" creg = ClassicalRegister(19) qc = QuantumCircuit(25) qc.add_register(creg) qc.h(0) for i in range(18): qc.cx(0, i + 1) for i in range(18): qc.measure(i, creg[i]) qc.ecr(20, 21).c_if(creg, 0) tqc = transpile(qc, self.backend, optimization_level=opt_level) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) @data(0, 1, 2, 3) def test_shared_classical_between_components_condition_large_to_small(self, opt_level): """Test a condition sharing classical bits between components.""" creg = ClassicalRegister(2) qc = QuantumCircuit(25) qc.add_register(creg) # Component 0 qc.h(24) qc.cx(24, 23) qc.measure(24, creg[0]) qc.measure(23, creg[1]) # Component 1 qc.h(0).c_if(creg, 0) for i in range(18): qc.ecr(0, i + 1).c_if(creg, 0) tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=123456789) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) # Check that virtual qubits that interact with each other via quantum links are placed into # the same component of the coupling map. initial_layout = tqc.layout.initial_layout coupling_map = self.backend.target.build_coupling_map() components = [ connected_qubits(initial_layout[qc.qubits[23]], coupling_map), connected_qubits(initial_layout[qc.qubits[0]], coupling_map), ] self.assertLessEqual({initial_layout[qc.qubits[i]] for i in [23, 24]}, components[0]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(19)}, components[1]) # Check clbits are in order. # Traverse the output dag over the sole clbit, checking that the qubits of the ops # go in order between the components. This is a sanity check to ensure that routing # doesn't reorder a classical data dependency between components. Inside a component # we have the dag ordering so nothing should be out of order within a component. tqc_dag = circuit_to_dag(tqc) qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)} input_node = tqc_dag.input_map[tqc_dag.clbits[0]] first_meas_node = tqc_dag._multi_graph.find_successors_by_edge( input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] # The first node should be a measurement self.assertIsInstance(first_meas_node.op, Measure) # This should be in the first component self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0]) op_node = tqc_dag._multi_graph.find_successors_by_edge( first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while isinstance(op_node, DAGOpNode): self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] @data(1, 2, 3) def test_shared_classical_between_components_condition_large_to_small_reverse_index( self, opt_level ): """Test a condition sharing classical bits between components.""" creg = ClassicalRegister(2) qc = QuantumCircuit(25) qc.add_register(creg) # Component 0 qc.h(0) qc.cx(0, 1) qc.measure(0, creg[0]) qc.measure(1, creg[1]) # Component 1 qc.h(24).c_if(creg, 0) for i in range(23, 5, -1): qc.ecr(24, i).c_if(creg, 0) tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) # Check that virtual qubits that interact with each other via quantum links are placed into # the same component of the coupling map. initial_layout = tqc.layout.initial_layout coupling_map = self.backend.target.build_coupling_map() components = [ connected_qubits(initial_layout[qc.qubits[0]], coupling_map), connected_qubits(initial_layout[qc.qubits[6]], coupling_map), ] self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(2)}, components[0]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(6, 25)}, components[1]) # Check clbits are in order. # Traverse the output dag over the sole clbit, checking that the qubits of the ops # go in order between the components. This is a sanity check to ensure that routing # doesn't reorder a classical data dependency between components. Inside a component # we have the dag ordering so nothing should be out of order within a component. tqc_dag = circuit_to_dag(tqc) qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)} input_node = tqc_dag.input_map[tqc_dag.clbits[0]] first_meas_node = tqc_dag._multi_graph.find_successors_by_edge( input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] # The first node should be a measurement self.assertIsInstance(first_meas_node.op, Measure) # This shoulde be in the first ocmponent self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0]) op_node = tqc_dag._multi_graph.find_successors_by_edge( first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while isinstance(op_node, DAGOpNode): self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] @data(1, 2, 3) def test_chained_data_dependency(self, opt_level): """Test 3 component circuit with shared clbits between each component.""" creg = ClassicalRegister(1) qc = QuantumCircuit(30) qc.add_register(creg) # Component 0 qc.h(0) for i in range(9): qc.cx(0, i + 1) measure_op = Measure() qc.append(measure_op, [9], [creg[0]]) # Component 1 qc.h(10).c_if(creg, 0) for i in range(11, 20): qc.ecr(10, i).c_if(creg, 0) measure_op = Measure() qc.append(measure_op, [19], [creg[0]]) # Component 2 qc.h(20).c_if(creg, 0) for i in range(21, 30): qc.cz(20, i).c_if(creg, 0) measure_op = Measure() qc.append(measure_op, [29], [creg[0]]) tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) # Check that virtual qubits that interact with each other via quantum links are placed into # the same component of the coupling map. initial_layout = tqc.layout.initial_layout coupling_map = self.backend.target.build_coupling_map() components = [ connected_qubits(initial_layout[qc.qubits[0]], coupling_map), connected_qubits(initial_layout[qc.qubits[10]], coupling_map), connected_qubits(initial_layout[qc.qubits[20]], coupling_map), ] self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10)}, components[0]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10, 20)}, components[1]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(20, 30)}, components[2]) # Check clbits are in order. # Traverse the output dag over the sole clbit, checking that the qubits of the ops # go in order between the components. This is a sanity check to ensure that routing # doesn't reorder a classical data dependency between components. Inside a component # we have the dag ordering so nothing should be out of order within a component. tqc_dag = circuit_to_dag(tqc) qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)} input_node = tqc_dag.input_map[tqc_dag.clbits[0]] first_meas_node = tqc_dag._multi_graph.find_successors_by_edge( input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] self.assertIsInstance(first_meas_node.op, Measure) self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0]) op_node = tqc_dag._multi_graph.find_successors_by_edge( first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while not isinstance(op_node.op, Measure): self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while not isinstance(op_node.op, Measure): self.assertIn(qubit_map[op_node.qargs[0]], components[2]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] self.assertIn(qubit_map[op_node.qargs[0]], components[2]) @data("sabre", "stochastic", "basic", "lookahead") def test_basic_connected_circuit_dense_layout(self, routing_method): """Test basic connected circuit on disjoint backend""" qc = QuantumCircuit(5) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.measure_all() tqc = transpile( qc, self.backend, layout_method="dense", routing_method=routing_method, seed_transpiler=42, ) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) # Lookahead swap skipped for performance @data("sabre", "stochastic", "basic") def test_triple_circuit_dense_layout(self, routing_method): """Test a split circuit with one circuit component per chip.""" qc = QuantumCircuit(30) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.measure_all() tqc = transpile( qc, self.backend, layout_method="dense", routing_method=routing_method, seed_transpiler=42, ) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data("sabre", "stochastic", "basic", "lookahead") def test_triple_circuit_invalid_layout(self, routing_method): """Test a split circuit with one circuit component per chip.""" qc = QuantumCircuit(30) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.measure_all() with self.assertRaises(TranspilerError): transpile( qc, self.backend, layout_method="trivial", routing_method=routing_method, seed_transpiler=42, ) # Lookahead swap skipped for performance reasons @data("sabre", "stochastic", "basic") def test_six_component_circuit_dense_layout(self, routing_method): """Test input circuit with more than 1 component per backend component.""" qc = QuantumCircuit(42) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.h(30) qc.cx(30, 31) qc.cx(30, 32) qc.cx(30, 33) qc.h(34) qc.cx(34, 35) qc.cx(34, 36) qc.cx(34, 37) qc.h(38) qc.cx(38, 39) qc.cx(39, 40) qc.cx(39, 41) qc.measure_all() tqc = transpile( qc, self.backend, layout_method="dense", routing_method=routing_method, seed_transpiler=42, ) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops(self, opt_level): """Test qubits without operations aren't ever used.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]} ) qc = QuantumCircuit(3) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) tqc = transpile(qc, target=target, optimization_level=opt_level) invalid_qubits = {3, 4} self.assertEqual(tqc.num_qubits, 5) for inst in tqc.data: for bit in inst.qubits: self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops_with_routing(self, opt_level): """Test qubits without operations aren't ever used.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0), (2, 3)]}, ) qc = QuantumCircuit(4) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(1, 3) qc.cx(0, 3) tqc = transpile(qc, target=target, optimization_level=opt_level) invalid_qubits = { 4, } self.assertEqual(tqc.num_qubits, 5) for inst in tqc.data: for bit in inst.qubits: self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops_circuit_too_large(self, opt_level): """Test qubits without operations aren't ever used and error if circuit needs them.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]} ) qc = QuantumCircuit(4) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) with self.assertRaises(TranspilerError): transpile(qc, target=target, optimization_level=opt_level) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops_circuit_too_large_disconnected( self, opt_level ): """Test qubits without operations aren't ever used if a disconnected circuit needs them.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]} ) qc = QuantumCircuit(5) qc.x(0) qc.x(1) qc.x(3) qc.x(4) with self.assertRaises(TranspilerError): transpile(qc, target=target, optimization_level=opt_level) @data(0, 1, 2, 3) def test_transpile_does_not_affect_backend_coupling(self, opt_level): """Test that transpiliation of a circuit does not mutate the `CouplingMap` stored by a V2 backend. Regression test of gh-9997.""" if opt_level == 3: raise unittest.SkipTest("unitary resynthesis fails due to gh-10004") qc = QuantumCircuit(127) for i in range(1, 127): qc.ecr(0, i) backend = FakeSherbrooke() original_map = copy.deepcopy(backend.coupling_map) transpile(qc, backend, optimization_level=opt_level) self.assertEqual(original_map, backend.coupling_map) @combine( optimization_level=[0, 1, 2, 3], scheduling_method=["asap", "alap"], ) def test_transpile_target_with_qubits_without_delays_with_scheduling( self, optimization_level, scheduling_method ): """Test qubits without operations aren't ever used.""" no_delay_qubits = [1, 3, 4] target = Target(num_qubits=5, dt=1) target.add_instruction( XGate(), {(i,): InstructionProperties(duration=160) for i in range(4)} ) target.add_instruction( HGate(), {(i,): InstructionProperties(duration=160) for i in range(4)} ) target.add_instruction( CXGate(), { edge: InstructionProperties(duration=800) for edge in [(0, 1), (1, 2), (2, 0), (2, 3)] }, ) target.add_instruction( Delay(Parameter("t")), {(i,): None for i in range(4) if i not in no_delay_qubits} ) qc = QuantumCircuit(4) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(1, 3) qc.cx(0, 3) tqc = transpile( qc, target=target, optimization_level=optimization_level, scheduling_method=scheduling_method, ) invalid_qubits = { 4, } self.assertEqual(tqc.num_qubits, 5) for inst in tqc.data: for bit in inst.qubits: self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits) if isinstance(inst.operation, Delay): self.assertNotIn(tqc.find_bit(bit).index, no_delay_qubits)
https://github.com/qBraid/qBraid
qBraid
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. """ Unit tests for converting Braket circuits to/from OpenQASM """ import numpy as np import qiskit from braket.circuits import Circuit from qbraid.interface import circuits_allclose from qbraid.transpiler.conversions.braket import braket_to_qasm3 from qbraid.transpiler.conversions.qasm3 import qasm3_to_braket from qbraid.transpiler.conversions.qiskit import qiskit_to_qasm3 def test_braket_to_qasm3_bell_circuit(): """Test converting braket bell circuit to OpenQASM 3.0 string""" qasm_expected = """ OPENQASM 3.0; bit[2] b; qubit[2] q; h q[0]; cnot q[0], q[1]; b[0] = measure q[0]; b[1] = measure q[1]; """ qasm_expected_2 = """ OPENQASM 3.0; bit[2] __bits__; qubit[2] __qubits__; h __qubits__[0]; cnot __qubits__[0], __qubits__[1]; __bits__[0] = measure __qubits__[0]; __bits__[1] = measure __qubits__[1]; """ bell = Circuit().h(0).cnot(0, 1) qbraid_qasm = braket_to_qasm3(bell) assert qasm_expected.strip("\n") == qbraid_qasm or qasm_expected_2.strip("\n") == qbraid_qasm def test_braket_from_qasm3(): """Test converting OpenQASM 3 string to braket circuit""" qasm_str = """ OPENQASM 3.0; bit[2] b; qubit[2] q; rx(0.15) q[0]; rx(0.3) q[1]; """ circuit_expected = Circuit().rx(0, 0.15).rx(1, 0.3) assert circuit_expected == qasm3_to_braket(qasm_str) def test_qiskit_to_qasm3_to_braket(): """Test converting Qiskit circuit to Braket via OpenQASM 3.0 for mapped gate defs""" qc = qiskit.QuantumCircuit(4) qc.cx(0, 1) qc.s(0) qc.sdg(1) qc.t(2) qc.tdg(3) qc.sx(0) qc.sxdg(1) qc.p(np.pi / 8, 3) qc.cp(np.pi / 4, 2, 3) qasm3_str = qiskit_to_qasm3(qc) circuit = qasm3_to_braket(qasm3_str) assert circuits_allclose(qc, circuit)
https://github.com/qBraid/qBraid
qBraid
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. """ Unit tests for QASM preprocessing functions """ import pytest from qiskit import QuantumCircuit from qbraid.interface import circuits_allclose from qbraid.passes.qasm2 import flatten_qasm_program from qbraid.programs import load_program from qbraid.transpiler.conversions.qasm2 import qasm2_to_cirq qasm_0 = """OPENQASM 2.0; include "qelib1.inc"; gate rzx(param0) q0,q1 { h q1; cx q0,q1; rz(-pi/4) q1; cx q0,q1; h q1; } gate ecr q0,q1 { rzx(pi/4) q0,q1; x q0; rzx(-pi/4) q0,q1; } gate rzx_6320157840(param0) q0,q1 { h q1; cx q0,q1; rz(2.3200048200765524) q1; cx q0,q1; h q1; } qreg q[4]; cry(5.518945082555831) q[0],q[1]; u(5.75740842861076,5.870881397684582,1.8535618384181967) q[2]; ecr q[3],q[0]; rzx_6320157840(2.3200048200765524) q[2],q[1]; rccx q[1],q[2],q[3]; csx q[0],q[1]; rxx(5.603791034636421) q[2],q[0]; """ qasm_1 = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; rccx q[1],q[2],q[0]; cu(5.64,3.60,3.73, 5.68) q[1],q[0]; c3x q[1],q[3],q[0],q[2]; c3sqrtx q[3],q[1],q[2],q[0]; c4x q[2],q[0],q[1],q[4],q[3]; rc3x q[1],q[2],q[0],q[3]; """ qasm_lst = [qasm_0, qasm_1] def strings_equal(s1, s2): """Check if two strings are equal, ignoring spaces and newlines.""" s1_clean = s1.replace(" ", "").replace("\n", "") s2_clean = s2.replace(" ", "").replace("\n", "") return s1_clean == s2_clean @pytest.mark.parametrize("qasm_str", qasm_lst) def test_preprocess_qasm(qasm_str): """Test converting qasm string to format supported by Cirq parser""" qiskit_circuit = QuantumCircuit().from_qasm_str(qasm_str) supported_qasm = flatten_qasm_program(qasm_str) cirq_circuit = qasm2_to_cirq(supported_qasm) qprogram = load_program(cirq_circuit) qprogram._convert_to_line_qubits() cirq_circuit_compat = qprogram.program assert circuits_allclose(cirq_circuit_compat, qiskit_circuit)
https://github.com/qBraid/qBraid
qBraid
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. """ Benchmarking tests for Qiskit conversions """ import pytest import qiskit from qbraid.interface import circuits_allclose from qbraid.transpiler import ConversionGraph, transpile from ...fixtures.qiskit.gates import get_qiskit_gates TARGETS = [("braket", 0.98), ("cirq", 0.98), ("pyquil", 0.98), ("pytket", 0.98)] qiskit_gates = get_qiskit_gates(seed=0) graph = ConversionGraph(require_native=True) def convert_from_qiskit_to_x(target, gate_name): """Construct a Qiskit circuit with the given gate, transpile it to target program type, and check equivalence. """ gate = qiskit_gates[gate_name] source_circuit = qiskit.QuantumCircuit(gate.num_qubits) source_circuit.compose(gate, inplace=True) target_circuit = transpile(source_circuit, target, conversion_graph=graph) assert circuits_allclose(source_circuit, target_circuit, strict_gphase=False) @pytest.mark.parametrize(("target", "baseline"), TARGETS) def test_qiskit_coverage(target, baseline): """Test converting Qiskit circuits to supported target program type over all Qiskit standard gates and check against baseline expected accuracy. """ ACCURACY_BASELINE = baseline ALLOWANCE = 0.01 failures = {} for gate_name in qiskit_gates: try: convert_from_qiskit_to_x(target, gate_name) except Exception as e: # pylint: disable=broad-exception-caught failures[f"{target}-{gate_name}"] = e total_tests = len(qiskit_gates) nb_fails = len(failures) nb_passes = total_tests - nb_fails accuracy = float(nb_passes) / float(total_tests) assert accuracy >= ACCURACY_BASELINE - ALLOWANCE, ( f"The coverage threshold was not met. {nb_fails}/{total_tests} tests failed " f"({nb_fails / (total_tests):.2%}) and {nb_passes}/{total_tests} passed " f"(expected >= {ACCURACY_BASELINE}).\nFailures: {failures.keys()}\n\n" )
https://github.com/qBraid/qBraid
qBraid
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. """ Unit tests for OpenQASM 3 conversions """ import braket.circuits import numpy as np import qiskit from qbraid.interface import circuits_allclose from qbraid.transpiler.converter import transpile def test_one_qubit_qiskit_to_braket(): """Test converting qiskit to braket for one qubit circuit.""" qiskit_circuit = qiskit.QuantumCircuit(1) qiskit_circuit.h(0) qiskit_circuit.ry(np.pi / 2, 0) qasm3_program = transpile(qiskit_circuit, "qasm3") braket_circuit = transpile(qasm3_program, "braket") circuits_allclose(qiskit_circuit, braket_circuit, strict_gphase=True) def test_one_qubit_braket_to_qiskit(): """Test converting braket to qiskit for one qubit circuit.""" braket_circuit = braket.circuits.Circuit().h(0).ry(0, np.pi / 2) qasm3_program = transpile(braket_circuit, "qasm3") qiskit_circuit = transpile(qasm3_program, "qiskit") assert circuits_allclose(braket_circuit, qiskit_circuit, strict_gphase=True) def test_two_qubit_braket_to_qiskit(): """Test converting braket to qiskit for two qubit circuit.""" braket_circuit = braket.circuits.Circuit().h(0).cnot(0, 1) qasm3_program = transpile(braket_circuit, "qasm3") qiskit_circuit = transpile(qasm3_program, "qiskit") assert circuits_allclose(braket_circuit, qiskit_circuit, strict_gphase=True) def test_braket_to_qiskit_stdgates(): """Test converting braket to qiskit for standard gates.""" circuit = braket.circuits.Circuit() circuit.h([0, 1, 2, 3]) circuit.x([0, 1]) circuit.y(2) circuit.z(3) circuit.s(0) circuit.si(1) circuit.t(2) circuit.ti(3) circuit.rx(0, np.pi / 4) circuit.ry(1, np.pi / 2) circuit.rz(2, 3 * np.pi / 4) circuit.phaseshift(3, np.pi / 8) circuit.v(0) # circuit.vi(1) circuit.iswap(2, 3) circuit.swap(0, 2) circuit.swap(1, 3) circuit.cnot(0, 1) circuit.cphaseshift(2, 3, np.pi / 4) cirq_circuit = transpile(circuit, "cirq") qasm3_program = transpile(circuit, "qasm3") qasm2_program = transpile(cirq_circuit, "qasm2") qiskit_circuit_1 = transpile(qasm3_program, "qiskit") qiskit_circuit_2 = transpile(qasm2_program, "qiskit") assert circuits_allclose(circuit, qiskit_circuit_1, strict_gphase=True) assert circuits_allclose(circuit, qiskit_circuit_2, strict_gphase=False) def test_braket_to_qiskit_vi_sxdg(): """Test converting braket to qiskit with vi/sxdg gate with non-strict global phase comparison.""" circuit = braket.circuits.Circuit().vi(0) qasm3_program = transpile(circuit, "qasm3") qiskit_circuit = transpile(qasm3_program, "qiskit") assert circuits_allclose(circuit, qiskit_circuit, strict_gphase=False)
https://github.com/qBraid/qBraid
qBraid
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. """ Unit tests for conversions between Cirq circuits and Qiskit circuits. """ import cirq import numpy as np import pytest import qiskit from cirq import Circuit, LineQubit, ops, testing from qiskit import QuantumCircuit from qiskit.circuit.random import random_circuit from qbraid.interface import circuits_allclose from qbraid.programs import load_program from qbraid.programs.exceptions import QasmError from qbraid.transpiler.conversions.cirq import cirq_to_qasm2 from qbraid.transpiler.conversions.qasm2 import qasm2_to_cirq from qbraid.transpiler.conversions.qasm3 import qasm3_to_qiskit from qbraid.transpiler.conversions.qiskit import qiskit_to_qasm2, qiskit_to_qasm3 from qbraid.transpiler.converter import transpile from qbraid.transpiler.exceptions import CircuitConversionError from ..cirq_utils import _equal def test_bell_state_to_from_circuits(): """Tests cirq.Circuit --> qiskit.QuantumCircuit --> cirq.Circuit with a Bell state circuit. """ qreg = cirq.LineQubit.range(2) cirq_circuit = cirq.Circuit([cirq.ops.H.on(qreg[0]), cirq.ops.CNOT.on(qreg[0], qreg[1])]) qiskit_circuit = transpile(cirq_circuit, "qiskit") # Qiskit from Cirq circuit_cirq = transpile(qiskit_circuit, "cirq") # Cirq from Qiskit assert np.allclose(cirq_circuit.unitary(), circuit_cirq.unitary()) def test_bell_state_to_qiskit(): """Tests cirq.Circuit --> qiskit.QuantumCircuit --> cirq.Circuit with a Bell state circuit.""" qreg = LineQubit.range(2) cirq_circuit = Circuit([ops.H.on(qreg[0]), ops.CNOT.on(qreg[0], qreg[1])]) qiskit_circuit = transpile(cirq_circuit, "qiskit") assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) @pytest.mark.parametrize("num_qubits", [1, 2, 3, 4, 5]) def test_random_circuit_to_qiskit(num_qubits): """Tests converting random Cirq circuits to Qiskit circuits.""" for _ in range(10): cirq_circuit = testing.random_circuit( qubits=num_qubits, n_moments=np.random.randint(1, 6), op_density=1, random_state=np.random.randint(1, 10), ) qiskit_circuit = transpile(cirq_circuit, "qiskit") assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) def test_bell_state_to_from_qasm(): """Tests cirq.Circuit --> QASM string --> cirq.Circuit with a Bell state circuit. """ qreg = cirq.LineQubit.range(2) cirq_circuit = cirq.Circuit([cirq.ops.H.on(qreg[0]), cirq.ops.CNOT.on(qreg[0], qreg[1])]) qasm = cirq_to_qasm2(cirq_circuit) # Qasm from Cirq circuit_cirq = qasm2_to_cirq(qasm) assert np.allclose(cirq_circuit.unitary(), circuit_cirq.unitary()) def test_random_circuit_to_from_circuits(): """Tests cirq.Circuit --> qiskit.QuantumCircuit --> cirq.Circuit with a random two-qubit circuit. """ cirq_circuit = cirq.testing.random_circuit( qubits=2, n_moments=10, op_density=0.99, random_state=1 ) qiskit_circuit = transpile(cirq_circuit, "qiskit") circuit_cirq = transpile(qiskit_circuit, "cirq") assert np.allclose(cirq_circuit.unitary(), circuit_cirq.unitary()) def test_random_circuit_to_from_qasm(): """Tests cirq.Circuit --> QASM string --> cirq.Circuit with a random one-qubit circuit. """ circuit_0 = cirq.testing.random_circuit(qubits=2, n_moments=10, op_density=0.99, random_state=2) qasm = cirq_to_qasm2(circuit_0) circuit_1 = qasm2_to_cirq(qasm) u_0 = circuit_0.unitary() u_1 = circuit_1.unitary() assert cirq.equal_up_to_global_phase(u_0, u_1) @pytest.mark.parametrize("as_qasm", (True, False)) def test_convert_with_barrier(as_qasm): """Tests converting a Qiskit circuit with a barrier to a Cirq circuit.""" n = 5 qiskit_circuit = qiskit.QuantumCircuit(qiskit.QuantumRegister(n)) qiskit_circuit.barrier() if as_qasm: cirq_circuit = qasm2_to_cirq(qiskit_to_qasm2(qiskit_circuit)) else: cirq_circuit = transpile(qiskit_circuit, "cirq") assert _equal(cirq_circuit, cirq.Circuit()) @pytest.mark.parametrize("as_qasm", (True, False)) def test_convert_with_multiple_barriers(as_qasm): """Tests converting a Qiskit circuit with barriers to a Cirq circuit.""" n = 1 num_ops = 10 qreg = qiskit.QuantumRegister(n) qiskit_circuit = qiskit.QuantumCircuit(qreg) for _ in range(num_ops): qiskit_circuit.h(qreg) qiskit_circuit.barrier() if as_qasm: cirq_circuit = qasm2_to_cirq(qiskit_to_qasm2(qiskit_circuit)) else: cirq_circuit = transpile(qiskit_circuit, "cirq") qbit = cirq.LineQubit(0) correct = cirq.Circuit(cirq.ops.H.on(qbit) for _ in range(num_ops)) assert _equal(cirq_circuit, correct) assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) def test_bell_state_from_qiskit(): """Tests qiskit.QuantumCircuit --> cirq.Circuit with a Bell state circuit. """ qiskit_circuit = QuantumCircuit(2) qiskit_circuit.h(0) qiskit_circuit.cx(0, 1) cirq_circuit = transpile(qiskit_circuit, "cirq") assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) def test_common_gates_from_qiskit(): """Tests converting standard gates from Qiskit to Cirq.""" qiskit_circuit = QuantumCircuit(4) qiskit_circuit.h([0, 1, 2, 3]) qiskit_circuit.x([0, 1]) qiskit_circuit.y(2) qiskit_circuit.z(3) qiskit_circuit.s(0) qiskit_circuit.sdg(1) qiskit_circuit.t(2) qiskit_circuit.tdg(3) qiskit_circuit.rx(np.pi / 4, 0) qiskit_circuit.ry(np.pi / 2, 1) qiskit_circuit.rz(3 * np.pi / 4, 2) qiskit_circuit.p(np.pi / 8, 3) qiskit_circuit.sx(0) qiskit_circuit.sxdg(1) qiskit_circuit.iswap(2, 3) qiskit_circuit.swap([0, 1], [2, 3]) qiskit_circuit.cx(0, 1) qiskit_circuit.cp(np.pi / 4, 2, 3) cirq_circuit = transpile(qiskit_circuit, "cirq") assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) @pytest.mark.parametrize("qubits", ([0, 1], [1, 0])) def test_crz_gate_from_qiskit(qubits): """Tests converting controlled Rz gate from Qiskit to Cirq.""" qiskit_circuit = QuantumCircuit(2) qiskit_circuit.crz(np.pi / 4, *qubits) cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True) assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) @pytest.mark.parametrize("qubits", ([0, 1], [1, 0])) @pytest.mark.parametrize("theta", (0, 2 * np.pi, np.pi / 2, np.pi / 4)) def test_rzz_gate_from_qiskit(qubits, theta): """Tests converting Rzz gate from Qiskit to Cirq.""" qiskit_circuit = QuantumCircuit(2) qiskit_circuit.rzz(theta, *qubits) cirq_circuit = transpile(qiskit_circuit, "cirq") assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) def test_iswap_gate_from_qiskit(): """Tests converting iSwap gate from Qiskit to Cirq.""" qiskit_circuit = QuantumCircuit(2) qiskit_circuit.h([0, 1]) qiskit_circuit.iswap(0, 1) cirq_circuit = transpile(qiskit_circuit, "cirq") assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) def test_qiskit_roundtrip(): """Test converting qiskit gates that previously failed qiskit roundtrip test.""" qiskit_circuit = QuantumCircuit(3) qiskit_circuit.ccz(0, 1, 2) qiskit_circuit.ecr(1, 2) qiskit_circuit.cs(2, 0) cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True) assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=False) def test_qiskit_roundtrip_noncontig(): """Test converting gates that previously failed qiskit roundtrip test with non-contiguous qubits.""" qiskit_circuit = QuantumCircuit(4) qiskit_circuit.ccz(0, 1, 2) qiskit_circuit.ecr(1, 2) qiskit_circuit.cs(2, 0) cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True) qprogram = load_program(cirq_circuit) qprogram.remove_idle_qubits() qiskit_contig = qprogram.program assert circuits_allclose(qiskit_contig, cirq_circuit, strict_gphase=False) def test_100_random_qiskit(): """Test converting 100 random qiskit circuits to cirq.""" for _ in range(100): qiskit_circuit = random_circuit(4, 1) cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True) assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=False) def test_qiskit_to_from_qasm3(): """Test converting qiskit circuit to/from OpenQASM 3.0 string""" circuit_in = QuantumCircuit(2) circuit_in.h(0) circuit_in.cx(0, 1) qasm3_str = qiskit_to_qasm3(circuit_in) circuit_out = qasm3_to_qiskit(qasm3_str) assert circuits_allclose(circuit_in, circuit_out, strict_gphase=True) def test_raise_circuit_conversion_error(): """Tests raising error for unsupported gates.""" with pytest.raises(CircuitConversionError): probs = np.random.uniform(low=0, high=0.5) cirq_circuit = Circuit(ops.PhaseDampingChannel(probs).on(*LineQubit.range(1))) transpile(cirq_circuit, "qiskit") def test_raise_qasm_error(): """Test raising error for unsupported gates.""" with pytest.raises(QasmError): qiskit_circuit = QuantumCircuit(1) qiskit_circuit.delay(300, 0) qasm2 = qiskit_to_qasm2(qiskit_circuit) _ = qasm2_to_cirq(qasm2)
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 31.05.2023 @ 21:26:45 Component: Controlled-NOT Gate (CNOT) Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with two qubits circuit = QuantumCircuit(2) # Apply the CNOT gate with control qubit 0 and target qubit 1 circuit.cx(0, 1) # Measure the qubits circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 11.06.2023 @ 18:00:01 Component: Controlled-T Gate Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with two qubits circuit = QuantumCircuit(2) # Apply the Controlled-T gate using a combination of gates circuit.h(1) circuit.cx(0, 1) circuit.tdg(1) circuit.cx(0, 1) circuit.t(1) circuit.cx(0, 1) # Measure the qubits circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 05.06.2023 @ 20:25:12 Component: Controlled-Z Gate Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with two qubits circuit = QuantumCircuit(2) # Apply the Controlled-Z gate with control qubit 0 and target qubit 1 circuit.cz(0, 1) # Measure the qubits circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 30.05.2023 @ 22:30:05 Component: Hadamard Gate Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with one qubit circuit = QuantumCircuit(1) # Apply Hadamard gate to the qubit circuit.h(0) # Measure the qubit circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 27.05.2023 @ 22:41:54 Component: Pauli-X-Gate (bit-flip-gate) Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with one qubit circuit = QuantumCircuit(1) # Apply Pauli-X gate to the qubit circuit.x(0) # Measure the qubit circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 28.05.2023 @ 20:22:15 Component: Pauli-Y-Gate (bit-flip-gate) Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with one qubit circuit = QuantumCircuit(1) # Apply Pauli-Y gate to the qubit circuit.y(0) # Measure the qubit circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 29.05.2023 @ 22:57:01 Component: Pauli-Z-Gate (bit-flip-gate) Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with one qubit circuit = QuantumCircuit(1) # Apply Pauli-Z gate to the qubit circuit.z(0) # Measure the qubit circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 01.06.2023 @ 22:19:42 Component: Swap Gate Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with two qubits circuit = QuantumCircuit(2) # Apply the SWAP gate circuit.swap(0, 1) # Measure the qubits circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 02.06.2023 @ 21:34:23 Component: Toffoli Gate Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with three qubits circuit = QuantumCircuit(3) # Apply the Toffoli gate circuit.ccx(0, 1, 2) # Measure the qubits circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 18.06.2023 @ 22:29:12 Component: U1, U2, U3 Gates Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with one qubit circuit = QuantumCircuit(1) # Apply the U1 gate theta = 0.3 # Parameter for U1 gate circuit.u1(theta, 0) # Apply the U2 gate phi = 0.4 # Parameter for U2 gate lambda_ = 0.5 # Parameter for U2 gate circuit.u2(phi, lambda_, 0) # Apply the U3 gate theta_ = 0.2 # Parameter for U3 gate phi_ = 0.6 # Parameter for U3 gate lambda_ = 0.7 # Parameter for U3 gate circuit.u3(theta_, phi_, lambda_, 0) # Measure the qubit circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/erikberter/qiskit-quantum-artificial-life
erikberter
from qiskit import * from qiskit.aqua.circuits.gates import cry from qiskit.visualization import plot_histogram import numpy as np import random import sys import matplotlib.pyplot as plt theta = 2*np.pi/3 thetaR = np.pi/4 fileNum = 30 # Devuelve el valor esperado de un circuito con un solo bit de registro def getExpectedValue(qc, sim = Aer.get_backend('qasm_simulator') , shots=8192): job = execute(qc, sim, shots=shots) count = job.result().get_counts() a,b = [count[a]/shots if a in count else 0 for a in ['0','1']] return a-b def printHistogram(qc, sim = Aer.get_backend('qasm_simulator') , shots=8192): job = execute(qc, sim, shots=shots) return plot_histogram(job.result().get_counts()) # Devuelve la Gate time_Lapse que aplica una iteracion de paso de tiempo # # Changed : Float que representa el valor en radianes del gate CRY def getDecoherence(changed): decoherenceG = QuantumCircuit(2,1, name='decoherence') decoherenceG.ry(changed,1) decoherenceG.cx(0,1) decoherenceG.ry(-changed,1) decoherenceG.cx(0,1) decoherenceG.cx(1,0) decoherenceG.measure([1],[0]) decoherenceG.reset(1) return decoherenceG # Crea un circuito general de una Artificial Life de poblacion 1 # # time : Integer representando la cantidad de iteraciones # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # pop : Integer representando la cantidad de poblacion que tendra el algoritmo def getCircuit(pop=1,time=3, initial=theta, changed=theta, measure = True): decoherenceG = getDecoherence(changed).to_instruction() qc = QuantumCircuit(3*pop,pop) for i in range(pop): qc.u3(initial,0,0,i*3) qc.cx(i*3,i*3+1) qc.barrier() for i in range(0,time): #cry for j in range(pop): qc.append(decoherenceG, [j*3+1,j*3+2],[j]) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc # Aumenta el la cantidad de capas de tiempo del circuito. def addTimeLapse(qc,time,measure=False, changed = theta): decoherenceG = getDecoherence(changed).to_instruction() qBits = int(len(qc.qubits)/3) for i in range(0,time): #cry for j in range(qBits): qc.append(decoherenceG, [j*3+1,j*3+2],[j]) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) # Crea un escenario general de clonacion de poblacion asexual mediante clonacion exponencial # # time : Integer representando la cantidad de iteraciones # pop : Integer representando la cantidad de poblacion que tendra el algoritmo # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # mutationRate : Float que representa el ratio de mutacion def getCircuitG(time=3, pop=2, initial=theta, changed=theta, mutationRate = 0, mutation=False): decoherenceG = getDecoherence(changed).to_instruction() qc = QuantumCircuit(3*pop,pop) qc.u3(initial,0,0,0) qc.cx(0,1) actPop = 1 qc.barrier() for i in range(0,time): # Adding the Time_Lapse gates for j in range(0,actPop): qc.append(decoherenceG, [3*j+1,3*j+2],[j]) qc.barrier() # Adding the new population actPopi = actPop for z in range(0,min(actPop, pop-actPop)): qc.cx(3*z, 3*actPopi) if mutation: x = np.random.normal(loc=0, scale=mutationRate) qc.rx(x, 3*actPopi) y = np.random.normal(loc=0, scale=mutationRate) qc.ry(y, 3*actPopi) qc.cx(3*actPopi, 3*actPopi+1) qc.barrier() actPopi+=1 actPop = actPopi qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc # Crea un circuito general de una Artificial Life de poblacion 1 con un background customizado # # time : Integer representando la cantidad de iteraciones # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # pop : Integer representando la cantidad de poblacion que tendra el algoritmo def getCircuitCB(pop=1,time=3, initial=theta, changed=theta, measure = True, background_change=[np.pi/4,np.pi/8,np.pi/4], background_sign = [0,1,0]): qc = QuantumCircuit(3*pop,pop) for i in range(pop): qc.u3(initial,0,0,i*3) qc.cx(i*3,i*3+1) qc.barrier() for i in range(0,time): #cry for j in range(pop): decoherenceG = getDecoherence(background_change[i]).to_instruction() if(background_sign[i]==1): qc.x(j*3+1) qc.append(decoherenceG, [j*3+1,j*3+2],[j]) if(background_sign[i]==1): qc.x(j*3+1) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc # Devuelve un circuito de un conjunto de individuos con reproduccion sexual def getSexualCircuit(): q=QuantumRegister(10) c=ClassicalRegister(2) qc=QuantumCircuit(q,c) qc.h(q[0]) qc.cx(q[0],q[2]) qc.h(q[3]) qc.cx(q[3],q[5]) qc.barrier() qc.cx(q[2],q[6]) qc.cx(q[5],q[6]) qc.barrier() qc.u3(np.pi/4,0,0,q[0]) qc.cx(q[0],q[1]) qc.u3(3*np.pi/4,0,0,q[3]) qc.cx(q[3],q[4]) qc.barrier() qc.h(q[8]) qc.cu3(5*np.pi/2,0,0,q[0],q[8]) qc.cu3(5*np.pi/2,0,0,q[3],q[8]) qc.cx(q[8],q[7]) qc.barrier() qc.x(q[6]) qc.ccx(q[6],q[7],q[8]) qc.x(q[6]) qc.barrier() qc.cx(q[8],q[9]) qc.measure(q[6],c[0]) qc.measure(q[8],c[1]) return qc # Crea un circuito general de una Artificial Life de poblacion 1 con un background customizado # # time : Integer representando la cantidad de iteraciones # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # pop : Integer representando la cantidad de poblacion que tendra el algoritmo def getCircuitCB(pop=1,time=3, initial=theta, changed=theta, measure = True, background_change=[np.pi/4,np.pi/8,np.pi/4], background_sign = [0,1,0]): qc = QuantumCircuit(3*pop,pop) for i in range(pop): qc.u3(initial,0,0,i*3) qc.cx(i*3,i*3+1) qc.barrier() for i in range(0,time): #cry for j in range(pop): decoherenceG = getDecoherence(background_change[i]).to_instruction() if(background_sign[i]==1): qc.x(j*3+1) qc.append(decoherenceG, [j*3+1,j*3+2],[j]) if(background_sign[i]==1): qc.x(j*3+1) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc
https://github.com/erikberter/qiskit-quantum-artificial-life
erikberter
from qiskit import * from qiskit.aqua.circuits.gates import cry from qiskit.visualization import plot_histogram import numpy as np import random import sys import matplotlib.pyplot as plt theta = 2*np.pi/3 thetaR = np.pi/4 fileNum = 30 sim = Aer.get_backend('qasm_simulator') # Devuelve el valor esperado de un circuito con un solo bit de registro def getExpectedValue(qc, shots=8192): job = execute(qc, sim, shots=shots) count = job.result().get_counts() a,b = [count[a]/shots if a in count else 0 for a in ['0','1']] return a-b def printHistogram(qc, shots=8192): job = execute(qc, sim, shots=shots) return plot_histogram(job.result().get_counts()) # Devuelve la Gate time_Lapse que aplica una iteración de paso de tiempo # # Changed : Float que representa el valor en radianes del gate CRY def getDecoherence(changed): decoherenceG = QuantumCircuit(2,1, name='decoherence') decoherenceG.ry(changed,1) decoherenceG.cx(0,1) decoherenceG.ry(-changed,1) decoherenceG.cx(0,1) decoherenceG.cx(1,0) decoherenceG.measure([1],[0]) decoherenceG.reset(1) return decoherenceG # Crea un circuito general de una Artificial Life de población 1 # # time : Integer representando la cantidad de iteraciones # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # pop : Integer representando la cantidad de poblacion que tendra el algoritmo def getCircuit(pop=1,time=3, initial=theta, changed=theta, measure = True): decoherenceG = getDecoherence(changed).to_instruction() qc = QuantumCircuit(3*pop,pop) for i in range(pop): qc.u3(initial,0,0,i*3) qc.cx(i*3,i*3+1) qc.barrier() for i in range(0,time): #cry for j in range(pop): qc.append(decoherenceG, [j*3+1,j*3+2],[j]) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc # Aumenta el la cantidad de capas de tiempo del circuito. def addTimeLapse(qc,time,measure=False, changed = theta): decoherenceG = getDecoherence(changed).to_instruction() qBits = int(len(qc.qubits)/3) for i in range(0,time): #cry for j in range(qBits): qc.append(decoherenceG, [j*3+1,j*3+2],[j]) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) # Crea un escenario general de clonación de población asexual mediante clonación exponencial # # time : Integer representando la cantidad de iteraciones # pop : Integer representando la cantidad de poblacion que tendra el algoritmo # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # mutationRate : Float que representa el ratio de mutación def getCircuitG(time=3, pop=2, initial=theta, changed=theta, mutationRate = 0, mutation=False): decoherenceG = getDecoherence(changed).to_instruction() qc = QuantumCircuit(3*pop,pop) qc.u3(initial,0,0,0) qc.cx(0,1) actPop = 1 qc.barrier() for i in range(0,time): # Adding the Time_Lapse gates for j in range(0,actPop): qc.append(decoherenceG, [3*j+1,3*j+2],[j]) qc.barrier() # Adding the new population actPopi = actPop for z in range(0,min(actPop, pop-actPop)): qc.cx(3*z, 3*actPopi) if mutation: x = np.random.normal(loc=0, scale=mutationRate) qc.rx(x, 3*actPopi) y = np.random.normal(loc=0, scale=mutationRate) qc.ry(y, 3*actPopi) qc.cx(3*actPopi, 3*actPopi+1) qc.barrier() actPopi+=1 actPop = actPopi qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc getCircuitG(pop=2, time=2).draw(output='mpl') getCircuit(pop=2, time=2).draw(output='mpl') color = ["b","g","r"] def checkPopulationParameters(shot = 50, timeSet = [0,1,2], parameter = "changed"): global fileNum for j in range(0,len(timeSet)): x = [] y = [] for i in range(int(shot)): if(i%10==0): sys.stdout.write(f"Work progress: Iteration {j} - {100*float(i)/(shot)}% \r" ) sys.stdout.flush() rand = random.uniform(0, 1) x+= [rand] timeT = timeSet[j] if (parameter=="changed"): qc = getCircuit(time = timeT, changed=rand*np.pi) elif(parameter=="initial"): qc = getCircuit(time = timeT, initial=rand*np.pi) y += [getExpectedValue(qc)] plt.scatter(x, y,c=color[j], label=f"Time {timeSet[j]}") plt.legend(loc="lower left") plt.savefig(f"file_RA{fileNum}_N{shot}.png") fileNum+=1 checkPopulationParameters(parameter="initial") qc = getCircuitG(time=3,pop=3, initial=np.pi, changed = np.pi/5) printHistogram(qc, shots=1000) qc = getCircuitG(pop=2, time=2,mutation=True, mutationRate=0.5) #addTimeLapse(qc, time=3) qc.draw(output='mpl') #Creación del circuito cuantico q=QuantumRegister(10) c=ClassicalRegister(10) qc=QuantumCircuit(q,c) #Asignación aleatoria de sexos a cada individuo qc.h(q[0]) qc.cx(q[0],q[2]) qc.h(q[3]) qc.cx(q[3],q[5]) qc.barrier() #Comprobación de la posibilidad de la reproducción qc.cx(q[2],q[6]) qc.cx(q[5],q[6]) qc.barrier() #Determinación del fenotipo qc.u3(np.pi/4,0,0,q[0]) qc.cx(q[0],q[1]) qc.u3(3*np.pi/4,0,0,q[3]) qc.cx(q[3],q[4]) qc.barrier() #Creación del hijo qc.h(q[8]) qc.cu3(5*np.pi/2,0,0,q[0],q[8]) qc.cu3(5*np.pi/2,0,0,q[3],q[8]) qc.cx(q[8],q[7]) qc.barrier() #Supervivencia del hijo qc.x(q[6]) qc.ccx(q[6],q[7],q[8]) qc.x(q[6]) qc.barrier() qc.cx(q[8],q[9]) #Medida qc.measure(q[6],c[6]) qc.measure(q[8],c[8]) backend=Aer.get_backend('qasm_simulator') result=execute(qc,backend).result().get_counts() qc.draw(output='mpl') plot_histogram(result) # Crea un circuito general de una Artificial Life de población 1 con un background customizado # # time : Integer representando la cantidad de iteraciones # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # pop : Integer representando la cantidad de población que tendrá el algoritmo def getCircuitCB(pop=1,time=3, initial=theta, changed=theta, measure = True, background_change=[np.pi/4,np.pi/8,np.pi/4], background_sign = [0,1,0]): qc = QuantumCircuit(3*pop,pop) for i in range(pop): qc.u3(initial,0,0,i*3) qc.cx(i*3,i*3+1) qc.barrier() for i in range(0,time): #cry for j in range(pop): decoherenceG = getDecoherence(background_change[i]).to_instruction() if(background_sign[i]==1): qc.x(j*3+1) qc.append(decoherenceG, [j*3+1,j*3+2],[j]) if(background_sign[i]==1): qc.x(j*3+1) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc getCircuitCB(pop=1, time=3).draw(output='mpl')
https://github.com/erikberter/qiskit-quantum-artificial-life
erikberter
from qiskit import * from qiskit.aqua.circuits.gates import cry from qiskit.visualization import plot_histogram import numpy as np import random import sys import matplotlib.pyplot as plt theta = 2*np.pi/3 thetaR = np.pi/4 fileNum = 30 sim = Aer.get_backend('qasm_simulator') # Devuelve el valor esperado de un circuito con un solo bit de registro def getExpectedValue(qc, shots=8192): job = execute(qc, sim, shots=shots) count = job.result().get_counts() a,b = [count[a]/shots if a in count else 0 for a in ['0','1']] return a-b def printHistogram(qc, shots=8192): job = execute(qc, sim, shots=shots) return plot_histogram(job.result().get_counts()) # Devuelve la Gate time_Lapse que aplica una iteración de paso de tiempo # # Changed : Float que representa el valor en radianes del gate CRY def getDecoherence(changed): decoherenceG = QuantumCircuit(2,1, name='decoherence') decoherenceG.ry(changed,1) decoherenceG.cx(0,1) decoherenceG.ry(-changed,1) decoherenceG.cx(0,1) decoherenceG.cx(1,0) decoherenceG.measure([1],[0]) decoherenceG.reset(1) return decoherenceG # Crea un circuito general de una Artificial Life de población 1 # # time : Integer representando la cantidad de iteraciones # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # pop : Integer representando la cantidad de poblacion que tendra el algoritmo def getCircuit(pop=1,time=3, initial=theta, changed=theta, measure = True): decoherenceG = getDecoherence(changed).to_instruction() qc = QuantumCircuit(3*pop,pop) for i in range(pop): qc.u3(initial,0,0,i*3) qc.cx(i*3,i*3+1) qc.barrier() for i in range(0,time): #cry for j in range(pop): qc.append(decoherenceG, [j*3+1,j*3+2],[j]) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc # Aumenta el la cantidad de capas de tiempo del circuito. def addTimeLapse(qc,time,measure=False, changed = theta): decoherenceG = getDecoherence(changed).to_instruction() qBits = int(len(qc.qubits)/3) for i in range(0,time): #cry for j in range(qBits): qc.append(decoherenceG, [j*3+1,j*3+2],[j]) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) # Crea un escenario general de clonación de población asexual mediante clonación exponencial # # time : Integer representando la cantidad de iteraciones # pop : Integer representando la cantidad de poblacion que tendra el algoritmo # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # mutationRate : Float que representa el ratio de mutación def getCircuitG(time=3, pop=2, initial=theta, changed=theta, mutationRate = 0, mutation=False): decoherenceG = getDecoherence(changed).to_instruction() qc = QuantumCircuit(3*pop,pop) qc.u3(initial,0,0,0) qc.cx(0,1) actPop = 1 qc.barrier() for i in range(0,time): # Adding the Time_Lapse gates for j in range(0,actPop): qc.append(decoherenceG, [3*j+1,3*j+2],[j]) qc.barrier() # Adding the new population actPopi = actPop for z in range(0,min(actPop, pop-actPop)): qc.cx(3*z, 3*actPopi) if mutation: x = np.random.normal(loc=0, scale=mutationRate) qc.rx(x, 3*actPopi) y = np.random.normal(loc=0, scale=mutationRate) qc.ry(y, 3*actPopi) qc.cx(3*actPopi, 3*actPopi+1) qc.barrier() actPopi+=1 actPop = actPopi qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc getCircuitG(pop=2, time=2).draw(output='mpl') getCircuit(pop=2, time=2).draw(output='mpl') color = ["b","g","r"] def checkPopulationParameters(shot = 50, timeSet = [0,1,2], parameter = "changed"): global fileNum for j in range(0,len(timeSet)): x = [] y = [] for i in range(int(shot)): if(i%10==0): sys.stdout.write(f"Work progress: Iteration {j} - {100*float(i)/(shot)}% \r" ) sys.stdout.flush() rand = random.uniform(0, 1) x+= [rand] timeT = timeSet[j] if (parameter=="changed"): qc = getCircuit(time = timeT, changed=rand*np.pi) elif(parameter=="initial"): qc = getCircuit(time = timeT, initial=rand*np.pi) y += [getExpectedValue(qc)] plt.scatter(x, y,c=color[j], label=f"Time {timeSet[j]}") plt.legend(loc="lower left") plt.savefig(f"file_RA{fileNum}_N{shot}.png") fileNum+=1 checkPopulationParameters(parameter="initial") qc = getCircuitG(time=3,pop=3, initial=np.pi, changed = np.pi/5) printHistogram(qc, shots=1000) qc = getCircuitG(pop=2, time=2,mutation=True, mutationRate=0.5) #addTimeLapse(qc, time=3) qc.draw(output='mpl') #Creación del circuito cuantico q=QuantumRegister(10) c=ClassicalRegister(10) qc=QuantumCircuit(q,c) #Asignación aleatoria de sexos a cada individuo qc.h(q[0]) qc.cx(q[0],q[2]) qc.h(q[3]) qc.cx(q[3],q[5]) qc.barrier() #Comprobación de la posibilidad de la reproducción qc.cx(q[2],q[6]) qc.cx(q[5],q[6]) qc.barrier() #Determinación del fenotipo qc.u3(np.pi/4,0,0,q[0]) qc.cx(q[0],q[1]) qc.u3(3*np.pi/4,0,0,q[3]) qc.cx(q[3],q[4]) qc.barrier() #Creación del hijo qc.h(q[8]) qc.cu3(5*np.pi/2,0,0,q[0],q[8]) qc.cu3(5*np.pi/2,0,0,q[3],q[8]) qc.cx(q[8],q[7]) qc.barrier() #Supervivencia del hijo qc.x(q[6]) qc.ccx(q[6],q[7],q[8]) qc.x(q[6]) qc.barrier() qc.cx(q[8],q[9]) #Medida qc.measure(q[6],c[6]) qc.measure(q[8],c[8]) backend=Aer.get_backend('qasm_simulator') result=execute(qc,backend).result().get_counts() qc.draw(output='mpl') plot_histogram(result) # Crea un circuito general de una Artificial Life de población 1 con un background customizado # # time : Integer representando la cantidad de iteraciones # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # pop : Integer representando la cantidad de población que tendrá el algoritmo def getCircuitCB(pop=1,time=3, initial=theta, changed=theta, measure = True, background_change=[np.pi/4,np.pi/8,np.pi/4], background_sign = [0,1,0]): qc = QuantumCircuit(3*pop,pop) for i in range(pop): qc.u3(initial,0,0,i*3) qc.cx(i*3,i*3+1) qc.barrier() for i in range(0,time): #cry for j in range(pop): decoherenceG = getDecoherence(background_change[i]).to_instruction() if(background_sign[i]==1): qc.x(j*3+1) qc.append(decoherenceG, [j*3+1,j*3+2],[j]) if(background_sign[i]==1): qc.x(j*3+1) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc getCircuitCB(pop=1, time=3).draw(output='mpl')
https://github.com/omarcostahamido/Qu-Beats
omarcostahamido
from qiskit import * import numpy as np from mido import Message, MidiFile, MidiTrack from mido import * import mido from qiskit.tools.visualization import plot_histogram def add_circuit(qc): qc.h(0) qc.cx(0,1) return qc def Teleportation(qc): qc.z(0); qc.h(0) qc.h(1) qc.cx(1,2); qc.cx(0,1) qc.measure(1,1) qc.cx(1,2); qc.h(0) qc.measure(0,0) qc.cz(0,2) qc.h(2); qc.z(2) qc.measure(2,2) return qc def grover(qc): qc.h(0) qc.h(1) qc.x(0) qc.x(1) qc.cz(0,1) qc.x(0) qc.x(1) qc.h(0) qc.h(1) qc.cz(0,1) qc.h(0) qc.h(1) return qc def Bertstein_Vazirani(qc): qc.h(0); qc.h(1); qc.h(2); qc.h(3) qc.z(0); qc.z(1); qc.z(2); qc.z(3) qc.h(0); qc.h(1); qc.h(2); qc.h(3) qc.measure([0,1,2,3], [0,1,2,3]) return qc Beat_array = [] Beat1 = [0,1,0,0,1,0,1,0,1,0]; Beat_array.append(Beat1) Beat2 = [1,1,0,1,1,0,1,1,1,1]; Beat_array.append(Beat2) Beat3 = [0,0,0,1,1,1,1,0,0,1]; Beat_array.append(Beat3) Beat4 = [1,0,0,0,1,1,0,0,0,1]; Beat_array.append(Beat4) ## The 4 starting Beats being converted to MIDI mid = MidiFile() track = MidiTrack() mid.tracks.append(track) current_time = 0 for bt in Beat_array[0]: if bt == 1: track.append(Message('note_on', note=32, time=100))#current_time)) else: track.append(Message('note_off', note=32,time=100))#current_time)) #current_time = current_time + 32 mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat1.mid') mid = MidiFile() track = MidiTrack() mid.tracks.append(track) for bt in Beat_array[1]: if bt == 1: track.append(Message('note_on', note=35, time=100))#current_time)) else: track.append(Message('note_off', note=35, time=100))#current_time)) #current_time = current_time + 32 mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat2.mid') mid = MidiFile() track = MidiTrack() mid.tracks.append(track) for bt in Beat_array[2]: if bt == 1: track.append(Message('note_on', note=38, time=100))#current_time)) else: track.append(Message('note_off', note=38, time=100))#current_time)) #current_time = current_time + 32 mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat3.mid') mid = MidiFile() track = MidiTrack() mid.tracks.append(track) for bt in Beat_array[3]: if bt == 1: track.append(Message('note_on', note=40, time=100))#current_time)) else: track.append(Message('note_off', note=40, time=100))#current_time)) #current_time = current_time + 32 mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat4.mid') qr = QuantumRegister(2) cr = ClassicalRegister(2) #qc = QuantumCircuit(qr, cr) circuits = [] for i, val in enumerate(Beat1): qc = QuantumCircuit(qr, cr) if val == 1: qc.x(0) if Beat2[i] == 1: qc.x(1) add_circuit(qc) qc.measure([0,1], [0,1]) circuits.append(qc) circuits[0].draw(output='mpl') ## Execuuting code simulator = Aer.get_backend('qasm_simulator') result = execute(circuits, backend = simulator, shots=1).result() cir_array = [] for c in circuits: cir_array.append([k for k in result.get_counts(c).keys()][0]) new_track1 = [] new_track2 = [] for b in cir_array: new_track1.append(int(b[0])) new_track2.append(int(b[1])) #print(cir_array); print(new_track1), print(new_track2) ## New Midi Rhythms mid = MidiFile() track = MidiTrack() mid.tracks.append(track) current_time = 0 for bt in new_track1: if bt == 1: track.append(Message('note_on', note=32, time=100))#current_time)) else: track.append(Message('note_off', note=32, time=100))#current_time)) #current_time = current_time + 32 mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/Bell_Circ.mid') mid = MidiFile() track2 = MidiTrack() mid.tracks.append(track2) current_time = 0 for bt in new_track2: if bt == 1: track2.append(Message('note_on', note=35, time=100))#current_time)) else: track2.append(Message('note_off', note=35, time=100))#current_time)) #current_time = current_time + 32 mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/Bell_Circ2.mid') ###--------------- Rhythm #2 ------------------------------------------------------------------------------------------ qr = QuantumRegister(3) cr = ClassicalRegister(3) circuits = [] for i, val in enumerate(Beat1): qc = QuantumCircuit(qr, cr) if val == 1: qc.x(0) if Beat2[i] == 1: qc.x(1) if Beat3[i] == 1: qc.x(2) qc.barrier() Teleportation(qc) circuits.append(qc) circuits[0].draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuits, backend = simulator, shots=1).result() plot_histogram(result.get_counts(qc)) print(len(result.results)) ## Execuuting code cir_array = [] for c in circuits: cir_array.append([k for k in result.get_counts(c).keys()][0]) new_track1 = [] new_track2 = [] new_track3 = [] for b in cir_array: new_track1.append(int(b[0])) new_track2.append(int(b[1])) new_track3.append(int(b[2])) #print(cir_array); print(new_track1), print(new_track2); print(new_track3) qr = QuantumRegister(4) cr = ClassicalRegister(4) circuits = [] for i, val in enumerate(Beat1): qc = QuantumCircuit(qr, cr) if val == 1: qc.x(0) if Beat2[i] == 1: qc.x(1) if Beat2[i] == 1: qc.x(2) if Beat2[i] == 1: qc.x(3) qc.barrier() Bertstein_Vazirani(qc) circuits.append(qc) circuits[0].draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuits, backend = simulator, shots=1024).result() plot_histogram(result.get_counts(circuits[4])) ## Execuuting code cir_array = [] for c in circuits: cir_array.append([k for k in result.get_counts(c).keys()][0]) new_track1 = [] new_track2 = [] new_track3 = [] for b in cir_array: new_track1.append(int(b[0])) new_track2.append(int(b[1])) new_track3.append(int(b[2])) #print(cir_array); print(new_track1), print(new_track2); print(new_track3) mid = MidiFile() track = MidiTrack() mid.tracks.append(track) for bt in new_track1: if bt == 1: track.append(Message('note_on', note=32, time=100))#current_time)) else: track.append(Message('note_off', note=32, time=100))#current_time)) #current_time = current_time + 32 mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/new_teleport1.mid') mid = MidiFile() track2 = MidiTrack() mid.tracks.append(track2) for bt in new_track2: if bt == 1: track2.append(Message('note_on', note=35, time=100))#current_time)) else: track2.append(Message('note_off', note=35,time=100))#current_time)) #current_time = current_time + 32 mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/new_teleport2.mid') mid = MidiFile() track3 = MidiTrack() mid.tracks.append(track3) for bt in new_track3: if bt == 1: track3.append(Message('note_on', note=38, time=100))#current_time)) else: track3.append(Message('note_off', note=38, time=100))#current_time)) #current_time = current_time + 32 mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/new_teleport3.mid') ## ----------------------------------------------------------------------- ## The 4 starting Beats being converted to MIDI mid = MidiFile() track = MidiTrack() mid.tracks.append(track) current_time = 0 for bt in Beat_array[0]: if bt == 1: track.append(Message('note_on', time=100))#current_time)) else: track.append(Message('note_off', time=100))#current_time)) #current_time = current_time + 32 mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat1.mid') mid = MidiFile() track = MidiTrack() mid.tracks.append(track) for bt in Beat_array[1]: if bt == 1: track.append(Message('note_on', time=100))#current_time)) else: track.append(Message('note_off', time=100))#current_time)) #current_time = current_time + 32 mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat2.mid') mid = MidiFile() track = MidiTrack() mid.tracks.append(track) for bt in Beat_array[2]: if bt == 1: track.append(Message('note_on', time=100))#current_time)) else: track.append(Message('note_off', time=100))#current_time)) #current_time = current_time + 32 mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat3.mid') mid = MidiFile() track = MidiTrack() mid.tracks.append(track) for bt in Beat_array[3]: if bt == 1: track.append(Message('note_on', time=100))#current_time)) else: track.append(Message('note_off', time=100))#current_time)) #current_time = current_time + 32 mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat4.mid')
https://github.com/omarcostahamido/Qu-Beats
omarcostahamido
#!/usr/bin/env python # coding: utf-8 from typing import List, Callable import numpy as np from mido import Message, MidiFile, MidiTrack from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute from qiskit.tools.visualization import plot_histogram #~~~~~~~ Circuit Transformations ~~~~~~~# def add_bell_state(qc: QuantumCircuit) -> None: """This transformation modifies the input circuit by preparing a Bell State.""" qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) def add_teleportation(qc: QuantumCircuit) -> None: """This transformation modifies the input circuit by implementing the teleportation protocol. """ qc.z(0) qc.h(0) qc.h(1) qc.cx(1, 2) qc.cx(0,1) qc.measure(1, 1) qc.cx(1,2) qc.h(0) qc.measure(0, 0) qc.cz(0,2) qc.h(2) qc.z(2) qc.measure([0, 1, 2], [0, 1, 2]) def add_grover(qc: QuantumCircuit) -> None: """This transformation modifies the input circuit by implementing Grover's algorithm.""" qc.h(0) qc.h(1) qc.x(0) qc.x(1) qc.cz(0, 1) qc.x(0) qc.x(1) qc.h(0) qc.h(1) qc.cz(0, 1) qc.h(0) qc.h(1) qc.measure([0, 1], [0, 1]) def bertstein_vazirani(qc: QuantumCircuit) -> None: """This transformation modifies the input circuit by implementing Bertstein-Vazirani.""" qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc.z(0) qc.z(1) qc.z(2) qc.z(3) qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc.measure([0, 1, 2, 3], [0, 1, 2, 3]) #~~~~~~~ Input arrays, representing beats over time ~~~~~~~# beat1 = [0, 1, 0, 0, 1, 0, 1, 0, 1, 0] beat2 = [1, 1, 0, 1, 1, 0, 1, 1, 1, 1] beat3 = [0, 0, 0, 1, 1, 1, 1, 0, 0, 1] beat4 = [1, 0, 0, 0, 1, 1, 0, 0, 0, 1] #~~~~~~~ Conversion to MIDI ~~~~~~~# def save_to_midi(beat_array: List[int], filename: str, note: int = 32, time: int = 100) -> None: """Save the input to a new midi file.""" mid = MidiFile() track = MidiTrack() mid.tracks.append(track) for bt in beat_array: message = 'note_{}'.format('on' if bt == 1 else 'off') track.append(Message(message, note=note, time=time)) mid.save(filename) save_to_midi(beat1, '/Users/lauren@ibm.com/Documents/pBeat1.mid') save_to_midi(beat2, '/Users/lauren@ibm.com/Documents/pBeat2.mid') save_to_midi(beat3, '/Users/lauren@ibm.com/Documents/pBeat3.mid') save_to_midi(beat4, '/Users/lauren@ibm.com/Documents/pBeat4.mid') #~~~~~~~ Build QuantumCircuits ~~~~~~~# def build_circuits(transformation: Callable, beat1: List[int], *beats: List[List[int]]) -> List[QuantumCircuit]: circuits = [] for i in range(len(beats[0])): qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr) for j, beat in enumerate(beats): if beat[i] == 1: qc.x(j) qc.barrier() # Add transformation (and measurement) transformation(qc) circuits.append(qc) return circuits #~~~~~~~ BELL STATE ~~~~~~~# circuits = build_circuits(add_bell_state, beat1, beat2) circuits[0].draw(output='mpl') ## Executing code simulator = Aer.get_backend('qasm_simulator') result = execute(circuits, backend=simulator, shots=1).result() cir_array = [] for c in circuits: cir_array.append([k for k in result.get_counts(c).keys()][0]) new_track1 = [] new_track2 = [] for b in cir_array: new_track1.append(int(b[0])) new_track2.append(int(b[1])) ## New Midi Rhythms save_to_midi(new_track1, '/Users/lauren@ibm.com/Documents/Bell_Circ.mid') save_to_midi(new_track2, '/Users/lauren@ibm.com/Documents/Bell_Circ2.mid') #~~~~~~~ TELEPORTATION ~~~~~~~# circuits = build_circuits(add_teleportation, beat1, beat2, beat3) circuits[0].draw(output='mpl') # Executing code simulator = Aer.get_backend('qasm_simulator') result = execute(circuits, backend = simulator, shots=1).result() cir_array = [] for c in circuits: cir_array.append([k for k in result.get_counts(c).keys()][0]) new_track1 = [] new_track2 = [] new_track3 = [] for b in cir_array: new_track1.append(int(b[0])) new_track2.append(int(b[1])) new_track3.append(int(b[2])) #~~~~~~~ BERNSTEIN VAZIRANI ~~~~~~~# circuits = build_circuits(bertstein_vazirani, beat1, beat2, beat2, beat2) circuits[0].draw(output='mpl') ## Executing code simulator = Aer.get_backend('qasm_simulator') result = execute(circuits, backend = simulator, shots=1024).result() plot_histogram(result.get_counts(circuits[4])) cir_array = [] for c in circuits: cir_array.append([k for k in result.get_counts(c).keys()][0]) new_track1 = [] new_track2 = [] new_track3 = [] for b in cir_array: new_track1.append(int(b[0])) new_track2.append(int(b[1])) new_track3.append(int(b[2])) save_to_midi(new_track1, '/Users/lauren@ibm.com/Documents/new_teleport1.mid') save_to_midi(new_track2, '/Users/lauren@ibm.com/Documents/new_teleport2.mid') save_to_midi(new_track3, '/Users/lauren@ibm.com/Documents/new_teleport3.mid')
https://github.com/joemoorhouse/quantum-mc
joemoorhouse
import sys, os import numpy as np import scipy from scipy.stats import norm sys.path.append("../../../quantum-mc") # see os.getcwd() import matplotlib.pyplot as plt import quantum_mc.calibration.fitting as ft import quantum_mc.calibration.time_series as ts import matplotlib.dates as mdates from matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator) # AAPL, MSFT, SPX ticker = "MSFT" data = ts.get_data(ticker) ((cdf_x, cdf_y), sigma) = ft.get_cdf_data(ticker) (x, y) = ft.get_fit_data(ticker, norm_to_rel = False) pl = ft.fit_piecewise_linear(x, y) pc = ft.fit_piecewise_cubic(x, y) xf = np.linspace(-3, 3, 100) cm = 1 / 2.54 years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month years_fmt = mdates.DateFormatter('%Y') fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) #fig, ax = plt.subplots(nrows=1, figsize=(8*cm, 6*cm)) fig.set_facecolor('w') ax.plot(data.index, data["Close"], linewidth=0.5) ax.set_xlabel('Time (years)') ax.set_ylabel('Closing price') # format the ticks ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(years_fmt) ax.xaxis.set_minor_locator(months) fig.savefig('hist_series.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') ax.plot(cdf_x, cdf_y, label="Empirical") ax.plot(cdf_x, norm.cdf(cdf_x), '--', label="Normal") ax.set_xlim(-5, 4) ax.xaxis.set_major_locator(MultipleLocator(1)) ax.yaxis.set_major_locator(MultipleLocator(0.2)) ax.set_xlabel('Return ($\sigma$)') ax.set_ylabel('Cumulative probability') ax.legend() fig.savefig('hist_cdf_linear.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') ax.plot(cdf_x, cdf_y, label="Empirical") ax.plot(cdf_x, norm.cdf(cdf_x), '--', label="Normal") ax.set_xlim(-5, 4) ax.set_ylim(0.005, 1.0) ax.set_yscale("log") ax.xaxis.set_major_locator(MultipleLocator(1)) #ax.yaxis.set_major_locator(MultipleLocator(0.2)) ax.set_xlabel('Return ($\sigma$)') ax.set_ylabel('Cumulative probability') ax.legend() fig.savefig('hist_cdf_log.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) cm = 1 / 2.54 fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') ax.plot(x, y, "o", markersize = 2, label="Observed") ax.set_xlabel('Normal return ($\sigma$)') ax.set_ylabel('Empirical return ($\sigma$)') ax.xaxis.set_major_locator(MultipleLocator(1)) ax.yaxis.set_major_locator(MultipleLocator(2)) fig.savefig('hist_scatter.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) cm = 1 / 2.54 fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') ax.plot(x, y, "o", markersize = 2, label="Observed") ax.plot(xf, pl(xf), label="Fitted", color = "green") ax.set_xlabel('Normal return ($\sigma$)') ax.set_ylabel('Empirical return ($\sigma$)') ax.xaxis.set_major_locator(MultipleLocator(1)) ax.yaxis.set_major_locator(MultipleLocator(2)) ax.legend() fig.savefig('hist_scatter_fitted.pdf', formt='pdf', facecolor=fig.get_facecolor(), transparent=True) cm = 1 / 2.54 fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') ax.plot(x, y, "o", markersize = 2, label="Observed") ax.plot(xf, pc(xf), label="Fitted", color = "green") ax.set_xlabel('Normal return ($\sigma$)') ax.set_ylabel('Empirical return ($\sigma$)') ax.xaxis.set_major_locator(MultipleLocator(1)) ax.yaxis.set_major_locator(MultipleLocator(2)) ax.legend() fig.savefig('hist_scatter_spline_fitted.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') ax.plot(cdf_x, cdf_y, label="Empirical") ax.plot(cdf_x, norm.cdf(cdf_x), '--', label="Normal") ax.plot(pc(xf), norm.cdf(xf), ':', label="Fitted") # plot the fitted ax.set_xlim(-5, 4) ax.set_ylim(0.005, 1.0) ax.set_yscale("log") ax.xaxis.set_major_locator(MultipleLocator(1)) #ax.yaxis.set_major_locator(MultipleLocator(0.2)) ax.set_xlabel('Return ($\sigma$)') ax.set_ylabel('Cumulative probability') ax.legend() fig.savefig('hist_cdf_fitted_log.pdf', formt='pdf', facecolor=fig.get_facecolor(), transparent=True) lookup = scipy.interpolate.interp1d(norm.cdf(cdf_x), cdf_x) print(lookup(0.01)) lookup = scipy.interpolate.interp1d(cdf_y, cdf_x) print(lookup(0.01)) lookup = scipy.interpolate.interp1d(norm.cdf(xf), pc(xf)) print(lookup(0.01)) rets = ts.returns(ticker) # 10 day log returns rets = rets - np.mean(rets) # normalize returns into units of (maximum-likelihood-estimated) standard deviations sig = np.std(rets) rets = rets / sig # create discretised version import scipy cdf_fn = scipy.interpolate.interp1d(pc(xf), norm.cdf(xf)) def pdf_fn(x): return (cdf_fn(x + 1e-9) - cdf_fn(x - 1e-9)) / 2e-9 xf2 = np.linspace(-4.8, 3.4, 100) #plt.plot(xf2, cdf_fn(xf2)) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') plt.plot(xf2, pdf_fn(xf2), label = "Fitted") ax.hist(rets, density = True, bins = 100, label = "Empirical") ax.set_xlim(-6, 4) ax.set_xlabel('Return ($\sigma$)') ax.set_ylabel('Probability density') ax.legend() fig.savefig('hist_pdf_spline_fitted.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) from qiskit import execute, Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, AncillaRegister from qiskit.aqua.algorithms import IterativeAmplitudeEstimation from qiskit.circuit.library import NormalDistribution, LogNormalDistribution, LinearAmplitudeFunction, IntegerComparator, WeightedAdder from qiskit.visualization import plot_histogram from quantum_mc.probability_distributions.gaussian_copula import GaussianCopula rho = ts.correl(ts.returns("AAPL"), ts.returns("MSFT")) mu = [0, 0] sigma = [[1, rho], [rho, 1]] num_qubits = [4, 4] bounds = [(-3.4, 3.4), (-3.4, 3.4)] def F(x): return cdf_fn(x) #return norm.cdf(x) def f(x): return pdf_fn(x) #return norm.pdf(x) cdfs = [F, F] pdfs = [f, f] pdf_circ = GaussianCopula(num_qubits, cdfs, sigma=sigma, bounds=bounds, pdfs = pdfs) #pdf_circ = NormalDistribution(num_qubits, mu=mu, sigma=sigma, bounds=bounds) qr_state1 = QuantumRegister(4, 'state1') qr_state2 = QuantumRegister(4, 'state2') state_out = ClassicalRegister(4, 'state_out') circ = QuantumCircuit(qr_state1, qr_state2, state_out) circ.append(pdf_circ, qr_state1[:] + qr_state2[:]) circ.measure(qr_state1, state_out) circ.draw() pdf_circ._probabilities pdf_circ._values pdf_circ._values[0] comb = list(zip(pdf_circ._values, pdf_circ._probabilities)) print(comb[0]) values = sorted(set(map(lambda x:x[0], pdf_circ._values))) #newlist = [sum([y[0] for y in values if y[1]==x]) for x in values] print(values) probs = [sum([y[1] for y in comb if y[0][0]==x]) for x in values] print(probs) #plt.plot(values, probs) fig = plt.figure(figsize=(2*8*cm,8*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') rects = ax.bar(values, probs, width = 0.3) ax.set_ylim(0, 0.3) ax.set_xlabel('Return ($\sigma$)') ax.set_ylabel('Probability') labels = [r"$ | " + "{:04b}".format(i) + r" \rangle $" for i in range(len(values))] ax.bar_label(rects, padding=4, labels = labels, rotation=60) fig.savefig('hist_state.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) #plt.plot(xf2, pdf_fn(xf2), label = "Fitted") #fig = plt.figure(figsize=(8*cm,6*cm)) counts = execute(circ, Aer.get_backend('qasm_simulator', shots = 10000)).result().get_counts() #plot_histogram(counts, figsize=(9,5)) fig = plt.figure(figsize=(2*8*cm,8*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') cnts = [counts.get(('{0:0%sb}' % 4).format(i), 0) for i, v in enumerate(values)] cnts = np.array(cnts) cnts = cnts / sum(cnts) rects = ax.bar(values, cnts, width = 0.3) ax.set_ylim(0, 0.3) ax.set_xlabel('Return ($\sigma$)') ax.set_ylabel('Probability') labels = [r"$ | " + "{:04b}".format(i) + r" \rangle $" for i in range(len(values))] ax.bar_label(rects, padding=4, labels = labels, rotation=60) fig.savefig('hist_state_simulated.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) shots=1000 #sim_statevector = Aer.get_backend('statevector_simulator') job = execute(circ, Aer.get_backend('statevector_simulator')) result = job.result() outputstate = result.get_statevector(circ, decimals=3) from qiskit.visualization import plot_state_city plot_state_city(outputstate) plt.plot(np.linspace(-4, 4, 100), np.exp(np.linspace(-4, 4, 100) * sigma) - 1) Aer.backends()
https://github.com/joemoorhouse/quantum-mc
joemoorhouse
import sys sys.path.append("..") # see os.getcwd() import time from quantum_mc.arithmetic.piecewise_linear_transform import PiecewiseLinearTransform3 import numpy as np from qiskit.test.base import QiskitTestCase import quantum_mc.calibration.fitting as ft import quantum_mc.calibration.time_series as ts from scipy.stats import multivariate_normal, norm from qiskit.test.base import QiskitTestCase from qiskit import execute, Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, AncillaRegister from qiskit.quantum_info import Statevector #from qiskit_finance.circuit.library import NormalDistribution from qiskit.circuit.library import NormalDistribution, LogNormalDistribution, IntegerComparator from qiskit.utils import QuantumInstance from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem import matplotlib.pyplot as plt cm = 1 / 2.54 correl = ft.get_correl("AAPL", "MSFT") nbits = 3 bounds_std = 3. num_qubits = [nbits, nbits] sigma = correl bounds = [(-bounds_std, bounds_std), (-bounds_std, bounds_std)] mu = [0, 0] # starting point is a multi-variate normal distribution normal = NormalDistribution(num_qubits, mu=mu, sigma=sigma, bounds=bounds) coeff_set = [] xs = [] ys = [] pl_set = [] for ticker in ["MSFT", "AAPL"]: ((cdf_x, cdf_y), sigma) = ft.get_cdf_data(ticker) (x, y) = ft.get_fit_data(ticker, norm_to_rel = False) (pl, coeffs) = ft.fit_piecewise_linear(x, y) # scale, to apply an arbitrary delta (we happen to use the same value here, but could be different) coeffs = ft.scaled_coeffs(coeffs, 1.0 if ticker == "MSFT" else 1.0) coeff_set.append(coeffs) xs.append(x) ys.append(y) # calculate the max and min P&Ls pl_set.append(lambda z : ft.piecewise_linear(z, *coeff_set[0])) pl_set.append(lambda z : ft.piecewise_linear(z, *coeff_set[1])) p_max = max(pl_set[0](bounds_std), pl_set[1](bounds_std)) p_min = min(pl_set[0](-bounds_std), pl_set[1](-bounds_std)) # we discretise the transforms and create the circuits transforms = [] i_to_js = [] i_to_xs = [] j_to_ys = [] for i, ticker in enumerate(["MSFT", "AAPL"]): (i_0, i_1, a0, a1, a2, b0, b1, b2, i_to_j, i_to_x, j_to_y) = ft.integer_piecewise_linear_coeffs(coeff_set[i], x_min = -bounds_std, x_max = bounds_std, y_min = p_min, y_max = p_max, nbits_norm=nbits, nbits_extra = 1 if nbits == 2 else 2) transforms.append(PiecewiseLinearTransform3(i_0, i_1, a0, a1, a2, b0, b1, b2, nbits = nbits)) i_to_js.append(np.vectorize(i_to_j)) i_to_xs.append(np.vectorize(i_to_x)) j_to_ys.append(np.vectorize(j_to_y)) p_min, p_max i = np.arange(0, 2**nbits) index = 0 cm = 1 / 2.54 fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') ax.plot(xs[index], ys[index], "o", markersize = 2, label = "Observed") ax.plot(xs[index], np.vectorize(pl_set[index])(xs[index]), label = "Fitted") ax.plot(i_to_xs[index](i), j_to_ys[index](i_to_js[index](i)), '--', label = "Fitted, discretised") ax.set_xlabel('Normal return ($\sigma$)') ax.set_ylabel('Empirical return ($\sigma$)') ax.legend() fig.savefig('piecewise_fit.pdf', formt='pdf', facecolor=fig.get_facecolor(), transparent=True) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') ax.plot(i, i_to_js[index](i)) ax.set_xlabel('Normal return integer') ax.set_ylabel('Empirical return integer') fig.savefig('piecewise_fit_ints.pdf', formt='pdf', facecolor=fig.get_facecolor(), transparent=True) # starting point is a multi-variate normal distribution single_normal = NormalDistribution(3, mu=0, sigma=1, bounds=(-3, 3) ) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') ax.bar(np.arange(0, 2**3), single_normal._probabilities) ax.set_yscale("log") ax.set_xlabel('Register integer value pre-transform') ax.set_ylabel('Probability') fig.savefig('piecewise_transform_before.pdf', formt='pdf', facecolor=fig.get_facecolor(), transparent=True) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') ax.bar(i_to_js[0](np.arange(0, 2**3)), single_normal._probabilities) ax.set_yscale("log") ax.set_xlabel('Register integer value post-transform') ax.set_ylabel('Probability') fig.savefig('piecewise_transform_after.pdf', formt='pdf', facecolor=fig.get_facecolor(), transparent=True) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') plt.plot(xf2, pdf_fn(xf2), label = "Fitted") ax.hist(rets, density = True, bins = 100, label = "Empirical") ax.set_xlim(-6, 4) ax.set_xlabel('Return ($\sigma$)') ax.set_ylabel('Probability density') ax.legend() fig.savefig('hist_pdf_spline_fitted.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) num_ancillas = transforms[0].num_ancilla_qubits qr_input = QuantumRegister(nbits * 2, 'input') # 2 times 3 registers qr_objective = QuantumRegister(1, 'objective') qr_result = QuantumRegister(nbits * 2, 'result') qr_ancilla = QuantumRegister(num_ancillas, 'ancilla') output = ClassicalRegister(nbits * 2, 'output') state_preparation = QuantumCircuit(qr_input, qr_objective, qr_result, qr_ancilla, output) state_preparation.append(normal, qr_input) for i in range(2): offset = i * nbits state_preparation.append(transforms[i], qr_input[offset:offset + nbits] + qr_result[:] + qr_ancilla[:]) # to calculate the cdf, we use an additional comparator x_eval = 5 comparator = IntegerComparator(len(qr_result), x_eval + 1, geq=False) state_preparation.append(comparator, qr_result[:] + qr_objective[:] + qr_ancilla[0:comparator.num_ancillas]) state_preparation.measure(qr_result, output) # now check check = False if check: job = execute(state_preparation, backend=Aer.get_backend('statevector_simulator')) var_prob = 0 for i, a in enumerate(job.result().get_statevector()): b = ('{0:0%sb}' % (len(qr_input) + 1)).format(i)[-(len(qr_input) + 1):] prob = np.abs(a)**2 if prob > 1e-6 and b[0] == '1': var_prob += prob print('Operator CDF(%s)' % x_eval + ' = %.4f' % var_prob) state_preparation.draw() #state_preparation.draw() fig = state_preparation.draw(output='mpl') fig.savefig('../../../outputs/trans_circuit_detail.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True, bbox_inches='tight') counts = execute(state_preparation, Aer.get_backend('qasm_simulator'), shots = 100000).result().get_counts() from qiskit.visualization import plot_histogram plot_histogram(counts, title = "transform of normal") vals = [int(i, 2) for i,j in counts.items()] cnts = np.array([j for i,j in counts.items()]) plt.bar(vals, cnts) vals2 = p_min * 2 + np.array(vals) * 2 * (p_max - p_min) / (2**(nbits * 2) - 1) cnts = np.array([j for i,j in counts.items()]) cnts2 = cnts / np.sum(cnts) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') plt.bar(vals2, cnts2, width = 0.2) ax.set_xlabel('Normalised P&L') ax.set_ylabel('Probability') ax.legend() fig.savefig('pnl_quantum.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) # based on Sascha's noise model import qiskit.providers.aer.noise as noise from qiskit.utils import QuantumInstance # Noise settings use_noise = True #False error_scaling_factor = 2 ** 0 # Reference point: 1.0 (= no scaling) error_prob_1_gate = 0.001 * error_scaling_factor error_prob_2_gates = 0.001 * error_scaling_factor error_prob_measure = 0.001 * error_scaling_factor error_1 = noise.depolarizing_error(error_prob_1_gate, 1) error_2 = noise.depolarizing_error(error_prob_2_gates, 2) # Measurement errors error_m = noise.pauli_error([('X', error_prob_measure), ('I', 1 - error_prob_measure)]) noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3']) noise_model.add_all_qubit_quantum_error(error_2, ['cx']) noise_model.add_all_qubit_quantum_error(error_m, "measure") # Prepare IQAE backend = Aer.get_backend(simulator) qinstance = QuantumInstance(backend=backend, seed_simulator=2, seed_transpiler=2, shots=shots, noise_model=noise_model) problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=obj_qubit_ID) iqae = IterativeAmplitudeEstimation(epsilon_target=epsilon, alpha=alpha, quantum_instance=qinstance) result = iqae.estimate(problem) IBMQ.save_account("543dce4ab356df3a024dfcf606c9d74a31277e39232f0429dacdb0e00daa3622d02865023f613afd659783251eb5bde6f06e9d0f5f1a95b03fdf8a0d34449bef") provider = IBMQ.load_account() provider.backends() backend = provider.get_backend('ibmq_montreal') from qiskit import IBMQ, transpile from qiskit import QuantumCircuit from qiskit.providers.aer import AerSimulator from qiskit.test.mock import FakeMontreal device_backend = FakeMontreal() sim_be = AerSimulator.from_backend(device_backend) #sim_ideal = AerSimulator() #result = sim_ideal.run(transpile(state_preparation, sim_ideal)).result() #counts = result.get_counts(0) tcirc = transpile(state_preparation, sim_be) result_noise = sim_be.run(tcirc).result() counts_noise = result_noise.get_counts(0) from qiskit.visualization import plot_histogram plot_histogram(counts, title = "transform of normal") vals = [int(i, 2) for i,j in counts.items()] cnts = [j for i,j in counts.items()] plt.bar(vals, cnts) from qiskit import QuantumCircuit, execute from qiskit import IBMQ, Aer from qiskit.visualization import plot_histogram from qiskit.providers.aer.noise import NoiseModel # Build noise model from backend properties #provider = IBMQ.load_account() from qiskit.test.mock import FakeMontreal backend = FakeMontreal() #backend = provider.get_backend('ibmq_montreal') noise_model = NoiseModel.from_backend(backend) # Get coupling map from backend coupling_map = backend.configuration().coupling_map # Get basis gates from noise model basis_gates = noise_model.basis_gates counts = execute(state_preparation, Aer.get_backend('qasm_simulator'), #shots = 500000, coupling_map=coupling_map, basis_gates=basis_gates, noise_model=noise_model ).result().get_counts() from qiskit.visualization import plot_histogram plot_histogram(counts, title = "transform of normal") vals = [int(i, 2) for i,j in counts.items()] cnts = [j for i,j in counts.items()] plt.bar(vals, cnts) import qiskit.providers.aer.noise as noise from qiskit.utils import QuantumInstance print(time.strftime("%H:%M:%S", time.localtime())) error_scaling_factor = 2 ** 0 # Reference point: 1.0 (= no scaling) error_prob_1_gate = 0.001 * error_scaling_factor error_prob_2_gates = 0.001 * error_scaling_factor error_prob_measure = 0.001 * error_scaling_factor error_1 = noise.depolarizing_error(error_prob_1_gate, 1) error_2 = noise.depolarizing_error(error_prob_2_gates, 2) # Measurement errors error_m = noise.pauli_error([('X', error_prob_measure), ('I', 1 - error_prob_measure)]) noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3']) noise_model.add_all_qubit_quantum_error(error_2, ['cx']) noise_model.add_all_qubit_quantum_error(error_m, "measure") # now do AE problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_input)]) # target precision and confidence level epsilon = 0.01 alpha = 0.05 qi = QuantumInstance(Aer.get_backend('aer_simulator'), noise_model=noise_model) ae_cdf = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=qi) result_cdf = ae_cdf.estimate(problem) conf_int = np.array(result_cdf.confidence_interval) print('Estimated value:\t%.4f' % result_cdf.estimation) print('Confidence interval: \t[%.4f, %.4f]' % tuple(conf_int)) #state_preparation.draw() print(time.strftime("%H:%M:%S", time.localtime())) def get_sims(normal_distribution): import numpy as np values = normal_distribution._values probs = normal_distribution._probabilities # we generate a bunch of realisation of values, based upper_bounds = [0.0] stop = 0.0 for val, prob in zip(values, probs): stop += prob upper_bounds.append(stop) np.random.seed = 101 r = np.random.uniform(low=0.0, high=1.0, size=1000000) indices = np.searchsorted(upper_bounds, r, side='left', sorter=None) - 1 g1, g2 = np.meshgrid(range(2**nbits), range(2**nbits), indexing="ij",) i1 = g1.flatten()[indices] i2 = g2.flatten()[indices] #x = list(zip(*(grid.flatten() for grid in meshgrid))) return i1, i2 i1, i2 = get_sims(normal) j1 = i_to_js[0](i1) j2 = i_to_js[1](i2) j_tot = j1 + j2 import collections counts = {} for item in j_tot: if item in counts: counts[item] += 1 else: counts[item] = 1 counts = collections.OrderedDict(sorted(counts.items())) vals = [i for i,j in counts.items()] cnts = [j for i,j in counts.items()] plt.bar(vals, cnts) vals2 = p_min * 2 + np.array(vals) * 2 * (p_max - p_min) / (2**(nbits * 2) - 1) cnts = np.array([j for i,j in counts.items()]) cnts2 = cnts / np.sum(cnts) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') plt.bar(vals2, cnts2, width = 0.2) ax.set_xlabel('Normalised P&L') ax.set_ylabel('Probability') ax.legend() fig.savefig('pnl_classical.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) sum = 0 for v,c in zip(vals, cnts): if v <= 8: sum += c print(float(sum) / 1000000) print(p_min * 2 + 14 * 2 * (p_max - p_min) / (2**(nbits * 2) - 1) ) correl = ft.get_correl("AAPL", "MSFT") c = np.linalg.cholesky(correl) r = np.random.normal(0, 1, size = (2, 1000000)) v = c@r v1 = np.vectorize(pl_set[0])(v[0, :]) v2 = np.vectorize(pl_set[1])(v[1, :]) vt = v1 + v2 cm = 1 / 2.54 fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') _ = plt.hist(vt, bins = 200, density = True) ax.set_xlabel('Normalised P&L') ax.set_ylabel('Probability density') ax.set_xlim(-10, 10) fig.savefig('pnl_classical_continuous.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) np.percentile(vt, 1.0) import quantum_mc.calibration.time_series as ts (cdf_c_x, cdf_c_y) = ts.ecdf(vt) #(cdf_d_x, cdf_d_y) = ts.ecdf(vt) sum = 0 cum_sum = [] for v,c in zip(vals, cnts): sum += c cum_sum.append(sum) cum_sum = np.array(cum_sum) cum_sum = cum_sum / np.max(cum_sum) vals2 = p_min * 2 + np.array(vals) * 2 * (p_max - p_min) / (2**(nbits * 2) - 1) vals_2bits = np.array([-10.70188609, -7.39985348, -6.29917595, -5.19849841, -2.99714334, -1.8964658, -0.79578826, 1.40556681, 2.50624435, 4.70759942]) cum_prob_2bits = np.array([0.003903, 0.007387, 0.010792, 0.010795, 0.462747, 0.537787, 0.98928, 0.992701, 0.996142, 1.]) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') plt.plot(cdf_c_x, cdf_c_y, label = "Continuous", ) plt.plot(vals2, cum_sum, '--', label = "3 qubit") plt.plot(vals_2bits, cum_prob_2bits, ':', label = "2 qubit") ax.set_yscale("log") ax.set_xlabel('Normalised P&L') ax.set_ylabel('Cumulative probability') ax.set_xlim(-8, 5) #ax.set_ylim(0.001, 0.02) ax.set_ylim(0.001, 0.999) ax.legend() fig.savefig('cdf_class_quant_log.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') plt.plot(cdf_c_x, cdf_c_y, label = "Continuous") plt.plot(vals2, cum_sum, '--', label = "3 qubit") plt.plot(vals_2bits, cum_prob_2bits, ':', label = "2 qubit") #ax.set_yscale("log") ax.set_xlabel('Normalised P&L') ax.set_ylabel('Cumulative probability') ax.set_xlim(-8, 5) #ax.set_ylim(0.001, 0.02) ax.set_ylim(0.001, 0.999) ax.legend() fig.savefig('cdf_class_quant_lin.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) cont = np.interp([0.01, 0.025, 0.05], cdf_c_y, cdf_c_x) quant3 = np.interp([0.01, 0.025, 0.05], cum_sum, vals2) quant2 = np.interp([0.01, 0.025, 0.05], cum_prob_2bits, vals_2bits) np.set_printoptions(formatter={'float': lambda x: "{0:0.2f}".format(x)}) print('Continuous') print(cont) print('3 qubits') print(quant3) print(abs(quant3/cont - 1) * 100) print('2 qubits') print(quant2) print(abs(quant2/cont - 1) * 100) print("Check")
https://github.com/joemoorhouse/quantum-mc
joemoorhouse
from math import pi from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister from .qft import qft, iqft, cqft, ciqft, ccu1 from qiskit.circuit.library import SXdgGate # Modified version of qarithmetic https://github.com/hkhetawat/QArithmetic ################################################################################ # Bitwise Operators ################################################################################ # bit-wise operations def bitwise_and(qc, a, b, c, N): for i in range(0, N): qc.ccx(a[i], b[i], c[i]) def bitwise_or(qc, a, b, c, N): for i in range(0, N): qc.ccx(a[i], b[i], c[i]) qc.cx(a[i], c[i]) qc.cx(b[i], c[i]) def bitwise_xor(qc, a, b, c, N): for i in range(0, N): qc.cx(a[i], c[i]) qc.cx(b[i], c[i]) def bitwise_not(qc, a, c, N): for i in range(0, N): qc.cx(a[i], c[i]) qc.x(c[i]) # Cyclically left-shifts a binary string "a" of length n. # If "a" is zero-padded, equivalent to multiplying "a" by 2. def lshift(circ, a, n=-1): # Init n if it was not if n == -1: n = len(a) # Iterate through pairs and do swaps. for i in range(n,1,-1): circ.swap(a[i-1],a[i-2]) # Cyclically left-shifts a binary string "a" of length n, controlled by c. # If "a" is zero-padded, equivalent to multiplying "a" by 2, if and only if c. def c_lshift(circ, c, a, n=-1): # Init n if it was not if n == -1: n = len(a) # Iterate through pairs and do swaps. for i in range(n,1,-1): circ.cswap(c, a[i-1],a[i-2]) # Cyclically right-shifts a binary string "a" of length n. # If "a" is zero-padded, equivalent to dividing "a" by 2. def rshift(circ, a, n=-1): # Init n if it was not if n == -1: n = len(a) # Iterate through pairs and do swaps. for i in range(n-1): circ.swap(a[i],a[i+1]) # Cyclically right-shifts a binary string "a" of length n, controlled by c. # If "a" is zero-padded, equivalent to dividing "a" by 2, if and only if c. def c_rshift(circ, c, a, n=-1): # Init n if it was not if n == -1: n = len(a) # Iterate through pairs and do swaps. for i in range(n,1,-1): circ.cswap(c, a[i-1],a[i-2]) ################################################################################ # Addition Circuits ################################################################################ # Define some functions for the ripple adder. def sum(circ, cin, a, b): circ.cx(a,b) circ.cx(cin,b) def sum_cq(circ, cin, a, b): if a == 1: circ.x(b) circ.cx(cin,b) def carry(circ, cin, a, b, cout): circ.ccx(a, b, cout) circ.cx(a, b) circ.ccx(cin, b, cout) # in this version a is classical and b quatum def carry_cq(circ, cin, a, b, cout): if a == 1: circ.cx(b, cout) circ.x(b) circ.ccx(cin, b, cout) def carry_dg_cq(circ, cin, a, b, cout): circ.ccx(cin, b, cout) if a == 1: circ.x(b) circ.cx(b, cout) def carry_dg(circ, cin, a, b, cout): circ.ccx(cin, b, cout) circ.cx(a, b) circ.ccx(a, b, cout) # Draper adder that takes |a>|b> to |a>|a+b>. # |a> has length x and is less than or equal to n # |b> has length n+1 (left padded with a zero). # https://arxiv.org/pdf/quant-ph/0008033.pdf def add(circ, a, b, n): # move n forward by one to account for overflow n += 1 # Take the QFT. qft(circ, b, n) # Compute controlled-phases. # Iterate through the targets. for i in range(n,0,-1): # Iterate through the controls. for j in range(i,0,-1): # If the qubit a[j-1] exists run cu1, if not assume the qubit is 0 and never existed if len(a) - 1 >= j - 1: circ.cu1(2*pi/2**(i-j+1), a[j-1], b[i-1]) # Take the inverse QFT. iqft(circ, b, n) # Draper adder that takes |a>|b> to |a>|a+b>, controlled on |c>. # |a> has length x and is less than or equal to n # |b> has length n+1 (left padded with a zero). # |c> is a single qubit that's the control. def cadd(circ, c, a, b, n): # move n forward by one to account for overflow n += 1 # Take the QFT. cqft(circ, c, b, n) # Compute controlled-phases. # Iterate through the targets. for i in range(n,0,-1): # Iterate through the controls. for j in range(i,0,-1): # If the qubit a[j-1] exists run ccu, if not assume the qubit is 0 and never existed if len(a) - 1 >= j - 1: ccu1(circ, 2*pi/2**(i-j+1), c, a[j-1], b[i-1]) # Take the inverse QFT. ciqft(circ, c, b, n) # Adder that takes |a>|b> to |a>|a+b>. # |a> has length n. # |b> has length n+1. # Based on Vedral, Barenco, and Ekert (1996). def add_ripple(circ, a, b, n): # Create a carry register of length n. c = QuantumRegister(n) circ.add_register(c) # Calculate all the carries except the last one. for i in range(0, n-1): carry(circ, c[i], a[i], b[i], c[i+1]) # The last carry bit is the leftmost bit of the sum. carry(circ, c[n-1], a[n-1], b[n-1], b[n]) # Calculate the second-to-leftmost bit of the sum. circ.cx(c[n-1],b[n-1]) # Invert the carries and calculate the remaining sums. for i in range(n-2,-1,-1): carry_dg(circ, c[i], a[i], b[i], c[i+1]) sum(circ, c[i], a[i], b[i]) # Adder that takes |a>|b> to |a>|a+b>. # |a> has length n. # |b> has length n+1. # Based on Vedral, Barenco, and Ekert (1996). def add_ripple_in_place(circ, a, b, anc, n): # Calculate all the carries except the last one. for i in range(0, n-1): carry(circ, anc[i], a[i], b[i], anc[i+1]) # The last carry bit is the leftmost bit of the sum. carry(circ, anc[n-1], a[n-1], b[n-1], b[n]) # Calculate the second-to-leftmost bit of the sum. circ.cx(anc[n-1],b[n-1]) # Invert the carries and calculate the remaining sums. for i in range(n-2,-1,-1): carry_dg(circ, anc[i], a[i], b[i], anc[i+1]) sum(circ, anc[i], a[i], b[i]) # Adder that takes |a>|b> to |a>|a+b>. # |a> has length <= n. |a> will be padded with zeros to length n # |b> has length n+1. # Based on Vedral, Barenco, and Ekert (1996). def add_ripple_in_place_padding(circ, a, b, anc, n): # Calculate all the carries except the last one. for i in range(0, n - 1): if i < len(a): carry(circ, anc[i], a[i], b[i], anc[i+1]) else: # pad with zeros carry_cq(circ, anc[i], 0, b[i], anc[i+1]) # The last carry bit is the leftmost bit of the sum. if (n-1) < len(a): carry(circ, anc[n-1], a[n-1], b[n-1], b[n]) else: carry_cq(circ, anc[n-1], 0, b[n-1], b[n]) # Calculate the second-to-leftmost bit of the sum. circ.cx(anc[n-1],b[n-1]) # Invert the carries and calculate the remaining sums. for i in range(n-2,-1,-1): if i < len(a): carry_dg(circ, anc[i], a[i], b[i], anc[i+1]) sum(circ, anc[i], a[i], b[i]) else: carry_dg_cq(circ, anc[i], 0, b[i], anc[i+1]) sum_cq(circ, anc[i], 0, b[i]) # Adder that takes |a>|b> to |a>|a+b>. # |a> has length n *and is classical*. # |b> has length n+1. # Based on Vedral, Barenco, and Ekert (1996). def add_ripple_in_place_cq(circ, a, qr_b, qr_anc, n): # Calculate all the carries except the last one. for i in range(0, n-1): carry_cq(circ, qr_anc[i], a[i], qr_b[i], qr_anc[i+1]) # The last carry bit is the leftmost bit of the sum. carry_cq(circ, qr_anc[n-1], a[n-1], qr_b[n-1], qr_b[n]) # Calculate the second-to-leftmost bit of the sum. circ.cx(qr_anc[n-1],qr_b[n-1]) # Invert the carries and calculate the remaining sums. for i in range(n-2,-1,-1): carry_dg_cq(circ, qr_anc[i], a[i], qr_b[i], qr_anc[i+1]) sum_cq(circ, qr_anc[i], a[i], qr_b[i]) # Adder that takes |a>|b>|0> to |a>|b>|a+b>. # |a> has length n. # |b> has length n. # |s> = |0> has length n+1. def add_ripple_ex(circ, a, b, s, n): # Copy b to s. for i in range(0, n): circ.cx(b[i],s[i]) # Add a and s. add_ripple(circ, a, s, n) ################################################################################ # Subtraction Circuits ################################################################################ # Subtractor that takes |a>|b> to |a>|a-b>. # |a> has length n+1 (left padded with a zero). # |b> has length n+1 (left padded with a zero). def sub(circ, a, b, n): # Flip the bits of a. circ.x(a) # Add it to b. add(circ, a, b, n - 1) # Flip the bits of the result. This yields the sum. circ.x(b) # Flip back the bits of a. circ.x(a) # Subtractor that takes |a>|b> to |a-b>|b>. # |a> has length n+1 (left padded with a zero). # |b> has length n+1 (left padded with a zero). def sub_swap(circ, a, b, n): # Flip the bits of a. circ.x(a) # Add it to b. add(circ, b, a, n - 1) # Flip the bits of the result. This yields the sum. circ.x(a) # Subtractor that takes |a>|b> to |a>|a-b>. # |a> has length n. # |b> has length n+1. def sub_ripple(circ, a, b, n): # We add "a" to the 2's complement of "b." # First flip the bits of "b." circ.x(b) # Create a carry register of length n. c = QuantumRegister(n) circ.add_register(c) # Add 1 to the carry register, which adds 1 to b, negating it. circ.x(c[0]) # Calculate all the carries except the last one. for i in range(0, n-1): carry(circ, c[i], a[i], b[i], c[i+1]) # The last carry bit is the leftmost bit of the sum. carry(circ, c[n-1], a[n-1], b[n-1], b[n]) # Calculate the second-to-leftmost bit of the sum. circ.cx(c[n-1],b[n-1]) # Invert the carries and calculate the remaining sums. for i in range(n-2,-1,-1): carry_dg(circ, c[i], a[i], b[i], c[i+1]) sum(circ, c[i], a[i], b[i]) # Flip the carry to restore it to zero. circ.x(c[0]) # Subtractor that takes |a>|b>|0> to |a>|b>|a-b>. # |a> has length n. # |b> has length n. # |s> = |0> has length n+1. def sub_ripple_ex(circ, a, b, s, n): # Copy b to s. for i in range(0, n): circ.cx(b[i],s[i]) # Subtract a and s. sub_ripple(circ, a, s, n) ################################################################################ # Multiplication Circuit ################################################################################ # Controlled operations # Take a subset of a quantum register from index x to y, inclusive. def sub_qr(qr, x, y): # may also be able to use qbit_argument_conversion sub = [] for i in range (x, y+1): sub = sub + [(qr[i])] return sub def full_qr(qr): return sub_qr(qr, 0, len(qr) - 1) # Computes the product c=a*b. # a has length n. # b has length n. # c has length 2n. def mult(circ, a, b, c, n): for i in range (0, n): cadd(circ, a[i], b, sub_qr(c, i, n+i), n) # Computes the product c=a*b if and only if control. # a has length n. # b has length n. # control has length 1. # c has length 2n. def cmult(circ, control, a, b, c, n): qa = QuantumRegister(len(a)) qb = QuantumRegister(len(b)) qc = QuantumRegister(len(c)) tempCircuit = QuantumCircuit(qa, qb, qc) mult(tempCircuit, qa, qb, qc, n) tempCircuit = tempCircuit.control(1) #Add Decomposition after pull request inclusion #5446 on terra print("Remember To Decompose after release >0.16.1") circ.compose(tempCircuit, qubits=full_qr(control) + full_qr(a) + full_qr(b) + full_qr(c), inplace=True) ################################################################################ # Division Circuit ################################################################################ # Divider that takes |p>|d>|q>. # |p> is length 2n and has n zeros on the left: 0 ... 0 p_n ... p_1. # |d> has length 2n and has n zeros on the right: d_2n ... d_{n+1) 0 ... 0. # |q> has length n and is initially all zeros. # At the end of the algorithm, |q> will contain the quotient of p/d, and the # left n qubits of |p> will contain the remainder of p/d. def div(circ, p, d, q, n): # Calculate each bit of the quotient and remainder. for i in range(n,0,-1): # Left shift |p>, which multiplies it by 2. lshift(circ, p, 2*n) # Subtract |d> from |p>. sub_swap(circ, p, d, 2*n) # If |p> is positive, indicated by its most significant bit being 0, # the (i-1)th bit of the quotient is 1. circ.x(p[2*n-1]) circ.cx(p[2*n-1], q[i-1]) circ.x(p[2*n-1]) # If |p> is negative, indicated by the (i-1)th bit of |q> being 0, add D back # to P. circ.x(q[i-1]) cadd(circ, q[i-1], d, p, 2*n - 1) circ.x(q[i-1]) ################################################################################ # Expontential Circuit ################################################################################ # square that takes |a> |b> # |a> is length n and is a unsigned integer # |b> is length 2n and has 2n zeros, after execution b = a^2 def square(circ, a, b, n=-1): if n == -1: n = len(a) # First Addition circ.cx(a[0], b[0]) for i in range(1, n): circ.ccx(a[0], a[i], b[i]) # Custom Addition Circuit For Each Qubit of A for k in range(1, n): # modifying qubits d = b[k:n+k+1] qft(circ, d, n+1) #Technically the first few QFT could be refactored to use less gates due to guaranteed controls # Compute controlled-phases. # Iterate through the targets. for i in range(n+1,0,-1): # Iterate through the controls. for j in range(i,0,-1): if len(a) - 1 < j - 1: pass # skip over non existent qubits elif k == j - 1: # Cannot control twice circ.cu1(2*pi/2**(i-j+1), a[j-1], d[i-1]) else: ccu1(circ, 2*pi/2**(i-j+1), a[k], a[j-1], d[i-1]) iqft(circ, d, n+1) # a has length n # b has length v # finalOut has length n*((2^v)-1), for safety def power(circ, a, b, finalOut): #Because this is reversible/gate friendly memory blooms to say the least # Track Number of Qubits n = len(a) v = len(b) # Left 0 pad a, to satisfy multiplication function arguments aPad = AncillaRegister(n * (pow(2, v) - 3)) # Unsure of where to Anciallas these circ.add_register(aPad) padAList = full_qr(aPad) aList = full_qr(a) a = aList + padAList # Create a register d for mults and init with state 1 d = AncillaRegister(n) # Unsure of where to Anciallas these circ.add_register(d) # Create a register for tracking the output of cmult to the end ancOut = AncillaRegister(n*2) # Unsure of where to Anciallas these circ.add_register(ancOut) # Left 0 pad finalOut to provide safety to the final multiplication if (len(a) * 2) - len(finalOut) > 0: foPad = AncillaRegister((len(a) * 2) - len(finalOut)) circ.add_register(foPad) padFoList = full_qr(foPad) foList = full_qr(finalOut) finalOut = foList + padFoList # Create zero bits num_recycle = (2 * n * (pow(2, v) - 2)) - (n * pow(2, v)) # 24 permaZeros = [] if num_recycle > 0: permaZeros = AncillaRegister(num_recycle) #8 circ.add_register(permaZeros) permaZeros = full_qr(permaZeros) # Instead of MULT copy bits over if v >= 1: for i in range(n): circ.ccx(b[0], a[i], d[i]) circ.x(b[0]) circ.cx(b[0], d[0]) circ.x(b[0]) # iterate through every qubit of b for i in range(1,v): # for every bit of b for j in range(pow(2, i)): # run multiplication operation if and only if b is 1 bonus = permaZeros[:2*len(d) - len(ancOut)] cmult(circ, [b[i]], a[:len(d)], d, full_qr(ancOut) + bonus, len(d)) # if the multiplication was not run copy the qubits so they are not destroyed when creating new register circ.x(b[i]) for qub in range(0,len(d)): circ.ccx(b[i], d[qub], ancOut[qub]) circ.x(b[i]) # Move the output to the input for next function and double the qubit length d = ancOut if i == v - 1 and j == pow(2, i) - 2: # this is the second to last step send qubiits to output ancOut = finalOut elif not (i == v - 1 and j == pow(2, i) - 1): # if this is not the very last step # create a new output register of twice the length and register it ancOut = AncillaRegister(len(d) + n) # Should label permazero bits circ.add_register(ancOut)
https://github.com/joemoorhouse/quantum-mc
joemoorhouse
from math import pi from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister from .qft import qft, iqft, cqft, ciqft, ccu1 from .arithmetic import cadd, full_qr, add_ripple_in_place, add_ripple_in_place_padding, add_ripple_in_place_cq def classical_add_mult(circ, a, b, qr_in, qr_res, qr_anc): """qr_res = qr_res + a * qr_in + b where a and b are integers""" classical_mult(circ, a, qr_in, qr_res, qr_anc) classical_add(circ, b, qr_res, qr_anc) def classical_mult(circ, a, qr_in, qr_res, qr_anc): """qr_res = a * qr_in where a is an integer and qr_in is a quantum register res must have at least na + nin qubits where na is the number of bits required to represent a and nin the number of qubits in qr_in """ l_a = _to_bool_list(a) na = len(l_a) nin = len(qr_in) nres = len(qr_res) for i in range (0, na): if l_a[i] == 1: add_ripple_in_place_padding(circ, qr_in, _sub_qr(qr_res, i, nres - 1), qr_anc, nres - 1 - i) #add_ripple_in_place(circ, qr_in, _sub_qr(qr_res, i, nin + i), qr_anc, nin) def cond_classical_add_mult(a, b, qr_in, qr_res, qr_anc): """qr_res = qr_res + a* qr_in + b if control is set where a and b are integers""" temp_qr_in = QuantumRegister(len(qr_in)) temp_qr_res = QuantumRegister(len(qr_res)) temp_qr_anc = AncillaRegister(len(qr_anc)) temp_circuit = QuantumCircuit(temp_qr_in, temp_qr_res, temp_qr_anc, name = "inplace_mult_add") classical_add_mult(temp_circuit, a, b, temp_qr_in, temp_qr_res, temp_qr_anc) temp_circuit = temp_circuit.control(1) return temp_circuit def classical_add(circ, a, qr_b, qr_anc): """qr_b = a + qr_b where a is an integer and qr_b is a quantum register """ nb = len(qr_b) if a >= 0: l_a = _to_bool_list(a) if len(l_a) > nb - 1: raise Exception("number of classical integer bits cannot exceed number of register qubits - 1") else: l_a = _to_bool_list(twos_comp(a, nb)) l_a = l_a + [0 for i in range(nb - len(l_a))] # pad with zeros add_ripple_in_place_cq(circ, l_a, qr_b, qr_anc, nb - 1) if a < 0: circ.x(qr_b[nb - 1]) def _to_bool_list(a): s = a res = [] while (s > 0): res.append(s & 1) s = s >> 1 return res def _sub_qr(qr, x, y): """ Take a subset of a quantum register from index x to y, inclusive. """ sub = [] for i in range (x, y + 1): sub = sub + [(qr[i])] return sub def scalar_mult_plot(control, a, b, c, anc, na, nb): qa = QuantumRegister(len(a), name = "input") qc = QuantumRegister(len(c), name = "output") qanc = AncillaRegister(len(anc), name = "ancilla") tempCircuit = QuantumCircuit(qa, qc, qanc) #scalar_mult(tempCircuit, qa, b, qc, qanc, na, nb) return tempCircuit def twos_comp(val, bits): if (val < 0): return (1 << bits) - abs(val) else: return val
https://github.com/joemoorhouse/quantum-mc
joemoorhouse
from qiskit import QuantumRegister, QuantumCircuit, Aer, execute from qiskit.circuit.library import LinearAmplitudeFunction from qiskit.aqua.algorithms import IterativeAmplitudeEstimation import numpy as np # define linear objective function num_sum_qubits = 5 breakpoints = [0] slopes = [1] offsets = [0] f_min = 0 f_max = 10 c_approx = 0.25 objective = LinearAmplitudeFunction( num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**num_sum_qubits-1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints ) qr_sum = QuantumRegister(5, "sum") state_preparation = QuantumCircuit(qr_sum) # to complete # set target precision and confidence level epsilon = 0.01 alpha = 0.05 # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation(state_preparation=state_preparation, epsilon=epsilon, alpha=alpha, objective_qubits=[len(qr_sum)]) result_cdf = ae_cdf.run(quantum_instance=Aer.get_backend('qasm_simulator'), shots=100) # print results exact_value = 1 # to calculate conf_int = np.array(result_cdf['confidence_interval']) print('Exact value: \t%.4f' % exact_value) print('Estimated value:\t%.4f' % result_cdf['estimation']) print('Confidence interval: \t[%.4f, %.4f]' % tuple(conf_int)) def transform_from_
https://github.com/joemoorhouse/quantum-mc
joemoorhouse
from quantum_mc.arithmetic.piecewise_linear_transform import PiecewiseLinearTransform3 import unittest import numpy as np from qiskit.circuit.library.arithmetic import weighted_adder from scipy.stats import multivariate_normal, norm from qiskit.test.base import QiskitTestCase from qiskit import execute, Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, AncillaRegister from qiskit.circuit.library import UniformDistribution, NormalDistribution, LogNormalDistribution from qiskit.quantum_info import Statevector import quantum_mc.arithmetic.multiply_add as multiply_add from qiskit.circuit.library import NormalDistribution, LogNormalDistribution, LinearAmplitudeFunction, IntegerComparator, WeightedAdder class TestArithmetic(QiskitTestCase): def test_replicate_bug(self): import numpy as np import matplotlib.pyplot as plt from qiskit import execute, Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, AncillaRegister from qiskit.aqua.algorithms import IterativeAmplitudeEstimation from qiskit.circuit.library import NormalDistribution, LogNormalDistribution, LinearAmplitudeFunction, IntegerComparator, WeightedAdder from qiskit.visualization import plot_histogram from quantum_mc.arithmetic import piecewise_linear_transform trans = PiecewiseLinearTransform3(3, 5, 5, 3, 4, 1, 7, 2) num_ancillas = trans.num_ancilla_qubits qr_input = QuantumRegister(3, 'input') qr_result = QuantumRegister(7, 'result') qr_ancilla = QuantumRegister(num_ancillas, 'ancilla') output = ClassicalRegister(7, 'output') circ = QuantumCircuit(qr_input, qr_result, qr_ancilla, output) #circ.append(normal, qr_input) # put 3 into input circ.x(qr_input[0]) circ.x(qr_input[1]) # put value 30 in result circ.x(qr_result[1]) circ.x(qr_result[2]) circ.x(qr_result[3]) circ.x(qr_result[4]) #circ.append(trans, qr_input[:] + qr_result[:] + qr_ancilla[:]) #multiply_add.classical_add_mult(circ, 3, 7, qr_input, qr_result, qr_ancilla) multiply_add.classical_mult(circ, 3, qr_input, qr_result, qr_ancilla) circ.measure(qr_result, output) counts = execute(circ, Aer.get_backend('qasm_simulator'), shots = 128).result().get_counts() np.testing.assert_equal(counts['01011'], 128) def test_adder(self): """Simple end-to-end test of the (semi-classical) multiply and add building block.""" qr_input = QuantumRegister(3, 'input') qr_result = QuantumRegister(5, 'result') qr_ancilla = QuantumRegister(5, 'ancilla') output = ClassicalRegister(5, 'output') circ = QuantumCircuit(qr_input, qr_result, qr_ancilla, output) circ.x(qr_input[0]) circ.x(qr_input[1]) circ.x(qr_input[2]) # i.e. load up 7 into register add_mult = multiply_add.classical_add_mult(circ, 2, 3, qr_input, qr_result, qr_ancilla) #circ.append(cond_add_mult, qr_input[:] + qr_result[:] + qr_ancilla[:]) for the conditional form circ.measure(qr_result, output) # 7 * 2 + 3 = 17: expect 10001 counts = execute(circ, Aer.get_backend('qasm_simulator'), shots = 128).result().get_counts() np.testing.assert_equal(counts['10001'], 128) def test_adder_subtract(self): """Simple end-to-end test of the (semi-classical) multiply and add building block.""" qr_input = QuantumRegister(3, 'input') qr_result = QuantumRegister(5, 'result') qr_ancilla = QuantumRegister(5, 'ancilla') output = ClassicalRegister(5, 'output') circ = QuantumCircuit(qr_input, qr_result, qr_ancilla, output) circ.x(qr_input[0]) circ.x(qr_input[1]) circ.x(qr_input[2]) # i.e. load up 7 into register add_mult = multiply_add.classical_add_mult(circ, 2, -3, qr_input, qr_result, qr_ancilla) #circ.append(cond_add_mult, qr_input[:] + qr_result[:] + qr_ancilla[:]) for the conditional form circ.measure(qr_result, output) # 7 * 2 - 3 = 11: expect 01011 counts = execute(circ, Aer.get_backend('qasm_simulator'), shots = 128).result().get_counts() np.testing.assert_equal(counts['01011'], 128) def test_piecewise_transform(self): import numpy as np import matplotlib.pyplot as plt from qiskit import execute, Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, AncillaRegister from qiskit.aqua.algorithms import IterativeAmplitudeEstimation from qiskit.circuit.library import NormalDistribution, LogNormalDistribution, LinearAmplitudeFunction, IntegerComparator, WeightedAdder from qiskit.visualization import plot_histogram from quantum_mc.arithmetic import piecewise_linear_transform sigma = 1 low = -3 high = 3 mu = 0 #normal = NormalDistribution(3, mu=mu, sigma=sigma**2, bounds=(low, high)) # our test piece-wise transforms: # trans0 if x <= 2, x => 6*x + 7 # trans1 if 2 < x <= 5, x => x + 17 # trans2 if x > 5, x => 3*x + 7 trans = PiecewiseLinearTransform3(2, 5, 6, 1, 3, 7, 17, 7) num_ancillas = trans.num_ancilla_qubits qr_input = QuantumRegister(3, 'input') qr_result = QuantumRegister(6, 'result') qr_ancilla = QuantumRegister(num_ancillas, 'ancilla') output = ClassicalRegister(6, 'output') circ = QuantumCircuit(qr_input, qr_result, qr_ancilla, output) #circ.append(normal, qr_input) circ.append(trans, qr_input + qr_result + qr_ancilla) circ.measure(qr_result, output) counts = execute(circ, Aer.get_backend('qasm_simulator'), shots = 128).result().get_counts() np.testing.assert_equal(counts['01011'], 128) def in_progress_test_piecewise_transform(self): """Simple end-to-end test of the (semi-classical) multiply and add building block.""" import numpy as np import matplotlib.pyplot as plt from qiskit import execute, Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, AncillaRegister from qiskit.aqua.algorithms import IterativeAmplitudeEstimation from qiskit.circuit.library import NormalDistribution, LogNormalDistribution, LinearAmplitudeFunction, IntegerComparator, WeightedAdder from qiskit.visualization import plot_histogram from quantum_mc.arithmetic import multiply_add qr_input = QuantumRegister(3, 'input') qr_result = QuantumRegister(6, 'result') qr_comp = QuantumRegister(2, 'comparisons') qr_ancilla = QuantumRegister(6, 'ancilla') qr_comp_anc = QuantumRegister(3, 'cond_ancilla') output = ClassicalRegister(6, 'output') circ = QuantumCircuit(qr_input, qr_result, qr_comp, qr_ancilla, qr_comp_anc, output) # our test piece-wise transforms: # trans0 if x <= 2, x => 6*x + 7 # trans1 if 2 < x <= 5, x => x + 17 # trans2 if x > 5, x => 3*x + 7 sigma = 1 low = -3 high = 3 mu = 0 normal = NormalDistribution(3, mu=mu, sigma=sigma**2, bounds=(low, high)) circ.append(normal, qr_input) comp0 = IntegerComparator(num_state_qubits=3, value=3, name = "comparator0") # true if i >= point comp1 = IntegerComparator(num_state_qubits=3, value=6, name = "comparator1") # true if i >= point trans0 = multiply_add.cond_classical_add_mult(6, 7, qr_input, qr_result, qr_ancilla) trans1 = multiply_add.cond_classical_add_mult(1, 17, qr_input, qr_result, qr_ancilla) trans2 = multiply_add.cond_classical_add_mult(3, 7, qr_input, qr_result, qr_ancilla) circ.append(comp0, qr_input[:] + [qr_comp[0]] + qr_ancilla[0:comp0.num_ancillas]) circ.append(comp1, qr_input[:] + [qr_comp[1]] + qr_ancilla[0:comp0.num_ancillas]) # use three additional ancillas to define the ranges circ.cx(qr_comp[0], qr_comp_anc[0]) circ.x(qr_comp_anc[0]) circ.cx(qr_comp[1], qr_comp_anc[2]) circ.x(qr_comp_anc[2]) circ.ccx(qr_comp[0], qr_comp_anc[2], qr_comp_anc[1]) circ.append(trans0, [qr_comp_anc[0]] + qr_input[:] + qr_result[:] + qr_ancilla[:]) circ.append(trans1, [qr_comp_anc[1]] + qr_input[:] + qr_result[:] + qr_ancilla[:]) circ.append(trans2, [qr_comp[1]] + qr_input[:] + qr_result[:] + qr_ancilla[:]) # can uncompute qr_comp_anc # then uncompute the comparators circ.measure(qr_result, output)
https://github.com/joemoorhouse/quantum-mc
joemoorhouse
from quantum_mc.arithmetic.piecewise_linear_transform import PiecewiseLinearTransform3 import unittest import numpy as np from qiskit.test.base import QiskitTestCase import quantum_mc.calibration.fitting as ft import quantum_mc.calibration.time_series as ts from scipy.stats import multivariate_normal, norm from qiskit.test.base import QiskitTestCase from qiskit import execute, Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, AncillaRegister from qiskit.circuit.library import NormalDistribution from qiskit.quantum_info import Statevector from qiskit.circuit.library import NormalDistribution, LogNormalDistribution, IntegerComparator from qiskit.utils import QuantumInstance from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem def get_sims(normal_distribution): import numpy as np values = normal_distribution._values probs = normal_distribution._probabilities # we generate a bunch of realisation of values, based upper_bounds = [0.0] stop = 0.0 for val, prob in zip(values, probs): stop += prob upper_bounds.append(stop) r = np.random.uniform(low=0.0, high=1.0, size=10) indices = np.searchsorted(upper_bounds, r, side='left', sorter=None) - 1 g1, g2 = np.meshgrid(range(2**3), range(2**3), indexing="ij",) i1 = g1.flatten()[indices] i2 = g2.flatten()[indices] #x = list(zip(*(grid.flatten() for grid in meshgrid))) return i1, i2 class TestMcVar(QiskitTestCase): def test_no_discretisation(self): correl = ft.get_correl("AAPL", "MSFT") coeff_set = [] pl_set = [] for ticker in ["MSFT", "AAPL"]: ((cdf_x, cdf_y), sigma) = ft.get_cdf_data(ticker) (x, y) = ft.get_fit_data(ticker, norm_to_rel = False) (pl, coeffs) = ft.fit_piecewise_linear(x, y) # scale, to apply an arbitrary delta (we happen to use the same value here, but could be different) coeffs = ft.scaled_coeffs(coeffs, 1.0 if ticker == "MSFT" else 1.0) coeff_set.append(coeffs) pl_set.append(lambda z : ft.piecewise_linear(z, *coeff_set[0])) pl_set.append(lambda z : ft.piecewise_linear(z, *coeff_set[1])) c = np.linalg.cholesky(correl) r = np.random.normal(0, 1, size = (2, 10)) v = c@r v1 = np.vectorize(pl_set[0])(v[0, :]) v2 = np.vectorize(pl_set[1])(v[1, :]) v = v1 + v2 def test_distribution_load(self): """ Test that calculates a cumulative probability from the P&L distribution.""" correl = ft.get_correl("AAPL", "MSFT") bounds_std = 3.0 num_qubits = [3, 3] sigma = correl bounds = [(-bounds_std, bounds_std), (-bounds_std, bounds_std)] mu = [0, 0] # starting point is a multi-variate normal distribution normal = NormalDistribution(num_qubits, mu=mu, sigma=sigma, bounds=bounds) pl_set = [] coeff_set = [] for ticker in ["MSFT", "AAPL"]: ((cdf_x, cdf_y), sigma) = ft.get_cdf_data(ticker) (x, y) = ft.get_fit_data(ticker, norm_to_rel = False) (pl, coeffs) = ft.fit_piecewise_linear(x, y) # scale, to apply an arbitrary delta (we happen to use the same value here, but could be different) coeffs = ft.scaled_coeffs(coeffs, 1.2) pl_set.append(lambda z : ft.piecewise_linear(z, *coeffs)) coeff_set.append(coeffs) # calculate the max and min P&Ls p_max = max(pl_set[0](bounds_std), pl_set[1](bounds_std)) p_min = min(pl_set[0](-bounds_std), pl_set[1](-bounds_std)) # we discretise the transforms and create the circuits transforms = [] i_to_js = [] for i,ticker in enumerate(["MSFT", "AAPL"]): (i_0, i_1, a0, a1, a2, b0, b1, b2, i_to_j, i_to_x, j_to_y) = ft.integer_piecewise_linear_coeffs(coeff_set[i], x_min = -bounds_std, x_max = bounds_std, y_min = p_min, y_max = p_max) transforms.append(PiecewiseLinearTransform3(i_0, i_1, a0, a1, a2, b0, b1, b2)) i_to_js.append(np.vectorize(i_to_j)) i1, i2 = get_sims(normal) j1 = i_to_js[0](i1) j2 = i_to_js[1](i2) j_tot = j1 + j2 num_ancillas = transforms[0].num_ancilla_qubits qr_input = QuantumRegister(6, 'input') # 2 times 3 registers qr_objective = QuantumRegister(1, 'objective') qr_result = QuantumRegister(6, 'result') qr_ancilla = QuantumRegister(num_ancillas, 'ancilla') #output = ClassicalRegister(6, 'output') state_preparation = QuantumCircuit(qr_input, qr_objective, qr_result, qr_ancilla) #, output) state_preparation.append(normal, qr_input) for i in range(2): offset = i * 3 state_preparation.append(transforms[i], qr_input[offset:offset + 3] + qr_result[:] + qr_ancilla[:]) # to calculate the cdf, we use an additional comparator x_eval = 4 comparator = IntegerComparator(len(qr_result), x_eval + 1, geq=False) state_preparation.append(comparator, qr_result[:] + qr_objective[:] + qr_ancilla[0:comparator.num_ancillas]) # now check check = False if check: job = execute(state_preparation, backend=Aer.get_backend('statevector_simulator')) var_prob = 0 for i, a in enumerate(job.result().get_statevector()): b = ('{0:0%sb}' % (len(qr_input) + 1)).format(i)[-(len(qr_input) + 1):] prob = np.abs(a)**2 if prob > 1e-6 and b[0] == '1': var_prob += prob print('Operator CDF(%s)' % x_eval + ' = %.4f' % var_prob) # now do AE problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_input)]) # target precision and confidence level epsilon = 0.01 alpha = 0.05 qi = QuantumInstance(Aer.get_backend('aer_simulator'), shots=100) ae_cdf = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=qi) result_cdf = ae_cdf.estimate(problem) conf_int = np.array(result_cdf.confidence_interval) print('Estimated value:\t%.4f' % result_cdf.estimation) print('Confidence interval: \t[%.4f, %.4f]' % tuple(conf_int)) state_preparation.draw()
https://github.com/mrvee-qC-bee/UNHAN_Quantum_Workshop_2023
mrvee-qC-bee
#make sure your qiskit version is up to date import qiskit.tools.jupyter %qiskit_version_table from qiskit import QuantumCircuit # Create a Quantum Circuit acting on a quantum register of two qubits circ = QuantumCircuit(2) print(circ) # Add a H gate on qubit 0, putting this qubit in superposition. circ.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. circ.cx(0, 1) circ.draw('mpl', style="iqp") #One can also draw this as an ascii drawing circ.draw() from qiskit.primitives import Sampler #Instantiate a new Sampler object sampler = Sampler() #We'll also need to add measurement circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) # Insert measurements on all qubits circ.measure_all() circ.draw('mpl', style='iqp') # Now run the job and examine the results sampler_job = sampler.run(circ) result = sampler_job.result() print(f"Job Result:\n>>> {result}") print(f" > Quasi-probability distribution (integer): {result.quasi_dists[0]}") print(f" > Quasi-probability distribution (bits): {result.quasi_dists[0].binary_probabilities(2)}") print(f" > Metadata: {result.metadata[0]}") from qiskit.tools.visualization import plot_distribution prob_distribution = sampler_job.result().quasi_dists[0].binary_probabilities() plot_distribution(prob_distribution) from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session #Initialize a QiskitRuntimeService object service = QiskitRuntimeService() #We will use the 127-qubit ibm_nazca or 133-qubit ibm_torino backend backend = service.get_backend('ibm_cusco') session = Session(service=service, backend=backend) # sampler = Sampler(backend=backend) sampler = Sampler(session=session) job = sampler.run(circ) print(f">>> Job ID: {job.job_id()}") print(f">>> Session ID: {job.session_id}") print(f">>> Job Status: {job.status()}") # Use a job id from a previous result job = service.job("cnxwrpjmbjng0081zhc0") print(f">>> Job Status: {job.status()}") result = job.result() print(f"Job Result:\n>>> {result}") print(f" > Quasi-probability distribution (integer): {result.quasi_dists[0]}") print(f" > Quasi-probability distribution (bits): {result.quasi_dists[0].binary_probabilities(2)}") print(f" > Metadata: {result.metadata[0]}") from qiskit.visualization import plot_distribution import matplotlib.pyplot as plt plt.style.use('dark_background') #plot_distribution(result.quasi_dists[0]) plot_distribution([result.quasi_dists[0].binary_probabilities(2),prob_distribution]) from qiskit import QuantumRegister, ClassicalRegister #Create the circuit qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) # we can also write "qc = QuantumCircuit(2,2)" #Add the hadamard and CNOT gates to the circuit qc.h(0) qc.cx(0, 1) qc.draw('mpl', style="iqp") # Import the SparesPauliOp class and create our observables variable from qiskit.quantum_info import SparsePauliOp observable = SparsePauliOp(["II", "XX", "YY", "ZZ"], coeffs=[1, 1, -1, 1]) # Import qiskit primitives from qiskit.primitives import Estimator estimator = Estimator() job = estimator.run(qc, observable) result_exact = job.result() print(result_exact) print(f"Expectation Value of <II+XX-YY+ZZ> = {result_exact.values[0]:.3f}") from qiskit_ibm_runtime import Estimator, Session #Initialize a QiskitRuntimeService object service = QiskitRuntimeService() #We will use the 127-qubit ibm_nazca backend backend = service.get_backend('ibm_torino') # create a Runtime session for efficient execution (optional) session = Session(service=service, backend=backend) # estimator = Estimator(backend=backend) estimator = Estimator(session=session) #Here we can get some status information about the backend status = backend.status() is_operational = status.operational jobs_in_queue = status.pending_jobs print('Operational?: {} \n Jobs in Queue: {}\n'.format(is_operational, jobs_in_queue)) # We can also obtain some configuration information config = backend.configuration() print(64*"#","\nConfiguration for: {}, version: {}".format(config.backend_name, config.backend_version)) print(" Number of Qubits: {}".format(config.n_qubits)) print(" Basis Gates: {}".format(config.basis_gates)) print(" OpenPulse Enabled: {}".format(config.open_pulse)) job = estimator.run(qc, observable) print(f">>> Job ID: {job.job_id()}") print(f">>> Session ID: {job.session_id}") print(f">>> Job Status: {job.status()}") # Use a job id from a previous result job = service.job("cnxwwhtmbjng0081zhxg") print(f">>> Job Status: {job.status()}") #Examine our results once the job has completed result = job.result() print(f">>> {result}") print(f" > Expectation value: {result.values[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt plt.style.use('dark_background') data = {"Ideal": result_exact.values[0],"Result": result.values[0]} plt.bar(range(len(data)), data.values(), align='center', color = "#7793f2") plt.xticks(range(len(data)), list(data.keys())) plt.show() from qiskit_ibm_runtime import Options # To set our resilience and optimization level we need to create this `Options` object options = Options() options.resilience_level = 2 options.optimization_level = 3 # We'll prepare the same example circuit as before qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) # we can also write "qc = QuantumCircuit(2,2)" #Add the hadamard and CNOT gates to the circuit qc.h(0) qc.cx(0, 1) # We'll also instantiate a new Runtime Estimator() object # estimator = Estimator(options=options, backend=backend) estimator = Estimator(options=options, session=session) # and use the same observable as before observable = SparsePauliOp(["II", "XX", "YY", "ZZ"], coeffs=[1, 1, -1, 1]) job = estimator.run(circuits=qc, observables=observable) print(f">>> Job ID: {job.job_id()}") print(f">>> Session ID: {job.session_id}") print(f">>> Job Status: {job.status()}") # Use a job id from a previous result job = service.job("cnxwx04ja3gg0085f6cg") print(f">>> Job Status: {job.status()}") #Examine our results once the job has completed result_mitigated = job.result() print(f">>> {result_mitigated}") print(f" > Expectation value: {result_mitigated.values[0]}") print(f" > Metadata: {result_mitigated.metadata[0]}") from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt plt.style.use('dark_background') data = {"Ideal": result_exact.values[0],"Result": result.values[0],"Mitigated result": result_mitigated.values[0]} plt.bar(range(len(data)), data.values(), align='center', color = "#7793f2") plt.xticks(range(len(data)), list(data.keys())) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/donaldkaito/quantum-100knocks
donaldkaito
import numpy as np from qiskit import QuantumCircuit, Aer from qiskit.visualization import plot_bloch_multivector from qiskit.quantum_info import Statevector sim = Aer.get_backend("aer_simulator") # 13の2進数表記 binary_13 = f"{13:05b}" print(binary_13) new_binary = binary_13[:2] + ("0" if binary_13[2] == "1" else "1") + binary_13[3:] print(new_binary) def flip_3rd_digid(integer): binary = f"{integer:05b}" new_binary = binary[:2] + ("0" if binary[2] == "1" else "1") + binary[3:] return new_binary qc = QuantumCircuit(4, 2) # A QuantumCircuit with 4 qubits and 2 classical bits`` # Xゲートを配置せよ # <write your code> qc.barrier() # CNOTゲートを配置せよ # <write your code> qc.ccx(0, 1, 3) qc.barrier() qc.measure([2, 3], [0, 1]) qc.draw(output="mpl") qc = QuantumCircuit(4, 2) # A QuantumCircuit with 4 qubits and 2 classical bits`` # Xゲートを配置せよ qc.x([0, 1]) qc.barrier() # CNOTゲートを配置せよ qc.cx(0, 2) qc.cx(1, 2) qc.ccx(0, 1, 3) qc.barrier() qc.measure([2, 3], [0, 1]) qc.draw(output="mpl") qc = QuantumCircuit(1) # A QuantumCircuit with 1 qubits # 適切なゲートを配置せよ # <write your code > state = Statevector.from_instruction(qc) plot_bloch_multivector(state) qc = QuantumCircuit(1) # A QuantumCircuit with 1 qubits # 適切なゲートを配置せよ qc.h(0) state = Statevector.from_instruction(qc) plot_bloch_multivector(state) for state_label in ["+", "-"]: qc = QuantumCircuit(1,1) if state_label == "+": qc.initialize([1 / np.sqrt(2), 1 / np.sqrt(2)], 0) elif state_label == "-": qc.initialize([1 / np.sqrt(2), -1 / np.sqrt(2)], 0) qc.barrier() # 適切な測定基底をゲートを配置することで完成させよ # <write your code> qc.measure(0,0) counts = sim.run(qc).result().get_counts() print(f"|{state_label}> : ", "counts=",counts) qc.draw(output="mpl") for state_label in ["+", "-"]: qc = QuantumCircuit(1,1) if state_label == "+": qc.initialize([1 / np.sqrt(2), 1 / np.sqrt(2)], 0) elif state_label == "-": qc.initialize([1 / np.sqrt(2), -1 / np.sqrt(2)], 0) qc.barrier() # 適切な測定基底をゲートを配置することで完成させよ qc.h(0) qc.measure(0,0) counts = sim.run(qc).result().get_counts() print(f"|{state_label}> : ", "counts=",counts) qc.draw(output="mpl") for state_label in ["0", "1", "+", "-"]: for gate_label in ["X", "Z", "H", "ZH"]: qc = QuantumCircuit(1, 1) # 初期状態の設定 if state_label == "1": qc.initialize([0, 1], 0) elif state_label == "+": qc.initialize([1 / np.sqrt(2), 1 / np.sqrt(2)], 0) elif state_label == "-": qc.initialize([1 / np.sqrt(2), -1 / np.sqrt(2)], 0) # ゲートの配置 if gate_label =="X": qc.x(0) elif gate_label =="Z": qc.z(0) elif gate_label =="H": qc.h(0) elif gate_label =="ZH": qc.h(0) qc.z(0) # Statevectorは測定前に取得する必要がある state = Statevector.from_instruction(qc).data qc.measure(0, 0) counts = sim.run(qc).result().get_counts() print(f"{gate_label} |{state_label}> : ", "state=", state.round(3), "counts=",counts) print()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import qiskit qiskit.__qiskit_version__ #initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load our saved IBMQ accounts. IBMQ.load_account() nQubits = 14 # number of physical qubits a = 101 # the hidden integer whose bitstring is 1100101 # make sure that a can be represented with nQubits a = a % 2**(nQubits) # Creating registers # qubits for querying the oracle and finding the hidden integer qr = QuantumRegister(nQubits) # for recording the measurement on qr cr = ClassicalRegister(nQubits) circuitName = "BernsteinVazirani" bvCircuit = QuantumCircuit(qr, cr) # Apply Hadamard gates before querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Apply barrier so that it is not optimized by the compiler bvCircuit.barrier() # Apply the inner-product oracle for i in range(nQubits): if (a & (1 << i)): bvCircuit.z(qr[i]) else: bvCircuit.iden(qr[i]) # Apply barrier bvCircuit.barrier() #Apply Hadamard gates after querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Measurement bvCircuit.barrier(qr) bvCircuit.measure(qr, cr) bvCircuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1000 results = execute(bvCircuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') shots = 1000 bvCompiled = transpile(bvCircuit, backend=backend, optimization_level=1) job_exp = execute(bvCircuit, backend=backend, shots=shots) job_monitor(job_exp) results = job_exp.result() answer = results.get_counts(bvCircuit) threshold = int(0.01 * shots) #the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} #filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) #number of counts removed filteredAnswer['other_bitstrings'] = removedCounts #the removed counts is assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import qiskit qiskit.__qiskit_version__ # useful additional packages import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import BasicAer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load our saved IBMQ accounts IBMQ.load_account() n = 13 # the length of the first register for querying the oracle # Choose a type of oracle at random. With probability half it is constant, # and with the same probability it is balanced oracleType, oracleValue = np.random.randint(2), np.random.randint(2) if oracleType == 0: print("The oracle returns a constant value ", oracleValue) else: print("The oracle returns a balanced function") a = np.random.randint(1,2**n) # this is a hidden parameter for balanced oracle. # Creating registers # n qubits for querying the oracle and one qubit for storing the answer qr = QuantumRegister(n+1) #all qubits are initialized to zero # for recording the measurement on the first register cr = ClassicalRegister(n) circuitName = "DeutschJozsa" djCircuit = QuantumCircuit(qr, cr) # Create the superposition of all input queries in the first register by applying the Hadamard gate to each qubit. for i in range(n): djCircuit.h(qr[i]) # Flip the second register and apply the Hadamard gate. djCircuit.x(qr[n]) djCircuit.h(qr[n]) # Apply barrier to mark the beginning of the oracle djCircuit.barrier() if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue for all input. if oracleValue == 1: djCircuit.x(qr[n]) else: djCircuit.iden(qr[n]) else: # Otherwise, it returns the inner product of the input with a (non-zero bitstring) for i in range(n): if (a & (1 << i)): djCircuit.cx(qr[i], qr[n]) # Apply barrier to mark the end of the oracle djCircuit.barrier() # Apply Hadamard gates after querying the oracle for i in range(n): djCircuit.h(qr[i]) # Measurement djCircuit.barrier() for i in range(n): djCircuit.measure(qr[i], cr[i]) #draw the circuit djCircuit.draw(output='mpl',scale=0.5) backend = BasicAer.get_backend('qasm_simulator') shots = 1000 job = execute(djCircuit, backend=backend, shots=shots) results = job.result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') djCompiled = transpile(djCircuit, backend=backend, optimization_level=1) djCompiled.draw(output='mpl',scale=0.5) job = execute(djCompiled, backend=backend, shots=1024) job_monitor(job) results = job.result() answer = results.get_counts() threshold = int(0.01 * shots) # the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} # filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) # number of counts removed filteredAnswer['other_bitstrings'] = removedCounts # the removed counts are assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import qiskit qiskit.__qiskit_version__ import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import BasicAer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.visualization import plot_histogram q = QuantumRegister(6) qc = QuantumCircuit(q) qc.x(q[2]) qc.cx(q[1], q[5]) qc.cx(q[2], q[5]) qc.cx(q[3], q[5]) qc.ccx(q[1], q[2], q[4]) qc.ccx(q[3], q[4], q[5]) qc.ccx(q[1], q[2], q[4]) qc.x(q[2]) qc.draw(output='mpl') def black_box_u_f(circuit, f_in, f_out, aux, n, exactly_1_3_sat_formula): """Circuit that computes the black-box function from f_in to f_out. Create a circuit that verifies whether a given exactly-1 3-SAT formula is satisfied by the input. The exactly-1 version requires exactly one literal out of every clause to be satisfied. """ num_clauses = len(exactly_1_3_sat_formula) for (k, clause) in enumerate(exactly_1_3_sat_formula): # This loop ensures aux[k] is 1 if an odd number of literals # are true for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) # Flip aux[k] if all literals are true, using auxiliary qubit # (ancilla) aux[num_clauses] circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) # Flip back to reverse state of negative literals and ancilla circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # The formula is satisfied if and only if all auxiliary qubits # except aux[num_clauses] are 1 if (num_clauses == 1): circuit.cx(aux[0], f_out[0]) elif (num_clauses == 2): circuit.ccx(aux[0], aux[1], f_out[0]) elif (num_clauses == 3): circuit.ccx(aux[0], aux[1], aux[num_clauses]) circuit.ccx(aux[2], aux[num_clauses], f_out[0]) circuit.ccx(aux[0], aux[1], aux[num_clauses]) else: raise ValueError('We only allow at most 3 clauses') # Flip back any auxiliary qubits to make sure state is consistent # for future executions of this routine; same loop as above. for (k, clause) in enumerate(exactly_1_3_sat_formula): for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # -- end function def n_controlled_Z(circuit, controls, target): """Implement a Z gate with multiple controls""" if (len(controls) > 2): raise ValueError('The controlled Z with more than 2 ' + 'controls is not implemented') elif (len(controls) == 1): circuit.h(target) circuit.cx(controls[0], target) circuit.h(target) elif (len(controls) == 2): circuit.h(target) circuit.ccx(controls[0], controls[1], target) circuit.h(target) # -- end function def inversion_about_average(circuit, f_in, n): """Apply inversion about the average step of Grover's algorithm.""" # Hadamards everywhere for j in range(n): circuit.h(f_in[j]) # D matrix: flips the sign of the state |000> only for j in range(n): circuit.x(f_in[j]) n_controlled_Z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1]) for j in range(n): circuit.x(f_in[j]) # Hadamards everywhere again for j in range(n): circuit.h(f_in[j]) # -- end function qr = QuantumRegister(3) qInvAvg = QuantumCircuit(qr) inversion_about_average(qInvAvg, qr, 3) qInvAvg.draw(output='mpl') """ Grover search implemented in Qiskit. This module contains the code necessary to run Grover search on 3 qubits, both with a simulator and with a real quantum computing device. This code is the companion for the paper "An introduction to quantum computing, without the physics", Giacomo Nannicini, https://arxiv.org/abs/1708.03684. """ def input_state(circuit, f_in, f_out, n): """(n+1)-qubit input state for Grover search.""" for j in range(n): circuit.h(f_in[j]) circuit.x(f_out) circuit.h(f_out) # -- end function # Make a quantum program for the n-bit Grover search. n = 3 # Exactly-1 3-SAT formula to be satisfied, in conjunctive # normal form. We represent literals with integers, positive or # negative, to indicate a Boolean variable or its negation. exactly_1_3_sat_formula = [[1, 2, -3], [-1, -2, -3], [-1, 2, 3]] # Define three quantum registers: 'f_in' is the search space (input # to the function f), 'f_out' is bit used for the output of function # f, aux are the auxiliary bits used by f to perform its # computation. f_in = QuantumRegister(n) f_out = QuantumRegister(1) aux = QuantumRegister(len(exactly_1_3_sat_formula) + 1) # Define classical register for algorithm result ans = ClassicalRegister(n) # Define quantum circuit with above registers grover = QuantumCircuit() grover.add_register(f_in) grover.add_register(f_out) grover.add_register(aux) grover.add_register(ans) input_state(grover, f_in, f_out, n) T = 2 for t in range(T): # Apply T full iterations black_box_u_f(grover, f_in, f_out, aux, n, exactly_1_3_sat_formula) inversion_about_average(grover, f_in, n) # Measure the output register in the computational basis for j in range(n): grover.measure(f_in[j], ans[j]) # Execute circuit backend = BasicAer.get_backend('qasm_simulator') job = execute([grover], backend=backend, shots=1000) result = job.result() # Get counts and plot histogram counts = result.get_counts(grover) plot_histogram(counts) IBMQ.load_account() # get ibmq_16_melbourne configuration and coupling map backend = IBMQ.get_backend('ibmq_16_melbourne') # compile the circuit for ibmq_16_rueschlikon grover_compiled = transpile(grover, backend=backend, seed_transpiler=1, optimization_level=3) print('gates = ', grover_compiled.count_ops()) print('depth = ', grover_compiled.depth()) grover.draw(output='mpl', scale=0.5)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import qiskit qiskit.__qiskit_version__ from math import pi import numpy as np import scipy as sp import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import BasicAer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit.tools.visualization import plot_histogram from qiskit.tools.monitor import job_monitor # Load saved IBMQ accounts IBMQ.load_account() # We first define controlled gates used in the IPEA def cu1fixed(qProg, c, t, a): qProg.u1(-a, t) qProg.cx(c, t) qProg.u1(a, t) qProg.cx(c, t) def cu5pi8(qProg, c, t): cu1fixed(qProg, c, t, -5.0*pi/8.0) # We then prepare quantum and classical registers and the circuit qr = QuantumRegister(2) cr = ClassicalRegister(4) circuitName="IPEAonSimulator" ipeaCircuit = QuantumCircuit(qr, cr) # Apply IPEA ipeaCircuit.h(qr[0]) for i in range(8): cu5pi8(ipeaCircuit, qr[0], qr[1]) ipeaCircuit.h(qr[0]) ipeaCircuit.measure(qr[0], cr[0]) ipeaCircuit.reset(qr[0]) ipeaCircuit.h(qr[0]) for i in range(4): cu5pi8(ipeaCircuit, qr[0], qr[1]) ipeaCircuit.u1(-pi/2, qr[0]).c_if(cr, 1) ipeaCircuit.h(qr[0]) ipeaCircuit.measure(qr[0], cr[1]) ipeaCircuit.reset(qr[0]) ipeaCircuit.h(qr[0]) for i in range(2): cu5pi8(ipeaCircuit, qr[0], qr[1]) ipeaCircuit.u1(-pi/4, qr[0]).c_if(cr, 1) ipeaCircuit.u1(-pi/2, qr[0]).c_if(cr, 2) ipeaCircuit.u1(-3*pi/4, qr[0]).c_if(cr, 3) ipeaCircuit.h(qr[0]) ipeaCircuit.measure(qr[0], cr[2]) ipeaCircuit.reset(qr[0]) ipeaCircuit.h(qr[0]) cu5pi8(ipeaCircuit, qr[0], qr[1]) ipeaCircuit.u1(-pi/8, qr[0]).c_if(cr, 1) ipeaCircuit.u1(-2*pi/8, qr[0]).c_if(cr, 2) ipeaCircuit.u1(-3*pi/8, qr[0]).c_if(cr, 3) ipeaCircuit.u1(-4*pi/8, qr[0]).c_if(cr, 4) ipeaCircuit.u1(-5*pi/8, qr[0]).c_if(cr, 5) ipeaCircuit.u1(-6*pi/8, qr[0]).c_if(cr, 6) ipeaCircuit.u1(-7*pi/8, qr[0]).c_if(cr, 7) ipeaCircuit.h(qr[0]) ipeaCircuit.measure(qr[0], cr[3]) backend = BasicAer.get_backend('qasm_simulator') shots = 1000 results = execute(ipeaCircuit, backend=backend, shots=shots).result() plot_histogram(results.get_counts()) # We then prepare quantum and classical registers and the circuit qr = QuantumRegister(5) cr = ClassicalRegister(5) realStep1Circuit = QuantumCircuit(qr, cr) # Apply IPEA realStep1Circuit.h(qr[0]) for i in range(8): cu5pi8(realStep1Circuit, qr[0], qr[1]) realStep1Circuit.h(qr[0]) realStep1Circuit.measure(qr[0], cr[0]) #connect to remote API to be able to use remote simulators and real devices print("Available backends:", [BasicAer.backends(), IBMQ.backends()]) backend = IBMQ.get_backend("ibmq_5_yorktown") shots = 1000 job_exp1 = execute(realStep1Circuit, backend=backend, shots=shots) job_monitor(job_exp1) results1 = job_exp1.result() plot_histogram(results1.get_counts()) realStep2Circuit = QuantumCircuit(qr, cr) # Apply IPEA realStep2Circuit.h(qr[0]) for i in range(4): cu5pi8(realStep2Circuit, qr[0], qr[1]) realStep2Circuit.u1(-pi/2, qr[0]) # Assuming the value of the measurement on Step 1 realStep2Circuit.h(qr[0]) realStep2Circuit.measure(qr[0], cr[0]) job_exp2 = execute(realStep2Circuit, backend=backend, shots=shots) job_monitor(job_exp1) results2 = job_exp2.result() plot_histogram(results2.get_counts()) realStep3Circuit = QuantumCircuit(qr, cr) # Apply IPEA realStep3Circuit.h(qr[0]) for i in range(2): cu5pi8(realStep3Circuit, qr[0], qr[1]) realStep3Circuit.u1(-3*pi/4, qr[0]) # Assuming the value of the measurement on Step 1 and Step 2 realStep3Circuit.h(qr[0]) realStep3Circuit.measure(qr[0], cr[0]) job_exp3 = execute(realStep3Circuit, backend=backend, shots=shots) job_monitor(job_exp3) results3 = job_exp3.result() plot_histogram(results3.get_counts()) realStep4Circuit = QuantumCircuit(qr, cr) # Apply IPEA realStep4Circuit.h(qr[0]) cu5pi8(realStep4Circuit, qr[0], qr[1]) realStep4Circuit.u1(-3*pi/8, qr[0]) # Assuming the value of the measurement on Step 1, 2, and 3 realStep4Circuit.h(qr[0]) realStep4Circuit.measure(qr[0], cr[0]) job_exp4 = execute(realStep4Circuit, backend=backend, shots=shots) job_monitor(job_exp4) results4 = job_exp4.result() plot_histogram(results4.get_counts())
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from IPython.display import YouTubeVideo YouTubeVideo('BYKc2RnQMqo', width=858, height=540) !pip install qiskit --quiet !pip install qiskit-aer --quiet !pip install pylatexenc --quiet # @markdown ### **1. Import `Qiskit` and essential packages** { display-mode: "form" } from qiskit import QuantumCircuit, transpile, assemble from qiskit.circuit.library import QFT from qiskit_aer import AerSimulator from fractions import Fraction import random import sympy import math # @markdown ### **2. Controlled Modular Multiplication for $U(x) = a^x mod N$** { display-mode: "form" } class CtrlMultCircuit(QuantumCircuit): def __init__(self, a, binary_power, N): super().__init__(N.bit_length()) self.a = a self.power = 2 ** binary_power # Convert binary to decimal self.N = N self.name = f'{self.a}^{self.power} mod {self.N}' self._create_circuit() def _create_circuit(self): for dec_power in range(self.power): a_exp = self.a ** dec_power % self.N for i in range(self.num_qubits): if a_exp >> i & 1: self.x(i) for j in range(i + 1, self.num_qubits): if a_exp >> j & 1: self.swap(i, j) # @markdown ### **3. Quantum Phase Estimation with `Modular Exponentiation` and `Quantum Fourier Transform` to find period $r$** { display-mode: "form" } # @markdown ![](https://reneroliveira.github.io/quantum-shors-algorithm/images/shor_circuit.png) class QPECircuit(QuantumCircuit): def __init__(self, a, N): super().__init__(2 * N.bit_length(), N.bit_length()) self.a = a self.N = N self._create_circuit() def _modular_exponentiation(self): for qbit_idx in range(self.num_qubits // 2): self.append( CtrlMultCircuit(self.a, qbit_idx, self.N).to_gate().control(), [qbit_idx] + list(range(self.num_qubits // 2, 2 * self.num_qubits // 2)) ) def _create_circuit(self): self.h(range(self.num_qubits // 2)) # Apply Hadamard gates to the first n qubits self.x(self.num_qubits - 1) self.barrier() self._modular_exponentiation() # Apply controlled modular exponentiation self.barrier() self.append( QFT(self.num_qubits // 2, inverse=True), range(self.num_qubits // 2) # Apply inverse QFT to the first n qubits ) def collapse(self, simulator): self.measure(range(self.num_qubits // 2), range(self.num_qubits // 2)) transpiled_circuit = transpile(self, simulator) self.collapse_result = simulator.run(transpiled_circuit, memory=True).result() return self.collapse_result # @markdown ### **4. Completed Shor's Algorithm for Integer Factorization** { display-mode: "form" } class ShorAlgorithm: def __init__(self, N, max_attempts=-1, random_coprime_only=False, simulator=None): self.N = N self.simulator = simulator self.max_attempts = max_attempts # -1 for all possible values of a self.random_coprime_only = random_coprime_only # True to select only coprime values of a and N def execute(self): is_N_invalid = self._is_N_invalid() if is_N_invalid: return is_N_invalid # Only coprime values remain if random_coprime_only is enabled, # Otherwise select a random integer in [2, N) as initial guess a_values = [a for a in range(2, self.N) if not self.random_coprime_only or (math.gcd(a, self.N) == 1)] print(f'[INFO] {len(a_values)} possible values of a: {a_values}') self.max_attempts = len(a_values) if self.max_attempts <= -1 else min(self.max_attempts, len(a_values)) attempts_count = 0 while attempts_count < self.max_attempts: print(f'\n===== Attempt {attempts_count + 1}/{self.max_attempts} =====') attempts_count += 1 self.chosen_a = random.choice(a_values) self.r = 1 print(f'[START] Chosen base a: {self.chosen_a}') if not self.random_coprime_only: gcd = math.gcd(self.chosen_a, self.N) if gcd != 1: print(f'=> {self.chosen_a} and {self.N} share common factor: {self.N} = {gcd} * {self.N // gcd}') return gcd, self.N // gcd print(f'>>> {self.chosen_a} and {self.N} are coprime => Perform Quantum Phase Estimation to find {self.chosen_a}^r - 1 = 0 (MOD {self.N})') if not self._quantum_period_finding(): a_values.remove(self.chosen_a) self.r = self.chosen_a = self.qpe_circuit = None continue factors = self._classical_postprocess() if factors: return factors a_values.remove(self.chosen_a) self.r = self.chosen_a = self.qpe_circuit = None print(f'[FAIL] No non-trivial factors found after {self.max_attempts} attempts.') def _is_N_invalid(self): if self.N <= 3: print('[ERR] N must be > 3') return 1, self.N if self.N % 2 == 0: print(f'=> {self.N} is an even number: {self.N} = 2 * {self.N // 2}') return 2, self.N // 2 if sympy.isprime(self.N): print(f'=> {self.N} is a prime number: {self.N} = 1 * {self.N}') return 1, self.N max_exponent = int(math.log2(self.N)) # Start with a large exponent and reduce for k in range(max_exponent, 1, -1): p = round(self.N ** (1 / k)) if p ** k == self.N: print(f'=> {self.N} is a power of prime: {self.N} = {p}^{k}') return p, k return False def _quantum_period_finding(self): while self.chosen_a ** self.r % self.N != 1: # QPE + continued fractions may find wrong r self.qpe_circuit = QPECircuit(self.chosen_a, self.N) # Find phase s/r result = self.qpe_circuit.collapse(self.simulator) state_bin = result.get_memory()[0] state_dec = int(state_bin, 2) # Convert to decimal bits_count = 2 ** (self.N.bit_length() - 1) phase = state_dec / bits_count # Continued fraction to find r self.r = Fraction(phase).limit_denominator(self.N).denominator # Get fraction that most closely approximates phase if self.r > self.N or self.r == 1: # Safety check to avoid infinite loops print(f'[ERR] Invalid period found: r = {self.r} => Retry with different a.') return False print(f'>>> Output State: |{state_bin}⟩ = {state_dec} (dec) => Phase = {state_dec} / {bits_count} = {phase:.3f}') return True def _classical_postprocess(self): # Classical postprocessing to find factors from the period print(f'>>> Found r = {self.r} => a^{{r/2}} ± 1 = {self.chosen_a:.0f}^{self.r/2:.0f} ± 1') if self.r % 2 != 0: print(f'[ERR] r = {self.r} is odd => Retry with different a.') return None int1, int2 = self.chosen_a ** (self.r // 2) - 1, self.chosen_a ** (self.r // 2) + 1 if int1 % self.N == 0 or int2 % self.N == 0: print(f'[ERR] {self.chosen_a}^{self.r/2:.0f} ± 1 is a multiple of {self.N} => Retry with different a.') return None factor1, factor2 = math.gcd(int1, self.N), math.gcd(int2, self.N) if factor1 not in [1, self.N] and factor2 not in [1, self.N]: # Check to see if factor is non-trivial print(f'[DONE] Successfully found non-trivial factors: {self.N} = {factor1} * {factor2}') return factor1, factor2 print(f'[FAIL] Trivial factors found: [1, {self.N}] => Retry with different a.') return None # @markdown ### **5. Run the Factorization** { display-mode: "form" } number_to_factor = 21 # @param {type:"slider", min: 15, max: 55, step: 1} max_attempts = -1 # @param {type:"slider", min:-1, max:100, step:10} random_coprime_only = False # @param {type:"boolean"} # @markdown ***Note**: `max_attempts` will be limited to number of available values. shor = ShorAlgorithm(number_to_factor, max_attempts, random_coprime_only, AerSimulator()) factors = shor.execute() try: display(shor.qpe_circuit.draw(output='mpl', fold=-1)) except Exception: pass
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import qiskit qiskit.__qiskit_version__ #initialization import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import BasicAer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load the saved IBMQ accounts IBMQ.load_account() s = "010101" # the hidden bitstring assert 1 < len(s) < 20, "The length of s must be between 2 and 19" for c in s: assert c == "0" or c == "1", "s must be a bitstring of '0' and '1'" n = len(s) #the length of the bitstring # Step 1 # Creating registers # qubits for querying the oracle and recording its output qr = QuantumRegister(2*n) # for recording the measurement on the first register of qr cr = ClassicalRegister(n) circuitName = "Simon" simonCircuit = QuantumCircuit(qr, cr) # Step 2 # Apply Hadamard gates before querying the oracle for i in range(n): simonCircuit.h(qr[i]) # Apply barrier to mark the beginning of the blackbox function simonCircuit.barrier() # Step 3 query the blackbox function # copy the content of the first register to the second register for i in range(n): simonCircuit.cx(qr[i], qr[n+i]) # get the least index j such that s_j is "1" j = -1 for i, c in enumerate(s): if c == "1": j = i break # Creating 1-to-1 or 2-to-1 mapping with the j-th qubit of x as control to XOR the second register with s for i, c in enumerate(s): if c == "1" and j >= 0: simonCircuit.cx(qr[j], qr[n+i]) #the i-th qubit is flipped if s_i is 1 # get random permutation of n qubits perm = list(np.random.permutation(n)) #initial position init = list(range(n)) i = 0 while i < n: if init[i] != perm[i]: k = perm.index(init[i]) simonCircuit.swap(qr[n+i], qr[n+k]) #swap qubits init[i], init[k] = init[k], init[i] #marked swapped qubits else: i += 1 # randomly flip the qubit for i in range(n): if np.random.random() > 0.5: simonCircuit.x(qr[n+i]) # Apply the barrier to mark the end of the blackbox function simonCircuit.barrier() # Step 4 apply Hadamard gates to the first register for i in range(n): simonCircuit.h(qr[i]) # Step 5 perform measurement on the first register for i in range(n): simonCircuit.measure(qr[i], cr[i]) #draw the circuit simonCircuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend("qasm_simulator") # the number of shots is twice the length of the bitstring shots = 2*n job = execute(simonCircuit, backend=backend, shots=shots) answer = job.result().get_counts() plot_histogram(answer) # Post-processing step # Constructing the system of linear equations Y s = 0 # By k[::-1], we reverse the order of the bitstring lAnswer = [ (k[::-1],v) for k,v in answer.items() if k != "0"*n ] #excluding the trivial all-zero #Sort the basis by their probabilities lAnswer.sort(key = lambda x: x[1], reverse=True) Y = [] for k, v in lAnswer: Y.append( [ int(c) for c in k ] ) #import tools from sympy from sympy import Matrix, pprint, MatrixSymbol, expand, mod_inverse Y = Matrix(Y) #pprint(Y) #Perform Gaussian elimination on Y Y_transformed = Y.rref(iszerofunc=lambda x: x % 2==0) # linear algebra on GF(2) #to convert rational and negatives in rref of linear algebra on GF(2) def mod(x,modulus): numer, denom = x.as_numer_denom() return numer*mod_inverse(denom,modulus) % modulus Y_new = Y_transformed[0].applyfunc(lambda x: mod(x,2)) #must takecare of negatives and fractional values #pprint(Y_new) print("The hidden bistring s[ 0 ], s[ 1 ]....s[",n-1,"] is the one satisfying the following system of linear equations:") rows, cols = Y_new.shape for r in range(rows): Yr = [ "s[ "+str(i)+" ]" for i, v in enumerate(list(Y_new[r,:])) if v == 1 ] if len(Yr) > 0: tStr = " + ".join(Yr) print(tStr, "= 0") #Use one of the available backends backend = IBMQ.get_backend("ibmq_16_melbourne") # show the status of the backend print("Status of", backend, "is", backend.status()) shots = 10*n #run more experiments to be certain max_credits = 3 # Maximum number of credits to spend on executions. simonCompiled = transpile(simonCircuit, backend=backend, optimization_level=1) job_exp = execute(simonCompiled, backend=backend, shots=shots, max_credits=max_credits) job_monitor(job_exp) results = job_exp.result() answer = results.get_counts(simonCircuit) plot_histogram(answer) # Post-processing step # Constructing the system of linear equations Y s = 0 # By k[::-1], we reverse the order of the bitstring lAnswer = [ (k[::-1][:n],v) for k,v in answer.items() ] #excluding the qubits that are not part of the inputs #Sort the basis by their probabilities lAnswer.sort(key = lambda x: x[1], reverse=True) Y = [] for k, v in lAnswer: Y.append( [ int(c) for c in k ] ) Y = Matrix(Y) #Perform Gaussian elimination on Y Y_transformed = Y.rref(iszerofunc=lambda x: x % 2==0) # linear algebra on GF(2) Y_new = Y_transformed[0].applyfunc(lambda x: mod(x,2)) #must takecare of negatives and fractional values #pprint(Y_new) print("The hidden bistring s[ 0 ], s[ 1 ]....s[",n-1,"] is the one satisfying the following system of linear equations:") rows, cols = Y_new.shape for r in range(rows): Yr = [ "s[ "+str(i)+" ]" for i, v in enumerate(list(Y_new[r,:])) if v == 1 ] if len(Yr) > 0: tStr = " + ".join(Yr) print(tStr, "= 0")
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from datasets import * from qiskit import Aer from qiskit_aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name from qiskit_aqua import run_algorithm, QuantumInstance from qiskit_aqua.input import SVMInput from qiskit_aqua.components.feature_maps import SecondOrderExpansion from qiskit_aqua.algorithms import QSVMKernel feature_dim = 2 # dimension of each data point training_dataset_size = 20 testing_dataset_size = 10 random_seed = 10598 shots = 1024 sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=training_dataset_size, test_size=testing_dataset_size, n=feature_dim, gap=0.3, PLOT_DATA=False) datapoints, class_to_label = split_dataset_to_data_and_labels(test_input) print(class_to_label) params = { 'problem': {'name': 'svm_classification', 'random_seed': random_seed}, 'algorithm': { 'name': 'QSVM.Kernel' }, 'backend': {'shots': shots}, 'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entanglement': 'linear'} } backend = Aer.get_backend('qasm_simulator') algo_input = SVMInput(training_input, test_input, datapoints[0]) result = run_algorithm(params, algo_input, backend=backend) print("kernel matrix during the training:") kernel_matrix = result['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r') plt.show() print("testing success ratio: ", result['testing_accuracy']) print("predicted classes:", result['predicted_classes']) backend = Aer.get_backend('qasm_simulator') feature_map = SecondOrderExpansion(num_qubits=feature_dim, depth=2, entangler_map={0: [1]}) svm = QSVMKernel(feature_map, training_input, test_input, None)# the data for prediction can be feeded later. svm.random_seed = random_seed quantum_instance = QuantumInstance(backend, shots=shots, seed=random_seed, seed_mapper=random_seed) result = svm.run(quantum_instance) print("kernel matrix during the training:") kernel_matrix = result['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r') plt.show() print("testing success ratio: ", result['testing_accuracy']) predicted_labels = svm.predict(datapoints[0]) predicted_classes = map_label_to_class_name(predicted_labels, svm.label_to_class) print("ground truth: {}".format(datapoints[1])) print("preduction: {}".format(predicted_labels))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from datasets import * from qiskit import Aer from qiskit_aqua.input import SVMInput from qiskit_aqua import run_algorithm import numpy as np n = 2 # dimension of each data point sample_Total, training_input, test_input, class_labels = Wine(training_size=40, test_size=10, n=n, PLOT_DATA=True) temp = [test_input[k] for k in test_input] total_array = np.concatenate(temp) aqua_dict = { 'problem': {'name': 'svm_classification', 'random_seed': 10598}, 'algorithm': { 'name': 'QSVM.Kernel' }, 'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entangler_map': {0: [1]}}, 'multiclass_extension': {'name': 'AllPairs'}, 'backend': {'shots': 1024} } backend = Aer.get_backend('qasm_simulator') algo_input = SVMInput(training_input, test_input, total_array) result = run_algorithm(aqua_dict, algo_input, backend=backend) for k,v in result.items(): print("'{}' : {}".format(k, v))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from datasets import * from qiskit_aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name from qiskit import Aer from qiskit_aqua.input import SVMInput from qiskit_aqua import run_algorithm, QuantumInstance from qiskit_aqua.algorithms import QSVMVariational from qiskit_aqua.components.optimizers import SPSA from qiskit_aqua.components.feature_maps import SecondOrderExpansion from qiskit_aqua.components.variational_forms import RYRZ feature_dim = 2 # dimension of each data point training_dataset_size = 20 testing_dataset_size = 10 random_seed = 10598 shots = 1024 sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=training_dataset_size, test_size=testing_dataset_size, n=feature_dim, gap=0.3, PLOT_DATA=True) datapoints, class_to_label = split_dataset_to_data_and_labels(test_input) print(class_to_label) params = { 'problem': {'name': 'svm_classification', 'random_seed': 10598}, 'algorithm': {'name': 'QSVM.Variational', 'override_SPSA_params': True}, 'backend': {'shots': 1024}, 'optimizer': {'name': 'SPSA', 'max_trials': 200, 'save_steps': 1}, 'variational_form': {'name': 'RYRZ', 'depth': 3}, 'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2} } svm_input = SVMInput(training_input, test_input, datapoints[0]) backend = Aer.get_backend('qasm_simulator') result = run_algorithm(params, svm_input, backend=backend) print("testing success ratio: ", result['testing_accuracy']) print("predicted classes:", result['predicted_classes']) backend = Aer.get_backend('qasm_simulator') optimizer = SPSA(max_trials=100, c0=4.0, skip_calibration=True) optimizer.set_options(save_steps=1) feature_map = SecondOrderExpansion(num_qubits=feature_dim, depth=2) var_form = RYRZ(num_qubits=feature_dim, depth=3) svm = QSVMVariational(optimizer, feature_map, var_form, training_input, test_input) quantum_instance = QuantumInstance(backend, shots=shots, seed=random_seed, seed_mapper=random_seed) result = svm.run(quantum_instance) print("testing success ratio: ", result['testing_accuracy']) predicted_probs, predicted_labels = svm.predict(datapoints[0]) predicted_classes = map_label_to_class_name(predicted_labels, svm.label_to_class) print("prediction: {}".format(predicted_labels))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from datasets import * from qiskit_aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name from qiskit_aqua.input import SVMInput from qiskit_aqua import run_algorithm feature_dim = 2 # dimension of each data point training_dataset_size = 20 testing_dataset_size = 10 sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=training_dataset_size, test_size=testing_dataset_size, n=feature_dim, gap=0.3, PLOT_DATA=True) datapoints, class_to_label = split_dataset_to_data_and_labels(test_input) print(class_to_label) params = { 'problem': {'name': 'svm_classification'}, 'algorithm': { 'name': 'SVM' } } algo_input = SVMInput(training_input, test_input, datapoints[0]) result = run_algorithm(params, algo_input) print("kernel matrix during the training:") kernel_matrix = result['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r') plt.show() print("testing success ratio: ", result['testing_accuracy']) print("predicted classes:", result['predicted_classes']) sample_Total, training_input, test_input, class_labels = Breast_cancer(training_size=20, test_size=10, n=2, PLOT_DATA=True) # n =2 is the dimension of each data point datapoints, class_to_label = split_dataset_to_data_and_labels(test_input) label_to_class = {label:class_name for class_name, label in class_to_label.items()} print(class_to_label, label_to_class) algo_input = SVMInput(training_input, test_input, datapoints[0]) result = run_algorithm(params, algo_input) # print(result) print("kernel matrix during the training:") kernel_matrix = result['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r') plt.show() print("testing success ratio: ", result['testing_accuracy']) print("ground truth: {}".format(map_label_to_class_name(datapoints[1], label_to_class))) print("predicted: {}".format(result['predicted_classes']))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from datasets import * from qiskit_aqua.utils import split_dataset_to_data_and_labels from qiskit_aqua.input import SVMInput from qiskit_aqua import run_algorithm import numpy as np feature_dim = 2 # dimension of each data point sample_Total, training_input, test_input, class_labels = Wine(training_size=20, test_size=10, n=feature_dim, PLOT_DATA=True) temp = [test_input[k] for k in test_input] total_array = np.concatenate(temp) aqua_dict = { 'problem': {'name': 'svm_classification'}, 'algorithm': { 'name': 'SVM' }, 'multiclass_extension': {'name': 'OneAgainstRest'} } algo_input = SVMInput(training_input, test_input, total_array) extensions = [ {'name': 'OneAgainstRest'}, {'name': 'AllPairs'}, {'name': 'ErrorCorrectingCode', 'code_size': 5} ] for extension in extensions: aqua_dict['multiclass_extension'] = extension result = run_algorithm(aqua_dict, algo_input) print("\n----- Using multiclass extension: '{}' -----\n".format(extension['name'])) for k,v in result.items(): print("'{}' : {}".format(k, v))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'qubit_mapping': 'parity', 'two_qubit_reduction': True, 'freeze_core': True, 'orbital_reduction': []}, 'algorithm': {'name': 'ExactEigensolver'} } molecule = 'H .0 .0 -{0}; Be .0 .0 .0; H .0 .0 {0}' reductions = [[], [-2, -1], [-3, -2], [-4, -3], [-1], [-2], [-3], [-4]] pts = [x * 0.1 for x in range(6, 20)] pts += [x * 0.25 for x in range(8, 16)] pts += [4.0] energies = np.empty([len(reductions), len(pts)]) distances = np.empty(len(pts)) print('Processing step __', end='') for i, d in enumerate(pts): print('\b\b{:2d}'.format(i), end='', flush=True) qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d) for j in range(len(reductions)): qiskit_chemistry_dict['operator']['orbital_reduction'] = reductions[j] solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[j][i] = result['energy'] distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) pylab.rcParams['figure.figsize'] = (12, 8) for j in range(len(reductions)): pylab.plot(distances, energies[j], label=reductions[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('BeH2 Ground State Energy') pylab.legend(loc='upper right') pylab.rcParams['figure.figsize'] = (12, 8) for j in range(len(reductions)): pylab.plot(distances, np.subtract(energies[j], energies[0]), label=reductions[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference compared to no reduction []') pylab.legend(loc='upper left') pylab.rcParams['figure.figsize'] = (6, 4) for j in range(1, len(reductions)): pylab.plot(distances, np.subtract(energies[j], energies[0]), color=[1.0, 0.6, 0.2], label=reductions[j]) pylab.ylim(0, 0.4) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference compared to no reduction []') pylab.legend(loc='upper left') pylab.show() e_nofreeze = np.empty(len(pts)) qiskit_chemistry_dict['operator']['orbital_reduction'] = [] qiskit_chemistry_dict['operator']['freeze_core'] = False for i, d in enumerate(pts): print('\b\b{:2d}'.format(i), end='', flush=True) qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d) solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) e_nofreeze[i] = result['energy'] print(e_nofreeze) pylab.rcParams['figure.figsize'] = (8, 6) pylab.plot(distances, energies[0], label='Freeze Core: True') pylab.plot(distances, e_nofreeze, label='Freeze Core: False') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference, no reduction [], freeze core true/false') pylab.legend(loc='upper right') pylab.show() pylab.title('Energy difference of freeze core True from False') pylab.plot(distances, np.subtract(energies[0], e_nofreeze), label='Freeze Core: False') pylab.show()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# -*- coding: utf-8 -*- # Copyright 2018 IBM. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= import qiskit_chemistry # An example of using a loop to vary inter-atomic distance. A dictionary is # created outside the loop, but inside the loop the 'atom' value is updated # with a new molecular configuration. The molecule is H2 and its inter-atomic distance # i.e the distance between the two atoms, is altered from 0.5 to 1.0. Each atom is # specified by x, y, z coords and the atoms are set on the z-axis, equidistant from # the origin, and updated by d inside the loop where the molecule string has this value # substituted by format(). Note the negative sign preceding the first format # substitution point i.e. the {} brackets # input_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': None, 'unit': 'Angstrom', 'charge': 0, 'spin': 0, 'basis': 'sto3g'}, 'algorithm': {'name': 'ExactEigensolver'}, } molecule = 'H .0 .0 -{0}; H .0 .0 {0}' for i in range(21): d = (0.5 + i * 0.5 / 20) / 2 input_dict['PYSCF']['atom'] = molecule.format(d) solver = qiskit_chemistry.QiskitChemistry() result = solver.run(input_dict) print('{:.4f} : {}'.format(d * 2, result['energy']))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. # Note: In order to allow this to run reasonably quickly it takes advantage # of the ability to freeze core orbitals and remove unoccupied virtual # orbitals to reduce the size of the problem. The result without this # will be more accurate but it takes rather longer to run. qiskit_chemistry_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'algorithm': {'name': 'ExactEigensolver'}, 'operator': {'name': 'hamiltonian', 'freeze_core': True, 'orbital_reduction': [-3, -2]}, } molecule = 'Li .0 .0 -{0}; H .0 .0 {0}' start = 1.25 # Start distance by = 0.5 # How much to increase distance by steps = 20 # Number of steps to increase by energies = np.empty(steps+1) distances = np.empty(steps+1) dipoles = np.empty(steps+1) print('Processing step __', end='') for i in range(steps+1): print('\b\b{:2d}'.format(i), end='', flush=True) d = start + i*by/steps qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2) solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) distances[i] = d energies[i] = result['energy'] dipoles[i] = result['total_dipole_moment'] print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Dipole moments:', dipoles) pylab.plot(distances, energies) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('LiH Ground State Energy') pylab.plot(distances, dipoles) pylab.xlabel('Interatomic distance') pylab.ylabel('Moment a.u') pylab.title('LiH Dipole Moment')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'problem': {'random_seed': 50}, 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': 'O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0', 'basis': 'sto-3g'}, 'operator': {'name': 'hamiltonian', 'freeze_core': True}, 'algorithm': {'name': 'ExactEigensolver'} } solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) print('Ground state energy: {}'.format(result['energy'])) for line in result['printable']: print(line) qiskit_chemistry_dict['algorithm']['name'] = 'VQE' qiskit_chemistry_dict['optimizer'] = {'name': 'COBYLA', 'maxiter': 25000} qiskit_chemistry_dict['variational_form'] = {'name': 'UCCSD'} qiskit_chemistry_dict['initial_state'] = {'name': 'HartreeFock'} solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) print('Ground state energy: {}'.format(result['energy'])) for line in result['printable']: print(line) print('Actual VQE evaluations taken: {}'.format(result['algorithm_retvals']['eval_count']))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'driver': {'name': 'PSI4'}, 'PSI4': '', 'algorithm': {'name': 'ExactEigensolver'}, } # PSI4 config here is a multi-line string that we update using format() # To do so all other curly brackets from PSI4 config must be doubled psi4_cfg = """ molecule h2 {{ 0 1 H 0.0 0.0 -{0} H 0.0 0.0 {0} }} set {{ basis {1} scf_type pk }} """ basis_sets = ['sto-3g', '3-21g', '6-31g'] start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 20 # Number of steps to increase by energies = np.empty([len(basis_sets), steps+1]) distances = np.empty(steps+1) print('Processing step __', end='') for i in range(steps+1): print('\b\b{:2d}'.format(i), end='', flush=True) d = start + i*by/steps for j in range(len(basis_sets)): qiskit_chemistry_dict['PSI4'] = psi4_cfg.format(d/2, basis_sets[j]) solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[j][i] = result['energy'] distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) for j in range(len(basis_sets)): pylab.plot(distances, energies[j], label=basis_sets[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 Ground State Energy in different basis sets') pylab.legend(loc='upper right')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'qubit_mapping': 'parity', 'two_qubit_reduction': True}, 'algorithm': {'name': 'ExactEigensolver', 'k': 4}, } molecule = 'H .0 .0 -{0}; H .0 .0 {0}' start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 20 # Number of steps to increase by energies = np.empty([4, steps+1]) distances = np.empty(steps+1) print('Processing step __', end='') for i in range(steps+1): print('\b\b{:2d}'.format(i), end='', flush=True) d = start + i*by/steps qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2) solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[:, i] = result['energies'] distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) pylab.rcParams['figure.figsize'] = (12, 8) for j in range(energies.shape[0]): label = 'Ground state' if j ==0 else 'Excited state {}'.format(j) pylab.plot(distances, energies[j], label=label) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 Ground and Excited States') pylab.legend(loc='upper right') pylab.show() pylab.rcParams['figure.figsize'] = (6, 4) prop_cycle = pylab.rcParams['axes.prop_cycle'] colors = prop_cycle.by_key()['color'] for j in range(energies.shape[0]): label = 'Ground state' if j ==0 else 'Excited state {}'.format(j) pylab.plot(distances, energies[j], color=colors[j], label=label) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 {}'.format(label)) pylab.legend(loc='upper right') pylab.show()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit import LegacySimulators from qiskit_chemistry import QiskitChemistry import time # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'transformation': 'full', 'qubit_mapping': 'parity'}, 'algorithm': {'name': ''}, 'initial_state': {'name': 'HartreeFock'}, } molecule = 'H .0 .0 -{0}; H .0 .0 {0}' algorithms = [ { 'name': 'IQPE', 'num_iterations': 16, 'num_time_slices': 3000, 'expansion_mode': 'trotter', 'expansion_order': 1, }, { 'name': 'ExactEigensolver' } ] backends = [ LegacySimulators.get_backend('qasm_simulator'), None ] start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 20 # Number of steps to increase by energies = np.empty([len(algorithms), steps+1]) hf_energies = np.empty(steps+1) distances = np.empty(steps+1) import concurrent.futures import multiprocessing as mp import copy def subrountine(i, qiskit_chemistry_dict, d, backend, algorithm): solver = QiskitChemistry() qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2) qiskit_chemistry_dict['algorithm'] = algorithm result = solver.run(qiskit_chemistry_dict, backend=backend) return i, d, result['energy'], result['hf_energy'] start_time = time.time() max_workers = max(4, mp.cpu_count()) with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as executor: futures = [] for j in range(len(algorithms)): algorithm = algorithms[j] backend = backends[j] for i in range(steps+1): d = start + i*by/steps future = executor.submit( subrountine, i, copy.deepcopy(qiskit_chemistry_dict), d, backend, algorithm ) futures.append(future) for future in concurrent.futures.as_completed(futures): i, d, energy, hf_energy = future.result() energies[j][i] = energy hf_energies[i] = hf_energy distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print("--- %s seconds ---" % (time.time() - start_time)) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[j], label=algorithms[j]['name']) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 Ground State Energy') pylab.legend(loc='upper right') pylab.show() pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock') pylab.plot(distances, np.subtract(energies[0], energies[1]), label='IQPE') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference from ExactEigensolver') pylab.legend(loc='upper right') pylab.show()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'problem': {'random_seed': 50}, 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'qubit_mapping': '', 'two_qubit_reduction': False}, 'algorithm': {'name': ''}, 'optimizer': {'name': 'L_BFGS_B', 'maxfun': 2500}, 'variational_form': {'name': 'RYRZ', 'depth': 5} } molecule = 'H .0 .0 -{0}; H .0 .0 {0}' algorithms = ['VQE', 'ExactEigensolver'] mappings = ['jordan_wigner', 'parity', 'bravyi_kitaev'] start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 20 # Number of steps to increase by energies = np.empty([len(mappings), len(algorithms), steps+1]) hf_energies = np.empty(steps+1) distances = np.empty(steps+1) print('Processing step __', end='') for i in range(steps+1): print('\b\b{:2d}'.format(i), end='', flush=True) d = start + i*by/steps qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2) for j in range(len(algorithms)): qiskit_chemistry_dict['algorithm']['name'] = algorithms[j] for k in range(len(mappings)): qiskit_chemistry_dict['operator']['qubit_mapping'] = mappings[k] solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[k][j][i] = result['energy'] hf_energies[i] = result['hf_energy'] # Independent of algorithm & mapping distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) pylab.rcParams['figure.figsize'] = (12, 8) pylab.ylim(-1.14, -1.04) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): for k in range(len(mappings)): pylab.plot(distances, energies[k][j], label=algorithms[j] + ", " + mappings[k]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 Ground State Energy in different mappings') pylab.legend(loc='upper right') pylab.show() pylab.rcParams['figure.figsize'] = (6, 4) for k in range(len(mappings)): pylab.ylim(-1.14, -1.04) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[k][j], label=algorithms[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 Ground State Energy with {} mapping'.format(mappings[k])) pylab.legend(loc='upper right') pylab.show() #pylab.plot(distances, np.subtract(hf_energies, energies[k][1]), label='Hartree-Fock') pylab.plot(distances, np.subtract(energies[k][0], energies[k][1]), color=[0.8500, 0.3250, 0.0980], label='VQE') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.yscale('log') pylab.title('Energy difference from ExactEigensolver with {} mapping'.format(mappings[k])) pylab.legend(loc='upper right') pylab.show()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'problem': {'random_seed': 50}, 'driver': {'name': 'PYQUANTE'}, 'PYQUANTE': {'atoms': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'qubit_mapping': 'jordan_wigner', 'two_qubit_reduction': False}, 'algorithm': {'name': ''}, 'optimizer': {'name': 'COBYLA', 'maxiter': 10000 }, 'variational_form': {'name': 'UCCSD'}, 'initial_state': {'name': 'HartreeFock'} } molecule = 'H .0 .0 -{0}; H .0 .0 {0}' algorithms = ['VQE', 'ExactEigensolver'] transformations = ['full', 'particle_hole'] start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 20 # Number of steps to increase by energies = np.empty([len(transformations), len(algorithms), steps+1]) hf_energies = np.empty(steps+1) distances = np.empty(steps+1) eval_counts = np.empty([len(transformations), steps+1]) print('Processing step __', end='') for i in range(steps+1): print('\b\b{:2d}'.format(i), end='', flush=True) d = start + i*by/steps qiskit_chemistry_dict['PYQUANTE']['atoms'] = molecule.format(d/2) for j in range(len(algorithms)): qiskit_chemistry_dict['algorithm']['name'] = algorithms[j] for k in range(len(transformations)): qiskit_chemistry_dict['operator']['transformation'] = transformations[k] solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[k][j][i] = result['energy'] hf_energies[i] = result['hf_energy'] if algorithms[j] == 'VQE': eval_counts[k][i] = result['algorithm_retvals']['eval_count'] distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print('VQE num evaluations:', eval_counts) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): for k in range(len(transformations)): pylab.plot(distances, energies[k][j], label=algorithms[j]+' + '+transformations[k]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 Ground State Energy') pylab.legend(loc='upper right') pylab.plot(distances, np.subtract(hf_energies, energies[0][1]), label='Hartree-Fock') for k in range(len(transformations)): pylab.plot(distances, np.subtract(energies[k][0], energies[k][1]), label='VQE + '+transformations[k]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference from ExactEigensolver') pylab.legend(loc='upper left') for k in range(len(transformations)): pylab.plot(distances, eval_counts[k], '-o', label='VQE + ' + transformations[k]) pylab.xlabel('Interatomic distance') pylab.ylabel('Evaluations') pylab.title('VQE number of evaluations') pylab.legend(loc='upper left')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from collections import OrderedDict from qiskit import LegacySimulators from qiskit.transpiler import PassManager from qiskit_aqua import AquaError from qiskit_aqua import QuantumInstance from qiskit_aqua.algorithms import ExactEigensolver from qiskit_aqua.algorithms import QPE from qiskit_aqua.components.iqfts import Standard from qiskit_chemistry import FermionicOperator from qiskit_chemistry import QiskitChemistry from qiskit_chemistry.drivers import ConfigurationManager from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock import time distance = 0.735 cfg_mgr = ConfigurationManager() pyscf_cfg = OrderedDict([ ('atom', 'H .0 .0 .0; H .0 .0 {}'.format(distance)), ('unit', 'Angstrom'), ('charge', 0), ('spin', 0), ('basis', 'sto3g') ]) section = {} section['properties'] = pyscf_cfg try: driver = cfg_mgr.get_driver_instance('PYSCF') except ModuleNotFoundError: raise AquaError('PYSCF driver does not appear to be installed') molecule = driver.run(section) qubit_mapping = 'parity' fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubit_op = fer_op.mapping(map_type=qubit_mapping,threshold=1e-10).two_qubit_reduced_operator(2) exact_eigensolver = ExactEigensolver(qubit_op, k=1) result_ee = exact_eigensolver.run() reference_energy = result_ee['energy'] print('The exact ground state energy is: {}'.format(result_ee['energy'])) num_particles = molecule.num_alpha + molecule.num_beta two_qubit_reduction = True num_orbitals = qubit_op.num_qubits + (2 if two_qubit_reduction else 0) num_time_slices = 50 n_ancillae = 9 state_in = HartreeFock(qubit_op.num_qubits, num_orbitals, num_particles, qubit_mapping, two_qubit_reduction) iqft = Standard(n_ancillae) qpe = QPE(qubit_op, state_in, iqft, num_time_slices, n_ancillae, paulis_grouping='random', expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) backend = LegacySimulators.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=100, pass_manager=PassManager()) result_qpe = qpe.run(quantum_instance) print('The ground state energy as computed by QPE is: {}'.format(result_qpe['energy'])) molecule = 'H .0 .0 0; H .0 .0 {}'.format(distance) # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_qpe_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': { 'atom': molecule, 'basis': 'sto3g' }, 'operator': {'name': 'hamiltonian', 'transformation': 'full', 'qubit_mapping': 'parity'}, 'algorithm': { 'name': 'QPE', 'num_ancillae': 9, 'num_time_slices': 50, 'expansion_mode': 'suzuki', 'expansion_order': 2, }, 'initial_state': {'name': 'HartreeFock'}, 'backend': {'shots': 100} } qiskit_chemistry_ees_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': molecule, 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'transformation': 'full', 'qubit_mapping': 'parity'}, 'algorithm': { 'name': 'ExactEigensolver', } } result_qpe = QiskitChemistry().run(qiskit_chemistry_qpe_dict, backend=backend) result_ees = QiskitChemistry().run(qiskit_chemistry_ees_dict) print('The groundtruth total ground state energy is {}.'.format( result_ees['energy'] - result_ees['nuclear_repulsion_energy'] )) print('The total ground state energy as computed by QPE is {}.'.format( result_qpe['energy'] - result_qpe['nuclear_repulsion_energy'] )) print('In comparison, the Hartree-Fock ground state energy is {}.'.format( result_ees['hf_energy'] - result_ees['nuclear_repulsion_energy'] ))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure qiskit chemistry for the chemistry problem. qiskit_chemistry_dict = { 'problem': {'random_seed': 50}, 'driver': {'name': 'PYQUANTE'}, 'PYQUANTE': {'atoms': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'qubit_mapping': 'jordan_wigner', 'two_qubit_reduction': False}, 'algorithm': {'name': ''}, 'optimizer': {'name': 'COBYLA', 'maxiter': 10000 }, 'variational_form': {'name': 'SWAPRZ'}, 'initial_state': {'name': 'HartreeFock'} } molecule = 'H .0 .0 -{0}; H .0 .0 {0}' algorithms = ['VQE', 'ExactEigensolver'] start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 20 # Number of steps to increase by energies = np.empty([len(algorithms), steps+1]) hf_energies = np.empty(steps+1) distances = np.empty(steps+1) eval_counts = np.empty(steps+1) print('Processing step __', end='') for i in range(steps+1): print('\b\b{:2d}'.format(i), end='', flush=True) d = start + i*by/steps qiskit_chemistry_dict['PYQUANTE']['atoms'] = molecule.format(d/2) for j in range(len(algorithms)): qiskit_chemistry_dict['algorithm']['name'] = algorithms[j] solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[j][i] = result['energy'] hf_energies[i] = result['hf_energy'] if algorithms[j] == 'VQE': eval_counts[i] = result['algorithm_retvals']['eval_count'] distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print('VQE num evaluations:', eval_counts) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[j], label=algorithms[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 Ground State Energy') pylab.legend(loc='upper right') pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock') pylab.plot(distances, np.subtract(energies[0], energies[1]), label='VQE') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.yscale('log') pylab.title('Energy difference from ExactEigensolver') pylab.legend(loc='center right') pylab.plot(distances, eval_counts, '-o', color=[0.8500, 0.3250, 0.0980], label='VQE') pylab.xlabel('Interatomic distance') pylab.ylabel('Evaluations') pylab.title('VQE number of evaluations') pylab.legend(loc='upper left')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'driver': {'name': 'PYQUANTE'}, 'PYQUANTE': {'atoms': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'qubit_mapping': 'jordan_wigner', 'two_qubit_reduction': False}, 'algorithm': {'name': ''}, 'optimizer': {'name': 'COBYLA', 'maxiter': 10000 }, 'variational_form': {'name': 'UCCSD'}, 'initial_state': {'name': 'HartreeFock'} } molecule = 'H .0 .0 -{0}; H .0 .0 {0}' algorithms = ['VQE', 'ExactEigensolver'] start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 20 # Number of steps to increase by energies = np.empty([len(algorithms), steps+1]) hf_energies = np.empty(steps+1) distances = np.empty(steps+1) eval_counts = np.empty(steps+1) print('Processing step __', end='') for i in range(steps+1): print('\b\b{:2d}'.format(i), end='', flush=True) d = start + i*by/steps qiskit_chemistry_dict['PYQUANTE']['atoms'] = molecule.format(d/2) for j in range(len(algorithms)): qiskit_chemistry_dict['algorithm']['name'] = algorithms[j] solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[j][i] = result['energy'] hf_energies[i] = result['hf_energy'] if algorithms[j] == 'VQE': eval_counts[i] = result['algorithm_retvals']['eval_count'] distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print('VQE num evaluations:', eval_counts) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[j], label=algorithms[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 Ground State Energy') pylab.legend(loc='upper right') pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock') pylab.plot(distances, np.subtract(energies[0], energies[1]), label='VQE') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference from ExactEigensolver') pylab.legend(loc='upper left') pylab.plot(distances, eval_counts, '-o', color=[0.8500, 0.3250, 0.0980], label='VQE') pylab.xlabel('Interatomic distance') pylab.ylabel('Evaluations') pylab.title('VQE number of evaluations') pylab.legend(loc='upper left')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'problem': {'random_seed': 50}, 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': 'H .0 .0 -0.3625; H .0 .0 0.3625', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'qubit_mapping': 'jordan_wigner', 'two_qubit_reduction': False}, 'algorithm': {'name': 'ExactEigensolver'}, 'optimizer': {'name': 'COBYLA', 'maxiter': 10000 }, 'variational_form': {'name': 'RYRZ', 'depth': 3, 'entanglement': 'full'}, 'initial_state': {'name': 'ZERO'} } var_forms = ['RYRZ', 'RY'] entanglements = ['full', 'linear'] depths = [x for x in range(3, 11)] energies = np.empty([len(var_forms), len(entanglements), len(depths)]) hf_energy = None energy = None eval_counts = np.empty([len(var_forms), len(entanglements), len(depths)]) solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) hf_energy = result['hf_energy'] energy = result['energy'] print('Hartree-Fock energy:', hf_energy) print('FCI energy:', energy) qiskit_chemistry_dict['algorithm']['name'] = 'VQE' print('Processing step __', end='') for i, d in enumerate(depths): print('\b\b{:2d}'.format(i), end='', flush=True) qiskit_chemistry_dict['variational_form']['depth'] = d for j in range(len(entanglements)): qiskit_chemistry_dict['variational_form']['entanglement'] = entanglements[j] for k in range(len(var_forms)): qiskit_chemistry_dict['variational_form']['name'] = var_forms[k] solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[k][j][i] = result['energy'] eval_counts[k][j][i] = result['algorithm_retvals']['eval_count'] print(' --- complete') print('Depths: ', depths) print('Energies:', energies) print('Num evaluations:', eval_counts) for k in range(len(var_forms)): for j in range(len(entanglements)): pylab.plot(depths, energies[k][j]-energy, label=var_forms[k]+' + '+entanglements[j]) pylab.xlabel('Variational form depth') pylab.ylabel('Energy difference') pylab.yscale('log') pylab.title('H2 Ground State Energy Difference from Reference') pylab.legend(loc='upper right') for k in range(len(var_forms)): for j in range(len(entanglements)): pylab.plot(depths, eval_counts[k][j], '-o', label=var_forms[k]+' + '+entanglements[j]) pylab.xlabel('Variational form depth') pylab.ylabel('Evaluations') pylab.title('VQE number of evaluations') pylab.legend(loc='upper right')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'problem': {'random_seed': 50}, 'driver': {'name': 'PYQUANTE'}, 'PYQUANTE': {'atoms': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'qubit_mapping': 'parity', 'two_qubit_reduction': True}, 'algorithm': {'name': ''}, 'optimizer': {'name': 'COBYLA', 'maxiter': 10000 }, 'variational_form': {'name': 'RYRZ', 'depth': '5', 'entanglement': 'linear'} } molecule = 'H .0 .0 -{0}; H .0 .0 {0}' algorithms = [{'name': 'VQE'}, {'name': 'VQE'}, {'name': 'ExactEigensolver'}] titles= ['VQE Random Seed', 'VQE + Initial Point', 'ExactEigensolver'] start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 20 # Number of steps to increase by energies = np.empty([len(algorithms), steps+1]) hf_energies = np.empty(steps+1) distances = np.empty(steps+1) eval_counts = np.zeros([len(algorithms), steps+1], dtype=np.intp) print('Processing step __', end='') for i in range(steps+1): print('\b\b{:2d}'.format(i), end='', flush=True) d = start + i*by/steps qiskit_chemistry_dict['PYQUANTE']['atoms'] = molecule.format(d/2) for j in range(len(algorithms)): qiskit_chemistry_dict['algorithm'] = algorithms[j] solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[j][i] = result['energy'] hf_energies[i] = result['hf_energy'] if algorithms[j]['name'] == 'VQE': eval_counts[j][i] = result['algorithm_retvals']['eval_count'] if j == 1: algorithms[j]['initial_point'] = result['algorithm_retvals']['opt_params'] distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print('VQE num evaluations:', eval_counts) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[j], label=titles[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 Ground State Energy') pylab.legend(loc='upper right') for i in range(2): pylab.plot(distances, np.subtract(energies[i], energies[2]), label=titles[i]) pylab.plot(distances, np.subtract(hf_energies, energies[2]), label='Hartree-Fock') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference from ExactEigensolver') pylab.legend(loc='upper left') for i in range(2): pylab.plot(distances, eval_counts[i], '-o', label=titles[i]) pylab.xlabel('Interatomic distance') pylab.ylabel('Evaluations') pylab.title('VQE number of evaluations') pylab.legend(loc='center left')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'transformation': 'full', 'qubit_mapping': 'parity', 'two_qubit_reduction': True}, 'algorithm': {'name': 'VQE'}, 'optimizer': {'name': 'SPSA', 'max_trials': 350}, 'variational_form': {'name': 'RYRZ', 'depth': 3, 'entanglement': 'full'} } molecule = 'H .0 .0 -{0}; H .0 .0 {0}' algorithms = ['VQE', 'ExactEigensolver'] backends = [{'name': 'qasm_simulator', 'shots': 1024}, None ] start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 20 # Number of steps to increase by energies = np.empty([len(algorithms), steps+1]) hf_energies = np.empty(steps+1) distances = np.empty(steps+1) print('Processing step __', end='') for i in range(steps+1): print('\b\b{:2d}'.format(i), end='', flush=True) d = start + i*by/steps qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2) for j in range(len(algorithms)): qiskit_chemistry_dict['algorithm']['name'] = algorithms[j] if backends[j] is not None: qiskit_chemistry_dict['backend'] = backends[j] else: qiskit_chemistry_dict.pop('backend') solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[j][i] = result['energy'] hf_energies[i] = result['hf_energy'] distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[j], label=algorithms[j]) pylab.xlabel('Interatomic distance (Angstrom)') pylab.ylabel('Energy (Hartree)') pylab.title('H2 Ground State Energy') pylab.legend(loc='upper right') pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock') pylab.plot(distances, np.subtract(energies[0], energies[1]), label=algorithms[0]) pylab.xlabel('Interatomic distance (Angstrom)') pylab.ylabel('Energy (Hartree)') pylab.title('Energy difference from ExactEigensolver') pylab.legend(loc='upper left')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. # Note: In order to allow this to run reasonably quickly it takes advantage # of the ability to freeze core orbitals and remove unoccupied virtual # orbitals to reduce the size of the problem. The result without this # will be more accurate but it takes rather longer to run. # qiskit_chemistry_dict_eigen uses classical approach to produce the reference ground state energy. qiskit_chemistry_dict_eigen = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'algorithm': {'name': 'ExactEigensolver'}, 'operator': {'name':'hamiltonian','freeze_core': True, 'orbital_reduction': [-3, -2], 'qubit_mapping': 'parity', 'two_qubit_reduction': True}, } # qiskit_chemistry_dict_vqe uses quantum approach to evaluate the ground state energy. qiskit_chemistry_dict_vqe = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'algorithm': {'name': 'VQE', 'operator_mode': 'matrix'}, 'operator': {'name':'hamiltonian','freeze_core': True, 'orbital_reduction': [-3, -2], 'qubit_mapping': 'parity', 'two_qubit_reduction': True}, 'optimizer': {'name': 'COBYLA', 'maxiter': 20000}, 'variational_form': {'name': 'RYRZ', 'depth': 10}, 'backend': {'name': 'statevector_simulator'} } # tested molecular, LiH molecule = 'Li .0 .0 -{0}; H .0 .0 {0}' # choose one of configurations above for experiments qiskit_chemistry_dict = qiskit_chemistry_dict_eigen # configure distance between two atoms pts = [x * 0.1 for x in range(6, 20)] pts += [x * 0.25 for x in range(8, 16)] pts += [4.0] distances = np.empty(len(pts)) hf_energies = np.empty(len(pts)) energies = np.empty(len(pts)) dipoles = np.empty(len(pts)) print('Processing step __', end='') for i, d in enumerate(pts): print('\b\b{:2d}'.format(i), end='', flush=True) qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2) solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) distances[i] = d hf_energies[i] = result['hf_energy'] energies[i] = result['energy'] dipoles[i] = result['total_dipole_moment'] / 0.393430307 print(' --- complete') print('Distances: ', distances) print('HF Energies:', hf_energies) print('Energies:', energies) print('Dipole moments:', dipoles) pylab.plot(distances, hf_energies, label='HF') pylab.plot(distances, energies, label='Computed') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('LiH Ground State Energy') pylab.legend(loc='upper right') pylab.plot(distances, dipoles) pylab.xlabel('Interatomic distance') pylab.ylabel('Moment debye') pylab.title('LiH Dipole Moment')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'qubit_mapping': 'parity', 'two_qubit_reduction': True, 'freeze_core': True, 'orbital_reduction': [-3, -2]}, 'algorithm': {'name': ''}, 'optimizer': {'name': 'COBYLA', 'maxiter': 10000 }, 'variational_form': {'name': 'UCCSD'}, 'initial_state': {'name': 'HartreeFock'} } molecule = 'H .0 .0 -{0}; Li .0 .0 {0}' algorithms = ['VQE', 'ExactEigensolver'] pts = [x * 0.1 for x in range(6, 20)] pts += [x * 0.25 for x in range(8, 16)] pts += [4.0] energies = np.empty([len(algorithms), len(pts)]) hf_energies = np.empty(len(pts)) distances = np.empty(len(pts)) dipoles = np.empty([len(algorithms), len(pts)]) eval_counts = np.empty(len(pts)) print('Processing step __', end='') for i, d in enumerate(pts): print('\b\b{:2d}'.format(i), end='', flush=True) qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2) for j in range(len(algorithms)): qiskit_chemistry_dict['algorithm']['name'] = algorithms[j] solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[j][i] = result['energy'] hf_energies[i] = result['hf_energy'] dipoles[j][i] = result['total_dipole_moment'] / 0.393430307 if algorithms[j] == 'VQE': eval_counts[i] = result['algorithm_retvals']['eval_count'] distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print('VQE num evaluations:', eval_counts) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[j], label=algorithms[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('LiH Ground State Energy') pylab.legend(loc='upper right') pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock') pylab.plot(distances, np.subtract(energies[0], energies[1]), label='VQE') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference from ExactEigensolver') pylab.legend(loc='upper left') for j in reversed(range(len(algorithms))): pylab.plot(distances, dipoles[j], label=algorithms[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Moment in debye') pylab.title('LiH Dipole Moment') pylab.legend(loc='upper right') pylab.plot(distances, eval_counts, '-o', color=[0.8500, 0.3250, 0.0980], label='VQE') pylab.xlabel('Interatomic distance') pylab.ylabel('Evaluations') pylab.title('VQE number of evaluations') pylab.legend(loc='upper left')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import common packages import itertools import logging import numpy as np from qiskit import Aer from qiskit_aqua import Operator, set_aqua_logging, QuantumInstance from qiskit_aqua.algorithms.adaptive import VQE from qiskit_aqua.algorithms.classical import ExactEigensolver from qiskit_aqua.components.optimizers import COBYLA from qiskit_chemistry.drivers import PySCFDriver, UnitsType from qiskit_chemistry.core import Hamiltonian, TransformationType, QubitMappingType from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock # set_aqua_logging(logging.INFO) # using driver to get fermionic Hamiltonian driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True) algo_input = core.run(molecule) qubit_op = algo_input.qubit_op print("Originally requires {} qubits".format(qubit_op.num_qubits)) print(qubit_op) [symmetries, sq_paulis, cliffords, sq_list] = qubit_op.find_Z2_symmetries() print('Z2 symmetries found:') for symm in symmetries: print(symm.to_label()) print('single qubit operators found:') for sq in sq_paulis: print(sq.to_label()) print('cliffords found:') for clifford in cliffords: print(clifford.print_operators()) print('single-qubit list: {}'.format(sq_list)) tapered_ops = [] for coeff in itertools.product([1, -1], repeat=len(sq_list)): tapered_op = Operator.qubit_tapering(qubit_op, cliffords, sq_list, list(coeff)) tapered_ops.append((list(coeff), tapered_op)) print("Number of qubits of tapered qubit operator: {}".format(tapered_op.num_qubits)) ee = ExactEigensolver(qubit_op, k=1) result = core.process_algorithm_result(ee.run()) for line in result[0]: print(line) smallest_eig_value = 99999999999999 smallest_idx = -1 for idx in range(len(tapered_ops)): ee = ExactEigensolver(tapered_ops[idx][1], k=1) curr_value = ee.run()['energy'] if curr_value < smallest_eig_value: smallest_eig_value = curr_value smallest_idx = idx print("Lowest eigenvalue of the {}-th tapered operator (computed part) is {:.12f}".format(idx, curr_value)) the_tapered_op = tapered_ops[smallest_idx][1] the_coeff = tapered_ops[smallest_idx][0] print("The {}-th tapered operator matches original ground state energy, with corresponding symmetry sector of {}".format(smallest_idx, the_coeff)) # setup initial state init_state = HartreeFock(num_qubits=the_tapered_op.num_qubits, num_orbitals=core._molecule_info['num_orbitals'], qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction, num_particles=core._molecule_info['num_particles'], sq_list=sq_list) # setup variationl form var_form = UCCSD(num_qubits=the_tapered_op.num_qubits, depth=1, num_orbitals=core._molecule_info['num_orbitals'], num_particles=core._molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction, num_time_slices=1, cliffords=cliffords, sq_list=sq_list, tapering_values=the_coeff, symmetries=symmetries) # setup optimizer optimizer = COBYLA(maxiter=1000) # set vqe algo = VQE(the_tapered_op, var_form, optimizer, 'matrix') # setup backend backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend) algo_result = algo.run(quantum_instance) result = core.process_algorithm_result(algo_result) for line in result[0]: print(line) print("The parameters for UCCSD are:\n{}".format(algo_result['opt_params']))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'qubit_mapping': 'parity', 'two_qubit_reduction': True, 'freeze_core': True, 'orbital_reduction': []}, 'algorithm': {'name': ''}, 'optimizer': {'name': 'COBYLA', 'maxiter': 10000 }, 'variational_form': {'name': 'UCCSD'}, 'initial_state': {'name': 'HartreeFock'} } molecule = 'H .0 .0 -{0}; Na .0 .0 {0}' algorithms = ['VQE', 'ExactEigensolver'] pts = [x * 0.1 for x in range(10, 25)] pts += [x * 0.25 for x in range(10, 18)] pts += [4.5] energies = np.empty([len(algorithms), len(pts)]) hf_energies = np.empty(len(pts)) distances = np.empty(len(pts)) dipoles = np.empty([len(algorithms), len(pts)]) eval_counts = np.empty(len(pts)) print('Processing step __', end='') for i, d in enumerate(pts): print('\b\b{:2d}'.format(i), end='', flush=True) qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2) for j in range(len(algorithms)): qiskit_chemistry_dict['algorithm']['name'] = algorithms[j] solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[j][i] = result['energy'] hf_energies[i] = result['hf_energy'] dipoles[j][i] = result['total_dipole_moment'] / 0.393430307 if algorithms[j] == 'VQE': eval_counts[i] = result['algorithm_retvals']['eval_count'] distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print('Dipoles:', dipoles) print('VQE num evaluations:', eval_counts) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[j], label=algorithms[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('NaH Ground State Energy') pylab.legend(loc='upper right') pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock') pylab.plot(distances, np.subtract(energies[0], energies[1]), label='VQE') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference from ExactEigensolver') pylab.legend(loc='upper left') for j in reversed(range(len(algorithms))): pylab.plot(distances, dipoles[j], label=algorithms[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Moment in debye') pylab.title('NaH Dipole Moment') pylab.legend(loc='upper right') pylab.plot(distances, eval_counts, '-o', color=[0.8500, 0.3250, 0.0980], label='VQE') pylab.xlabel('Interatomic distance') pylab.ylabel('Evaluations') pylab.title('VQE number of evaluations') pylab.legend(loc='upper left')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit import Aer from qiskit.transpiler import PassManager from qiskit_aqua import Operator, QuantumInstance from qiskit_aqua.algorithms.adaptive import VQE from qiskit_aqua.algorithms.classical import ExactEigensolver from qiskit_aqua.components.optimizers import L_BFGS_B from qiskit_aqua.components.variational_forms import RY from qiskit_chemistry import FermionicOperator from qiskit_chemistry.drivers import PySCFDriver, UnitsType driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubitOp_jw = ferOp.mapping(map_type='JORDAN_WIGNER', threshold=0.00000001) qubitOp_jw.chop(10**-10) # Using exact eigensolver to get the smallest eigenvalue exact_eigensolver = ExactEigensolver(qubitOp_jw, k=1) ret = exact_eigensolver.run() # print(qubitOp_jw.print_operators()) print('The exact ground state energy is: {}'.format(ret['energy'])) print('The Hartree Fock Electron Energy is: {}'.format(molecule.hf_energy - molecule.nuclear_repulsion_energy)) # particle hole transformation newferOp, energy_shift = ferOp.particle_hole_transformation(num_particles=2) print('Energy shift is: {}'.format(energy_shift)) newqubitOp_jw = newferOp.mapping(map_type='JORDAN_WIGNER', threshold=0.00000001) newqubitOp_jw.chop(10**-10) exact_eigensolver = ExactEigensolver(newqubitOp_jw, k=1) ret = exact_eigensolver.run() # print(newqubitOp_jw.print_operators()) print('The exact ground state energy in PH basis is {}'.format(ret['energy'])) print('The exact ground state energy in PH basis is {} (with energy_shift)'.format(ret['energy'] - energy_shift)) # setup VQE # setup optimizer, use L_BFGS_B optimizer for example lbfgs = L_BFGS_B(maxfun=1000, factr=10, iprint=10) # setup variational form generator (generate trial circuits for VQE) var_form = RY(newqubitOp_jw.num_qubits, 5, entangler_map = {0: [1], 1:[2], 2:[3]}) # setup VQE with operator, variational form, and optimizer vqe_algorithm = VQE(newqubitOp_jw, var_form, lbfgs, 'matrix') backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, pass_manager=PassManager()) results = vqe_algorithm.run(quantum_instance) print("Minimum value: {}".format(results['eigvals'][0].real)) print("Minimum value: {}".format(results['eigvals'][0].real - energy_shift)) print("Parameters: {}".format(results['opt_params']))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit import Aer from qiskit.transpiler import PassManager from qiskit_aqua import Operator, QuantumInstance from qiskit_aqua.algorithms.adaptive import VQE from qiskit_aqua.algorithms.classical import ExactEigensolver from qiskit_aqua.components.optimizers import L_BFGS_B from qiskit_aqua.components.variational_forms import RY from qiskit_chemistry import FermionicOperator from qiskit_chemistry.drivers import PyQuanteDriver, UnitsType, BasisType # using driver to get fermionic Hamiltonian # PyQuante example driver = PyQuanteDriver(atoms='H .0 .0 .0; H .0 .0 0.735', units=UnitsType.ANGSTROM, charge=0, multiplicity=1, basis=BasisType.BSTO3G) molecule = driver.run() h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals # convert from fermionic hamiltonian to qubit hamiltonian ferOp = FermionicOperator(h1=h1, h2=h2) qubitOp_jw = ferOp.mapping(map_type='JORDAN_WIGNER', threshold=0.00000001) qubitOp_pa = ferOp.mapping(map_type='PARITY', threshold=0.00000001) qubitOp_bi = ferOp.mapping(map_type='BRAVYI_KITAEV', threshold=0.00000001) # print out qubit hamiltonian in Pauli terms and exact solution qubitOp_jw.to_matrix() qubitOp_jw.chop(10**-10) print(qubitOp_jw.print_operators()) # Using exact eigensolver to get the smallest eigenvalue exact_eigensolver = ExactEigensolver(qubitOp_jw, k=1) ret = exact_eigensolver.run() print('The exact ground state energy is: {}'.format(ret['energy'])) # setup VQE # setup optimizer, use L_BFGS_B optimizer for example lbfgs = L_BFGS_B(maxfun=1000, factr=10, iprint=10) # setup variational form generator (generate trial circuits for VQE) var_form = RY(qubitOp_jw.num_qubits, 5, entangler_map = {0: [1], 1:[2], 2:[3]}) # setup VQE with operator, variational form, and optimizer vqe_algorithm = VQE(qubitOp_jw, var_form, lbfgs, 'matrix') backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, pass_manager=PassManager()) results = vqe_algorithm.run(quantum_instance) print("Minimum value: {}".format(results['eigvals'][0])) print("Parameters: {}".format(results['opt_params']))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit import Aer from qiskit.transpiler import PassManager from qiskit_aqua import Operator, QuantumInstance from qiskit_aqua.algorithms.adaptive import VQE from qiskit_aqua.algorithms.classical import ExactEigensolver from qiskit_aqua.components.optimizers import L_BFGS_B from qiskit_aqua.components.variational_forms import RYRZ from qiskit_chemistry import FermionicOperator from qiskit_chemistry.drivers import PySCFDriver, UnitsType # using driver to get fermionic Hamiltonian # PySCF example driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() # get fermionic operator and mapping to qubit operator ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubitOp = ferOp.mapping(map_type='JORDAN_WIGNER', threshold=0.00000001) qubitOp.to_matrix() qubitOp.chop(10**-10) # If you do not install any driver and would like to start with a random Hamiltonian # SIZE=4 # matrix = np.random.random((SIZE,SIZE)) # qubitOp = Operator(matrix=matrix) # Using exact eigensolver to get the smallest eigenvalue exact_eigensolver = ExactEigensolver(qubitOp, k=1) ret = exact_eigensolver.run() print('The exact ground state energy is: {}'.format(ret['eigvals'][0].real)) # setup VQE # setup optimizer, use L_BFGS_B optimizer for example lbfgs = L_BFGS_B(maxfun=1000, factr=10, iprint=10) # setup variational form generator (generate trial circuits for VQE) var_form = RYRZ(qubitOp.num_qubits, 5, entangler_map = {0: [1], 1:[2], 2:[3]}) # setup VQE with operator, variational form, and optimizer vqe_algorithm = VQE(qubitOp, var_form, lbfgs, 'matrix') backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, pass_manager=PassManager()) results = vqe_algorithm.run(quantum_instance) print("Minimum value: {}".format(results['eigvals'][0].real)) print("Parameters: {}".format(results['opt_params']))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# numpy, for random number generation import numpy as np # Qiskit, for transpiler-related functions, the IBMQ provider, and the Aer simulator from qiskit import IBMQ, Aer, QuantumRegister from qiskit.transpiler import transpile, transpile_dag, PassManager from qiskit.converters import circuit_to_dag, dag_to_circuit # pytket, for optimization import pytket from pytket.qiskit import TketPass # Qiskit Aqua, for chemistry from qiskit_chemistry.drivers import PySCFDriver, UnitsType from qiskit_chemistry import FermionicOperator from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD IBMQ.load_accounts() # Choose a particular bond length # NOTE: Units are in Angstroms bond_length = 0.7 # Set up molecule # base_molecule_str = 'Li .0 .0 .0; H .0 .0 {}' base_molecule_str = 'H .0 .0 .0; H .0 .0 {}' # Specify other molecular properties charge = 0 spin = 0 basis = 'sto3g' # Using driver to get fermionic Hamiltonian # PySCF example driver = PySCFDriver(atom=base_molecule_str.format(bond_length), unit=UnitsType.ANGSTROM, charge=charge, spin=spin, basis=basis) molecule = driver.run() print("Molecular repulsion energy: ", molecule.nuclear_repulsion_energy) n_qubits = molecule.one_body_integrals.shape[0] n_electrons = molecule.num_alpha + molecule.num_beta - molecule.molecular_charge # get fermionic operator and mapping to qubit operator ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubitOp = ferOp.mapping(map_type='JORDAN_WIGNER', threshold=0.00000001) qubitOp.chop(10**-10) # Instantiate the initial state as a Hartree-Fock state initial_hf = HartreeFock(num_qubits=n_qubits, num_orbitals=n_qubits, qubit_mapping='jordan_wigner', two_qubit_reduction=False, num_particles= n_electrons) # Create the variational form var_form = UCCSD(num_qubits=n_qubits, num_orbitals=n_qubits, num_particles=n_electrons, depth=1, initial_state=initial_hf, qubit_mapping='jordan_wigner') # How many qubits do we need? print('Number of qubits: {0}'.format(n_qubits)) # Query the variational form for the number of parameters, and the parameter bounds. var_form.num_parameters, var_form.parameter_bounds[0] # Instantiate a concrete instance of the VQE ansatz by setting all the parameters to the # arbitrarily-chosen value of 0. var_circ = var_form.construct_circuit(np.zeros(var_form.num_parameters)) # Use Terra to convert the circuit to its directed, acyclic graph (DAG) representation. var_circ_dag = circuit_to_dag(var_circ) # The .properties() method of the DAG to get circuit properties. var_circ_dag.properties() # Grab an Aer backend aer_backend = Aer.get_backend('qasm_simulator') # Choose a random set of parameters seed = 0 np.random.seed(seed) params = np.random.uniform(low=-3.1, high=3.1, size=var_form.num_parameters) # Construct a random instance of the variational circuit var_circuit = var_form.construct_circuit(params) # Turn the circuit into a DAG var_dag = circuit_to_dag(var_circuit) var_dag.properties() # Create a Terra PassManager object tk_pass_manager = PassManager() # Set up the TketPass tk_pass = TketPass(aer_backend) # Add the TketPass to the PassManager tk_pass_manager.append(tk_pass) var_dag_transpiled = transpile_dag(var_dag, pass_manager=tk_pass_manager) var_dag_transpiled.properties() # Grab only backends that have at least 12 qubits IBMQ.backends(filters=lambda x: x.configuration().n_qubits >= 12) real_backend = IBMQ.get_backend('ibmq_16_melbourne') # Create a Terra PassManager object tk_pass_manager = PassManager() # Set up the TketPass tk_pass = TketPass(real_backend) # Add the TketPass to the PassManager tk_pass_manager.append(tk_pass) blank_qubits = QuantumRegister(len(real_backend.properties().qubits) - var_dag.width()) var_dag.add_qreg(blank_qubits) var_dag_transpiled = transpile_dag(var_dag, pass_manager=tk_pass_manager) var_dag_transpiled.properties() transpile_dag(var_dag, coupling_map=real_backend.configuration().coupling_map).properties() # Code imports # From Aqua, we need from qiskit_aqua import QuantumInstance from qiskit_aqua.algorithms.adaptive import VQE from qiskit_aqua.components.optimizers import L_BFGS_B # From pytket, we need QSE functions from pytket.chemistry import QseMatrices, QSE backend = Aer.get_backend('statevector_simulator') pass_manager = PassManager() tk_pass = TketPass(backend) pass_manager.append(tk_pass) quantum_instance = QuantumInstance(backend, pass_manager=pass_manager) # Temporary code for Aer on Macbook import os os.environ['KMP_DUPLICATE_LIB_OK']='True' # Set initial values of parameters number_amplitudes = len(var_form._single_excitations)+ len(var_form._double_excitations) amplitudes_0 = [] for i in range(number_amplitudes): amplitudes_0.append(0.00001) optimizer = L_BFGS_B() optimizer.set_options(maxfun=1000, factr=10, iprint=10) # setup VQE with operator, variation form, and optimzer vqe_algorithm = VQE(operator=qubitOp, operator_mode='matrix', var_form=var_form, optimizer=optimizer, initial_point=amplitudes_0) results = vqe_algorithm.run(quantum_instance) eigval = results['eigvals'][0] gs_energy = eigval.real + molecule.nuclear_repulsion_energy print("GS Minimum value: {}".format(gs_energy)) print("GS Parameters: {}".format(results['opt_params'])) # store ground state amplitudes for subsequent steps opti_amplitudes = results['opt_params'] qubitOp = ferOp.mapping(map_type='JORDAN_WIGNER', threshold=0.00000001) n_qubits = qubitOp.num_qubits qubitOp.chop(10**-10) # Use matrix term helper class matrix_terms = QseMatrices(qubitOp, n_qubits) # Instantiate an instance of the QSE algorithm qse_algorithm = QSE(matrix_terms, 'matrix', var_form, opt_init_point=opti_amplitudes) # Run the algorithm energies = qse_algorithm.run(quantum_instance)['eigvals'] # The excited state energies are the energies from above, # plus the nuclear repulsion energy. print("Excited State Energies: ", energies+molecule.nuclear_repulsion_energy)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit import BasicAer from qiskit.transpiler import PassManager from qiskit.aqua import QuantumInstance from qiskit.aqua.operators import MatrixOperator, op_converter from qiskit.aqua.algorithms import EOH from qiskit.aqua.components.initial_states import Custom num_qubits = 2 temp = np.random.random((2 ** num_qubits, 2 ** num_qubits)) qubit_op = op_converter.to_weighted_pauli_operator(MatrixOperator(matrix=temp + temp.T)) temp = np.random.random((2 ** num_qubits, 2 ** num_qubits)) evo_op = op_converter.to_weighted_pauli_operator(MatrixOperator(matrix=temp + temp.T)) evo_time = 1 num_time_slices = 1 state_in = Custom(qubit_op.num_qubits, state='uniform') eoh = EOH(qubit_op, state_in, evo_op, evo_time=evo_time, num_time_slices=num_time_slices) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) ret = eoh.run(quantum_instance) print('The result is\n{}'.format(ret))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from scipy.linalg import expm from qiskit import BasicAer from qiskit import execute as q_execute from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import state_fidelity from qiskit.aqua.operators import MatrixOperator, op_converter from qiskit.aqua.components.initial_states import Custom num_qubits = 2 evo_time = 1 temp = np.random.random((2 ** num_qubits, 2 ** num_qubits)) h1 = temp + temp.T qubitOp = MatrixOperator(matrix=h1) state_in = Custom(num_qubits, state='random') state_in_vec = state_in.construct_circuit('vector') groundtruth = expm(-1.j * h1 * evo_time) @ state_in_vec print('The directly computed groundtruth evolution result state is\n{}.'.format(groundtruth)) groundtruth_evolution = qubitOp.evolve(state_in_vec, evo_time, num_time_slices=0) print('The groundtruth evolution result as computed by the Dynamics algorithm is\n{}.'.format(groundtruth_evolution)) np.testing.assert_allclose(groundtruth_evolution, groundtruth) qubit_op = op_converter.to_weighted_pauli_operator(qubitOp) quantum_registers = QuantumRegister(qubit_op.num_qubits) circuit = state_in.construct_circuit('circuit', quantum_registers) circuit += qubit_op.evolve( None, evo_time, num_time_slices=1, quantum_registers=quantum_registers, expansion_mode='suzuki', expansion_order=3 ) circuit.draw(output='mpl') backend = BasicAer.get_backend('statevector_simulator') job = q_execute(circuit, backend) circuit_execution_result = np.asarray(job.result().get_statevector(circuit)) print('The evolution result state from executing the Dynamics circuit is\n{}.'.format(circuit_execution_result)) print('Fidelity between the groundtruth and the circuit result states is {}.'.format( state_fidelity(groundtruth, circuit_execution_result) ))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=4 max_qubits=15 #reference files are upto 12 Qubits only skip_qubits=2 max_circuits=3 num_shots=4092 gate_counts_plots = True Noise_Inclusion = False saveplots = False Memory_utilization_plot = True Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute from qiskit.opflow import PauliTrotterEvolution, Suzuki from qiskit.opflow.primitive_ops import PauliSumOp import time,os,json import matplotlib.pyplot as plt # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) # Benchmark Name benchmark_name = "VQE Simulation" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved circuits for display QC_ = None Hf_ = None CO_ = None ################### Circuit Definition ####################################### # Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz # param: n_spin_orbs - The number of spin orbitals. # return: return a Qiskit circuit for this VQE ansatz def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1): # number of alpha spin orbitals norb_a = int(n_spin_orbs / 2) # construct the Hamiltonian qubit_op = ReadHamiltonian(n_spin_orbs) # allocate qubits num_qubits = n_spin_orbs qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"vqe-ansatz({method})-{num_qubits}-{circuit_id}") # initialize the HF state Hf = HartreeFock(num_qubits, na, nb) qc.append(Hf, qr) # form the list of single and double excitations excitationList = [] for occ_a in range(na): for vir_a in range(na, norb_a): excitationList.append((occ_a, vir_a)) for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_b, vir_b)) for occ_a in range(na): for vir_a in range(na, norb_a): for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_a, vir_a, occ_b, vir_b)) # get cluster operators in Paulis pauli_list = readPauliExcitation(n_spin_orbs, circuit_id) # loop over the Pauli operators for index, PauliOp in enumerate(pauli_list): # get circuit for exp(-iP) cluster_qc = ClusterOperatorCircuit(PauliOp, excitationList[index]) # add to ansatz qc.append(cluster_qc, [i for i in range(cluster_qc.num_qubits)]) # method 1, only compute the last term in the Hamiltonian if method == 1: # last term in Hamiltonian qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits) # return the circuit return qc_with_mea # now we need to add the measurement parts to the circuit # circuit list qc_list = [] diag = [] off_diag = [] global normalization normalization = 0.0 # add the first non-identity term identity_qc = qc.copy() identity_qc.measure_all() qc_list.append(identity_qc) # add to circuit list diag.append(qubit_op[1]) normalization += abs(qubit_op[1].coeffs[0]) # add to normalization factor diag_coeff = abs(qubit_op[1].coeffs[0]) # add to coefficients of diagonal terms # loop over rest of terms for index, p in enumerate(qubit_op[2:]): # get the circuit with expectation measurements qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits) # accumulate normalization normalization += abs(p.coeffs[0]) # add to circuit list if non-diagonal if not is_diag: qc_list.append(qc_with_mea) else: diag_coeff += abs(p.coeffs[0]) # diagonal term if is_diag: diag.append(p) # off-diagonal term else: off_diag.append(p) # modify the name of diagonal circuit qc_list[0].name = qubit_op[1].primitive.to_list()[0][0] + " " + str(np.real(diag_coeff)) normalization /= len(qc_list) return qc_list # Function that constructs the circuit for a given cluster operator def ClusterOperatorCircuit(pauli_op, excitationIndex): # compute exp(-iP) exp_ip = pauli_op.exp_i() # Trotter approximation qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip) # convert to circuit qc = qc_op.to_circuit(); qc.name = f'Cluster Op {excitationIndex}' global CO_ if CO_ == None or qc.num_qubits <= 4: if qc.num_qubits < 7: CO_ = qc # return this circuit return qc # Function that adds expectation measurements to the raw circuits def ExpectationCircuit(qc, pauli, nqubit, method=2): # copy the unrotated circuit raw_qc = qc.copy() # whether this term is diagonal is_diag = True # primitive Pauli string PauliString = pauli.primitive.to_list()[0][0] # coefficient coeff = pauli.coeffs[0] # basis rotation for i, p in enumerate(PauliString): target_qubit = nqubit - i - 1 if (p == "X"): is_diag = False raw_qc.h(target_qubit) elif (p == "Y"): raw_qc.sdg(target_qubit) raw_qc.h(target_qubit) is_diag = False # perform measurements raw_qc.measure_all() # name of this circuit raw_qc.name = PauliString + " " + str(np.real(coeff)) # save circuit global QC_ if QC_ == None or nqubit <= 4: if nqubit < 7: QC_ = raw_qc return raw_qc, is_diag # Function that implements the Hartree-Fock state def HartreeFock(norb, na, nb): # initialize the quantum circuit qc = QuantumCircuit(norb, name="Hf") # alpha electrons for ia in range(na): qc.x(ia) # beta electrons for ib in range(nb): qc.x(ib+int(norb/2)) # Save smaller circuit global Hf_ if Hf_ == None or norb <= 4: if norb < 7: Hf_ = qc # return the circuit return qc ################ Helper Functions # Function that converts a list of single and double excitation operators to Pauli operators def readPauliExcitation(norb, circuit_id=0): # load pre-computed data filename = os.path.join(f'ansatzes/{norb}_qubit_{circuit_id}.txt') with open(filename) as f: data = f.read() ansatz_dict = json.loads(data) # initialize Pauli list pauli_list = [] # current coefficients cur_coeff = 1e5 # current Pauli list cur_list = [] # loop over excitations for ext in ansatz_dict: if cur_coeff > 1e4: cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4: pauli_list.append(PauliSumOp.from_list(cur_list)) cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] else: cur_list.append((ext, ansatz_dict[ext])) # add the last term pauli_list.append(PauliSumOp.from_list(cur_list)) # return Pauli list return pauli_list # Get the Hamiltonian by reading in pre-computed file def ReadHamiltonian(nqubit): # load pre-computed data filename = os.path.join(f'Hamiltonians/{nqubit}_qubit.txt') with open(filename) as f: data = f.read() ham_dict = json.loads(data) # pauli list pauli_list = [] for p in ham_dict: pauli_list.append( (p, ham_dict[p]) ) # build Hamiltonian ham = PauliSumOp.from_list(pauli_list) # return Hamiltonian return ham # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def analyzer(qc,references,num_qubits): # total circuit name (pauli string + coefficient) total_name = qc.name # pauli string pauli_string = total_name.split()[0] # get the correct measurement if (len(total_name.split()) == 2): correct_dist = references[pauli_string] else: circuit_id = int(total_name.split()[2]) correct_dist = references[f"Qubits - {num_qubits} - {circuit_id}"] return correct_dist,total_name # Max qubits must be 12 since the referenced files only go to 12 qubits MAX_QUBITS = 12 method = 1 def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=2, max_circuits=max_circuits, num_shots=num_shots): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() max_qubits = max(max_qubits, min_qubits) # max must be >= min # validate parameters (smallest circuit is 4 qubits and largest is 10 qubits) max_qubits = min(max_qubits, MAX_QUBITS) min_qubits = min(max(4, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) if method == 2: max_circuits = 1 if max_qubits < 4: print(f"Max number of qubits {max_qubits} is too low to run method {method} of VQE algorithm") return global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for input_size in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # determine the number of circuits to execute for this group num_circuits = min(3, max_circuits) num_qubits = input_size fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # decides number of electrons na = int(num_qubits/4) nb = int(num_qubits/4) # random seed np.random.seed(0) numckts.append(num_circuits) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() # circuit list qc_list = [] # Method 1 (default) if method == 1: # loop over circuits for circuit_id in range(num_circuits): # construct circuit qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method) qc_single.name = qc_single.name + " " + str(circuit_id) # add to list qc_list.append(qc_single) # method 2 elif method == 2: # construct all circuits qc_list = VQEEnergy(num_qubits, na, nb, 0, method) print(qc_list) print(f"************\nExecuting [{len(qc_list)}] circuits with num_qubits = {num_qubits}") for qc in qc_list: print("*********************************************") #print(f"qc of {qc} qubits for qc_list value: {qc_list}") # get circuit id if method == 1: circuit_id = qc.name.split()[2] else: circuit_id = qc.name.split()[0] #creation time creation_time = time.time() - ts creation_times.append(creation_time) #print(qc) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value print("operations: ",operations) algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() # load pre-computed data if len(qc.name.split()) == 2: filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit.json') with open(filename) as f: references = json.load(f) else: filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit_method2.json') with open(filename) as f: references = json.load(f) #Correct distribution to compare with counts correct_dist,total_name = analyzer(qc,references,num_qubits) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist) print(fidelity_dict) # modify fidelity based on the coefficient if (len(total_name.split()) == 2): fidelity_dict *= ( abs(float(total_name.split()[1])) / normalization ) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nHartree Fock Generator 'Hf' ="); print(Hf_ if Hf_ != None else " ... too large!") print("\nCluster Operator Example 'Cluster Op' ="); print(CO_ if CO_ != None else " ... too large!") return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit import BasicAer from qiskit.transpiler import PassManager from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver, IQPE from qiskit.aqua.operators import WeightedPauliOperator from qiskit.circuit.library import TwoLocal from qiskit.aqua.components.optimizers import SPSA from qiskit.aqua.components.initial_states.var_form_based import VarFormBased pauli_dict = { 'paulis': [{"coeff": {"imag": 0.0, "real": -1.052373245772859}, "label": "II"}, {"coeff": {"imag": 0.0, "real": 0.39793742484318045}, "label": "IZ"}, {"coeff": {"imag": 0.0, "real": -0.39793742484318045}, "label": "ZI"}, {"coeff": {"imag": 0.0, "real": -0.01128010425623538}, "label": "ZZ"}, {"coeff": {"imag": 0.0, "real": 0.18093119978423156}, "label": "XX"} ] } qubit_op = WeightedPauliOperator.from_dict(pauli_dict) result_reference = NumPyMinimumEigensolver(qubit_op).run() print('The reference ground energy level is {}.'.format(result_reference.eigenvalue.real)) random_seed = 0 np.random.seed(random_seed) backend = BasicAer.get_backend('qasm_simulator') var_form_depth = 3 var_form = TwoLocal(qubit_op.num_qubits, ['ry', 'rz'], 'cz', reps=var_form_depth) spsa_max_trials=10 optimizer = SPSA(max_trials=spsa_max_trials) vqe = VQE(qubit_op, var_form, optimizer) quantum_instance = QuantumInstance(backend) result_vqe = vqe.run(quantum_instance) print('VQE estimated the ground energy to be {}.'.format(result_vqe.eigenvalue.real)) state_in = VarFormBased(var_form, result_vqe.optimal_point) num_time_slices = 1 num_iterations = 6 iqpe = IQPE(qubit_op, state_in, num_time_slices, num_iterations, expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) quantum_instance = QuantumInstance(backend, shots=100, seed_simulator=random_seed, seed_transpiler=random_seed) result_iqpe = iqpe.run(quantum_instance) print("Continuing with VQE's result, IQPE estimated the ground energy to be {}.".format( result_iqpe.eigenvalue.real))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit import Aer from qiskit_aqua import run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import clique from qiskit_aqua.algorithms import ExactEigensolver K = 3 # K means the size of the clique np.random.seed(100) num_nodes = 5 w = clique.random_graph(num_nodes, edge_prob=0.8, weight_range=10) print(w) def brute_force(): # brute-force way: try every possible assignment! def bitfield(n, L): result = np.binary_repr(n, L) return [int(digit) for digit in result] L = num_nodes # length of the bitstring that represents the assignment max = 2**L has_sol = False for i in range(max): cur = bitfield(i, L) cur_v = clique.satisfy_or_not(np.array(cur), w, K) if cur_v: has_sol = True break return has_sol, cur has_sol, sol = brute_force() if has_sol: print("solution is ", sol) else: print("no solution found for K=", K) qubit_op, offset = clique.get_clique_qubitops(w, K) algo_input = EnergyInput(qubit_op) params = { 'problem': {'name': 'ising'}, 'algorithm': {'name': 'ExactEigensolver'} } result = run_algorithm(params, algo_input) x = clique.sample_most_likely(len(w), result['eigvecs'][0]) ising_sol = clique.get_graph_solution(x) if clique.satisfy_or_not(ising_sol, w, K): print("solution is", ising_sol) else: print("no solution found for K=", K) algo = ExactEigensolver(algo_input.qubit_op, k=1, aux_operators=[]) result = algo.run() x = clique.sample_most_likely(len(w), result['eigvecs'][0]) ising_sol = clique.get_graph_solution(x) if clique.satisfy_or_not(ising_sol, w, K): print("solution is", ising_sol) else: print("no solution found for K=", K) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'COBYLA' } var_form_cfg = { 'name': 'RY', 'depth': 5, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising', 'random_seed': 10598}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('statevector_simulator') result = run_algorithm(params, algo_input, backend=backend) x = clique.sample_most_likely(len(w), result['eigvecs'][0]) ising_sol = clique.get_graph_solution(x) if clique.satisfy_or_not(ising_sol, w, K): print("solution is", ising_sol) else: print("no solution found for K=", K)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import json from qiskit import Aer from qiskit_aqua import run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import exactcover from qiskit_aqua.algorithms import ExactEigensolver input_file = 'sample.exactcover' with open(input_file) as f: list_of_subsets = json.load(f) print(list_of_subsets) qubitOp, offset = exactcover.get_exactcover_qubitops(list_of_subsets) algo_input = EnergyInput(qubitOp) def brute_force(): # brute-force way: try every possible assignment! has_sol = False def bitfield(n, L): result = np.binary_repr(n, L) return [int(digit) for digit in result] # [2:] to chop off the "0b" part L = len(list_of_subsets) max = 2**L for i in range(max): cur = bitfield(i, L) cur_v = exactcover.check_solution_satisfiability(cur, list_of_subsets) if cur_v: has_sol = True break return has_sol, cur has_sol, cur = brute_force() if has_sol: print("solution is", cur) else: print("no solution is found") params = { 'problem': {'name': 'ising'}, 'algorithm': {'name': 'ExactEigensolver'} } result = run_algorithm(params, algo_input) x = exactcover.sample_most_likely(len(list_of_subsets), result['eigvecs'][0]) ising_sol = exactcover.get_solution(x) np.testing.assert_array_equal(ising_sol, [0, 1, 1, 0]) if exactcover.check_solution_satisfiability(ising_sol, list_of_subsets): print("solution is", ising_sol) else: print("no solution is found") algo = ExactEigensolver(algo_input.qubit_op, k=1, aux_operators=[]) result = algo.run() x = exactcover.sample_most_likely(len(list_of_subsets), result['eigvecs'][0]) ising_sol = exactcover.get_solution(x) np.testing.assert_array_equal(ising_sol, [0, 1, 1, 0]) if exactcover.check_solution_satisfiability(ising_sol, list_of_subsets): print("solution is", ising_sol) else: print("no solution is found") algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'COBYLA' } var_form_cfg = { 'name': 'RYRZ', 'depth': 5 } params = { 'problem': {'name': 'ising', 'random_seed': 10598}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('statevector_simulator') result = run_algorithm(params, algo_input, backend=backend) x = exactcover.sample_most_likely(len(list_of_subsets), result['eigvecs'][0]) ising_sol = exactcover.get_solution(x) if exactcover.check_solution_satisfiability(ising_sol, list_of_subsets): print("solution is", ising_sol) else: print("no solution is found")
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit import Aer from qiskit_aqua import run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import graphpartition from qiskit_aqua.algorithms import ExactEigensolver np.random.seed(100) num_nodes = 4 w = graphpartition.random_graph(num_nodes, edge_prob=0.8, weight_range=10) print(w) def brute_force(): # use the brute-force way to generate the oracle def bitfield(n, L): result = np.binary_repr(n, L) return [int(digit) for digit in result] # [2:] to chop off the "0b" part L = num_nodes max = 2**L minimal_v = np.inf for i in range(max): cur = bitfield(i, L) how_many_nonzero = np.count_nonzero(cur) if how_many_nonzero * 2 != L: # not balanced continue cur_v = graphpartition.objective_value(np.array(cur), w) if cur_v < minimal_v: minimal_v = cur_v return minimal_v sol = brute_force() print("objective value computed by the brute-force method is", sol) qubit_op, offset = graphpartition.get_graphpartition_qubitops(w) algo_input = EnergyInput(qubit_op) params = { 'problem': {'name': 'ising'}, 'algorithm': {'name': 'ExactEigensolver'} } result = run_algorithm(params, algo_input) x = graphpartition.sample_most_likely(result['eigvecs'][0]) # check against the oracle ising_sol = graphpartition.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [0, 1, 0, 1]) print("objective value computed by ExactEigensolver is", graphpartition.objective_value(x, w)) algo = ExactEigensolver(algo_input.qubit_op, k=1, aux_operators=[]) result = algo.run() x = graphpartition.sample_most_likely(result['eigvecs'][0]) # check against the oracle ising_sol = graphpartition.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [0, 1, 0, 1]) print("objective value computed by the ExactEigensolver is", graphpartition.objective_value(x, w)) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'SPSA', 'max_trials': 300 } var_form_cfg = { 'name': 'RY', 'depth': 5, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising', 'random_seed': 10598}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('statevector_simulator') result = run_algorithm(params, algo_input, backend=backend) x = graphpartition.sample_most_likely(result['eigvecs'][0]) # check against the oracle ising_sol = graphpartition.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [1, 0, 0, 1]) print("objective value computed by VQE is", graphpartition.objective_value(x, w))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import networkx as nx import timeit from qiskit import Aer from qiskit.circuit.library import TwoLocal from qiskit_optimization.applications import Maxcut from qiskit.algorithms import VQE, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import SPSA from qiskit.utils import algorithm_globals, QuantumInstance from qiskit_optimization.algorithms import MinimumEigenOptimizer # Generating a graph of 6 nodes n = 6 # Number of nodes in graph G = nx.Graph() G.add_nodes_from(np.arange(0, n, 1)) elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (1, 3, 1.0), (2, 4, 1.0), (3, 5, 1.0), (4, 5, 1.0)] # tuple is (i,j,weight) where (i,j) is the edge G.add_weighted_edges_from(elist) colors = ["y" for node in G.nodes()] pos = nx.spring_layout(G) def draw_graph(G, colors, pos): default_axes = plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=0.6, ax=default_axes, pos=pos) edge_labels = nx.get_edge_attributes(G, "weight") nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels) draw_graph(G, colors, pos) # Computing the weight matrix from the random graph w = np.zeros([n, n]) for i in range(n): for j in range(n): temp = G.get_edge_data(i, j, default=0) if temp != 0: w[i, j] = temp["weight"] print(w) def brute(): max_cost_brute = 0 for b in range(2**n): x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))] # create reverse of binary combinations from 0 to 2**n to create every possible set cost = 0 for i in range(n): for j in range(n): cost = cost + w[i, j] * x[i] * (1 - x[j]) if cost > max_cost_brute: max_cost_brute = cost xmax_brute = x max_cost_brute = 0 for b in range(2**n): x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))] # create reverse of binary combinations from 0 to 2**n to create every possible set cost = 0 for i in range(n): for j in range(n): cost = cost + w[i, j] * x[i] * (1 - x[j]) if cost > max_cost_brute: max_cost_brute = cost xmax_brute = x print("case = " + str(x) + " cost = " + str(cost)) colors = ["m" if xmax_brute[i] == 0 else "c" for i in range(n)] draw_graph(G, colors, pos) print("\nBest solution = " + str(xmax_brute) + " with cost = " + str(max_cost_brute)) time = timeit.timeit(brute, number = 1) print(f"\nTime taken for brute force: {time}") max_cut = Maxcut(w) qp = max_cut.to_quadratic_program() print(qp.export_as_lp_string()) qubitOp, offset = qp.to_ising() print("Offset:", offset) print("Ising Hamiltonian:") print(str(qubitOp)) # solving Quadratic Program using exact classical eigensolver exact = MinimumEigenOptimizer(NumPyMinimumEigensolver()) def classical_eigen(): result = exact.solve(qp) result = exact.solve(qp) print(result) time = timeit.timeit(classical_eigen, number = 1) print(f"\nTime taken for exact classical eigensolver force: {time}") # Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector ee = NumPyMinimumEigensolver() result = ee.compute_minimum_eigenvalue(qubitOp) x = max_cut.sample_most_likely(result.eigenstate) print("energy:", result.eigenvalue.real) print("max-cut objective:", result.eigenvalue.real + offset) print("solution:", x) print("solution objective:", qp.objective.evaluate(x)) colors = ["m" if x[i] == 0 else "c" for i in range(n)] draw_graph(G, colors, pos) algorithm_globals.random_seed = 99 seed = 1010 backend = Aer.get_backend("aer_simulator_statevector") quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed) # construct VQE spsa = SPSA(maxiter=300) ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear") vqe = VQE(ry, optimizer=spsa, quantum_instance=quantum_instance) # run VQE # def vqe_solve(): # result = vqe.compute_minimum_eigenvalue(qubitOp) # time = timeit.timeit(vqe_solve, number = 1) result = vqe.compute_minimum_eigenvalue(qubitOp) # print results x = max_cut.sample_most_likely(result.eigenstate) print("energy:", result.eigenvalue.real) print("time:", result.optimizer_time) print("max-cut objective:", result.eigenvalue.real + offset) print("solution:", x) print("solution objective:", qp.objective.evaluate(x)) # print(f"\nTime taken for VQE: {time}") # plot results colors = ["m" if x[i] == 0 else "c" for i in range(n)] draw_graph(G, colors, pos) # create minimum eigen optimizer based on VQE vqe_optimizer = MinimumEigenOptimizer(vqe) # solve quadratic program result = vqe_optimizer.solve(qp) print(result) colors = ["m" if result.x[i] == 0 else "c" for i in range(n)] draw_graph(G, colors, pos)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit_aqua import Operator, run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import partition from qiskit import Aer from qiskit_aqua.algorithms.classical.cplex.cplex_ising import CPLEX_Ising number_list = partition.read_numbers_from_file('sample.partition') qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input = EnergyInput(qubitOp) print(number_list) if True: np.random.seed(8123179) number_list = partition.random_number_list(5, weight_range=25) qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input.qubit_op = qubitOp print(number_list) to_be_tested_algos = ['ExactEigensolver', 'CPLEX.Ising', 'VQE'] print(to_be_tested_algos) algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) cplex_installed = True try: CPLEX_Ising.check_pluggable_valid() except Exception as e: cplex_installed = False if cplex_installed: algorithm_cfg = { 'name': 'CPLEX.Ising', 'display': 0 } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params, algo_input) x_dict = result['x_sol'] print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) x = np.array([x_dict[i] for i in sorted(x_dict.keys())]) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'L_BFGS_B', 'maxfun': 6000 } var_form_cfg = { 'name': 'RYRZ', 'depth': 3, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('statevector_simulator') result = run_algorithm(params, algo_input, backend=backend) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import json from qiskit import Aer from qiskit_aqua import run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import setpacking from qiskit_aqua.algorithms import ExactEigensolver input_file = 'sample.setpacking' with open(input_file) as f: list_of_subsets = json.load(f) print(list_of_subsets) qubitOp, offset = setpacking.get_setpacking_qubitops(list_of_subsets) algo_input = EnergyInput(qubitOp) def brute_force(): # brute-force way: try every possible assignment! def bitfield(n, L): result = np.binary_repr(n, L) return [int(digit) for digit in result] # [2:] to chop off the "0b" part L = len(list_of_subsets) max = 2**L max_v = -np.inf for i in range(max): cur = bitfield(i, L) cur_v = setpacking.check_disjoint(cur, list_of_subsets) if cur_v: if np.count_nonzero(cur) > max_v: max_v = np.count_nonzero(cur) return max_v size = brute_force() print("size of set packing", size) params = { 'problem': {'name': 'ising'}, 'algorithm': {'name': 'ExactEigensolver'} } result = run_algorithm(params, algo_input) x = setpacking.sample_most_likely(len(list_of_subsets), result['eigvecs'][0]) ising_sol = setpacking.get_solution(x) np.testing.assert_array_equal(ising_sol, [0, 1, 1]) print("size of set packing", np.count_nonzero(ising_sol)) algo = ExactEigensolver(algo_input.qubit_op, k=1, aux_operators=[]) result = algo.run() x = setpacking.sample_most_likely(len(list_of_subsets), result['eigvecs'][0]) ising_sol = setpacking.get_solution(x) np.testing.assert_array_equal(ising_sol, [0, 1, 1]) oracle = brute_force() print("size of set packing", np.count_nonzero(ising_sol)) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'paulis' } optimizer_cfg = { 'name': 'SPSA', 'max_trials': 200 } var_form_cfg = { 'name': 'RY', 'depth': 5, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising', 'random_seed': 100}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('qasm_simulator') result = run_algorithm(params, algo_input, backend=backend) x = setpacking.sample_most_likely(len(list_of_subsets), result['eigvecs'][0]) ising_sol = setpacking.get_solution(x) print("size of set packing", np.count_nonzero(ising_sol))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit_aqua import Operator, run_algorithm from qiskit_aqua.translators.ising import stableset from qiskit_aqua.input import EnergyInput from qiskit_aqua.algorithms.classical.cplex.cplex_ising import CPLEX_Ising from qiskit import Aer w = stableset.parse_gset_format('sample.maxcut') qubitOp, offset = stableset.get_stableset_qubitops(w) algo_input = EnergyInput(qubitOp) if True: np.random.seed(8123179) w = stableset.random_graph(5, edge_prob=0.5) qubitOp, offset = stableset.get_stableset_qubitops(w) algo_input.qubit_op = qubitOp print(w) to_be_tested_algos = ['ExactEigensolver', 'CPLEX.Ising', 'VQE'] print(to_be_tested_algos) algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) x = stableset.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('stable set objective:', result['energy'] + offset) print('solution:', stableset.get_graph_solution(x)) print('solution objective and feasibility:', stableset.stableset_value(x, w)) cplex_installed = True try: CPLEX_Ising.check_pluggable_valid() except Exception as e: cplex_installed = False if cplex_installed: algorithm_cfg = { 'name': 'CPLEX.Ising', 'display': 0 } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params, algo_input) x_dict = result['x_sol'] print('energy:', result['energy']) print('time:', result['eval_time']) print('stable set objective:', result['energy'] + offset) x = np.array([x_dict[i] for i in sorted(x_dict.keys())]) print('solution:', stableset.get_graph_solution(x)) print('solution objective and feasibility:', stableset.stableset_value(x, w)) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'L_BFGS_B', 'maxfun': 2000 } var_form_cfg = { 'name': 'RYRZ', 'depth': 3, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('statevector_simulator') result = run_algorithm(params, algo_input, backend=backend) x = stableset.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('stable set objective:', result['energy'] + offset) print('solution:', stableset.get_graph_solution(x)) print('solution objective and feasibility:', stableset.stableset_value(x, w))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit import Aer from qiskit_aqua import run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import vertexcover from qiskit_aqua.algorithms import ExactEigensolver np.random.seed(100) num_nodes = 3 w = vertexcover.random_graph(num_nodes, edge_prob=0.8, weight_range=10) print(w) qubit_op, offset = vertexcover.get_vertexcover_qubitops(w) algo_input = EnergyInput(qubit_op) def brute_force(): # brute-force way def bitfield(n, L): result = np.binary_repr(n, L) return [int(digit) for digit in result] # [2:] to chop off the "0b" part L = num_nodes max = 2**L minimal_v = np.inf for i in range(max): cur = bitfield(i, L) cur_v = vertexcover.check_full_edge_coverage(np.array(cur), w) if cur_v: nonzerocount = np.count_nonzero(cur) if nonzerocount < minimal_v: minimal_v = nonzerocount return minimal_v size = brute_force() print('size of the vertex cover', size) params = { 'problem': {'name': 'ising'}, 'algorithm': {'name': 'ExactEigensolver'} } result = run_algorithm(params, algo_input) x = vertexcover.sample_most_likely(len(w), result['eigvecs'][0]) sol = vertexcover.get_graph_solution(x) np.testing.assert_array_equal(sol, [0, 1, 1]) print('size of the vertex cover', np.count_nonzero(sol)) algo = ExactEigensolver(algo_input.qubit_op, k=1, aux_operators=[]) result = algo.run() x = vertexcover.sample_most_likely(len(w), result['eigvecs'][0]) sol = vertexcover.get_graph_solution(x) np.testing.assert_array_equal(sol, [0, 1, 1]) print('size of the vertex cover', np.count_nonzero(sol)) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'paulis' } optimizer_cfg = { 'name': 'SPSA', 'max_trials': 200 } var_form_cfg = { 'name': 'RYRZ', 'depth': 3, } params = { 'problem': {'name': 'ising', 'random_seed': 100}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('qasm_simulator') result = run_algorithm(params, algo_input, backend=backend) x = vertexcover.sample_most_likely(len(w), result['eigvecs'][0]) sol = vertexcover.get_graph_solution(x) print('size of the vertex cover', np.count_nonzero(sol))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# You may need to trust this notebook before the button below works from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''') def cplayer_output(strategy, inp): if(strategy == 1): return inp elif(strategy == 2): return abs(inp-1) elif(strategy == 3): return 1 elif(strategy == 4): return 0 else: print("INVALID choice") return 100 # Pick Alice's classical strategy A_st = int(input('select the classical strategy for Alice, input 1,2,3 or 4 to pick one of the strategies listed above ')) # Pick Bob's classical strategy B_st = int(input('select the classical strategy for Bob, input 1,2,3 or 4 to pick one of the strategies listed above ')) # useful packages import numpy as np import random as rand # fixes the numbers of games to be played N=100 # initializes counters used to keep track of the numbers of games won and played by Alice an Bob cont_win = 0 # counts games won cont_tot = 0 # counts games played # play the game N times for i in range(N): # generates two random input from the refree, x and y, to be given to Alice and Bob random_num1 = rand.random() # first random number random_num2 = rand.random() # second random number if(random_num1 >= 1/2): # converts the first random number to 0 or 1 x = 0 else: x = 1 if(random_num2 >= 1/2): # converts the second random number to 0 or 1 y = 0 else: y = 1 # generates Alice's and Bob's output a = cplayer_output(A_st, x) # Alice's output b = cplayer_output(B_st, y) # Bob's output # check if the condition for winning the game is met if(x*y == a^b): cont_win += 1 # increase thes won games' counter if the condition to win the game is met cont_tot += 1 # increases the played games' counter Prob_win = cont_win/cont_tot # winning probability print('Alice and Bob won the game with probability: ', Prob_win*100, '%') def qAlice_output(strategy, inp): if(strategy == 1): return 0 elif(strategy == 2): return rand.uniform(0,2*np.pi) elif(strategy == 3): if(inp == 0): return 0 elif(inp == 1): return np.pi/2 else: print("INVALID choice") return 100 def qBob_output(strategy, inp): if(strategy == 1): return 0 elif(strategy == 2): return rand.uniform(0,2*np.pi) elif(strategy == 3): if(inp == 0): return np.pi/4 elif(inp == 1): return -np.pi/4 else: print("INVALID choice") return 100 # Alice's strategy qA_st = int(input('select the quantum strategy for Alice, input 1,2 or 3 to pick one of the strategies listed above: ')) # Bob's strategy qB_st = int(input('select the quantum strategy for Bob, input 1,2 or 3 to pick one of the strategies listed above: ')) # import packages from qiskit import * import numpy as np import random as rand # set parameters of the quantum run of the game shots = 1 # set how many times the circuit is run, accumulating statistics about the measurement outcomes backend = 'local_qasm_simulator' # set the machine where the quantum circuit is to be run #fixes the numbers of games to be played N=100 # initializes counters used to keep track of the numbers of games won and played by Alice an Bob cont_win = 0 # counts games won cont_tot = 0 # counts games played #play N games for i in range(N): #creates quantum program, which allows to specify the details of the circuit like the register and the gates used Q_program = QuantumProgram() # creates registers for qubits and bits q = Q_program.create_quantum_register('q', 2) # creates a quantum register, it specifies the qubits which are going to be used for the program c = Q_program.create_classical_register('c', 2) # creates a classical register, the results of the measurement of the qubits are stored here # creates quantum circuit, to write a quantum algorithm we will add gates to the circuit game = Q_program.create_circuit('game', [q], [c]) # These gates prepare the entangled Bell pair to be shared by Alice and Bob as part of their quantum strategy # Alice will have qubit 0 and Bob will have qubit 1 game.h(q[0]) # Hadamard gate on qubit 0 game.cx(q[0],q[1]) # CNOT gate on qubit 1 controlled by qubit 0 # generates two random input from the refree, x and y, to be given to Alice and Bob random_num1 = rand.random() # first random number random_num2 = rand.random() # second random number if(random_num1 >= 1/2): # converts the first random number to 0 or 1 x = 0 else: x = 1 if(random_num2 >= 1/2): # converts the second random number to 0 or 1 y = 0 else: y = 1 # The main part of Alice and Bob quantum strategy is to fix different rotation angles for their qubit according to the input x,y theta = qAlice_output(qA_st, x) # fixes Alice's rotation for her qubit phi = qBob_output(qB_st, y) # fixes Bob's rotation for his qubit # The following gates rotate Alice's qubit and Bob's qubit game.ry(theta,q[0]) #rotates Alice's qubit of an angle theta game.ry(phi,q[1]) ##rotates Bob's qubit of an angle phi # These gates are used to measure the value of the qubits game.measure(q[0], c[0]) # measure Alice's qubit and stores the result in a classical bit game.measure(q[1], c[1]) # measure Bob's qubit and stores the result in a classical bit # Assemble the gates in the circuit circuits = ['game'] # assemble circuit # executes circuit and store the output of the measurements result = Q_program.execute(circuits, backend=backend, shots=shots, wait=10, timeout=240) data = result.get_counts('game') # extract the outcomes and their statistics from the result of the execution # reads the result of the measurements of the quantum system for outcomes in data.keys(): out = outcomes # converts the result of the measurements contained in the classical register as string '00', '01', '10', '11', # which are the answers of Alice(a) and Bob (b), from a 'string' type to 'integer' type if(out == '00'): a = 0 b = 0 if(out == '01'): a = 1 b = 0 if(out == '10'): a = 0 b = 1 if(out == '11'): a = 1 b = 1 # check if the condition for winning the game is met if(x*y == a^b): cont_win += 1 # increase thes won games' counter if the condition to win the game is met cont_tot += 1 # increases the played games' counter qProb_win = cont_win/cont_tot print('Alice and Bob won the game with probability: ', qProb_win*100, '%') if Prob_win > qProb_win : print("The classical strategy gave Alice and Bob higher chances of winning") else: print("The quantum strategy gave Alice and Bob higher chances of winning")
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# Checking the version of PYTHON; we only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # useful additional packages import numpy as np import random import re # regular expressions module # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram #import Qconfig # Quantum program setup Q_program = QuantumProgram() #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url # Creating registers qr = Q_program.create_quantum_register("qr", 2) cr = Q_program.create_classical_register("cr", 4) singlet = Q_program.create_circuit('singlet', [qr], [cr]) singlet.x(qr[0]) singlet.x(qr[1]) singlet.h(qr[0]) singlet.cx(qr[0],qr[1]) ## Alice's measurement circuits # measure the spin projection of Alice's qubit onto the a_1 direction (X basis) measureA1 = Q_program.create_circuit('measureA1', [qr], [cr]) measureA1.h(qr[0]) measureA1.measure(qr[0],cr[0]) # measure the spin projection of Alice's qubit onto the a_2 direction (W basis) measureA2 = Q_program.create_circuit('measureA2', [qr], [cr]) measureA2.s(qr[0]) measureA2.h(qr[0]) measureA2.t(qr[0]) measureA2.h(qr[0]) measureA2.measure(qr[0],cr[0]) # measure the spin projection of Alice's qubit onto the a_3 direction (standard Z basis) measureA3 = Q_program.create_circuit('measureA3', [qr], [cr]) measureA3.measure(qr[0],cr[0]) ## Bob's measurement circuits # measure the spin projection of Bob's qubit onto the b_1 direction (W basis) measureB1 = Q_program.create_circuit('measureB1', [qr], [cr]) measureB1.s(qr[1]) measureB1.h(qr[1]) measureB1.t(qr[1]) measureB1.h(qr[1]) measureB1.measure(qr[1],cr[1]) # measure the spin projection of Bob's qubit onto the b_2 direction (standard Z basis) measureB2 = Q_program.create_circuit('measureB2', [qr], [cr]) measureB2.measure(qr[1],cr[1]) # measure the spin projection of Bob's qubit onto the b_3 direction (V basis) measureB3 = Q_program.create_circuit('measureB3', [qr], [cr]) measureB3.s(qr[1]) measureB3.h(qr[1]) measureB3.tdg(qr[1]) measureB3.h(qr[1]) measureB3.measure(qr[1],cr[1]) ## Lists of measurement circuits aliceMeasurements = [measureA1, measureA2, measureA3] bobMeasurements = [measureB1, measureB2, measureB3] # Define the number of singlets N numberOfSinglets = 500 aliceMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b of Alice bobMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b' of Bob circuits = [] # the list in which the created circuits will be stored for i in range(numberOfSinglets): # create the name of the i-th circuit depending on Alice's and Bob's measurement choices circuitName = str(i) + ':A' + str(aliceMeasurementChoices[i]) + '_B' + str(bobMeasurementChoices[i]) # create the joint measurement circuit # add Alice's and Bob's measurement circuits to the singlet state curcuit Q_program.add_circuit(circuitName, singlet + # singlet state circuit aliceMeasurements[aliceMeasurementChoices[i]-1] + # measurement circuit of Alice bobMeasurements[bobMeasurementChoices[i]-1] # measurement circuit of Bob ) # add the created circuit to the circuits list circuits.append(circuitName) print(circuits[0]) result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240) print(result) result.get_counts(circuits[0]) abPatterns = [ re.compile('..00$'), # search for the '..00' output (Alice obtained -1 and Bob obtained -1) re.compile('..01$'), # search for the '..01' output re.compile('..10$'), # search for the '..10' output (Alice obtained -1 and Bob obtained 1) re.compile('..11$') # search for the '..11' output ] aliceResults = [] # Alice's results (string a) bobResults = [] # Bob's results (string a') for i in range(numberOfSinglets): res = list(result.get_counts(circuits[i]).keys())[0] # extract the key from the dict and transform it to str; execution result of the i-th circuit if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(-1) # Bob got the result -1 if abPatterns[1].search(res): aliceResults.append(1) bobResults.append(-1) if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(1) # Bob got the result 1 if abPatterns[3].search(res): aliceResults.append(1) bobResults.append(1) aliceKey = [] # Alice's key string k bobKey = [] # Bob's key string k' # comparing the stings with measurement choices for i in range(numberOfSinglets): # if Alice and Bob have measured the spin projections onto the a_2/b_1 or a_3/b_2 directions if (aliceMeasurementChoices[i] == 2 and bobMeasurementChoices[i] == 1) or (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 2): aliceKey.append(aliceResults[i]) # record the i-th result obtained by Alice as the bit of the secret key k bobKey.append(- bobResults[i]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k' keyLength = len(aliceKey) # length of the secret key abKeyMismatches = 0 # number of mismatching bits in Alice's and Bob's keys for j in range(keyLength): if aliceKey[j] != bobKey[j]: abKeyMismatches += 1 # function that calculates CHSH correlation value def chsh_corr(result): # lists with the counts of measurement results # each element represents the number of (-1,-1), (-1,1), (1,-1) and (1,1) results respectively countA1B1 = [0, 0, 0, 0] # XW observable countA1B3 = [0, 0, 0, 0] # XV observable countA3B1 = [0, 0, 0, 0] # ZW observable countA3B3 = [0, 0, 0, 0] # ZV observable for i in range(numberOfSinglets): res = list(result.get_counts(circuits[i]).keys())[0] # if the spins of the qubits of the i-th singlet were projected onto the a_1/b_1 directions if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 1): for j in range(4): if abPatterns[j].search(res): countA1B1[j] += 1 if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 3): for j in range(4): if abPatterns[j].search(res): countA1B3[j] += 1 if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 1): for j in range(4): if abPatterns[j].search(res): countA3B1[j] += 1 # if the spins of the qubits of the i-th singlet were projected onto the a_3/b_3 directions if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 3): for j in range(4): if abPatterns[j].search(res): countA3B3[j] += 1 # number of the results obtained from the measurements in a particular basis total11 = sum(countA1B1) total13 = sum(countA1B3) total31 = sum(countA3B1) total33 = sum(countA3B3) # expectation values of XW, XV, ZW and ZV observables (2) expect11 = (countA1B1[0] - countA1B1[1] - countA1B1[2] + countA1B1[3])/total11 # -1/sqrt(2) expect13 = (countA1B3[0] - countA1B3[1] - countA1B3[2] + countA1B3[3])/total13 # 1/sqrt(2) expect31 = (countA3B1[0] - countA3B1[1] - countA3B1[2] + countA3B1[3])/total31 # -1/sqrt(2) expect33 = (countA3B3[0] - countA3B3[1] - countA3B3[2] + countA3B3[3])/total33 # -1/sqrt(2) corr = expect11 - expect13 + expect31 + expect33 # calculate the CHSC correlation value (3) return corr corr = chsh_corr(result) # CHSH correlation value # CHSH inequality test print('CHSH correlation value: ' + str(round(corr, 3))) # Keys print('Length of the key: ' + str(keyLength)) print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n') # measurement of the spin projection of Alice's qubit onto the a_2 direction (W basis) measureEA2 = Q_program.create_circuit('measureEA2', [qr], [cr]) measureEA2.s(qr[0]) measureEA2.h(qr[0]) measureEA2.t(qr[0]) measureEA2.h(qr[0]) measureEA2.measure(qr[0],cr[2]) # measurement of the spin projection of Allice's qubit onto the a_3 direction (standard Z basis) measureEA3 = Q_program.create_circuit('measureEA3', [qr], [cr]) measureEA3.measure(qr[0],cr[2]) # measurement of the spin projection of Bob's qubit onto the b_1 direction (W basis) measureEB1 = Q_program.create_circuit('measureEB1', [qr], [cr]) measureEB1.s(qr[1]) measureEB1.h(qr[1]) measureEB1.t(qr[1]) measureEB1.h(qr[1]) measureEB1.measure(qr[1],cr[3]) # measurement of the spin projection of Bob's qubit onto the b_2 direction (standard Z measurement) measureEB2 = Q_program.create_circuit('measureEB2', [qr], [cr]) measureEB2.measure(qr[1],cr[3]) # lists of measurement circuits eveMeasurements = [measureEA2, measureEA3, measureEB1, measureEB2] # list of Eve's measurement choices # the first and the second elements of each row represent the measurement of Alice's and Bob's qubits by Eve respectively eveMeasurementChoices = [] for j in range(numberOfSinglets): if random.uniform(0, 1) <= 0.5: # in 50% of cases perform the WW measurement eveMeasurementChoices.append([0, 2]) else: # in 50% of cases perform the ZZ measurement eveMeasurementChoices.append([1, 3]) circuits = [] # the list in which the created circuits will be stored for j in range(numberOfSinglets): # create the name of the j-th circuit depending on Alice's, Bob's and Eve's choices of measurement circuitName = str(j) + ':A' + str(aliceMeasurementChoices[j]) + '_B' + str(bobMeasurementChoices[j] + 2) + '_E' + str(eveMeasurementChoices[j][0]) + str(eveMeasurementChoices[j][1] - 1) # create the joint measurement circuit # add Alice's and Bob's measurement circuits to the singlet state curcuit Q_program.add_circuit(circuitName, singlet + # singlet state circuit eveMeasurements[eveMeasurementChoices[j][0]-1] + # Eve's measurement circuit of Alice's qubit eveMeasurements[eveMeasurementChoices[j][1]-1] + # Eve's measurement circuit of Bob's qubit aliceMeasurements[aliceMeasurementChoices[j]-1] + # measurement circuit of Alice bobMeasurements[bobMeasurementChoices[j]-1] # measurement circuit of Bob ) # add the created circuit to the circuits list circuits.append(circuitName) result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240) print(result) print(str(circuits[0]) + '\t' + str(result.get_counts(circuits[0]))) ePatterns = [ re.compile('00..$'), # search for the '00..' result (Eve obtained the results -1 and -1 for Alice's and Bob's qubits) re.compile('01..$'), # search for the '01..' result (Eve obtained the results 1 and -1 for Alice's and Bob's qubits) re.compile('10..$'), re.compile('11..$') ] aliceResults = [] # Alice's results (string a) bobResults = [] # Bob's results (string a') # list of Eve's measurement results # the elements in the 1-st column are the results obtaned from the measurements of Alice's qubits # the elements in the 2-nd column are the results obtaned from the measurements of Bob's qubits eveResults = [] # recording the measurement results for j in range(numberOfSinglets): res = list(result.get_counts(circuits[j]).keys())[0] # extract a key from the dict and transform it to str # Alice and Bob if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(-1) # Bob got the result -1 if abPatterns[1].search(res): aliceResults.append(1) bobResults.append(-1) if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(1) # Bob got the result 1 if abPatterns[3].search(res): aliceResults.append(1) bobResults.append(1) # Eve if ePatterns[0].search(res): # check if the key is '00..' eveResults.append([-1, -1]) # results of the measurement of Alice's and Bob's qubits are -1,-1 if ePatterns[1].search(res): eveResults.append([1, -1]) if ePatterns[2].search(res): eveResults.append([-1, 1]) if ePatterns[3].search(res): eveResults.append([1, 1]) aliceKey = [] # Alice's key string a bobKey = [] # Bob's key string a' eveKeys = [] # Eve's keys; the 1-st column is the key of Alice, and the 2-nd is the key of Bob # comparing the strings with measurement choices (b and b') for j in range(numberOfSinglets): # if Alice and Bob measured the spin projections onto the a_2/b_1 or a_3/b_2 directions if (aliceMeasurementChoices[j] == 2 and bobMeasurementChoices[j] == 1) or (aliceMeasurementChoices[j] == 3 and bobMeasurementChoices[j] == 2): aliceKey.append(aliceResults[j]) # record the i-th result obtained by Alice as the bit of the secret key k bobKey.append(-bobResults[j]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k' eveKeys.append([eveResults[j][0], -eveResults[j][1]]) # record the i-th bits of the keys of Eve keyLength = len(aliceKey) # length of the secret skey abKeyMismatches = 0 # number of mismatching bits in the keys of Alice and Bob eaKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Alice ebKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Bob for j in range(keyLength): if aliceKey[j] != bobKey[j]: abKeyMismatches += 1 if eveKeys[j][0] != aliceKey[j]: eaKeyMismatches += 1 if eveKeys[j][1] != bobKey[j]: ebKeyMismatches += 1 eaKnowledge = (keyLength - eaKeyMismatches)/keyLength # Eve's knowledge of Bob's key ebKnowledge = (keyLength - ebKeyMismatches)/keyLength # Eve's knowledge of Alice's key corr = chsh_corr(result) # CHSH inequality test print('CHSH correlation value: ' + str(round(corr, 3)) + '\n') # Keys print('Length of the key: ' + str(keyLength)) print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n') print('Eve\'s knowledge of Alice\'s key: ' + str(round(eaKnowledge * 100, 2)) + ' %') print('Eve\'s knowledge of Bob\'s key: ' + str(round(ebKnowledge * 100, 2)) + ' %')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram #import Qconfig # import basic plotting tools from qiskit.tools.visualization import plot_histogram from qiskit.tools.qcvv.tomography import marginal_counts # create a QuantumProgram object instance. q_program = QuantumProgram() #q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url # backend #backend = 'ibmqx2' backend = 'local_qasm_simulator' # quantum plain addition algorithm for 1-qubit numbers def addition_1bit(circuit, q): circuit.h(q[2]) circuit.cx(q[1], q[2]) circuit.tdg(q[2]) circuit.cx(q[0], q[2]) circuit.t(q[2]) circuit.cx(q[1], q[2]) circuit.tdg(q[2]) circuit.cx(q[0], q[2]) circuit.t(q[2]) circuit.h(q[2]) circuit.t(q[1]) circuit.cx(q[0], q[1]) circuit.t(q[0]) circuit.tdg(q[1]) # n-qubit number input state def number_state(circuit, q, a, b): if a == 1: circuit.x(q[0]) # q[0] contains the value of a if b == 1: circuit.x(q[1]) # q[1] contain the value of b # we define the values (0 or 1) a = 1 b = 1 # one single quantum register which contains 'a' (1 qubit) and 'b' (2 qubits) q = q_program.create_quantum_register("q", 3) # 3 qubits # clasical register c = q_program.create_classical_register("cr", 2) # 2 bits # quantum circuit involving the quantum register and the classical register add1bit_circuit = q_program.create_circuit("add", [q] ,[c]) # create the state containing a and b number_state(add1bit_circuit, q, a, b) # addition addition_1bit(add1bit_circuit, q) # measurements to see the result, which has been written in b (q[1]q[2]) add1bit_circuit.measure(q[1], c[0]) add1bit_circuit.measure(q[2], c[1]) # compile and execute the quantum program in the backend result = q_program.execute(["add"], backend=backend, shots=1024, max_credits=3, wait=10, timeout=999999) # show the results print(result) print(result.get_data("add")) counts = marginal_counts(result.get_counts("add"), [0, 1]) plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2))) # checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram # import basic plotting tools from qiskit.tools.visualization import plot_histogram # create a QuantumProgram object instance. q_program = QuantumProgram() # backend backend = 'local_qasm_simulator' def carry(circuit, q0, q1, q2, q3): "carry module" circuit.ccx(q1, q2, q3) circuit.cx(q1, q2) circuit.ccx(q0, q2, q3) def carry_inv(circuit, q0, q1, q2, q3): "carry module but running backwards" circuit.ccx(q0, q2, q3) circuit.cx(q1, q2) circuit.ccx(q1, q2, q3) def summation(circuit, q0, q1, q2): "summation module" circuit.cx(q1, q2) circuit.cx(q0, q2) # quantum plain addition algorithm for n-qubit numbers def addition_nbit(circuit, qa, qb, qcar, n): if n == 1: circuit.ccx(qa[0], qb[0], qb[1]) circuit.cx(qa[0], qb[0]) else: circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) circuit.cx(qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): summation(circuit, qcar[i-1], qa[i], qb[i]) carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1]) summation(circuit, qcar[0], qa[1], qb[1]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) # n-qubit number input state def number_state(circuit, q, x, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: circuit.x(q[i]) # we define the values a = 9 b = 14 # computing the number of qubits n needed n = len("{0:b}".format(a)) n2 = len("{0:b}".format(b)) if n2 > n: n = n2 # classical register with n+1 bits. c = q_program.create_classical_register("cr", n+1) # quantum registers qa = q_program.create_quantum_register("qa", n) # a qubits qb = q_program.create_quantum_register("qb", n+1) # b qubits # if n = 1, no need of carry register if n == 1: qcar = 0 # quantum circuit involving the quantum registers and the classical register addnbit_circuit = q_program.create_circuit("add", [qa, qb],[c]) else: qcar = q_program.create_quantum_register("qcar", n-1) # carry qubits # quantum circuit involving the quantum registers and the classical register addnbit_circuit = q_program.create_circuit("add", [qa, qb, qcar],[c]) # create the state containing a number_state(addnbit_circuit, qa, a, n) # create the state containing b number_state(addnbit_circuit, qb, b, n) # addition addition_nbit(addnbit_circuit, qa, qb, qcar, n) # measurements to see the result for i in range(n+1): addnbit_circuit.measure(qb[i], c[i]) # compile and execute the quantum program in the backend result = q_program.execute(["add"], backend=backend, shots=1024, timeout=999999) # show the results. print(result) print(result.get_data("add")) counts = result.get_counts("add") plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2))) # checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram # import basic plotting tools from qiskit.tools.visualization import plot_histogram # create a QuantumProgram object instance. q_program = QuantumProgram() # backend backend = 'local_qasm_simulator' def carry(circuit, q0, q1, q2, q3): "carry module" circuit.ccx(q1, q2, q3) circuit.cx(q1, q2) circuit.ccx(q0, q2, q3) def carry_inv(circuit, q0, q1, q2, q3): "carry module running backwards" circuit.ccx(q0, q2, q3) circuit.cx(q1, q2) circuit.ccx(q1, q2, q3) def summation(circuit, q0, q1, q2): "summation module" circuit.cx(q1, q2) circuit.cx(q0, q2) def summation_inv(circuit, q0, q1, q2): "summation module running backwards" circuit.cx(q0, q2) circuit.cx(q1, q2) # quantum plain addition algorithm for n-qubit numbers def addition_nbit(circuit, qa, qb, qcar, n): if n == 1: circuit.ccx(qa[0], qb[0], qb[1]) circuit.cx(qa[0], qb[0]) else: circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) circuit.cx(qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): summation(circuit, qcar[i-1], qa[i], qb[i]) carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1]) summation(circuit, qcar[0], qa[1], qb[1]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) # quantum plain substraction algorithm for n-qubit numbers def subs_nbit(circuit, qa, qb, qcar, n): "same circuit as the plain addition but going backwards" if n == 1: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qb[1]) else: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) summation_inv(circuit, qcar[0], qa[1], qb[1]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2]) circuit.cx(qa[n-1], qb[n-1]) carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) for i in range(n-2, 0, -1): carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) def cond_toffoli(circuit, qcond, q1, q2, q3): "toffoli gate conditioned by an external qubit" circuit.h(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.h(q3) circuit.t(q2) circuit.ccx(qcond, q1, q2) circuit.t(q1) circuit.tdg(q2) circuit.ccx(qcond, q1, q2) def cond_carry(circuit, q0, q1, q2, q3, qcond): "conditional carry module" cond_toffoli(circuit, qcond, q1, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q0, q2, q3) def cond_carry_inv(circuit, q0, q1, q2, q3, qcond): "conditional carry module running backwards" cond_toffoli(circuit, qcond, q0, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q1, q2, q3) def cond_summation(circuit, q0, q1, q2, qcond): "conditional summation module" circuit.ccx(qcond, q1, q2) circuit.ccx(qcond, q0, q2) def cond_summation_inv(circuit, q0, q1, q2, qcond): "conditional summation module running backwards" circuit.ccx(qcond, q0, q2) circuit.ccx(qcond, q1, q2) # quantum conditional plain addition algorithm for n-qubit numbers def cond_addition_nbit(circuit, qa, qb, qcar, qcond, n): "plain addition algorithm conditioned by an external qubit" if n == 1: cond_toffoli(circuit, qcond[0], qa[0], qb[0], qb[1]) circuit.ccx(qcond[0], qa[0], qb[0]) else: cond_toffoli(circuit, qcond[0], qa[0], qb[0], qcar[0]) circuit.ccx(qcond[0], qa[0], qb[0]) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond[0]) cond_carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond[0]) circuit.ccx(qcond[0], qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): cond_summation(circuit, qcar[i-1], qa[i], qb[i], qcond[0]) cond_carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1], qcond[0]) cond_summation(circuit, qcar[0], qa[1], qb[1], qcond[0]) circuit.ccx(qcond[0], qa[0], qb[0]) cond_toffoli(circuit, qcond[0], qa[0], qb[0], qcar[0]) circuit.ccx(qcond[0], qa[0], qb[0]) # quantum conditional plain substraction algorithm for n-qubit numbers def cond_subs_nbit(circuit, qa, qb, qcar, qcond, n): "same circuit as the conditional plain addition but going backwards" if n == 1: circuit.ccx(qcond[0], qa[0], qb[0]) cond_toffoli(circuit, qcond[0], qa[0], qb[0], qb[1]) else: circuit.ccx(qcond[0], qa[0], qb[0]) cond_toffoli(circuit, qcond[0], qa[0], qb[0], qcar[0]) circuit.ccx(qcond[0], qa[0], qb[0]) cond_summation_inv(circuit, qcar[0], qa[1], qb[1], qcond[0]) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond[0]) cond_summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2], qcond[0]) circuit.ccx(qcond[0], qa[n-1], qb[n-1]) cond_carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond[0]) for i in range(n-2, 0, -1): cond_carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i], qcond[0]) circuit.ccx(qcond[0], qa[0], qb[0]) cond_toffoli(circuit, qcond[0], qa[0], qb[0], qcar[0]) # quantum modular addition algorithm for n-qubit numbers def mod_addition_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, n): addition_nbit(circuit, qa, qb, qcar, n) subs_nbit(circuit, qN, qb, qcar, n) circuit.x(qb[n]) circuit.cx(qb[n], qtemp[0]) circuit.x(qb[n]) cond_subs_nbit(circuit, qNtemp, qN, qcar, qtemp, n) addition_nbit(circuit, qN, qb, qcar, n) cond_addition_nbit(circuit, qNtemp, qN, qcar, qtemp, n) subs_nbit(circuit, qa, qb, qcar, n) circuit.cx(qb[n], qtemp[0]) addition_nbit(circuit, qa, qb, qcar, n) # n-qubit number input state def number_state(circuit, q, x, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: circuit.x(q[i]) # we define the values a = 2 b = 3 N = 3 # computing number of qubits n needed n = len("{0:b}".format(a)) n2 = len("{0:b}".format(b)) n3 = len("{0:b}".format(N)) if n2 > n: n = n2 if n3 > n: n = n3 # classical register with n+1 bits. c = q_program.create_classical_register("cr", n+1) # quantum registers qa = q_program.create_quantum_register("qa", n) # a qubits qb = q_program.create_quantum_register("qb", n+1) # b qubits qN = q_program.create_quantum_register("qN", n+1) # N qubits qNtemp = q_program.create_quantum_register("qNtemp", n) # temporary N qubits qtemp = q_program.create_quantum_register("qtemp", 1) # temporary qubit # if n = 1, no need of carry register if n == 1: qcar = 0 # quantum circuit involving the quantum registers and the classical register mod_add_circuit = q_program.create_circuit("mod_add", [qa, qb, qN, qNtemp, qtemp],[c]) else: qcar = q_program.create_quantum_register("qcar", n-1) # carry qubits # quantum circuit involving the quantum registers and the classical register mod_add_circuit = q_program.create_circuit("mod_add", [qa, qb, qN, qcar, qNtemp, qtemp],[c]) # create the state containing 'a' number_state(mod_add_circuit, qa, a, n) # create the state containing 'b' number_state(mod_add_circuit, qb, b, n) # create the state containing 'N' number_state(mod_add_circuit, qN, N, n) # create the temporary state containing 'N' number_state(mod_add_circuit, qNtemp, N, n) # modular addition mod_addition_nbit(mod_add_circuit, qa, qb, qN, qNtemp, qcar, qtemp, n) # measurements to see the result for i in range(n+1): mod_add_circuit.measure(qb[i], c[i]) # compile and execute the quantum program in the backend result = q_program.execute(["mod_add"], backend=backend, shots=1024, max_credits=3, wait=10, timeout=999999) # show the results. print(result) print(result.get_data("mod_add")) counts = result.get_counts("mod_add") plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2))) # checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram # import basic plotting tools from qiskit.tools.visualization import plot_histogram # create a QuantumProgram object instance. q_program = QuantumProgram() # backend backend = 'local_qasm_simulator' def carry(circuit, q0, q1, q2, q3): "carry module" circuit.ccx(q1, q2, q3) circuit.cx(q1, q2) circuit.ccx(q0, q2, q3) def carry_inv(circuit, q0, q1, q2, q3): "carry module running backwards" circuit.ccx(q0, q2, q3) circuit.cx(q1, q2) circuit.ccx(q1, q2, q3) def summation(circuit, q0, q1, q2): "summation module" circuit.cx(q1, q2) circuit.cx(q0, q2) def summation_inv(circuit, q0, q1, q2): "summation module running backwards" circuit.cx(q0, q2) circuit.cx(q1, q2) # quantum plain addition algorithm for n-qubit numbers def addition_nbit(circuit, qa, qb, qcar, n): if n == 1: circuit.ccx(qa[0], qb[0], qb[1]) circuit.cx(qa[0], qb[0]) else: circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) circuit.cx(qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): summation(circuit, qcar[i-1], qa[i], qb[i]) carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1]) summation(circuit, qcar[0], qa[1], qb[1]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) # quantum plain substraction algorithm for n-qubit numbers def subs_nbit(circuit, qa, qb, qcar, n): "same circuit as the addition but going backwards" if n == 1: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qb[1]) else: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) summation_inv(circuit, qcar[0], qa[1], qb[1]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2]) circuit.cx(qa[n-1], qb[n-1]) carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) for i in range(n-2, 0, -1): carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) def cond_toffoli(circuit, qcond, q1, q2, q3): "toffoli gate conditioned by an external qubit" circuit.h(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.h(q3) circuit.t(q2) circuit.ccx(qcond, q1, q2) circuit.t(q1) circuit.tdg(q2) circuit.ccx(qcond, q1, q2) def cond_carry(circuit, q0, q1, q2, q3, qcond): "conditional carry module" cond_toffoli(circuit, qcond, q1, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q0, q2, q3) def cond_carry_inv(circuit, q0, q1, q2, q3, qcond): "conditional carry module running backwards" cond_toffoli(circuit, qcond, q0, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q1, q2, q3) def cond_summation(circuit, q0, q1, q2, qcond): "conditional summation module" circuit.ccx(qcond, q1, q2) circuit.ccx(qcond, q0, q2) def cond_summation_inv(circuit, q0, q1, q2, qcond): "conditional summation module running backwards" circuit.ccx(qcond, q0, q2) circuit.ccx(qcond, q1, q2) # quantum conditional plain addition algorithm for n-qubit numbers def cond_addition_nbit(circuit, qa, qb, qcar, qcond, n): if n == 1: cond_toffoli(circuit, qcond, qa[0], qb[0], qb[1]) circuit.ccx(qcond, qa[0], qb[0]) else: cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond) cond_carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond) circuit.ccx(qcond, qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): cond_summation(circuit, qcar[i-1], qa[i], qb[i], qcond) cond_carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1], qcond) cond_summation(circuit, qcar[0], qa[1], qb[1], qcond) circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) # quantum conditional plain substraction algorithm for n-qubit numbers def cond_subs_nbit(circuit, qa, qb, qcar, qcond, n): "same circuit as the conditional plain addition but going backwards" if n == 1: circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qb[1]) else: circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) cond_summation_inv(circuit, qcar[0], qa[1], qb[1], qcond) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond) cond_summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2], qcond) circuit.ccx(qcond, qa[n-1], qb[n-1]) cond_carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond) for i in range(n-2, 0, -1): cond_carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i], qcond) circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) # quantum modular addition algorithm for n-qubit numbers def mod_addition_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, n): addition_nbit(circuit, qa, qb, qcar, n) subs_nbit(circuit, qN, qb, qcar, n) circuit.x(qb[n]) circuit.cx(qb[n], qtemp) circuit.x(qb[n]) cond_subs_nbit(circuit, qNtemp, qN, qcar, qtemp, n) addition_nbit(circuit, qN, qb, qcar, n) cond_addition_nbit(circuit, qNtemp, qN, qcar, qtemp, n) subs_nbit(circuit, qa, qb, qcar, n) circuit.cx(qb[n], qtemp) addition_nbit(circuit, qa, qb, qcar, n) # quantum controlled modular multiplication algorithm for n-qubit numbers def cont_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, qX, qext, N, n): for i in range(n): for j in range(n): classical_mod = (2**(i+j))%N cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) mod_addition_nbit(circuit, qtempst, qb, qN, qNtemp, qcar, qtemp, n) cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) circuit.x(qext) cond_addition_nbit(circuit, qX, qb, qcar, qext, n) circuit.x(qext) # n-qubit number input state def number_state(circuit, q, x, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: circuit.x(q[i]) # n-qubit number input state, controlled by 2 control qubits def cond_number_state(circuit, q, x, ext, control1, control2, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: cond_toffoli(circuit, ext, control1, control2, q[i]) # we define the values a = 1 x = 1 N = 1 # computing number of qubits n needed n = len("{0:b}".format(a)) n2 = len("{0:b}".format(x)) n3 = len("{0:b}".format(N)) if n2 > n: n = n2 if n3 > n: n = n3 # classical register with n+1 bits. c = q_program.create_classical_register("cr", n+1) # quantum registers qa = q_program.create_quantum_register("qa", n) # a qubits qb = q_program.create_quantum_register("qb", n+1) # result register qN = q_program.create_quantum_register("qN", n+1) # N qubits qNtemp = q_program.create_quantum_register("qNtemp", n) # temporary N qubits qtemp = q_program.create_quantum_register("qtemp", 1) # temporary qubit qtempst = q_program.create_quantum_register("qtempst", n) # temporary register qX = q_program.create_quantum_register("qX", n) # x register qext = q_program.create_quantum_register("qext", 1) # if n = 1, no need of carry register if n == 1: qcar = 0 # quantum circuit involving the quantum registers and the classical register mod_mult_circuit = q_program.create_circuit("mod_mult", [qa, qb, qN, qNtemp, qtemp, qtempst, qX, qext],[c]) else: qcar = q_program.create_quantum_register("qcar", n-1) # carry qubits # quantum circuit involving the quantum register and the classical register mod_mult_circuit = q_program.create_circuit("mod_mult", [qa, qb, qN, qcar, qNtemp, qtemp, qtempst, qX, qext],[c]) # create the state containing 'a' number_state(mod_mult_circuit, qa, a, n) # create the state containing 'b' number_state(mod_mult_circuit, qX, x, n) # create the state containing 'N' number_state(mod_mult_circuit, qN, N, n+1) # create a temporary state containing 'N' number_state(mod_mult_circuit, qNtemp, N, n) mod_mult_circuit.x(qext[0]) # we set the control qubit to |1> # controlled modular multiplication cont_mod_mult_nbit(mod_mult_circuit, qa, qb, qN, qNtemp, qcar, qtemp[0], qtempst, qX, qext[0], N, n) # measurements to see the result for i in range(n+1): mod_mult_circuit.measure(qb[i], c[i]) # compile and execute the quantum program in the backend result = q_program.execute(["mod_mult"], backend=backend, shots=1024, max_credits=3, wait=10, timeout=999999) # show the results. print(result) print(result.get_data("mod_mult")) counts = result.get_counts("mod_mult") plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2))) # checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram # import basic plotting tools from qiskit.tools.visualization import plot_histogram # create a QuantumProgram object instance. q_program = QuantumProgram() # backend backend = 'local_qasm_simulator' def carry(circuit, q0, q1, q2, q3): "carry module" circuit.ccx(q1, q2, q3) circuit.cx(q1, q2) circuit.ccx(q0, q2, q3) def carry_inv(circuit, q0, q1, q2, q3): "carry module running backwards" circuit.ccx(q0, q2, q3) circuit.cx(q1, q2) circuit.ccx(q1, q2, q3) def summation(circuit, q0, q1, q2): "summation module" circuit.cx(q1, q2) circuit.cx(q0, q2) def summation_inv(circuit, q0, q1, q2): "summation module running backwards" circuit.cx(q0, q2) circuit.cx(q1, q2) # quantum plain addition algorithm for n-qubit numbers def addition_nbit(circuit, qa, qb, qcar, n): if n == 1: circuit.ccx(qa[0], qb[0], qb[1]) circuit.cx(qa[0], qb[0]) else: circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) circuit.cx(qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): summation(circuit, qcar[i-1], qa[i], qb[i]) carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1]) summation(circuit, qcar[0], qa[1], qb[1]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) # quantum plain substraction algorithm for n-qubit numbers def subs_nbit(circuit, qa, qb, qcar, n): "same as the plain addition but running backwards" if n == 1: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qb[1]) else: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) summation_inv(circuit, qcar[0], qa[1], qb[1]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2]) circuit.cx(qa[n-1], qb[n-1]) carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) for i in range(n-2, 0, -1): carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) def cond_toffoli(circuit, qcond, q1, q2, q3): "conditional toffoli gate" circuit.h(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.h(q3) circuit.t(q2) circuit.ccx(qcond, q1, q2) circuit.t(q1) circuit.tdg(q2) circuit.ccx(qcond, q1, q2) def cond_carry(circuit, q0, q1, q2, q3, qcond): "conditional carry module" cond_toffoli(circuit, qcond, q1, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q0, q2, q3) def cond_carry_inv(circuit, q0, q1, q2, q3, qcond): "conditional carry module running backwards" cond_toffoli(circuit, qcond, q0, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q1, q2, q3) def cond_summation(circuit, q0, q1, q2, qcond): "conditional summation" circuit.ccx(qcond, q1, q2) circuit.ccx(qcond, q0, q2) def cond_summation_inv(circuit, q0, q1, q2, qcond): "conditional summation running backwards" circuit.ccx(qcond, q0, q2) circuit.ccx(qcond, q1, q2) # quantum conditional plain addition algorithm for n-qubit numbers def cond_addition_nbit(circuit, qa, qb, qcar, qcond, n): if n == 1: cond_toffoli(circuit, qcond, qa[0], qb[0], qb[1]) circuit.ccx(qcond, qa[0], qb[0]) else: cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond) cond_carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond) circuit.ccx(qcond, qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): cond_summation(circuit, qcar[i-1], qa[i], qb[i], qcond) cond_carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1], qcond) cond_summation(circuit, qcar[0], qa[1], qb[1], qcond) circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) # quantum conditional plain substraction algorithm for n-qubit numbers def cond_subs_nbit(circuit, qa, qb, qcar, qcond, n): "same as conditional plain addition but running backwards" if n == 1: circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qb[1]) else: circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) cond_summation_inv(circuit, qcar[0], qa[1], qb[1], qcond) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond) cond_summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2], qcond) circuit.ccx(qcond, qa[n-1], qb[n-1]) cond_carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond) for i in range(n-2, 0, -1): cond_carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i], qcond) circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) # quantum modular addition algorithm for n-qubit numbers def mod_addition_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, n): addition_nbit(circuit, qa, qb, qcar, n) subs_nbit(circuit, qN, qb, qcar, n) circuit.x(qb[n]) circuit.cx(qb[n], qtemp) circuit.x(qb[n]) cond_subs_nbit(circuit, qNtemp, qN, qcar, qtemp, n) addition_nbit(circuit, qN, qb, qcar, n) cond_addition_nbit(circuit, qNtemp, qN, qcar, qtemp, n) subs_nbit(circuit, qa, qb, qcar, n) circuit.cx(qb[n], qtemp) addition_nbit(circuit, qa, qb, qcar, n) # quantum modular substraction algorithm for n-qubit numbers def mod_subs_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, n): "same as modular addition but running backwards" subs_nbit(circuit, qa, qb, qcar, n) circuit.cx(qb[n], qtemp) addition_nbit(circuit, qa, qb, qcar, n) cond_subs_nbit(circuit, qNtemp, qN, qcar, qtemp, n) subs_nbit(circuit, qN, qb, qcar, n) cond_addition_nbit(circuit, qNtemp, qN, qcar, qtemp, n) circuit.x(qb[n]) circuit.cx(qb[n], qtemp) circuit.x(qb[n]) addition_nbit(circuit, qN, qb, qcar, n) subs_nbit(circuit, qa, qb, qcar, n) # quantum controlled modular multiplication algorithm for n-qubit numbers def cont_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, qX, qext, N, n): for i in range(n): for j in range(n): classical_mod = (2**(i+j))%N cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) mod_addition_nbit(circuit, qtempst, qb, qN, qNtemp, qcar, qtemp, n) cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) circuit.x(qext) cond_addition_nbit(circuit, qX, qb, qcar, qext, n) circuit.x(qext) def cont_inv_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, qX, qext, N, n): "same as the controlled modular multiplication but running backwards" circuit.x(qext) cond_subs_nbit(circuit, qX, qb, qcar, qext, n) circuit.x(qext) for i in range(n): for j in range(n): classical_mod = (2**(i+j))%N cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) mod_subs_nbit(circuit, qtempst, qb, qN, qNtemp, qcar, qtemp, n) cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) # quantum modular exponentiation algorithm for n-qubit numbers def mod_exp_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, q1, qX, N, a, n): for k in range(len(qX)): clas_value = (a**(2**(k)))%N if k % 2 == 0: number_state(circuit, qa, clas_value, n) cont_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, q1, qX[k], N, n) number_state(circuit, qa, clas_value, n) clas_value = modinv(a**(2**(k)), N) number_state(circuit, qa, clas_value, n) cont_inv_mod_mult_nbit(circuit, qa, q1, qN, qNtemp, qcar, qtemp, qtempst, qb, qX[k], N, n) number_state(circuit, qa, clas_value, n) else: number_state(circuit, qa, clas_value, n) cont_mod_mult_nbit(circuit, qa, q1, qN, qNtemp, qcar, qtemp, qtempst, qb, qX[k], N, n) number_state(circuit, qa, clas_value, n) clas_value = modinv(a**(2**(k)), N) number_state(circuit, qa, clas_value, n) cont_inv_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, q1, qX[k], N, n) number_state(circuit, qa, clas_value, n) # n-qubit number input state def number_state(circuit, q, x, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: circuit.x(q[i]) # n-qubit number input state, controlled by 2 control qubits def cond_number_state(circuit, q, x, ext, control1, control2, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: cond_toffoli(circuit, ext, control1, control2, q[i]) # efficient algorithm for computing the modular multiplicative inverse a^-1 mod m def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m # we define the values, a and N must be coprimes a = 1 x = 1 N = 1 # computing number of qubits n needed n = len("{0:b}".format(a)) n2 = len("{0:b}".format(x)) n3 = len("{0:b}".format(N)) if n3 > n: n = n3 # classical register with n+1 bits. c = q_program.create_classical_register("cr", n+1) # quantum registers qa = q_program.create_quantum_register("qa", n) # a qubits qb = q_program.create_quantum_register("qb", n+1) # initial state |0> qN = q_program.create_quantum_register("qN", n+1) # N qubits qNtemp = q_program.create_quantum_register("qNtemp", n) # temporary N qubits qtemp = q_program.create_quantum_register("qtemp", 1) # temporary qubit qtempst = q_program.create_quantum_register("qtempst", n) # temporary register q1 = q_program.create_quantum_register("q1", n+1) # initial state |1> qX = q_program.create_quantum_register("qX", n2) # x register # if n = 1, no need of carry register if n == 1: qcar = 0 # quantum circuit involving the quantum registers and the classical register mod_exp_circuit = q_program.create_circuit("mod_exp", [qa, qb, qN, qNtemp, qtemp, qtempst, q1, qX],[c]) else: qcar = q_program.create_quantum_register("qcar", n-1) # carry qubits # quantum circuit involving the quantum registers and the classical register mod_exp_circuit = q_program.create_circuit("mod_exp", [qa, qb, qN, qcar, qNtemp, qtemp, qtempst, q1, qX],[c]) # create the initial state |1>. If N = 1, initial state is |0> if N != 1: number_state(mod_exp_circuit, q1, 1, 1) # create the state containing 'x' number_state(mod_exp_circuit, qX, x, n2) # create the state containing 'N' number_state(mod_exp_circuit, qN, N, n+1) # create a temporary state containing 'N' number_state(mod_exp_circuit, qNtemp, N, n) # modular exponentiation mod_exp_nbit(mod_exp_circuit, qa, qb, qN, qNtemp, qcar, qtemp[0], qtempst, q1, qX, N, a, n) # measurements to see the result, the result would be in one of those registers, q1 or qb if n2 % 2 == 0: for i in range(n+1): mod_exp_circuit.measure(q1[i], c[i]) else: for i in range(n+1): mod_exp_circuit.measure(qb[i], c[i]) # compile and execute the quantum program in the backend result = q_program.execute(["mod_exp"], backend=backend, shots=1024, max_credits=3, wait=10, timeout=9999999) # show the results. print(result) print(result.get_data("mod_exp")) counts = result.get_counts("mod_exp") plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2)))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
def digit_sum(n): num_str = str(n) sum = 0 for i in range(0, len(num_str)): sum += int(num_str[i]) return sum # CZ (Controlled-Z) # control qubit: q0 # target qubit: q1 def CZ(qp,q0,q1): qp.h(q1) qp.cx(q0,q1) qp.h(q1) # f-SWAP # taking into account the one-directionality of CNOT gates in the available devices def fSWAP(qp,q0,q1): qp.cx(q0,q1) qp.h(q0) qp.h(q1) qp.cx(q0,q1) qp.h(q0) qp.h(q1) qp.cx(q0,q1) CZ(qp,q0,q1) # CH (Controlled-Haddamard) # control qubit: q1 # target qubit: q0 def CH2(qp,q0,q1): qp.sdg(q0) qp.h(q0) qp.tdg(q0) qp.h(q0) qp.h(q1) qp.cx(q0,q1) qp.h(q0) qp.h(q1) qp.t(q0) qp.h(q0) qp.s(q0) # Fourier transform gates def F2(qp,q0,q1): qp.cx(q0,q1) CH2(qp,q0,q1) qp.cx(q0,q1) CZ(qp,q0,q1) def F0(qp,q0,q1): F2(qp,q0,q1) def F1(qp,q0,q1): F2(qp,q0,q1) qp.sdg(q0) from math import pi # ROTATIONAL GATES def RZ(qp,th,q0): qp.u1(-th,q0) def RY(qp,th,q0): qp.u3(th,0.,0.,q0) def RX(qp,th,q0): qp.u3(th,0.,pi,q0) # CRX (Controlled-RX) # control qubit: q0 # target qubit: q1 def CRX(qp,th,q0,q1): RZ(qp,pi/2.0,q1) RY(qp,th/2.0,q1) qp.cx(q0,q1) RY(qp,-th/2.0,q1) qp.cx(q0,q1) RZ(qp,-pi/2.0,q1) # Bogoliubov B_1 def B(qp,thk,q0,q1): qp.x(q1) qp.cx(q1,q0) CRX(qp,thk,q0,q1) qp.cx(q1,q0) qp.x(q1) # This circuit can be implemented in ibmqx5 using qubits (q0,q1,q2,q3)=(6,7,11,10) # It can also be implemented between other qubits or in ibqmx2 and ibqmx4 using fermionic SWAPS # For instance, the lines commented correspond to the implementations: # ibmqx2 (q0,q1,q2,q3)=(4,2,0,1) # ibmqx4 (q0,q1,q2,q3)=(3,2,1,0) def Udisg(qc,lam,q0,q1,q2,q3): k=1 n=4 th1=-np.arccos((lam-np.cos(2*pi*k/n))/np.sqrt((lam-np.cos(2*pi*k/n))**2+np.sin(2*pi*k/n)**2)) B(Udis,th1,q0,q1) F1(Udis,q0,q1) F0(Udis,q2,q3) #fSWAP(Udis,q2,q1) # for ibmqx2 #fSWAP(Udis,q1,q2) # for ibmqx4 F0(Udis,q0,q2) F0(Udis,q1,q3) #fSWAP(Udis,q2,q1) # for ibmqx2 #fSWAP(Udis,q1,q2) # for ibmqx4 def Initial(qc,lam,q0,q1,q2,q3): if lam <1: qc.x(q3) def Ising(qc,ini,udis,mes,lam,q0,q1,q2,q3,c0,c1,c2,c3): Initial(ini,lam,q0,q1,q2,q3) Udisg(udis,lam,q0,q1,q2,q3) mes.measure(q0,c0) mes.measure(q1,c1) mes.measure(q2,c2) mes.measure(q3,c3) qc.add_circuit("Ising",ini+udis+mes) #import sys #sys.path.append("../../") # importing the QISKit from qiskit import QuantumCircuit,QuantumProgram #import Qconfig # useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from scipy import linalg as la # Simulator shots = 1024 backend ='ibmqx_qasm_simulator' coupling_map = None mag_sim = [] for i in range(8): Isex = QuantumProgram() q = Isex.create_quantum_register("q",4) c = Isex.create_classical_register("c", 4) Udis = Isex.create_circuit("Udis", [q], [c]) ini = Isex.create_circuit("ini",[q],[c]) mes = Isex.create_circuit("mes",[q],[c]) lam=i*0.25 Ising(Isex,ini,Udis,mes,lam,q[0],q[1],q[2],q[3],c[0],c[1],c[2],c[3]) # Isex.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url result = Isex.execute(["Ising"], backend=backend, coupling_map=coupling_map, shots=shots,timeout=240000) res=result.get_counts("Ising") r1=list(res.keys()) r2=list(res.values()) M=0 for j in range(0,len(r1)): M=M+(4-2*digit_sum(r1[j]))*r2[j]/shots #print("$\lambda$: ",lam,", $<\sigma_{z}>$: ",M/4) mag_sim.append(M/4) # Real device shots = 1024 #backend ='ibmqx5' max_credits = 5 mag=[] for i in range(8): Isex = QuantumProgram() q = Isex.create_quantum_register("q",12) c = Isex.create_classical_register("c", 4) Udis = Isex.create_circuit("Udis", [q], [c]) ini = Isex.create_circuit("ini",[q],[c]) mes = Isex.create_circuit("mes",[q],[c]) lam=i*0.25 Ising(Isex,ini,Udis,mes,lam,q[6],q[7],q[11],q[10],c[0],c[1],c[2],c[3]) # Isex.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url result = Isex.execute(["Ising"], backend=backend, max_credits=max_credits, wait=10, shots=shots,timeout=240000) res=result.get_counts("Ising") r1=list(res.keys()) r2=list(res.values()) M=0 for j in range(0,len(r1)): M=M+(4-2*digit_sum(r1[j]))*r2[j]/shots #print("$\lambda$: ",lam,", $<\sigma_{z}>$: ",M/4) mag.append(M/4) # As it is a system of only 4 particles, we can easily compute the exact result def exact(lam): if lam <1: return lam/(2*np.sqrt(1+lam**2)) if lam >1: return 1/2+lam/(2*np.sqrt(1+lam**2)) return None vexact = np.vectorize(exact) l=np.arange(0.0,2.0,0.01) l1=np.arange(0.0,2.0,0.25) plt.figure(figsize=(9,5)) plt.plot(l,vexact(l),'k',label='exact') plt.plot(l1, mag_sim, 'bo',label='simulation') plt.plot(l1, mag, 'r*',label='ibmqx5') plt.xlabel('$\lambda$') plt.ylabel('$<\sigma_{z}>$') plt.legend() plt.title('Magnetization of the ground state of n=4 Ising spin chain') plt.show() #This was the result when the real device is used: def Initial_time(qc,t,lam,q0,q1,q2,q3): qc.u3(np.arccos(lam/np.sqrt(1+lam**2)),pi/2.+4*t*np.sqrt(1+lam**2),0.,q0) qc.cx(q0,q1) def Ising_time(qc,ini,udis,mes,lam,t,q0,q1,q2,q3,c0,c1,c2,c3): Initial_time(ini,t,lam,q0,q1,q2,q3) Udisg(udis,lam,q0,q1,q2,q3) mes.measure(q0,c0) mes.measure(q1,c1) mes.measure(q2,c2) mes.measure(q3,c3) qc.add_circuit("Ising_time",ini+udis+mes) #Simulation shots = 1024 backend = 'ibmqx_qasm_simulator' coupling_map = None # We compute the time evolution for lambda=0.5,0.9 and 1.8 nlam=3 magt_sim=[[] for _ in range(nlam)] lam0=[0.5,0.9,1.8] for j in range(nlam): lam=lam0[j] for i in range(9): Isex_time = QuantumProgram() q = Isex_time.create_quantum_register("q",4) c = Isex_time.create_classical_register("c", 4) Udis = Isex_time.create_circuit("Udis", [q], [c]) ini = Isex_time.create_circuit("ini",[q],[c]) mes = Isex_time.create_circuit("mes",[q],[c]) t=i*0.25 Ising_time(Isex_time,ini,Udis,mes,lam,t,q[0],q[1],q[2],q[3],c[0],c[1],c[2],c[3]) Isex_time.set_api(Qconfig.APItoken, Qconfig.config["url"]) result = Isex_time.execute(["Ising_time"], backend=backend, coupling_map=coupling_map, shots=shots,timeout=240000) res=result.get_counts("Ising_time") r1=list(res.keys()) r2=list(res.values()) M=0 for k in range(0,len(r1)): M=M+(4-2*digit_sum(r1[k]))*r2[k]/shots magt_sim[j].append(M/4) shots = 1024 backend = 'ibmqx5' max_credits = 5 # We compute the time evolution for lambda=0.5,0.9 and 1.8 nlam=3 magt=[[] for _ in range(nlam)] lam0=[0.5,0.9,1.8] for j in range(nlam): lam=lam0[j] for i in range(9): Isex_time = QuantumProgram() q = Isex_time.create_quantum_register("q",12) c = Isex_time.create_classical_register("c", 4) Udis = Isex_time.create_circuit("Udis", [q], [c]) ini = Isex_time.create_circuit("ini",[q],[c]) mes = Isex_time.create_circuit("mes",[q],[c]) t=i*0.25 Ising_time(Isex_time,ini,Udis,mes,lam,t,q[6],q[7],q[11],q[10],c[0],c[1],c[2],c[3]) Isex_time.set_api(Qconfig.APItoken, Qconfig.config["url"]) result = Isex_time.execute(["Ising_time"], backend=backend, max_credits=max_credits, wait=10, shots=shots,timeout=240000) res=result.get_counts("Ising_time") r1=list(res.keys()) r2=list(res.values()) M=0 for k in range(0,len(r1)): M=M+(4-2*digit_sum(r1[k]))*r2[k]/shots magt[j].append(M/4) def exact_time(lam,tt): Mt=(1 + 2*lam**2 + np.cos(4*tt*np.sqrt(1 + lam**2)))/(2 + 2*lam**2) return Mt vexact_t = np.vectorize(exact_time) t=np.arange(0.0,2.0,0.01) tt=np.arange(0.0,2.25,0.25) plt.figure(figsize=(10,5)) plt.plot(t,vexact_t(0.5,t),'b',label='$\lambda=0.5$') plt.plot(t,vexact_t(0.9,t),'r',label='$\lambda=0.9$') plt.plot(t,vexact_t(1.8,t),'g',label='$\lambda=1.8$') #plt.plot(tt, magt_sim[0], 'bo',label='simulation') #plt.plot(tt, magt_sim[1], 'ro') #plt.plot(tt, magt_sim[2], 'go') plt.plot(tt, magt[0], 'b*',label='ibmqx5') plt.plot(tt, magt[1], 'r*') plt.plot(tt, magt[2], 'g*') plt.plot(tt, magt[0], 'b--') plt.plot(tt, magt[1], 'r--') plt.plot(tt, magt[2], 'g--') plt.xlabel('time') plt.ylabel('$<\sigma_{z}>$') plt.legend() plt.title('Time evolution |↑↑↑↑> state') plt.show() plt.figure(figsize=(13,3)) plt.subplot(1,3,1) plt.plot(t,vexact_t(0.5,t),'b',label='$\lambda=0.5$') plt.plot(tt, magt[0], 'b*',label='ibmqx5') plt.plot(tt, magt[0], 'b--',label='ibmqx5') plt.xlabel('time') plt.ylabel('$<\sigma_{z}>$') plt.title('$\lambda=0.5$') plt.subplot(132) plt.plot(t,vexact_t(0.9,t),'r',label='$\lambda=0.9$') plt.plot(tt, magt[1], 'r*',label='ibmqx5') plt.plot(tt, magt[1], 'r--',label='ibmqx5') plt.xlabel('time') plt.ylabel('$<\sigma_{z}>$') plt.title('$\lambda=0.9$') plt.subplot(133) plt.plot(t,vexact_t(1.8,t),'g',label='$\lambda=1.8$') plt.plot(tt, magt[2], 'g*',label='ibmqx5') plt.plot(tt, magt[2], 'g--',label='ibmqx5') plt.xlabel('time') plt.ylabel('$<\sigma_{z}>$') plt.title('$\lambda=1.8$') plt.tight_layout() plt.show()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np # These column vectors can be stored in numpy arrays so that we can operate # on them with the circuit diagram's corresponding matrix (which is to be evaluated) # as follows: zero_zero = np.array([[1],[0],[0],[0]]) zero_one = np.array([[0],[1],[0],[0]]) one_zero = np.array([[0],[0],[1],[0]]) one_one = np.array([[0],[0],[0],[1]]) Psi = {'zero_zero': zero_zero, 'zero_one': zero_one, 'one_zero': one_zero, 'one_one': one_one} # ^We can conveniently store all possible input states in a dictionary and then print to check the representations: for key, val in Psi.items(): print(key, ':', '\n', val) # storing CNOT as a numpy array: CNOT_1 = np.matrix([[1, 0, 0, 0],[0, 1, 0, 0],[0, 0, 0, 1],[0, 0, 1, 0]]) print(CNOT_1) print('FINAL STATE OF i):') #Apply CNOT to each possible state for |Psi> to find |Psi'> for key, val in Psi.items(): print(key, 'becomes..\n', CNOT_1*val) # storing this in a numpy array: H_2 = .5*np.matrix([[1, 1, 1, 1],[1, -1, 1, -1],[1, 1, -1, -1],[1, -1, -1, 1]]) print('H_2:') print(H_2) # storing this in a numpy array: CNOT_2 = np.matrix([[1, 0, 0, 0],[0, 0, 0, 1],[0, 0, 1, 0],[0, 1, 0, 0]]) A = H_2*CNOT_2*H_2 print(A) print(CNOT_1) for key, val in Psi.items(): print(key, 'becomes...\n', A*val) # import necessary libraries import numpy as np from pprint import pprint # import Qiskit from qiskit import execute, Aer, IBMQ from qiskit.backends.ibmq import least_busy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.tools.visualization import plot_histogram # useful additional packages from qiskit.tools.visualization import plot_histogram IBMQ.load_accounts() # This initial state register # can be realized in python by creating an instance of the # Qiskit quantum register of 2 qubits # and 2 classical ancilla bits for measuring the states n = 2 i_q = QuantumRegister(n, name="i_q") i_c = ClassicalRegister(n, name="i_c") IBMQ.available_backends() #check backends - if you've set up your APIToken properly you #should be able to see the quantum chips and simulators at IBM for backend in IBMQ.available_backends(): #check backend status print(backend.name()) pprint(backend.status()) def execute_and_plot(circuits, backend = Aer.get_backend('qasm_simulator')): """Executes circuits and plots the final state histograms the for each circuit. Adapted from 'execute_and_plot' function in the beginners_guide_composer_examples notebook provided in IBM's Qiskit tutorial library on GitHub. Args: circuits (list): list of circuits to execute backend (string): allows for specifying the backend to execute on. Defaults to local qasm simulator downloaded with Qiskit library, but can be specified to run on an actual quantum chip by using the string names of the available backends at IBM. """ # Store the results of the circuit implementation # using the .execute() method results = execute(circuits, backend = backend).result() plot_histogram(results.get_counts()) # .get_counts(): # method returns a dictionary that maps each possible # final state to the number of instances of # said state over n evaluations # (n defaults to 1024 for local qasm simulator), # where multiple evaluations are a necessity since # quantum computation outputs are probability # dependent # Initialize circuit: cnot_i_00 = QuantumCircuit(i_q, i_c, name="cnot_i_00") # Note: qubits are assumed by Qiskit # to be initialized in the |0> state # Apply gates according to diagram: cnot_i_00.cx(i_q[0], i_q[1]) # Apply CNOT on line 2 controlled by line 1 # Measure final state: cnot_i_00.measure(i_q[0], i_c[0]) # Write qubit 1 state onto classical ancilla bit 1 cnot_i_00.measure(i_q[1], i_c[1]) # Write qubit 2 state onto classical ancilla bit 2 # Display final state probabilities: execute_and_plot(cnot_i_00) print(cnot_i_00.qasm()) # Initialize circuit: cnot_i_01 = QuantumCircuit(i_q, i_c, name="cnot_i_01") cnot_i_01.x(i_q[0]) # Set the 1st qubit to |1> by flipping # the initialized |0> with an X gate before implementing # the circuit # Apply gates according to diagram: cnot_i_01.cx(i_q[0], i_q[1]) # Apply CNOT controlled by line 1 # Measure final state: cnot_i_01.measure(i_q[0], i_c[0]) cnot_i_01.measure(i_q[1], i_c[1]) # Display final state probabilities: execute_and_plot(cnot_i_01) # Initialize circuit: cnot_i_10 = QuantumCircuit(i_q, i_c, name="cnot_i_10") cnot_i_10.x(i_q[1]) # Set the 2nd qubit to |1> # Apply gates according to diagram: cnot_i_10.cx(i_q[0], i_q[1]) # Apply CNOT controlled by line 1 # Measure final state: cnot_i_10.measure(i_q[0], i_c[0]) cnot_i_10.measure(i_q[1], i_c[1]) # Display final state probabilities: execute_and_plot(cnot_i_10) # Initialize circuit: cnot_i_11 = QuantumCircuit(i_q, i_c, name="cnot_i_11") cnot_i_11.x(i_q[0]) # Set the 1st qubit to |1> cnot_i_11.x(i_q[1]) # Set the 2nd qubit to |1> # Apply gates according to diagram: cnot_i_11.cx(i_q[0], i_q[1]) # Apply CNOT controlled by line 1 # Measure final states: cnot_i_11.measure(i_q[0], i_c[0]) cnot_i_11.measure(i_q[1], i_c[1]) # Display final state probabilities: execute_and_plot(cnot_i_11) # For circuit ii, we can again create a quantum register of size # 2 with 2 classical ancilla bits for measurement n = 2 ii_q = QuantumRegister(n, name="ii_q") ii_c = ClassicalRegister(n, name="ii_c") IBMQ.available_backends() #check backends - if you've set up your APIToken properly you #should be able to see the quantum chips and simulators at IBM for backend in IBMQ.available_backends(): #check backend status print(backend.name()) pprint(backend.status()) # Initialize circuit: cnot_ii_00 = QuantumCircuit(ii_q, ii_c, name="cnot_ii_00") cnot_ii_01.x(ii_q[0]) # Apply gates according to diagram: cnot_ii_00.h(ii_q) # Apply hadamards in parallel. # Note that specifying a register (rather than a qubit) # for some gate method argument applies the gate to all # qubits in the register cnot_ii_00.cx(ii_q[1], ii_q[0]) # Apply CNOT controlled by line 2 cnot_ii_00.h(ii_q) # Apply hadamards in parallel. # Measure final state: cnot_ii_00.measure(ii_q[0], ii_c[0]) cnot_ii_00.measure(ii_q[1], ii_c[1]) # Display final state probabilities execute_and_plot(cnot_ii_00) # Initialize circuit: cnot_ii_01 = QuantumCircuit(ii_q, ii_c, name="cnot_ii_01") cnot_ii_01.x(ii_q[0]) # Set the 1st qubit to |1> # Apply gates according to diagram: cnot_ii_00.h(ii_q) # Apply hadamards in parallel cnot_ii_01.cx(ii_q[1], ii_q[0]) # Apply CNOT controlled by line 2 cnot_ii_00.h(ii_q) # Apply hadamards in parallel # Measure final state: cnot_ii_01.measure(ii_q[0], ii_c[0]) cnot_ii_01.measure(ii_q[1], ii_c[1]) # Display final state probabilities: execute_and_plot(cnot_ii_01) # Initialize circuits cnot_ii_10 = QuantumCircuit(ii_q, ii_c, name="cnot_ii_10") cnot_ii_10.x(ii_q[1]) # Set the 2nd qubit to |1> # Apply gates according to diagram: cnot_ii_00.h(ii_q) # Apply hadamards in parallel cnot_ii_10.cx(ii_q[1], ii_q[0]) # Apply CNOT controlled by line 2 cnot_ii_00.h(ii_q) # Apply hadamards in parallel # Measure final state: cnot_ii_10.measure(ii_q[0], ii_c[0]) cnot_ii_10.measure(ii_q[1], ii_c[1]) # Display final state probabilities: execute_and_plot(cnot_ii_10) # Initialize circuits: cnot_ii_11 = QuantumCircuit(ii_q, ii_c, name="cnot_ii_11") cnot_ii_11.x(ii_q[0]) # Set the 1st qubit to |1> cnot_ii_11.x(ii_q[1]) # Set the 2nd qubit to |1> # Apply gates according to diagram: cnot_ii_00.h(ii_q) # Apply hadamards in parallel cnot_ii_11.cx(ii_q[1], ii_q[0]) # Apply CNOT controlled by line 2 cnot_ii_00.h(ii_q) # Apply hadamards in parallel # Measure final state cnot_ii_11.measure(ii_q[0], ii_c[0]) cnot_ii_11.measure(ii_q[1], ii_c[1]) # Display final state probabilities execute_and_plot(cnot_ii_11) def circuit_i(): i_q = QuantumRegister(2, name='i_q') i_c = ClassicalRegister(2, name='i_c') initial_states = ['00','01','10','11'] initial_circuits = {state: QuantumCircuit(i_q, i_c, name='%s'%(state)) \ for state in initial_states} final_circuits = {} for state in initial_states: if state[0] is '1': initial_circuits[state].x(i_q[0]) if state[1] is '1': initial_circuits[state].x(i_q[1]) initial_circuits[state].cx(i_q[0], i_q[1]) initial_circuits[state].measure(i_q[0], i_c[0]) initial_circuits[state].measure(i_q[1], i_c[1]) final_circuits[state] = initial_circuits[state] return initial_circuits def circuit_ii(): ii_q = QuantumRegister(2, name='ii_q') ii_c = ClassicalRegister(2, name='ii_c') initial_states = ['00','01','10','11'] circuits = {state: QuantumCircuit(ii_q, ii_c, name='%s'%(state)) \ for state in initial_states} for state in initial_states: if state[0] is '1': circuits[state].x(ii_q[0]) if state[1] is '1': circuits[state].x(ii_q[1]) circuits[state].h(ii_q) circuits[state].cx(ii_q[1], ii_q[0]) circuits[state].h(ii_q) circuits[state].measure(ii_q[0], ii_c[0]) circuits[state].measure(ii_q[1], ii_c[1]) return circuits i = circuit_i() ii = circuit_ii() # Use the IBMQ Quantum Experience backend = least_busy(IBMQ.backends()) # Use local qasm simulator # backend = Aer.get_backend('qasm_simulator') results_i = execute(list(i.values()), backend=backend).result() results_ii = execute(list(ii.values()), backend=backend).result() results_i_mapping = {circuit: results_i.get_counts(circuit) for circuit in list(results_i.get_names())} results_ii_mapping = {circuit: results_ii.get_counts(circuit) for circuit in list(results_ii.get_names())} print(results_i_mapping) print(results_ii_mapping) print('results_i') for circuit in list(results_i.get_names()): plot_histogram(results_i.get_counts(circuit)) print('results_ii') for circuit in list(results_ii.get_names()): plot_histogram(results_ii.get_counts(circuit))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
#import all the packages # Checking the version of PYTHON import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') #append to system path so qiskit and Qconfig can be found from home directory sys.path.append('../qiskit-sdk-py/') # Import the QuantumProgram and configuration from qiskit import QuantumProgram #import Qconfig #other useful packages import math #Super secret message mes = 'hello world' print('Your super secret message: ',mes) #initial size of key n = len(mes)*3 #break up message into smaller parts if length > 10 nlist = [] for i in range(int(n/10)): nlist.append(10) if n%10 != 0: nlist.append(n%10) print('Initial key length: ',n) # Make random strings of length string_length def randomStringGen(string_length): #output variables used to access quantum computer results at the end of the function output_list = [] output = '' #start up your quantum program qp = QuantumProgram() backend = 'local_qasm_simulator' circuits = ['rs'] #run circuit in batches of 10 qubits for fastest results. The results #from each run will be appended and then clipped down to the right n size. n = string_length temp_n = 10 temp_output = '' for i in range(math.ceil(n/temp_n)): #initialize quantum registers for circuit q = qp.create_quantum_register('q',temp_n) c = qp.create_classical_register('c',temp_n) rs = qp.create_circuit('rs',[q],[c]) #create temp_n number of qubits all in superpositions for i in range(temp_n): rs.h(q[i]) #the .h gate is the Hadamard gate that makes superpositions rs.measure(q[i],c[i]) #execute circuit and extract 0s and 1s from key result = qp.execute(circuits, backend, shots=1) counts = result.get_counts('rs') result_key = list(result.get_counts('rs').keys()) temp_output = result_key[0] output += temp_output #return output clipped to size of desired string length return output[:n] key = randomStringGen(n) print('Initial key: ',key) #generate random rotation strings for Alice and Bob Alice_rotate = randomStringGen(n) Bob_rotate = randomStringGen(n) print("Alice's rotation string:",Alice_rotate) print("Bob's rotation string: ",Bob_rotate) #start up your quantum program backend = 'local_qasm_simulator' shots = 1 circuits = ['send_over'] Bob_result = '' for ind,l in enumerate(nlist): #define temp variables used in breaking up quantum program if message length > 10 if l < 10: key_temp = key[10*ind:10*ind+l] Ar_temp = Alice_rotate[10*ind:10*ind+l] Br_temp = Bob_rotate[10*ind:10*ind+l] else: key_temp = key[l*ind:l*(ind+1)] Ar_temp = Alice_rotate[l*ind:l*(ind+1)] Br_temp = Bob_rotate[l*ind:l*(ind+1)] #start up the rest of your quantum program qp2 = QuantumProgram() q = qp2.create_quantum_register('q',l) c = qp2.create_classical_register('c',l) send_over = qp2.create_circuit('send_over',[q],[c]) #prepare qubits based on key; add Hadamard gates based on Alice's and Bob's #rotation strings for i,j,k,n in zip(key_temp,Ar_temp,Br_temp,range(0,len(key_temp))): i = int(i) j = int(j) k = int(k) if i > 0: send_over.x(q[n]) #Look at Alice's rotation string if j > 0: send_over.h(q[n]) #Look at Bob's rotation string if k > 0: send_over.h(q[n]) send_over.measure(q[n],c[n]) #execute quantum circuit result_so = qp2.execute(circuits, backend, shots=shots) counts_so = result_so.get_counts('send_over') result_key_so = list(result_so.get_counts('send_over').keys()) Bob_result += result_key_so[0][::-1] print("Bob's results: ", Bob_result) def makeKey(rotation1,rotation2,results): key = '' count = 0 for i,j in zip(rotation1,rotation2): if i == j: key += results[count] count += 1 return key Akey = makeKey(Bob_rotate,Alice_rotate,key) Bkey = makeKey(Bob_rotate,Alice_rotate,Bob_result) print("Alice's key:",Akey) print("Bob's key: ",Bkey) #make key same length has message shortened_Akey = Akey[:len(mes)] encoded_m='' #encrypt message mes using encryption key final_key for m,k in zip(mes,shortened_Akey): encoded_c = chr(ord(m) + 2*ord(k) % 256) encoded_m += encoded_c print('encoded message: ',encoded_m) #make key same length has message shortened_Bkey = Bkey[:len(mes)] #decrypt message mes using encryption key final_key result = '' for m,k in zip(encoded_m,shortened_Bkey): encoded_c = chr(ord(m) - 2*ord(k) % 256) result += encoded_c print('recovered message:',result) #start up your quantum program backend = 'local_qasm_simulator' shots = 1 circuits = ['Eve'] Eve_result = '' for ind,l in enumerate(nlist): #define temp variables used in breaking up quantum program if message length > 10 if l < 10: key_temp = key[10*ind:10*ind+l] Ar_temp = Alice_rotate[10*ind:10*ind+l] else: key_temp = key[l*ind:l*(ind+1)] Ar_temp = Alice_rotate[l*ind:l*(ind+1)] #start up the rest of your quantum program qp3 = QuantumProgram() q = qp3.create_quantum_register('q',l) c = qp3.create_classical_register('c',l) Eve = qp3.create_circuit('Eve',[q],[c]) #prepare qubits based on key; add Hadamard gates based on Alice's and Bob's #rotation strings for i,j,n in zip(key_temp,Ar_temp,range(0,len(key_temp))): i = int(i) j = int(j) if i > 0: Eve.x(q[n]) if j > 0: Eve.h(q[n]) Eve.measure(q[n],c[n]) #execute result_eve = qp3.execute(circuits, backend, shots=shots) counts_eve = result_eve.get_counts('Eve') result_key_eve = list(result_eve.get_counts('Eve').keys()) Eve_result += result_key_eve[0][::-1] print("Eve's results: ", Eve_result) #start up your quantum program backend = 'local_qasm_simulator' shots = 1 circuits = ['Eve2'] Bob_badresult = '' for ind,l in enumerate(nlist): #define temp variables used in breaking up quantum program if message length > 10 if l < 10: key_temp = key[10*ind:10*ind+l] Eve_temp = Eve_result[10*ind:10*ind+l] Br_temp = Bob_rotate[10*ind:10*ind+l] else: key_temp = key[l*ind:l*(ind+1)] Eve_temp = Eve_result[l*ind:l*(ind+1)] Br_temp = Bob_rotate[l*ind:l*(ind+1)] #start up the rest of your quantum program qp4 = QuantumProgram() q = qp4.create_quantum_register('q',l) c = qp4.create_classical_register('c',l) Eve2 = qp4.create_circuit('Eve2',[q],[c]) #prepare qubits for i,j,n in zip(Eve_temp,Br_temp,range(0,len(key_temp))): i = int(i) j = int(j) if i > 0: Eve2.x(q[n]) if j > 0: Eve2.h(q[n]) Eve2.measure(q[n],c[n]) #execute result_eve = qp4.execute(circuits, backend, shots=shots) counts_eve = result_eve.get_counts('Eve2') result_key_eve = list(result_eve.get_counts('Eve2').keys()) Bob_badresult += result_key_eve[0][::-1] print("Bob's previous results (w/o Eve):",Bob_result) print("Bob's results from Eve:\t\t ",Bob_badresult) #make keys for Alice and Bob Akey = makeKey(Bob_rotate,Alice_rotate,key) Bkey = makeKey(Bob_rotate,Alice_rotate,Bob_badresult) print("Alice's key: ",Akey) print("Bob's key: ",Bkey) check_key = randomStringGen(len(Akey)) print('spots to check:',check_key) #find which values in rotation string were used to make the key Alice_keyrotate = makeKey(Bob_rotate,Alice_rotate,Alice_rotate) Bob_keyrotate = makeKey(Bob_rotate,Alice_rotate,Bob_rotate) # Detect Eve's interference #extract a subset of Alice's key sub_Akey = '' sub_Arotate = '' count = 0 for i,j in zip(Alice_rotate,Akey): if int(check_key[count]) == 1: sub_Akey += Akey[count] sub_Arotate += Alice_keyrotate[count] count += 1 #extract a subset of Bob's key sub_Bkey = '' sub_Brotate = '' count = 0 for i,j in zip(Bob_rotate,Bkey): if int(check_key[count]) == 1: sub_Bkey += Bkey[count] sub_Brotate += Bob_keyrotate[count] count += 1 print("subset of Alice's key:",sub_Akey) print("subset of Bob's key: ",sub_Bkey) #compare Alice and Bob's key subsets secure = True for i,j in zip(sub_Akey,sub_Bkey): if i == j: secure = True else: secure = False break; if not secure: print('Eve detected!') else: print('Eve escaped detection!') #sub_Akey and sub_Bkey are public knowledge now, so we remove them from Akey and Bkey if secure: new_Akey = '' new_Bkey = '' for index,i in enumerate(check_key): if int(i) == 0: new_Akey += Akey[index] new_Bkey += Bkey[index] print('new A and B keys: ',new_Akey,new_Bkey) if(len(mes)>len(new_Akey)): print('Your new key is not long enough.') #!!! you may need to execute this cell twice in order to see the output due to an problem with matplotlib import matplotlib.pyplot as plt import numpy as np x = np.arange(0., 30.0) y = 1-(3/4)**x plt.plot(y) plt.title('Probablity of detecting Eve') plt.xlabel('# of key bits compared') plt.ylabel('Probablity of detecting Eve') plt.show()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from IPython.display import Image Image(filename="error_correction_files/error_correction_1_0.png", width=450, height=300) Image(filename="error_correction_files/error_correction_3_0.png", width=450, height=300) Image(filename="error_correction_files/error_correction_5_0.png", width=450, height=300) Image(filename="error_correction_files/error_correction_7_0.png", width=450, height=300) import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') from qiskit import QuantumProgram #import Qconfig # Needed to visualize quantum circuits import os import shutil from qiskit.tools.visualization import latex_drawer import pdf2image from IPython.display import Image # Initialize quantum program qp = QuantumProgram() #qp.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url # Circuit requires 5 qubits and 5 classical bits qr = qp.create_quantum_register('qr', 5) cr = qp.create_classical_register('cr',5) qc = qp.create_circuit('Circuit', [qr], [cr]) circuit = qp.get_circuit('Circuit') # get the Quantum Register by Name quantum_r = qp.get_quantum_register('qr') # get the Classical Register by Name classical_r = qp.get_classical_register('cr') def circuitImage(circuit, filename, basis="u1,u2,u3,cx"): """ Obtain the circuit in image format Note: Requires pdflatex installed (to compile Latex) Note: Required pdf2image Python package (to display pdf as image) """ tmpdir='tmp/' if not os.path.exists(tmpdir): os.makedirs(tmpdir) latex_drawer(circuit, tmpdir+filename+".tex", basis=basis) os.system("pdflatex -output-directory {} {}".format(tmpdir, filename+".tex")) images = pdf2image.convert_from_path(tmpdir+filename+".pdf") shutil.rmtree(tmpdir) return images[0] def toffoli(circuit,quantum_r,a,b,c): """ Creates toffoli gate in existing circuit with a and b as the test points and c as the affected point """ circuit.iden(quantum_r[c]) circuit.h(quantum_r[c]) circuit.cx(quantum_r[b],quantum_r[c]) circuit.tdg(quantum_r[c]) circuit.cx(quantum_r[a],quantum_r[c]) circuit.t(quantum_r[c]) circuit.cx(quantum_r[b],quantum_r[c]) circuit.tdg(quantum_r[c]) circuit.cx(quantum_r[a],quantum_r[c]) circuit.t(quantum_r[c]) circuit.t(quantum_r[b]) circuit.h(quantum_r[c]) circuit.cx(quantum_r[b],quantum_r[c]) circuit.h(quantum_r[c]) circuit.h(quantum_r[b]) circuit.cx(quantum_r[b],quantum_r[c]) circuit.h(quantum_r[c]) circuit.h(quantum_r[b]) circuit.cx(quantum_r[b],quantum_r[c]) circuit.cx(quantum_r[a],quantum_r[c]) circuit.t(quantum_r[a]) circuit.tdg(quantum_r[c]) circuit.cx(quantum_r[a],quantum_r[c]) circuit.cx(quantum_r[b],quantum_r[c]) circuit.cx(quantum_r[c],quantum_r[b]) circuit.cx(quantum_r[b],quantum_r[c]) #circuit.x(quantum_r[2]) circuit.x(quantum_r[3]) circuit.x(quantum_r[4]) circuit.cx(quantum_r[2],quantum_r[0]) circuit.cx(quantum_r[3],quantum_r[0]) circuit.cx(quantum_r[3],quantum_r[1]) circuit.cx(quantum_r[4],quantum_r[1]) circuit.cx(quantum_r[0],quantum_r[2]) circuit.cx(quantum_r[1],quantum_r[4]) toffoli(circuit,quantum_r,0,1,2) toffoli(circuit,quantum_r,0,1,3) toffoli(circuit,quantum_r,0,1,4) circuit.measure(quantum_r[0], classical_r[0]) circuit.measure(quantum_r[1], classical_r[1]) circuit.measure(quantum_r[2], classical_r[2]) circuit.measure(quantum_r[3], classical_r[3]) circuit.measure(quantum_r[4], classical_r[4]) """ Image of the final circuit. Becuase it contains three Toffoli gates where each gate is made up of many basis gates, this circuit is unfortunately very hard to visualize. """ basis="u1,u2,u3,cx,x,y,z,h,s,t,rx,ry,rz" circuitImage(circuit,'circuit',basis) #!!! for better visibility plot using the now built-in code from qiskit.tools.visualization import circuit_drawer circuit_drawer(circuit) """ Results of the computation. Note that the states of the five qubits from up to down in the circuit are shown from right to left in the result. """ backend = 'ibmqx_qasm_simulator' circuits = ['Circuit'] # Group of circuits to execute qobj=qp.compile(circuits, backend, shots=1024, max_credits=3) result = qp.run(qobj, wait=2, timeout=240) print(result.get_counts('Circuit')) Image(filename="error_correction_files/error_correction_27_0.png", width=250, height=300) Image(filename="error_correction_files/error_correction_30_0.png", width=450, height=300) Image(filename="error_correction_files/error_correction_33_0.png", width=450, height=300) Image(filename="error_correction_files/error_correction_36_0.png", width=450, height=300) Image(filename="error_correction_files/error_correction_39_0.png", width=900, height=600) Image(filename="error_correction_files/error_correction_40_0.png", width=900, height=600) Image(filename="error_correction_files/error_correction_43_0.png", width=900, height=450)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from utils import version; version.version_information()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# Checking the version of PYTHON; we only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') #Importing qiskit and math lib from qiskit import QuantumProgram import math #import Qconfig pi = math.pi theta_list = [0.01, 0.02, 0.03, 0.04, 0.05, 1.31, 1.32, 1.33, 1.34, 1.35] Q_program = QuantumProgram() #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) def k_means(): # create Quantum Register called "qr" with 5 qubits qr = Q_program.create_quantum_register("qr", 5) # create Classical Register called "cr" with 5 bits cr = Q_program.create_classical_register("cr", 5) # Creating Quantum Circuit called "qc" involving your Quantum Register "qr" # and your Classical Register "cr" qc = Q_program.create_circuit("k_means", [qr], [cr]) #Define a loop to compute the distance between each pair of points for i in range(9): for j in range(1,10-i): # Set the parament theta about different point theta_1 = theta_list[i] theta_2 = theta_list[i+j] #Achieve the quantum circuit via qiskit qc.h(qr[2]) qc.h(qr[1]) qc.h(qr[4]) qc.u3(theta_1, pi, pi, qr[1]) qc.u3(theta_2, pi, pi, qr[4]) qc.cswap(qr[2], qr[1], qr[4]) qc.h(qr[2]) qc.measure(qr[2], cr[2]) qc.reset(qr) result = Q_program.execute("k_means", backend = 'local_qasm_simulator') print(result) print('theta_1:' + str(theta_1)) print('theta_2:' + str(theta_2)) print( result.get_data("k_means")) #result = Q_program.execute(["reset"], backend='ibmqx4', shots=1024, timeout=600) if __name__ == "__main__": k_means() %run "../version.ipynb"
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# Checking the version of PYTHON; we only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') from qiskit import QuantumProgram import math #import Qconfig #Define a QuantumProgram object Q_program = QuantumProgram() #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) pi = math.pi def solve_linear_sys(): #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # create Quantum Register called "qr" with 4 qubits qr = Q_program.create_quantum_register("qr", 4) # create Quantum Register called "cr" with 4 qubits cr = Q_program.create_classical_register("cr", 4) # Creating Quantum Circuit called "qc" involving your Quantum Register "qr" # and your Classical Register "cr" qc = Q_program.create_circuit("solve_linear_sys", [qr], [cr]) # Initialize times that we get the result vector n0 = 0 n1 = 0 for i in range(10): #Set the input|b> state" qc.x(qr[2]) #Set the phase estimation circuit qc.h(qr[0]) qc.h(qr[1]) qc.u1(pi, qr[0]) qc.u1(pi/2, qr[1]) qc.cx(qr[1], qr[2]) #The quantum inverse Fourier transform qc.h(qr[0]) qc.cu1(-pi/2, qr[0], qr[1]) qc.h(qr[1]) #R(lamda^-1) Rotation qc.x(qr[1]) qc.cu3(pi/16, 0, 0, qr[0], qr[3]) qc.cu3(pi/8, 0, 0, qr[1], qr[3]) #Uncomputation qc.x(qr[1]) qc.h(qr[1]) qc.cu1(pi/2, qr[0], qr[1]) qc.h(qr[0]) qc.cx(qr[1], qr[2]) qc.u1(-pi/2, qr[1]) qc.u1(-pi, qr[0]) qc.h(qr[1]) qc.h(qr[0]) # To measure the whole quantum register qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) qc.measure(qr[3], cr[3]) result = Q_program.execute("solve_linear_sys", shots=8192, backend='local_qasm_simulator') # Get the sum og all results n0 = n0 + result.get_data("solve_linear_sys")['counts']['1000'] n1 = n1 + result.get_data("solve_linear_sys")['counts']['1100'] # print the result print(result) print(result.get_data("solve_linear_sys")) # Reset the circuit qc.reset(qr) # calculate the scale of the elements in result vectot and print it. p = n0/n1 print(n0) print(n1) print(p) # The test function if __name__ == "__main__": solve_linear_sys() %run "../version.ipynb"
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
%run ../version.ipynb
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') from pprint import pprint import math # importing the QISKit from qiskit import QuantumProgram # To use API #import Qconfig # Definition of matchgate def gate_mu3(qcirc,theta,phi,lam,a,b): qcirc.cx(a,b) qcirc.cu3(theta,phi,lam,b,a) qcirc.cx(a,b) # Number of qubits (should be odd) n_nodes = 5 # Number of steps n_step = 2 # Histogram hist = True # Quantum Sphere #hist = False # Creating Programs qp = QuantumProgram() # Creating Registers qr = qp.create_quantum_register('qr', n_nodes) cr = qp.create_classical_register('cr', n_nodes) # Creating Circuits qc = qp.create_circuit('QWalk', [qr], [cr]) # Initial state qc.x(qr[0]) # Creating of two partitions with M1' and M2 # Repeating that n_step times for k in range(0,n_step): for i in range(0,n_nodes-1,2): gate_mu3(qc,math.pi, math.pi, 0, qr[i], qr[i+1]) for i in range(1,n_nodes,2): gate_mu3(qc,math.pi/2, 0, 0, qr[i], qr[i+1]) if hist: for i in range(0,n_nodes): qc.measure(qr[i], cr[i]) # To print the circuit # QASM_source = qp.get_qasm('QWalk') # print(QASM_source) # To use API # qp.set_api(Qconfig.APItoken, Qconfig.config['url']) backend = 'local_qasm_simulator' if hist: shots = 4096 else: shots = 1 # backend 'trick': produces amplitudes instead of probabilities qobj=qp.compile(['QWalk'], backend = backend, shots = shots ) # Compile quantum walk result = qp.run(qobj) print(result) # execute this cell twice to see the result due to an issue with matplotlib # import state tomography functions from qiskit.tools.visualization import plot_histogram, plot_state import numpy as np if hist: plot_histogram(result.get_counts('QWalk')) else: data_ampl = result.get_data('QWalk') state_walk = data_ampl['quantum_state'] rho_walk = np.outer(state_walk,state_walk.conj()) plot_state(rho_walk,'qsphere')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# execute this cell twice to see the output due to an issue with matplotlib import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') from pprint import pprint import math # importing the QISKit from qiskit import QuantumProgram # To use API #import Qconfig def gate_mu3(qcirc,theta,phi,lam,a,b): qcirc.cx(a,b) qcirc.cu3(theta,phi,lam,b,a) qcirc.cx(a,b) n_nodes = 5 n_step = 3 # Creating Programs qp = QuantumProgram() # Creating Registers qr = qp.create_quantum_register('qr', n_nodes) cr = qp.create_classical_register('cr', n_nodes) # Creating Circuits qc = qp.create_circuit('QWalk', [qr], [cr]) # Creating of two partitions with M1' and M2 for i in range(0,n_nodes-1,2): gate_mu3(qc,math.pi, math.pi, 0, qr[i], qr[i+1]) for i in range(1,n_nodes,2): gate_mu3(qc,math.pi/2, 0, 0, qr[i], qr[i+1]) # import state tomography functions from qiskit.tools.visualization import plot_histogram, plot_state import numpy as np # execute the quantum circuit backend = 'local_unitary_simulator' # the device to run on qobj = qp.compile(['QWalk'], backend=backend) result = qp.run(qobj) initial_state = np.zeros(2**n_nodes) initial_state[1]=1.0 # state 0 = ....0000, state 1 = ...000001 QWalk = result.get_data('QWalk')['unitary'] #Applying QWalk n_step times for i in range(0,n_step): if i > 0: initial_state = np.copy(state_QWalk) # Copy previous state state_QWalk = np.dot(QWalk,initial_state) # Multiply on QWalk matrix rho_QWalk=np.outer(state_QWalk, state_QWalk.conj()) # Calculate density matrix print('step = ',i+1) # print number plot_state(rho_QWalk,'qsphere') # draw Quantum Sphere
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import math import numpy as np from scipy import linalg import matplotlib.pyplot as plt # swap is 2x2 matrix swap = np.array([[0, 1], [1, 0]], dtype=complex) # Hadamard coin c_Hadamard = (1/math.sqrt(2))*np.array([[1, 1], [1, -1]], dtype=complex) # Balanced coin (not used) c_bal = (1/math.sqrt(2))*np.array([[1, 1j], [1j, 1]], dtype=complex) # step with swap and coin s_coin = c_Hadamard.dot(swap) # Number of nodes (should be odd) n_nodes = 15 # Step 1 includes swap and coin for first partition Step1 = np.identity(n_nodes, dtype=complex) for i in range(0,n_nodes-1,2): for i1 in range(0,2): for i2 in range(0,2): Step1[i+i1,i+i2] = s_coin[i1,i2] # Step 2 includes swap for second partition Step2 = np.identity(n_nodes, dtype=complex) for i in range(1,n_nodes,2): for i1 in range(0,2): for i2 in range(0,2): Step2[i+i1,i+i2] = swap[i1,i2] # Vector with chain nodes ch = np.zeros(n_nodes, dtype=complex) # Initial distribution for symmetric walk with Hadamard coin # two central nodes n_pos = n_nodes//2 ch[n_pos] = 1/math.sqrt(2) ch[n_pos+1] = 1j/math.sqrt(2) # Alternative initial distribution also could be used #ch[0] = 1 # Probability from complex amplitude def abs2(x): return x.real**2 + x.imag**2 # Vector with probabilities ch2 = np.zeros(n_nodes, dtype = float) # Number of steps n_step=12 for i in range(0,n_step): if i > 0: # step = 0 doing nothing, only draw if i%2 == 1 : ch = Step1.dot(ch) # odd steps 1 3 5 ... else: ch = Step2.dot(ch) # even steps 2 4 6 ... ch2 = abs2(ch) # calculate probabilities print(ch2) if i%2 == 0 : # plot for even steps 0 2 4 ... plt.plot(ch2) plt.show()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# Checking the version of PYTHON; we only support 3 at the moment import sys if sys.version_info < (3,0): raise Exception('Please use Python version 3 or greater.') # useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np import time from pprint import pprint # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram #import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram QPS_SPECS = { 'circuits': [{ 'name': 'W_states', 'quantum_registers': [{ 'name':'q', 'size':5 }], 'classical_registers': [{ 'name':'c', 'size':5 }]}], } Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) "Choice of the backend" # The flag_qx2 must be "True" for using the ibmqx2. # "True" is also better when using the simulator (shorter circuit) #backend = 'ibmqx2' #backend = 'ibmqx4' backend = 'local_qasm_simulator' #backend = 'ibmqx_hpc_qasm_simulator' flag_qx2 = True if backend == 'ibmqx4': flag_qx2 = False print("Your choice for the backend is: ", backend, "flag_qx2 is: ", flag_qx2) # Here, two useful routine # Define a F_gate def F_gate(circ,q,i,j,n,k) : theta = np.arccos(np.sqrt(1/(n-k+1))) circ.ry(-theta,q[j]) circ.cz(q[i],q[j]) circ.ry(theta,q[j]) circ.barrier(q[i]) # Define the cxrv gate which uses reverse CNOT instead of CNOT def cxrv(circ,q,i,j) : circ.h(q[i]) circ.h(q[j]) circ.cx(q[j],q[i]) circ.h(q[i]) circ.h(q[j]) circ.barrier(q[i],q[j]) # 3-qubit W state Step 1 Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[2]) #start is |100> F_gate(W_states,q,2,1,3,1) # Applying F12 for i in range(3) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 3-qubit (step 1) on', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 3-qubit (step 1) on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states')) # 3-qubit W state, first and second steps Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[2]) #start is |100> F_gate(W_states,q,2,1,3,1) # Applying F12 F_gate(W_states,q,1,0,3,2) # Applying F23 for i in range(3) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 3-qubit (steps 1 + 2) on', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 3-qubit (steps 1 + 2) on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states')) # 3-qubit W state Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[2]) #start is |100> F_gate(W_states,q,2,1,3,1) # Applying F12 F_gate(W_states,q,1,0,3,2) # Applying F23 if flag_qx2 : # option ibmqx2 W_states.cx(q[1],q[2]) # cNOT 21 W_states.cx(q[0],q[1]) # cNOT 32 else : # option ibmqx4 cxrv(W_states,q,1,2) cxrv(W_states,q,0,1) for i in range(3) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 3-qubit on', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 3-qubit on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states')) # 4-qubit W state Q_program = QuantumProgram(specs=QPS_SPECS) # Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[3]) #start is |1000> F_gate(W_states,q,3,2,4,1) # Applying F12 F_gate(W_states,q,2,1,4,2) # Applying F23 F_gate(W_states,q,1,0,4,3) # Applying F34 cxrv(W_states,q,2,3) # cNOT 21 if flag_qx2 : # option ibmqx2 W_states.cx(q[1],q[2]) # cNOT 32 W_states.cx(q[0],q[1]) # cNOT 43 else : # option ibmqx4 cxrv(W_states,q,1,2) cxrv(W_states,q,0,1) for i in range(4) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 4-qubit ', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 4-qubit on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states')) # 5-qubit W state Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[4]) #start is |10000> F_gate(W_states,q,4,3,5,1) # Applying F12 F_gate(W_states,q,3,2,5,2) # Applying F23 F_gate(W_states,q,2,1,5,3) # Applying F34 F_gate(W_states,q,1,0,5,4) # Applying F45 W_states.cx(q[3],q[4]) # cNOT 21 cxrv(W_states,q,2,3) # cNOT 32 if flag_qx2 : # option ibmqx2 W_states.cx(q[1],q[2]) # cNOT 43 W_states.cx(q[0],q[1]) # cNOT 54 else : # option ibmqx4 cxrv(W_states,q,1,2) cxrv(W_states,q,0,1) for i in range(5) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 5-qubit on', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=1200) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 5-qubit on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states'))