repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import *
from qiskit.visualization import plot_histogram
# quantum circuit to make a Bell state
bell = QuantumCircuit(2, 2)
bell.h(0)
bell.cx(0, 1)
meas = QuantumCircuit(2, 2)
meas.measure([0,1], [0,1])
# execute the quantum circuit
backend = BasicAer.get_backend('qasm_simulator') # the device to run on
circ = bell.compose(meas)
result = backend.run(transpile(circ, backend), shots=1000).result()
counts = result.get_counts(circ)
print(counts)
plot_histogram(counts)
# Execute 2-qubit Bell state again
second_result = backend.run(transpile(circ, backend), shots=1000).result()
second_counts = second_result.get_counts(circ)
# Plot results with legend
legend = ['First execution', 'Second execution']
plot_histogram([counts, second_counts], legend=legend)
plot_histogram([counts, second_counts], legend=legend, sort='desc', figsize=(15,12),
color=['orange', 'black'], bar_labels=False)
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_state_paulivec, plot_state_hinton
from qiskit.visualization import plot_state_qsphere
# execute the quantum circuit
backend = BasicAer.get_backend('statevector_simulator') # the device to run on
result = backend.run(transpile(bell, backend)).result()
psi = result.get_statevector(bell)
plot_state_city(psi)
plot_state_hinton(psi)
plot_state_qsphere(psi)
plot_state_paulivec(psi)
plot_bloch_multivector(psi)
plot_state_city(psi, title="My City", color=['black', 'orange'])
plot_state_hinton(psi, title="My Hinton")
plot_state_paulivec(psi, title="My Paulivec", color=['purple', 'orange', 'green'])
plot_bloch_multivector(psi, title="My Bloch Spheres")
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([0,1,0])
plot_bloch_vector([0,1,0], title='My Bloch Sphere')
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-aqt-provider
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, Alpine Quantum Technologies GmbH 2023.
#
# 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.
import itertools
import json
import math
import re
import uuid
from contextlib import AbstractContextManager, nullcontext
from typing import Any
from unittest import mock
import httpx
import pydantic as pdt
import pytest
import qiskit
from polyfactory.factories.pydantic_factory import ModelFactory
from pytest_httpx import HTTPXMock
from qiskit import QuantumCircuit
from qiskit.providers import JobStatus
from qiskit.providers.exceptions import JobTimeoutError
from typing_extensions import assert_type
from qiskit_aqt_provider import api_models, api_models_direct
from qiskit_aqt_provider.aqt_job import AQTJob
from qiskit_aqt_provider.aqt_options import AQTDirectAccessOptions, AQTOptions
from qiskit_aqt_provider.aqt_resource import AQTResource
from qiskit_aqt_provider.circuit_to_aqt import circuits_to_aqt_job
from qiskit_aqt_provider.test.circuits import assert_circuits_equal, empty_circuit, random_circuit
from qiskit_aqt_provider.test.fixtures import MockSimulator
from qiskit_aqt_provider.test.resources import (
DummyDirectAccessResource,
DummyResource,
TestResource,
)
from qiskit_aqt_provider.versions import USER_AGENT
class OptionsFactory(ModelFactory[AQTOptions]):
"""Factory of random but well-formed options data."""
__model__ = AQTOptions
query_timeout_seconds = 10.0
def test_options_set_query_timeout(offline_simulator_no_noise: AQTResource) -> None:
"""Set the query timeout for job status queries with different values."""
backend = offline_simulator_no_noise
# doesn't work with str
with pytest.raises(pdt.ValidationError):
backend.options.update_options(query_timeout_seconds="abc")
# works with integers
backend.options.update_options(query_timeout_seconds=123)
assert backend.options.query_timeout_seconds == 123
# works with floats
backend.options.update_options(query_timeout_seconds=123.45)
assert backend.options.query_timeout_seconds == 123.45
# works with None (no timeout)
backend.options.update_options(query_timeout_seconds=None)
assert backend.options.query_timeout_seconds is None
def test_options_set_query_period(offline_simulator_no_noise: AQTResource) -> None:
"""Set the query period for job status queries with different values."""
backend = offline_simulator_no_noise
# works with integers
backend.options.update_options(query_period_seconds=123)
assert backend.options.query_period_seconds == 123
# works with floats
backend.options.update_options(query_period_seconds=123.45)
assert backend.options.query_period_seconds == 123.45
# doesn't work with None
with pytest.raises(pdt.ValidationError):
backend.options.update_options(query_period_seconds=None)
# doesn't work with str
with pytest.raises(pdt.ValidationError):
backend.options.update_options(query_period_seconds="abc")
def test_options_types_and_constraints_cloud_resource(
offline_simulator_no_noise: AQTResource,
) -> None:
"""Check that the options models and constraints are as expected for cloud backends."""
assert_type(offline_simulator_no_noise.options, AQTOptions)
assert isinstance(offline_simulator_no_noise.options, AQTOptions)
assert offline_simulator_no_noise.options.max_shots() == 2000
# Check that the default options in Qiskit format match the Pydantic model.
assert offline_simulator_no_noise.options.model_dump() == {
**offline_simulator_no_noise.__class__._default_options()
}
def test_options_types_and_constraints_direct_access_resource() -> None:
"""Check that the options models and constraints are as expected for direct-access backends."""
backend = DummyDirectAccessResource("token")
assert_type(backend.options, AQTDirectAccessOptions)
assert isinstance(backend.options, AQTDirectAccessOptions)
assert backend.options.max_shots() == 200
# Check that the default options in Qiskit format match the Pydantic model.
assert backend.options.model_dump() == {**backend.__class__._default_options()}
def test_query_timeout_propagation() -> None:
"""Check that the query timeout is properly propagated from the backend options to
the job result polling loop.
Acquire a resource with 10s processing time, but set the job result timeout to 1s.
Check that calling `result()` on the job handle fails with a timeout error.
"""
response_delay = 10.0
timeout = 1.0
assert timeout < response_delay
backend = TestResource(min_running_duration=response_delay)
backend.options.update_options(query_timeout_seconds=timeout, query_period_seconds=0.5)
qc = QuantumCircuit(1)
qc.rx(3.14, 0)
qc.measure_all()
job = backend.run(qiskit.transpile(qc, backend))
with pytest.raises(JobTimeoutError):
job.result()
def test_query_period_propagation() -> None:
"""Check that the query wait duration is properly propagated from the backend options
to the job result polling loop.
Set the polling period (much) shorter than the backend's processing time. Check that
the backend is polled the calculated number of times.
"""
response_delay = 2.0
period_seconds = 0.5
timeout_seconds = 3.0
assert timeout_seconds > response_delay # won't time out
backend = TestResource(min_running_duration=response_delay)
backend.options.update_options(
query_timeout_seconds=timeout_seconds, query_period_seconds=period_seconds
)
qc = QuantumCircuit(1)
qc.rx(3.14, 0)
qc.measure_all()
job = backend.run(qiskit.transpile(qc, backend))
with mock.patch.object(AQTJob, "status", wraps=job.status) as mocked_status:
job.result()
lower_bound = math.floor(response_delay / period_seconds)
upper_bound = math.ceil(response_delay / period_seconds) + 1
assert lower_bound <= mocked_status.call_count <= upper_bound
def test_run_options_propagation(offline_simulator_no_noise: MockSimulator) -> None:
"""Check that options passed to AQTResource.run are propagated to the corresponding job."""
default = offline_simulator_no_noise.options.model_copy()
while True:
overrides = OptionsFactory.build()
if overrides != default:
break
qc = QuantumCircuit(1)
qc.measure_all()
# don't submit the circuit to the simulator
with mock.patch.object(AQTJob, "submit") as mocked_submit:
job = offline_simulator_no_noise.run(qc, **overrides.model_dump())
assert job.options == overrides
mocked_submit.assert_called_once()
def test_run_options_unknown(offline_simulator_no_noise: MockSimulator) -> None:
"""Check that AQTResource.run accepts but warns about unknown options."""
default = offline_simulator_no_noise.options.model_copy()
overrides = {"shots": 123, "unknown_option": True}
assert set(overrides) - set(default) == {"unknown_option"}
qc = QuantumCircuit(1)
qc.measure_all()
with mock.patch.object(AQTJob, "submit") as mocked_submit:
with pytest.warns(UserWarning, match="not used"):
job = offline_simulator_no_noise.run(qc, **overrides)
assert job.options.shots == 123
mocked_submit.assert_called_once()
def test_run_options_invalid(offline_simulator_no_noise: MockSimulator) -> None:
"""Check that AQTResource.run reject valid option names with invalid values."""
qc = QuantumCircuit(1)
qc.measure_all()
with pytest.raises(pdt.ValidationError, match="shots"):
offline_simulator_no_noise.run(qc, shots=-123)
def test_double_job_submission(offline_simulator_no_noise: MockSimulator) -> None:
"""Check that attempting to re-submit a job raises a RuntimeError."""
qc = QuantumCircuit(1)
qc.r(3.14, 0.0, 0)
qc.measure_all()
# AQTResource.run submits the job
job = offline_simulator_no_noise.run(qc)
with pytest.raises(RuntimeError, match=f"{job.job_id()}"):
job.submit()
# Check that the job was actually submitted
((submitted_circuit,),) = offline_simulator_no_noise.submitted_circuits
assert_circuits_equal(submitted_circuit, qc)
def test_offline_simulator_invalid_job_id(offline_simulator_no_noise: MockSimulator) -> None:
"""Check that the offline simulator raises UnknownJobError if the job id passed
to `result()` is invalid.
"""
qc = QuantumCircuit(1)
qc.measure_all()
job = offline_simulator_no_noise.run([qc], shots=1)
job_id = uuid.UUID(hex=job.job_id())
invalid_job_id = uuid.uuid4()
assert invalid_job_id != job_id
with pytest.raises(api_models.UnknownJobError, match=str(invalid_job_id)):
offline_simulator_no_noise.result(invalid_job_id)
# querying the actual job is successful
result = offline_simulator_no_noise.result(job_id)
assert result.job.job_id == job_id
def test_submit_valid_response(httpx_mock: HTTPXMock) -> None:
"""Check that AQTResource.submit passes the authorization token and
extracts the correct job_id when the response payload is valid.
"""
token = str(uuid.uuid4())
backend = DummyResource(token)
expected_job_id = uuid.uuid4()
def handle_submit(request: httpx.Request) -> httpx.Response:
assert request.headers["user-agent"] == USER_AGENT
assert request.headers["authorization"] == f"Bearer {token}"
return httpx.Response(
status_code=httpx.codes.OK,
json=json.loads(
api_models.Response.queued(
job_id=expected_job_id,
resource_id=backend.resource_id.resource_id,
workspace_id=backend.resource_id.workspace_id,
).model_dump_json()
),
)
httpx_mock.add_callback(handle_submit, method="POST")
job = AQTJob(backend, circuits=[empty_circuit(2)], options=AQTOptions(shots=10))
job.submit()
assert job.job_id() == str(expected_job_id)
def test_submit_payload_matches(httpx_mock: HTTPXMock) -> None:
"""Check that the quantum circuits jobs payload is correctly submitted to the API endpoint."""
backend = DummyResource("")
shots = 123
qc = qiskit.transpile(random_circuit(2), backend)
expected_job_payload = circuits_to_aqt_job([qc], shots=shots)
expected_job_id = uuid.uuid4()
def handle_submit(request: httpx.Request) -> httpx.Response:
assert request.headers["user-agent"] == USER_AGENT
assert request.url.path.endswith(
f"submit/{backend.resource_id.workspace_id}/{backend.resource_id.resource_id}"
)
data = api_models.SubmitJobRequest.model_validate_json(request.content.decode("utf-8"))
assert data == expected_job_payload
return httpx.Response(
status_code=httpx.codes.OK,
json=json.loads(
api_models.Response.queued(
job_id=expected_job_id,
resource_id=backend.resource_id.resource_id,
workspace_id=backend.resource_id.workspace_id,
).model_dump_json()
),
)
httpx_mock.add_callback(handle_submit, method="POST")
qc = qiskit.transpile(random_circuit(2), backend)
job = AQTJob(backend, circuits=[qc], options=AQTOptions(shots=shots))
job.submit()
assert job.job_id() == str(expected_job_id)
def test_submit_bad_request(httpx_mock: HTTPXMock) -> None:
"""Check that AQTResource.submit raises an HTTPError if the request
is flagged invalid by the server.
"""
backend = DummyResource("")
httpx_mock.add_response(status_code=httpx.codes.BAD_REQUEST)
job = AQTJob(backend, circuits=[empty_circuit(2)], options=AQTOptions(shots=10))
with pytest.raises(httpx.HTTPError):
job.submit()
def test_result_valid_response(httpx_mock: HTTPXMock) -> None:
"""Check that AQTResource.result passes the authorization token
and returns the raw response payload.
"""
token = str(uuid.uuid4())
backend = DummyResource(token)
job_id = uuid.uuid4()
payload = api_models.Response.cancelled(
job_id=job_id,
resource_id=backend.resource_id.resource_id,
workspace_id=backend.resource_id.workspace_id,
)
def handle_result(request: httpx.Request) -> httpx.Response:
assert request.headers["user-agent"] == USER_AGENT
assert request.headers["authorization"] == f"Bearer {token}"
assert request.url.path.endswith(f"result/{job_id}")
return httpx.Response(
status_code=httpx.codes.OK, json=json.loads(payload.model_dump_json())
)
httpx_mock.add_callback(handle_result, method="GET")
response = backend.result(job_id)
assert response == payload
def test_result_bad_request(httpx_mock: HTTPXMock) -> None:
"""Check that AQTResource.result raises an HTTPError if the request
is flagged invalid by the server.
"""
backend = DummyResource("")
httpx_mock.add_response(status_code=httpx.codes.BAD_REQUEST)
with pytest.raises(httpx.HTTPError):
backend.result(uuid.uuid4())
def test_result_unknown_job(httpx_mock: HTTPXMock) -> None:
"""Check that AQTResource.result raises UnknownJobError if the API
responds with an UnknownJob payload.
"""
backend = DummyResource("")
job_id = uuid.uuid4()
httpx_mock.add_response(
json=json.loads(api_models.Response.unknown_job(job_id=job_id).model_dump_json())
)
with pytest.raises(api_models.UnknownJobError, match=str(job_id)):
backend.result(job_id)
def test_offline_simulator_detects_invalid_circuits(
offline_simulator_no_noise: MockSimulator,
) -> None:
"""Pass a circuit that cannot be converted to the AQT API to the offline simulator.
This must fail.
"""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
with pytest.raises(ValueError, match="^Operation 'h' not in basis gate set"):
offline_simulator_no_noise.run(qc)
def test_offline_simulator_propagate_shots_option(
offline_simulator_no_noise: MockSimulator,
) -> None:
"""Check various ways of configuring the number of repetitions."""
qc = qiskit.transpile(random_circuit(2), offline_simulator_no_noise)
default_shots = sum(offline_simulator_no_noise.run(qc).result().get_counts().values())
assert default_shots == AQTOptions().shots
shots = min(default_shots + 40, AQTOptions.max_shots())
assert shots != default_shots
# configure shots in AQTResource.run
shots_run = sum(offline_simulator_no_noise.run(qc, shots=shots).result().get_counts().values())
assert shots_run == shots
# configure shots in resource options
offline_simulator_no_noise.options.shots = shots
shots_options = sum(offline_simulator_no_noise.run(qc).result().get_counts().values())
assert shots_options == shots
@pytest.mark.parametrize(
("memory", "context"),
[(True, nullcontext()), (False, pytest.raises(qiskit.QiskitError, match="No memory"))],
)
def test_offline_simulator_run_propagate_memory_option(
memory: bool,
context: AbstractContextManager[Any],
offline_simulator_no_noise: MockSimulator,
) -> None:
"""Check that the memory option can be set on `AQTResource.run`."""
qc = qiskit.transpile(random_circuit(2), offline_simulator_no_noise)
default_shots = AQTOptions().shots
result = offline_simulator_no_noise.run(qc, memory=memory).result()
with context:
assert len(result.get_memory()) == default_shots
@pytest.mark.parametrize(
("memory", "context"),
[(True, nullcontext()), (False, pytest.raises(qiskit.QiskitError, match="No memory"))],
)
def test_offline_simulator_resource_propagate_memory_option(
memory: bool, context: AbstractContextManager[Any], offline_simulator_no_noise: MockSimulator
) -> None:
"""Check that the memory option can be set as resource option."""
qc = qiskit.transpile(random_circuit(2), offline_simulator_no_noise)
default_shots = AQTOptions().shots
offline_simulator_no_noise.options.memory = memory
result = offline_simulator_no_noise.run(qc).result()
with context:
assert len(result.get_memory()) == default_shots
def test_direct_access_bad_request(httpx_mock: HTTPXMock) -> None:
"""Check that direct-access resources raise a httpx.HTTPError on bad requests."""
backend = DummyDirectAccessResource("token")
httpx_mock.add_response(status_code=httpx.codes.BAD_REQUEST)
job = backend.run(empty_circuit(2))
with pytest.raises(httpx.HTTPError):
job.result()
@pytest.mark.parametrize("success", [False, True])
def test_direct_access_job_status(success: bool, httpx_mock: HTTPXMock) -> None:
"""Check the expected Qiskit job status on direct-access resources.
Since the transactions are synchronous, there are only three possible statuses:
1. initializing: the job was created but is not executing
2. done: the job executed successfully
3. error: the job execution failed.
"""
shots = 100
def handle_submit(request: httpx.Request) -> httpx.Response:
assert request.headers["user-agent"] == USER_AGENT
return httpx.Response(status_code=httpx.codes.OK, text=f'"{uuid.uuid4()}"')
def handle_result(request: httpx.Request) -> httpx.Response:
assert request.headers["user-agent"] == USER_AGENT
_, job_id = request.url.path.rsplit("/", maxsplit=1)
return httpx.Response(
status_code=httpx.codes.OK,
json=json.loads(
api_models_direct.JobResult.create_finished(
job_id=uuid.UUID(job_id), result=[[0] for _ in range(shots)]
).model_dump_json()
if success
else api_models_direct.JobResult.create_error(
job_id=uuid.UUID(job_id)
).model_dump_json()
),
)
httpx_mock.add_callback(handle_submit, method="PUT", url=re.compile(".+/circuit/?$"))
httpx_mock.add_callback(
handle_result, method="GET", url=re.compile(".+/circuit/result/[0-9a-f-]+$")
)
backend = DummyDirectAccessResource("token")
job = backend.run(empty_circuit(1), shots=shots)
assert job.status() is JobStatus.INITIALIZING
result = job.result()
assert result.success is success
if success:
assert job.status() is JobStatus.DONE
else:
assert job.status() is JobStatus.ERROR
@pytest.mark.parametrize("token", [str(uuid.uuid4()), ""])
def test_direct_access_mocked_successful_transaction(token: str, httpx_mock: HTTPXMock) -> None:
"""Mock a successful single-circuit transaction on a direct-access resource."""
backend = DummyDirectAccessResource(token)
backend.options.with_progress_bar = False
shots = 122
qc = empty_circuit(2)
expected_job_id = str(uuid.uuid4())
def assert_valid_token(headers: httpx.Headers) -> None:
if token:
assert headers["authorization"] == f"Bearer {token}"
else:
assert "authorization" not in headers
def handle_submit(request: httpx.Request) -> httpx.Response:
assert request.headers["user-agent"] == USER_AGENT
assert_valid_token(request.headers)
data = api_models.QuantumCircuit.model_validate_json(request.content.decode("utf-8"))
assert data.repetitions == shots
return httpx.Response(
status_code=httpx.codes.OK,
text=f'"{expected_job_id}"',
)
def handle_result(request: httpx.Request) -> httpx.Response:
assert request.headers["user-agent"] == USER_AGENT
assert_valid_token(request.headers)
_, job_id = request.url.path.rsplit("/", maxsplit=1)
assert job_id == expected_job_id
return httpx.Response(
status_code=httpx.codes.OK,
json=json.loads(
api_models_direct.JobResult.create_finished(
job_id=uuid.UUID(job_id),
result=[[0, 0] if s % 2 == 0 else [1, 0] for s in range(shots)],
).model_dump_json()
),
)
httpx_mock.add_callback(handle_submit, method="PUT", url=re.compile(".+/circuit/?$"))
httpx_mock.add_callback(
handle_result, method="GET", url=re.compile(".+/circuit/result/[0-9a-f-]+$")
)
job = backend.run(qc, shots=shots)
result = job.result()
assert result.get_counts() == {"00": shots // 2, "01": shots // 2}
def test_direct_access_mocked_failed_transaction(httpx_mock: HTTPXMock) -> None:
"""Mock a failed multi-circuit transaction on a direct-access resource.
The first two circuits succeed, the third one not. The fourth circuit would succeed,
but is never executed.
"""
token = str(uuid.uuid4())
backend = DummyDirectAccessResource(token)
backend.options.with_progress_bar = False
shots = 122
qc = empty_circuit(2)
job_ids = [str(uuid.uuid4()) for _ in range(4)]
# produce 2 times the same id before going to the next, one value
# for handle_submit, the other one for handle result.
job_ids_iter = itertools.chain.from_iterable(zip(job_ids, job_ids))
# circuit executions' planned success
success = [True, True, False, True]
success_iter = iter(success)
circuit_submissions = 0
def handle_submit(request: httpx.Request) -> httpx.Response:
assert request.headers["user-agent"] == USER_AGENT
data = api_models.QuantumCircuit.model_validate_json(request.content.decode("utf-8"))
assert data.repetitions == shots
nonlocal circuit_submissions
circuit_submissions += 1
return httpx.Response(
status_code=httpx.codes.OK,
text=f'"{next(job_ids_iter)}"',
)
def handle_result(request: httpx.Request) -> httpx.Response:
assert request.headers["user-agent"] == USER_AGENT
_, job_id = request.url.path.rsplit("/", maxsplit=1)
assert job_id == next(job_ids_iter)
return httpx.Response(
status_code=httpx.codes.OK,
json=json.loads(
api_models_direct.JobResult.create_finished(
job_id=uuid.UUID(job_id), result=[[0, 1] for _ in range(shots)]
).model_dump_json()
if next(success_iter)
else api_models_direct.JobResult.create_error(
job_id=uuid.UUID(job_id)
).model_dump_json()
),
)
httpx_mock.add_callback(handle_submit, method="PUT", url=re.compile(".+/circuit/?$"))
httpx_mock.add_callback(
handle_result, method="GET", url=re.compile(".+/circuit/result/[0-9a-f-]+$")
)
job = backend.run([qc, qc, qc, qc], shots=shots)
result = job.result()
assert not result.success # not all circuits executed successfully
counts = result.get_counts()
assert isinstance(counts, list) # multiple successful circuit executions
assert len(counts) == 2 # the first two circuits executed successfully
assert counts == [{"10": shots}, {"10": shots}]
assert circuit_submissions == 3 # the last circuit was never submitted
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
import unittest
import hypothesis.strategies as st
from hypothesis import given, settings, note
from qiskit import QuantumCircuit
from qiskit import Aer, execute
from qiskit.circuit.library import Barrier, XGate, HGate, CXGate, ZGate, Measure
#####################################################################################
### Change the file to import from, in order to test a mutant version of the code ###
#####################################################################################
### e.g. from Add_mutant_1 import ...
#####################################################################################
from Replace_Mutant_5 import create_bell_pair, encode_message, decode_message
#############################
### Postcondition testing ###
#############################
@st.composite
def draw_message(draw):
drawnInt = draw(st.integers(min_value=0, max_value=1))
drawnInt2 = draw(st.integers(min_value=0, max_value=1))
return(str(drawnInt)+str(drawnInt2))
@given(draw_message())
@settings(deadline=None)
def test_encode_message_returns_only_sets_of_bell_pair_values(message):
qc = create_bell_pair()
qc = encode_message(qc, 1, message)
qc.measure_all()
note(message)
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=1000, memory=True)
readings = job.result().get_memory()
note(readings)
note(not(set(readings) == set(['11','00']) and set(readings) == set(['01','10'])))
note(set(readings) == set(['11','00']) or set(readings) == set(['01','10']))
assert(not(set(readings) == set(['11','00']) and set(readings) == set(['01','10'])))
assert(set(readings) == set(['11','00']) or set(readings) == set(['01','10']))
@given(draw_message())
def test_decode_message_equal_to_encode_message(message):
note(message)
qc = create_bell_pair()
qc = encode_message(qc, 1, message)
qc = decode_message(qc)
qc.measure_all()
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=1, memory=True)
readings = job.result().get_memory()
note(readings)
assert(readings == [message])
if __name__ == '__main__':
test_encode_message_returns_only_sets_of_bell_pair_values()
test_decode_message_equal_to_encode_message()
|
https://github.com/QuantumBarcelona/Qiskit-Hackathon-BCN
|
QuantumBarcelona
|
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 16}) # enlarge fonts
# Import standard qiskit modules
from qiskit import QuantumCircuit, QuantumRegister
#For doing exact simulation you can use Statevector (feel free to use something else)
from qiskit.quantum_info import Statevector
#Your code here
# loading IBMQ account
from qiskit import IBMQ
# IBMQ.save_account('Token') #you can replace TOKEN with your API token string (https://quantum-computing.ibm.com/lab/docs/iql/manage/account/ibmq)
IBMQ.load_account()
# Your answer here
# Your code here
# Your code here
# Your code here
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
from qiskit.primitives import Estimator
estimator = Estimator()
import numpy as np
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SLSQP
from qiskit.circuit.library import TwoLocal
from qiskit.utils import algorithm_globals
# we will iterate over these different optimizers
optimizers = [COBYLA(maxiter=80), L_BFGS_B(maxiter=60), SLSQP(maxiter=60)]
converge_counts = np.empty([len(optimizers)], dtype=object)
converge_vals = np.empty([len(optimizers)], dtype=object)
for i, optimizer in enumerate(optimizers):
print("\rOptimizer: {} ".format(type(optimizer).__name__), end="")
algorithm_globals.random_seed = 50
ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
vqe = VQE(estimator, ansatz, optimizer, callback=store_intermediate_result)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
converge_counts[i] = np.asarray(counts)
converge_vals[i] = np.asarray(values)
print("\rOptimization complete ");
import pylab
pylab.rcParams["figure.figsize"] = (12, 8)
for i, optimizer in enumerate(optimizers):
pylab.plot(converge_counts[i], converge_vals[i], label=type(optimizer).__name__)
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Energy convergence for various optimizers")
pylab.legend(loc="upper right");
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.opflow import PauliSumOp
numpy_solver = NumPyMinimumEigensolver()
result = numpy_solver.compute_minimum_eigenvalue(operator=PauliSumOp(H2_op))
ref_value = result.eigenvalue.real
print(f"Reference value: {ref_value:.5f}")
pylab.rcParams["figure.figsize"] = (12, 8)
for i, optimizer in enumerate(optimizers):
pylab.plot(
converge_counts[i],
abs(ref_value - converge_vals[i]),
label=type(optimizer).__name__,
)
pylab.xlabel("Eval count")
pylab.ylabel("Energy difference from solution reference value")
pylab.title("Energy convergence for various optimizers")
pylab.yscale("log")
pylab.legend(loc="upper right");
from qiskit.algorithms.gradients import FiniteDiffEstimatorGradient
estimator = Estimator()
gradient = FiniteDiffEstimatorGradient(estimator, epsilon=0.01)
algorithm_globals.random_seed = 50
ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
optimizer = SLSQP(maxiter=100)
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
vqe = VQE(
estimator, ansatz, optimizer, callback=store_intermediate_result, gradient=gradient
)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(f"Value using Gradient: {result.eigenvalue.real:.5f}")
pylab.rcParams["figure.figsize"] = (12, 8)
pylab.plot(counts, values, label=type(optimizer).__name__)
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Energy convergence using Gradient")
pylab.legend(loc="upper right");
print(result)
cost_function_evals = result.cost_function_evals
initial_pt = result.optimal_point
estimator1 = Estimator()
gradient1 = FiniteDiffEstimatorGradient(estimator, epsilon=0.01)
ansatz1 = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
optimizer1 = SLSQP(maxiter=1000)
vqe1 = VQE(
estimator1, ansatz1, optimizer1, gradient=gradient1, initial_point=initial_pt
)
result1 = vqe1.compute_minimum_eigenvalue(operator=H2_op)
print(result1)
cost_function_evals1 = result1.cost_function_evals
print()
print(
f"cost_function_evals is {cost_function_evals1} with initial point versus {cost_function_evals} without it."
)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a DensityMatrix
state = DensityMatrix(qc)
plot_state_city(state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate
from qiskit.converters import dag_to_circuit
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
circuit = dag_to_circuit(dag)
circuit.draw('mpl')
|
https://github.com/AmirhoseynpowAsghari/Qiskit-Tutorials
|
AmirhoseynpowAsghari
|
import numpy as np
# Parameters
J = 1
k_B = 1
T = 2.269 # Critical temperature
K = J / (k_B * T)
# Transfer matrix for a 2x2 Ising model (simplified example)
def transfer_matrix(K):
T = np.zeros((4, 4))
configs = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
for i, (s1, s2) in enumerate(configs):
for j, (s3, s4) in enumerate(configs):
E = K * (s1*s2 + s2*s3 + s3*s4 + s4*s1)
T[i, j] = np.exp(E)
return T
T_matrix = transfer_matrix(K)
eigenvalues, _ = np.linalg.eig(T_matrix)
lambda_max = np.max(eigenvalues)
# Free energy per spin
f = -k_B * T * np.log(lambda_max)
print(f"Free energy per spin: {f:.4f}")
# Output the transfer matrix and its largest eigenvalue
print("Transfer matrix:\n", T_matrix)
print("Largest eigenvalue:", lambda_max)
import numpy as np
import random
import math
def MC_step(config, beta):
'''Monte Carlo move using Metropolis algorithm '''
L = len(config)
for _ in range(L * L): # Corrected the loop
a = np.random.randint(0, L)
b = np.random.randint(0, L)
sigma = config[a, b]
neighbors = (config[(a + 1) % L, b] + config[a, (b + 1) % L] +
config[(a - 1) % L, b] + config[a, (b - 1) % L])
del_E = 2 * sigma * neighbors
if del_E < 0 or random.uniform(0, 1) < np.exp(-del_E * beta):
config[a, b] = -sigma
return config
def E_dimensionless(config, L):
'''Calculate the energy of the configuration'''
energy = 0
for i in range(L):
for j in range(L):
S = config[i, j]
neighbors = (config[(i + 1) % L, j] + config[i, (j + 1) % L] +
config[(i - 1) % L, j] + config[i, (j - 1) % L])
energy += -neighbors * S
return energy / 4 # To compensate for overcounting
def magnetization(config):
'''Calculate the magnetization of the configuration'''
return np.sum(config)
def calcul_energy_mag_C_X(config, L, eqSteps, err_runs):
print('finished')
nt = 100 # number of temperature points
mcSteps = 1000
T_c = 2 / math.log(1 + math.sqrt(2))
T = np.linspace(1., 7., nt)
E, M, C, X = np.zeros(nt), np.zeros(nt), np.zeros(nt), np.zeros(nt)
C_theoric, M_theoric = np.zeros(nt), np.zeros(nt)
delta_E, delta_M, delta_C, delta_X = np.zeros(nt), np.zeros(nt), np.zeros(nt), np.zeros(nt)
n1 = 1.0 / (mcSteps * L * L)
n2 = 1.0 / (mcSteps * mcSteps * L * L)
Energies, Magnetizations, SpecificHeats, Susceptibilities = [], [], [], []
delEnergies, delMagnetizations, delSpecificHeats, delSusceptibilities = [], [], [], []
for t in range(nt):
beta = 1. / T[t]
# Equilibrate the system
for _ in range(eqSteps):
MC_step(config, beta)
Ez, Cz, Mz, Xz = [], [], [], []
for _ in range(err_runs):
E, E_squared, M, M_squared = 0, 0, 0, 0
for _ in range(mcSteps):
MC_step(config, beta)
energy = E_dimensionless(config, L)
mag = abs(magnetization(config))
E += energy
E_squared += energy ** 2
M += mag
M_squared += mag ** 2
E_mean = E / mcSteps
E_squared_mean = E_squared / mcSteps
M_mean = M / mcSteps
M_squared_mean = M_squared / mcSteps
Energy = E_mean / (L ** 2)
SpecificHeat = beta ** 2 * (E_squared_mean - E_mean ** 2) / (L ** 2)
Magnetization = M_mean / (L ** 2)
Susceptibility = beta * (M_squared_mean - M_mean ** 2) / (L ** 2)
Ez.append(Energy)
Cz.append(SpecificHeat)
Mz.append(Magnetization)
Xz.append(Susceptibility)
Energies.append(np.mean(Ez))
delEnergies.append(np.std(Ez))
Magnetizations.append(np.mean(Mz))
delMagnetizations.append(np.std(Mz))
SpecificHeats.append(np.mean(Cz))
delSpecificHeats.append(np.std(Cz))
Susceptibilities.append(np.mean(Xz))
delSusceptibilities.append(np.std(Xz))
if T[t] < T_c:
M_theoric[t] = pow(1 - pow(np.sinh(2 * beta), -4), 1 / 8)
C_theoric[t] = (2.0 / np.pi) * (math.log(1 + math.sqrt(2)) ** 2) * (-math.log(1 - T[t] / T_c) + math.log(1.0 / math.log(1 + math.sqrt(2))) - (1 + np.pi / 4))
else:
C_theoric[t] = 0
return (T, Energies, Magnetizations, SpecificHeats, Susceptibilities,
delEnergies, delMagnetizations, M_theoric, C_theoric, delSpecificHeats, delSusceptibilities)
# Parameters
L = 10 # Size of the lattice
eqSteps = 1000 # Number of steps to reach equilibrium
err_runs = 10 # Number of error runs
# Initial configuration (random spins)
config = 2 * np.random.randint(2, size=(L, L)) - 1
# Perform calculations
results = calcul_energy_mag_C_X(config, L, eqSteps, err_runs)
# Unpack results
(T, Energies, Magnetizations, SpecificHeats, Susceptibilities,
delEnergies, delMagnetizations, M_theoric, C_theoric,
delSpecificHeats, delSusceptibilities) = results
# Plot results
import matplotlib.pyplot as plt
plt.figure()
plt.errorbar(T, Energies, yerr=delEnergies, label='Energy')
plt.xlabel('Temperature')
plt.ylabel('Energy')
plt.legend()
plt.show()
plt.figure()
plt.errorbar(T, Magnetizations, yerr=delMagnetizations, label='Magnetization')
plt.xlabel('Temperature')
plt.ylabel('Magnetization')
plt.legend()
plt.show()
plt.figure()
plt.errorbar(T, SpecificHeats, yerr=delSpecificHeats, label='Specific Heat')
plt.plot(T, C_theoric, label='Theoretical Specific Heat')
plt.xlabel('Temperature')
plt.ylabel('Specific Heat')
plt.legend()
plt.show()
plt.figure()
plt.errorbar(T, Susceptibilities, yerr=delSusceptibilities, label='Susceptibility')
plt.xlabel('Temperature')
plt.ylabel('Susceptibility')
plt.legend()
plt.show()
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
from utils import version; version.version_information()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import MCXGate
gate = MCXGate(4)
from qiskit import QuantumCircuit
circuit = QuantumCircuit(5)
circuit.append(gate, [0, 1, 4, 2, 3])
circuit.draw('mpl')
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister
qc=QuantumCircuit(QuantumRegister(3,'qr'))
qc.h(0)
qc.h(1)
qc.h(2)
qc.draw(output="mpl")
qc=QuantumCircuit(QuantumRegister(3,'qr'))
qc.h(range(3))
qc.draw(output="mpl")
q=QuantumRegister(3,'qr')
qc=QuantumCircuit(q)
qc.h(q[0:3])
qc.draw(output="mpl")
q=QuantumRegister(3,'qr')
qc=QuantumCircuit(q)
qc.h(q[0])
qc.draw(output="mpl")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 12345
from qiskit_machine_learning.datasets import ad_hoc_data
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=20,
test_size=5,
n=adhoc_dimension,
gap=0.3,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
import matplotlib.pyplot as plt
import numpy as np
def plot_features(ax, features, labels, class_label, marker, face, edge, label):
# A train plot
ax.scatter(
# x coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 0],
# y coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 1],
marker=marker,
facecolors=face,
edgecolors=edge,
label=label,
)
def plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total):
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
# A train plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "A train")
# B train plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B train")
# A test plot
plot_features(plt, test_features, test_labels, 0, "s", "b", "w", "A test")
# B test plot
plot_features(plt, test_features, test_labels, 1, "o", "r", "w", "B test")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset")
plt.show()
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
from qiskit.circuit.library import ZZFeatureMap
from qiskit.primitives import Sampler
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit_machine_learning.kernels import FidelityQuantumKernel
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
sampler = Sampler()
fidelity = ComputeUncompute(sampler=sampler)
adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map)
from sklearn.svm import SVC
adhoc_svc = SVC(kernel=adhoc_kernel.evaluate)
adhoc_svc.fit(train_features, train_labels)
adhoc_score_callable_function = adhoc_svc.score(test_features, test_labels)
print(f"Callable kernel classification test score: {adhoc_score_callable_function}")
adhoc_matrix_train = adhoc_kernel.evaluate(x_vec=train_features)
adhoc_matrix_test = adhoc_kernel.evaluate(x_vec=test_features, y_vec=train_features)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(
np.asmatrix(adhoc_matrix_train), interpolation="nearest", origin="upper", cmap="Blues"
)
axs[0].set_title("Ad hoc training kernel matrix")
axs[1].imshow(np.asmatrix(adhoc_matrix_test), interpolation="nearest", origin="upper", cmap="Reds")
axs[1].set_title("Ad hoc testing kernel matrix")
plt.show()
adhoc_svc = SVC(kernel="precomputed")
adhoc_svc.fit(adhoc_matrix_train, train_labels)
adhoc_score_precomputed_kernel = adhoc_svc.score(adhoc_matrix_test, test_labels)
print(f"Precomputed kernel classification test score: {adhoc_score_precomputed_kernel}")
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=adhoc_kernel)
qsvc.fit(train_features, train_labels)
qsvc_score = qsvc.score(test_features, test_labels)
print(f"QSVC classification test score: {qsvc_score}")
print(f"Classification Model | Accuracy Score")
print(f"---------------------------------------------------------")
print(f"SVC using kernel as a callable function | {adhoc_score_callable_function:10.2f}")
print(f"SVC using precomputed kernel matrix | {adhoc_score_precomputed_kernel:10.2f}")
print(f"QSVC | {qsvc_score:10.2f}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=0,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
# A label plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "B")
# B label plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for clustering")
plt.show()
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
adhoc_kernel = FidelityQuantumKernel(feature_map=adhoc_feature_map)
adhoc_matrix = adhoc_kernel.evaluate(x_vec=train_features)
plt.figure(figsize=(5, 5))
plt.imshow(np.asmatrix(adhoc_matrix), interpolation="nearest", origin="upper", cmap="Greens")
plt.title("Ad hoc clustering kernel matrix")
plt.show()
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score
adhoc_spectral = SpectralClustering(2, affinity="precomputed")
cluster_labels = adhoc_spectral.fit_predict(adhoc_matrix)
cluster_score = normalized_mutual_info_score(cluster_labels, train_labels)
print(f"Clustering score: {cluster_score}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=10,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement="linear")
qpca_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=feature_map)
matrix_train = qpca_kernel.evaluate(x_vec=train_features)
matrix_test = qpca_kernel.evaluate(x_vec=test_features, y_vec=test_features)
from sklearn.decomposition import KernelPCA
kernel_pca_rbf = KernelPCA(n_components=2, kernel="rbf")
kernel_pca_rbf.fit(train_features)
train_features_rbf = kernel_pca_rbf.transform(train_features)
test_features_rbf = kernel_pca_rbf.transform(test_features)
kernel_pca_q = KernelPCA(n_components=2, kernel="precomputed")
train_features_q = kernel_pca_q.fit_transform(matrix_train)
test_features_q = kernel_pca_q.fit_transform(matrix_test)
from sklearn.linear_model import LogisticRegression
logistic_regression = LogisticRegression()
logistic_regression.fit(train_features_q, train_labels)
logistic_score = logistic_regression.score(test_features_q, test_labels)
print(f"Logistic regression score: {logistic_score}")
fig, (q_ax, rbf_ax) = plt.subplots(1, 2, figsize=(10, 5))
plot_features(q_ax, train_features_q, train_labels, 0, "s", "w", "b", "A train")
plot_features(q_ax, train_features_q, train_labels, 1, "o", "w", "r", "B train")
plot_features(q_ax, test_features_q, test_labels, 0, "s", "b", "w", "A test")
plot_features(q_ax, test_features_q, test_labels, 1, "o", "r", "w", "A test")
q_ax.set_ylabel("Principal component #1")
q_ax.set_xlabel("Principal component #0")
q_ax.set_title("Projection of training and test data\n using KPCA with Quantum Kernel")
# Plotting the linear separation
h = 0.01 # step size in the mesh
# create a mesh to plot in
x_min, x_max = train_features_q[:, 0].min() - 1, train_features_q[:, 0].max() + 1
y_min, y_max = train_features_q[:, 1].min() - 1, train_features_q[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
predictions = logistic_regression.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
predictions = predictions.reshape(xx.shape)
q_ax.contourf(xx, yy, predictions, cmap=plt.cm.RdBu, alpha=0.2)
plot_features(rbf_ax, train_features_rbf, train_labels, 0, "s", "w", "b", "A train")
plot_features(rbf_ax, train_features_rbf, train_labels, 1, "o", "w", "r", "B train")
plot_features(rbf_ax, test_features_rbf, test_labels, 0, "s", "b", "w", "A test")
plot_features(rbf_ax, test_features_rbf, test_labels, 1, "o", "r", "w", "A test")
rbf_ax.set_ylabel("Principal component #1")
rbf_ax.set_xlabel("Principal component #0")
rbf_ax.set_title("Projection of training data\n using KernelPCA")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.tools.monitor import job_monitor
import matplotlib as mpl
# import basic plot tools
from qiskit.visualization import plot_histogram, plot_bloch_multivector
import numpy as np
from numpy import pi
qft_circuit = QuantumCircuit(3)
qft_circuit.clear()
#input state= 5
qft_circuit.x(0)
qft_circuit.x(2)
qft_circuit.h(0)
qft_circuit.cp(pi/2,0,1)
qft_circuit.cp(pi/4,0,2)
qft_circuit.h(1)
qft_circuit.cp(pi/2,1,2)
qft_circuit.h(2)
#qft_circuit.swap(0,2)
qft_circuit.draw('mpl')
#output is the bloch sphere representation in the fourier basis
sim = Aer.get_backend("aer_simulator")
qft_circuit_init = qft_circuit.copy()
qft_circuit_init.save_statevector()
statevector = sim.run(qft_circuit_init).result().get_statevector()
plot_bloch_multivector(statevector)
IBMQ.save_account('')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 2 and not b.configuration().simulator and b.status().operational==True))
print(backend)
t_qc = transpile(qft_circuit, backend, optimization_level=3)#transpile=assembling the circuit and everything
job = backend.run(t_qc)#backend means device
job_monitor(job)
|
https://github.com/hephaex/Quantum-Computing-Awesome-List
|
hephaex
|
from qiskit import QuantumCircuit, Aer, execute
from math import pi
import numpy as np
from qiskit.visualization import plot_bloch_multivector, plot_histogram
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.cx(0,1)
qc.draw()
statevector_backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,statevector_backend).result().get_statevector()
print(final_state)
plot_bloch_multivector(final_state)
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.z(1)
qc.draw()
final_state = execute(qc,statevector_backend).result().get_statevector()
print(final_state)
plot_bloch_multivector(final_state)
qc.cx(0,1)
qc.draw()
final_state = execute(qc,statevector_backend).result().get_statevector()
print(final_state)
plot_bloch_multivector(final_state)
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.cx(0,1)
qc.h(0)
qc.h(1)
display(qc.draw())
# `display` is an IPython tool, remove if it cases an error
unitary_backend = Aer.get_backend('unitary_simulator')
unitary = execute(qc,unitary_backend).result().get_unitary()
print(unitary)
qc = QuantumCircuit(2)
qc.cx(1,0)
display(qc.draw())
unitary_backend = Aer.get_backend('unitary_simulator')
unitary = execute(qc,unitary_backend).result().get_unitary()
print(unitary)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.x(0).c_if(cr, 0)
qc.measure(0, 0)
qc.draw('mpl')
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_lima')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
def qc_qft(n):
qr = QuantumRegister(n); qc = QuantumCircuit(qr, name = 'QFT')
for l in range(0, n):
qc.h(qr[l])
if l < n-1:
for q in range(l+1, n):
lb = 2*math.pi*2**(-q+l-1)
qc.cp(lb, qr[q], qr[l])
#qc.barrier()
#qc.barrier()
if n%2 == 0:
ul = n//2
else:
ul = (n-1)//2
for p in range(0, ul):
qc.swap(p, n-1-p)
return qc
n = 4; qc_qft_ = qc_qft(n); qc_qft_.draw(output='mpl')
def qc_iqft(n):
qr = QuantumRegister(n); qc = QuantumCircuit(qr, name = 'IQFT')
if n%2 == 0:
ul = n//2
else:
ul = (n-1)//2
for p in range(ul-1, -1, -1):
qc.swap(p, n-1-p)
#qc.barrier()
for l in range(n-1, -1, -1):
if l < n-1:
for q in range(n-1, l+1-1, -1):
lb = -2*math.pi*2**(-q+l-1)#; print(lb)
qc.cp(lb, qr[q], qr[l])
qc.h(qr[l])
#qc.barrier()
return qc
n = 4; qc_iqft_ = qc_iqft(n); qc_iqft_.draw(output='mpl')
#x0 = 1 + 0*1j; x1 = 0 + 0*1j # estado |0>
#x0 = 0 + 0*1j; x1 = 1 + 0*1j # estado |1>
x0 = 1/math.sqrt(2) + 0*1j; x1 = 1/math.sqrt(2) + 0*1j # estado |+>
mx0 = math.sqrt(x0.real**2 + x0.imag**2)
if x0.real != 0:
ph0 = math.atan(x0.imag/x0.real)
elif x0.real == 0 and x0.imag != 0:
ph0 = math.pi/2
elif x0.real == 0 and x0.imag == 0:
ph0 = 0
mx1 = math.sqrt(x1.real**2 + x1.imag**2)
if x1.real != 0:
ph1 = math.atan(x1.imag/x1.real)
elif x1.real == 0 and x1.imag != 0:
ph1 = math.pi/2
elif x1.real == 0 and x1.imag == 0:
ph1 = 0
print('|x0|=',mx0,', ph0=', ph0,', |x1|=', mx1,', ph1=', ph1)
th = 2*math.acos(mx1); ph = ph1-ph0+math.pi; lb = ph0-math.pi
print('th=',th,', ph=', ph,', lb=', lb)
n = 1
qr = QuantumRegister(n); qc = QuantumCircuit(qr)
qc.x(qr[0]); qc.u(th, ph, lb, qr[0]); qc.barrier()
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0])
qc.draw(output='mpl')
svsimulator = Aer.get_backend('statevector_simulator')
job = execute(qc, backend = svsimulator, shots = 1, memory = True)
print(job.result().get_statevector(qc))
def tfc(x): # classical discrete Fourier transform
d = len(x)
y = np.zeros(d, dtype = complex)
for k in range(0, d):
for j in range(0, d):
y[k] += x[j]*(math.cos(2*math.pi*j*k/d) + 1j*math.sin(2*math.pi*j*k/d))
return y/math.sqrt(d)
d = 4; x = np.zeros(d, dtype = complex);
#x = [1/2, 1/2, 1/2, 1/2]
x = [-1/2, -1/2, 1/2, 1/2]
y = tfc(x); print(y)
n = 2
qr = QuantumRegister(n); qc = QuantumCircuit(qr)
#qc.h([0,1]); qc.barrier() # ok
qc.x([0]); qc.h([0,1]); qc.barrier() # ok a menos de uma fase global de pi
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0,1])
qc.draw(output='mpl')
svsimulator = Aer.get_backend('statevector_simulator')
job = execute(qc, backend = svsimulator, shots = 1, memory = True)
print(job.result().get_statevector(qc)) # para >1 qubit tem a questao da ordem da bc
d = 4; x = np.zeros(d, dtype = complex);
x = [math.sqrt(1/6), math.sqrt(1/6), math.sqrt(2/3), 0]
y = tfc(x); print(y)
n = 3
qr = QuantumRegister(n); cr = ClassicalRegister(n); qc = QuantumCircuit(qr, cr)
qc.x([0,2]); qc.barrier()
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0,1,2]); qc.barrier()
qc_iqft_ = qc_iqft(n); iqft = qc_iqft_.to_gate(); qc.append(iqft, [0,1,2]); qc.barrier()
qc.measure([0,1,2],[0,1,2])
qc.draw(output='mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../../')
from composer.qs_circuit import QSCircuit
from qiskit import execute, QuantumCircuit
from qiskit_aer import AerSimulator
SIZE_REG = 16
CIRCUIT_SIZE = SIZE_REG * 2
ALPHABET = ['0', '1']
class QS_SAES_Circuit(QSCircuit):
def __init__(self, CIRCUIT_SIZE, msg, key, msg_indexes, key_indexes):
super().__init__(CIRCUIT_SIZE)
self.msg_indexes = msg_indexes
self.key_indexes = key_indexes
self.set_bin_reg(msg, self.msg_indexes)
self.set_bin_reg(key, self.key_indexes)
self.build()
def build(self):
self.barrier()
self.add_roundkey()
self.barrier()
self.s_box()
self.barrier()
self.shift_rows()
self.barrier()
self.mix_columns()
self.barrier()
self.key_expansion('10000000'[::-1])
self.barrier()
self.add_roundkey()
self.barrier()
self.s_box()
self.barrier()
self.shift_rows()
self.barrier()
self.key_expansion('00110000'[::-1])
self.barrier()
self.add_roundkey()
def add_roundkey(self):
self.xor2(self.key_indexes, self.msg_indexes)
def s_key(self):
for limit in range(0, 8, 4):
x0, x1, x2, x3 = [self.key_indexes[i] for i in list(range(limit, limit + 4))]
self.swap2(x0, x3)
self.swap2(x1, x2)
self.xor2(x2, x1)
self.ccx(x3, x1, x0)
self.ccx(x0, x2, x3)
self.ccx(x0, x3, x1)
self.mcx([x0, x1, x3], x2)
self.cx(x3, x0)
self.not1([x2, x3])
self.cx(x0, x2)
self.ccx(x1, x2, x0)
self.ccx(x0, x3, x1)
self.ccx(x0, x1, x3)
self.shift_right([x0, x1, x2, x3])
self.swap2(x0, x3)
self.swap2(x1, x2)
def s_key_inv(self):
qc = QuantumCircuit(4)
qc.swap(0, 3)
qc.swap(1, 2)
qc.cx(2, 1)
qc.ccx(3, 1, 0)
qc.ccx(0, 2, 3)
qc.ccx(0, 3, 1)
qc.mcx([0, 1, 3], 2)
qc.cx(3, 0)
qc.x([2, 3])
qc.cx(0, 2)
qc.ccx(1, 2, 0)
qc.ccx(0, 3, 1)
qc.ccx(0, 1, 3)
indexes = [0, 1, 2, 3]
indexes.sort(reverse=True)
qc.swap(indexes[:-1], indexes[1:])
qc.swap(0, 3)
qc.swap(1, 2)
qc_inv = qc.to_gate().inverse()
for limit in range(0, 8, 4):
self.append(qc_inv, [self.key_indexes[i] for i in list(range(limit, limit + 4))])
def s_box(self):
for limit in range(0, 16, 4):
x0, x1, x2, x3 = [self.msg_indexes[i] for i in list(range(limit, limit + 4))]
self.swap2(x0, x3)
self.swap2(x1, x2)
self.xor2(x2, x1)
self.ccx(x3, x1, x0)
self.ccx(x0, x2, x3)
self.ccx(x0, x3, x1)
self.mcx([x0, x1, x3], x2)
self.cx(x3, x0)
self.not1([x2, x3])
self.cx(x0, x2)
self.ccx(x1, x2, x0)
self.ccx(x0, x3, x1)
self.ccx(x0, x1, x3)
self.shift_right([x0, x1, x2, x3])
self.swap2(x0, x3)
self.swap2(x1, x2)
def mix_columns(self):
for limit in range(0, 16, 8):
b0, b1, b2, b3, b4, b5, b6, b7 = [self.msg_indexes[i] for i in list(range(limit, limit + 8))[::-1]]
self.xor2(b0, b6)
self.xor2(b5, b3)
self.xor2(b4, b2)
self.xor2(b1, b7)
self.xor2(b7, b4)
self.xor2(b2, b5)
self.xor2(b3, b0)
self.xor2(b6, b1)
self.swap2(b0, b6)
self.swap2(b1, b4)
self.swap2(b2, b5)
self.swap2(b4, b5)
self.swap2(b5, b6)
def shift_rows(self):
x0, x1, x3, x4 = [self.msg_indexes[i] for i in range(0, 4)]
x8, x9, x10, x11 = [self.msg_indexes[i] for i in range(8, 12)]
self.swap2(x0, x8)
self.swap2(x1, x9)
self.swap2(x3, x10)
self.swap2(x4, x11)
def key_expansion(self, constant):
self.swap2(self.key_indexes[:4], self.key_indexes[4:8])
self.s_key()
for i, bit in enumerate(constant):
if bit == '1':
self.not1(self.key_indexes[i])
self.xor2(self.key_indexes[:8], self.key_indexes[-8:])
for i, bit in enumerate(constant):
if bit == '1':
self.not1(self.key_indexes[i])
self.s_key_inv()
self.swap2(self.key_indexes[:4], self.key_indexes[4:8])
self.xor2(self.key_indexes[-8:], self.key_indexes[:8])
def saes_qcypher(msg, key):
msg_indexes = list(range(0, SIZE_REG))
msg_slice = slice(0, SIZE_REG)
key_indexes = list(range(SIZE_REG, 2 * SIZE_REG))
qc = QS_SAES_Circuit(CIRCUIT_SIZE, msg, key, msg_indexes, key_indexes)
qc.measure(msg_indexes, msg_indexes)
print(qc)
backend = AerSimulator(method='matrix_product_state')
job = execute(qc, backend, shots=1)
counts = job.result().get_counts(qc)
result_bin = ''.join(list(list(counts.keys())[0][::-1][msg_slice][::-1]))
return result_bin
if __name__ == "__main__":
msg = '0110111101101011' # input('Insert message: ')
key = '1010011100111011' # input('Insert key: ')
assert all(list(map(lambda c: c in ALPHABET, msg)))
assert all(list(map(lambda c: c in ALPHABET, key)))
assert len(msg) == SIZE_REG
assert len(msg) == len(key)
cypher = saes_qcypher(msg, key)
print()
print(f'Message: {msg}')
print(f'Key: {key}\n')
print(f'-> Expected: 0000011100111000')
print(f'Cypher text: {cypher}\n')
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
%run qlatvia.py
draw_qubit()
sqrttwo=2**0.5
draw_quantum_state(1,0,"")
draw_quantum_state(1/sqrttwo,1/sqrttwo,"|+>")
# drawing the angle with |0>-axis
from matplotlib.pyplot import gca, text
from matplotlib.patches import Arc
gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=45) )
text(0.08,0.05,'.',fontsize=30)
text(0.21,0.09,'\u03C0/4')
%run qlatvia.py
draw_qubit()
sqrttwo=2**0.5
draw_quantum_state(0,1,"")
draw_quantum_state(1/sqrttwo,-1/sqrttwo,"|->")
# drawing the angle with |0>-axis
from matplotlib.pyplot import gca, text
from matplotlib.patches import Arc
gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=-45,theta2=90) )
text(0.08,0.05,'.',fontsize=30)
text(0.21,0.09,'3\u03C0/4')
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
from math import pi
# we define a quantum circuit with one qubit and one bit
q = QuantumRegister(1) # quantum register with a single qubit
c = ClassicalRegister(1) # classical register with a single bit
qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers
# angle of rotation in radian
rotation_angle = 2*pi/3
# rotate the qubit with rotation_angle
qc.ry(2*rotation_angle,q[0])
# measure the qubit
qc.measure(q,c)
# draw the circuit
qc.draw(output='mpl')
# execute the program 1000 times
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000)
# print the results
counts = job.result().get_counts(qc)
print(counts)
# draw the histogram
plot_histogram(counts)
from math import sin,cos
# the quantum state
quantum_state = [ cos(rotation_angle) , sin (rotation_angle) ]
print("The quantum state is",round(quantum_state[0],4),"|0> +",round(quantum_state[1],4),"|1>")
the_expected_number_of_zeros = 1000*cos(rotation_angle)**2
the_expected_number_of_ones = 1000*sin(rotation_angle)**2
# expected results
print("The expected value of observing '0' is",round(the_expected_number_of_zeros,4))
print("The expected value of observing '1' is",round(the_expected_number_of_ones,4))
# draw the quantum state
%run qlatvia.py
draw_qubit()
draw_quantum_state(quantum_state[0],quantum_state[1],"|v>")
#
# your code is here
#
from random import randrange
from math import sin,cos, pi
# randomly pick an angle
random_angle = randrange(360)
print("random angle is",random_angle)
# pick angle in radian
rotation_angle = random_angle/360*2*pi
# the quantum state
quantum_state = [ cos(rotation_angle) , sin (rotation_angle) ]
the_expected_number_of_zeros = 1000*cos(rotation_angle)**2
the_expected_number_of_ones = 1000*sin(rotation_angle)**2
# expected results
print("The expected value of observing '0' is",round(the_expected_number_of_zeros,4))
print("The expected value of observing '1' is",round(the_expected_number_of_ones,4))
# draw the quantum state
%run qlatvia.py
draw_qubit()
draw_quantum_state(quantum_state[0],quantum_state[1],"|v>")
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
# we define a quantum circuit with one qubit and one bit
q = QuantumRegister(1) # quantum register with a single qubit
c = ClassicalRegister(1) # classical register with a single bit
qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers
# rotate the qubit with rotation_angle
qc.ry(2*rotation_angle,q[0])
# measure the qubit
qc.measure(q,c)
# draw the circuit
qc.draw(output='mpl')
# execute the program 1000 times
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000)
# print the results
counts = job.result().get_counts(qc)
print(counts)
the_observed_number_of_ones = 0
if '1' in counts:
the_observed_number_of_ones= counts['1']
# draw the histogram
plot_histogram(counts)
difference = abs(the_expected_number_of_ones - the_observed_number_of_ones)
print("The expected number of ones is",the_expected_number_of_ones)
print("The observed number of ones is",the_observed_number_of_ones)
print("The difference is",difference)
print("The difference in percentage is",difference/100,"%")
|
https://github.com/rishikhurana2/FourQuantumAlgorithms
|
rishikhurana2
|
from qiskit import QuantumCircuit
from QCLG_lvl3.oracles.secret_number_oracle import SecretNUmberOracle
class BernsteinVazirani:
@classmethod
def bernstein_vazirani(cls, random_binary, eval_mode: bool) -> QuantumCircuit:
# Construct secret number oracle
secret_number_oracle = SecretNUmberOracle.create_secret_number_oracle(random_binary=random_binary, eval_mode=eval_mode)
num_of_qubits = secret_number_oracle.num_qubits
# Construct circuit according to the length of the number
dj_circuit = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
dj_circuit_before_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
# Apply H-gates
for qubit in range(num_of_qubits - 1):
dj_circuit_before_oracle.h(qubit)
# Put output qubit in state |->
dj_circuit_before_oracle.x(num_of_qubits - 1)
dj_circuit_before_oracle.h(num_of_qubits - 1)
dj_circuit += dj_circuit_before_oracle
# Add oracle
dj_circuit += secret_number_oracle
dj_circuit_after_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
# Repeat H-gates
for qubit in range(num_of_qubits - 1):
dj_circuit_after_oracle.h(qubit)
dj_circuit_after_oracle.barrier()
# Measure
for i in range(num_of_qubits - 1):
dj_circuit_after_oracle.measure(i, i)
dj_circuit += dj_circuit_after_oracle
if not eval_mode:
print("Circuit before the oracle\n")
print(QuantumCircuit.draw(dj_circuit_before_oracle))
print("Circuit after the oracle\n")
print(QuantumCircuit.draw(dj_circuit_after_oracle))
print(dj_circuit)
return dj_circuit
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.tools.monitor import job_monitor
import matplotlib as mpl
# import basic plot tools
from qiskit.visualization import plot_histogram, plot_bloch_multivector
import numpy as np
from numpy import pi
qft_circuit = QuantumCircuit(3)
qft_circuit.clear()
#input state= 5
qft_circuit.x(0)
qft_circuit.x(2)
qft_circuit.h(0)
qft_circuit.cp(pi/2,0,1)
qft_circuit.cp(pi/4,0,2)
qft_circuit.h(1)
qft_circuit.cp(pi/2,1,2)
qft_circuit.h(2)
#qft_circuit.swap(0,2)
qft_circuit.draw('mpl')
#output is the bloch sphere representation in the fourier basis
sim = Aer.get_backend("aer_simulator")
qft_circuit_init = qft_circuit.copy()
qft_circuit_init.save_statevector()
statevector = sim.run(qft_circuit_init).result().get_statevector()
plot_bloch_multivector(statevector)
IBMQ.save_account('')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 2 and not b.configuration().simulator and b.status().operational==True))
print(backend)
t_qc = transpile(qft_circuit, backend, optimization_level=3)#transpile=assembling the circuit and everything
job = backend.run(t_qc)#backend means device
job_monitor(job)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.draw('mpl')
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
# %%
import h5py
import numpy as np
from qiskit import QuantumCircuit
from tqdm import tqdm
from external.NuOp.parallel_two_qubit_gate_decomposition import *
from clonk.utils.riswap_gates.riswap import RiSwapGate
# test
# %%
# don't change, would break previous data collection
# XXX
alpha_range = [2, 3, 4, 5, 6, 7]
# # alpha_range = [5]
# gate_range = range(2,11)#9
# alpha_range = [1,2,3,4,5,6]
gate_range = range(2, 9) # 11
from qiskit.quantum_info import random_unitary
def collect_random2q_data(base_fidelity, N=15, mode="swap", fn=None):
# alpha_range = [2,3,4,5,6,7]
# # alpha_range = [5]
# gate_range = range(2,9)#11
base_fidelity = base_fidelity
empty_flag = 0
filename = f"data-archive2/data1_{mode}.h5" # f'data-archive2/data1_{mode}.h5' #f'data-archive/data1_{mode}.h5', #archive2 uses 2-7, archive3 uses 1-6
# filename = f'src/clonk/benchmark_suite/data/data5_{mode}.h5'
if fn is not None:
filename = fn
# load in previous data
try:
with h5py.File(filename, "r") as h5f:
# gate_error = h5f['random2q_gate_error'][:]
decomp_error = h5f["decomp_error"][:]
# fidelity_error = h5f['random2q_fidelity_error'][:]
# backfill data
gate_error = np.zeros(
shape=(len(decomp_error), len(alpha_range), len(gate_range))
)
fidelity_error = np.zeros(
shape=(len(decomp_error), len(alpha_range), len(gate_range))
)
for i in range(len(decomp_error)):
for alpha_index, alpha in enumerate(alpha_range):
alpha = 1 / alpha
for gate_index, gate_count in enumerate(gate_range):
gate_error[i][alpha_index][gate_index] = (
1 - (alpha * (1 - base_fidelity))
) ** gate_count
fidelity_error[i][alpha_index][gate_index] = (
decomp_error[i][alpha_index][gate_index]
) * gate_error[i][alpha_index][gate_index]
except Exception:
# case where data doesn't already exist
empty_flag = 1
decomp_error = []
for n in tqdm(range(N - len(decomp_error))):
# if not empty_flag and len(gate_error) >= N:
# break
qc = QuantumCircuit(2)
if mode == "random":
qc.append(random_unitary(dims=(2, 2)), [0, 1])
else:
raise ValueError()
# qc.append(SwapGate(), [0,1])
dag = circuit_to_dag(qc)
# new data for this iteration
temp_gate_error = np.zeros(shape=(1, len(alpha_range), len(gate_range)))
temp_decomp_error = np.zeros(shape=(1, len(alpha_range), len(gate_range)))
temp_fidelity_error = np.zeros(shape=(1, len(alpha_range), len(gate_range)))
for alpha_index, alpha in enumerate(alpha_range):
alpha = 1 / alpha
for gate_index, gate_count in enumerate(gate_range):
params = [[alpha]]
gate_defs = [RiSwapGate]
temp_gate_error[0][alpha_index][gate_index] = (
1 - (alpha * (1 - base_fidelity))
) ** gate_count
# run perfect if it doesn't already exist
fid_2q = {(0, 1): [1]}
pgrp = ParallelGateReplacementPass(
gate_defs,
params,
fid_2q,
fidelity_list_1q_gate=[1 for _ in range(54)],
tol=1e-10,
force_gate_count=gate_count,
)
pgrp.run(dag)
temp_decomp_error[0][alpha_index][gate_index] = pgrp.property_set[
"best_fid"
]
temp_fidelity_error[0][alpha_index][gate_index] = (
temp_gate_error[0][alpha_index][gate_index]
) * temp_decomp_error[0][alpha_index][gate_index]
# run noisy
# fid_2q = {(0,1):[1-alpha*(1-base_fidelity)]}
# pgrp = ParallelGateReplacementPass(gate_defs, params ,fid_2q, fidelity_list_1q_gate=[1 for _ in range(54)], tol=1e-10, force_gate_count=gate_count)
# approx = pgrp.run(dag)
# temp_fidelity_error[0][alpha_index][gate_index] = (pgrp.property_set["best_fid"])
# these are equivalent - save some time and just calculate it using the previous values
# print(f"{gate_error[-1]}, {decomp_error[-1]}, {fidelity_error[-1]}")
# update data
if empty_flag:
gate_error = temp_gate_error
decomp_error = temp_decomp_error
fidelity_error = temp_fidelity_error
empty_flag = 0
else:
gate_error = np.append(gate_error, temp_gate_error, axis=0)
decomp_error = np.append(decomp_error, temp_decomp_error, axis=0)
fidelity_error = np.append(fidelity_error, temp_fidelity_error, axis=0)
# write back data after each iteration in case we end early
with h5py.File(filename, "a") as h5f:
print(f"saving iter {n}")
# delete old, differently sized dataset
try:
del h5f["gate_error"]
del h5f["decomp_error"]
del h5f["fidelity_error"]
except Exception:
# don't need to delete if they don't exist
pass
h5f.create_dataset("gate_error", data=gate_error)
h5f.create_dataset("decomp_error", data=decomp_error)
h5f.create_dataset("fidelity_error", data=fidelity_error)
return gate_error, decomp_error, fidelity_error
import matplotlib.pyplot as plt
# %%
from scipy.stats import sem
# import h5py
# with h5py.File('data.h5', 'r') as h5f:
# gate_error = h5f['random2q_gate_error'][:]
# decomp_error = h5f['random2q_decomp_error'][:]
# fidelity_error = h5f['random2q_fidelity_error'][:]
plt.style.use(["science", "no-latex"])
def create_plot(gate_error, decomp_error, fidelity_error):
fig, axs = plt.subplots(
1, len(gate_error[0]), sharey=True, sharex=True, figsize=(12, 4)
)
for alpha_index in range(len(gate_error[0])):
alpha = 1 / alpha_range[alpha_index]
gate_unit_time = [el * alpha for el in gate_range]
axs[alpha_index].plot(
gate_unit_time,
np.average(gate_error, axis=0)[alpha_index],
label="Gate Error",
linestyle="--",
marker="o",
)
axs[alpha_index].errorbar(
gate_unit_time,
np.average(decomp_error, axis=0)[alpha_index],
yerr=sem(decomp_error, axis=0)[alpha_index],
label="Decomp Error",
linestyle="--",
marker="s",
)
axs[alpha_index].errorbar(
gate_unit_time,
np.average(fidelity_error, axis=0)[alpha_index],
yerr=sem(fidelity_error, axis=0)[alpha_index],
label="Total Fidelity",
marker="^",
)
axs[alpha_index].set_xlabel("Gate Unit Time")
axs[alpha_index].set_title(f"iSwap^(1/{1/alpha})")
# for i, key in enumerate(np.max(np.average(fidelity_error, axis=0),axis=1)):
# axs[i].annotate(key, (i, frequency_list[key]))
# if i >= 3:
# break
axs[-1].legend()
axs[0].set_ylabel("Avg Fidelity")
axs[0].set_yscale("logit")
fig.tight_layout()
fig.show()
filename = "nuop_experiment"
fig.savefig("{}.pdf".format(filename), format="pdf", facecolor="white")
# %%
# gate_error, decomp_error, fidelity_error = collect_random2q_data(1-5e-2, N=25, mode="random")
# create_plot(gate_error, decomp_error, fidelity_error)
# %%
from scipy.stats import sem
def get_max(fidelity_error):
max_list = []
sem_list = []
for alpha_index in range(len(fidelity_error[0])):
best_over_templatelength = 0
sem_temp = []
for template_length_index in range(len(fidelity_error[0][0])):
best_temp_average = []
for n_repetition in range(len(fidelity_error)):
best_temp_average.append(
fidelity_error[n_repetition][alpha_index][template_length_index]
)
val = np.sum(best_temp_average) / len(fidelity_error)
if val > best_over_templatelength:
best_over_templatelength = val
sem_temp = sem(best_temp_average)
# print(best_over_templatelength)
sem_list.append(sem_temp)
max_list.append(best_over_templatelength)
return max_list, sem_list
# %%
import itertools
marker = itertools.cycle(("o", "^", "s", "d", "v", "*"))
color = itertools.cycle(
(
"tab:blue",
"tab:olive",
"tab:purple",
"tab:red",
"tab:green",
"tab:pink",
"tab:orange",
"tab:cyan",
)
)
# color = itertools.cycle(("tab:green", "tab:pink", "tab:orange", "tab:cyan"))
# base_fidelity_list = [.97, .98, 1-10e-3,1-5e-3, 1-10e-4, 1]
# gate_error, decomp_error, fidelity_error = collect_random2q_data(1-10e-3, N=20, mode="random")
from scipy.stats import sem
def create_plot2(gate_error, decomp_error, fidelity_error, plot_bool, N=20, fn=None):
plt.style.use(["science"]) # , 'ieee'])
SMALL_SIZE = 4
MEDIUM_SIZE = 6
plt.rc("font", size=MEDIUM_SIZE + 2) # controls default text sizes
plt.rc("axes", titlesize=MEDIUM_SIZE + 2) # fontsize of the axes title
plt.rc("axes", labelsize=MEDIUM_SIZE + 1) # fontsize of the x and y labels
plt.rc("xtick", labelsize=SMALL_SIZE + 2) # fontsize of the tick labels
plt.rc("ytick", labelsize=SMALL_SIZE + 2) # fontsize of the tick labels
plt.rc("legend", fontsize=MEDIUM_SIZE) # legend fontsize
plt.rc("figure", titlesize=MEDIUM_SIZE + 2) # fontsize of the figure title
plt.rc("lines", markersize=1.2, linewidth=0.65)
# fig = plt.figure()
# gs = fig.add_gridspec(2,2)
# ax1 = fig.add_subplot(gs[0, 0])
# ax2 = fig.add_subplot(gs[0, 1])
# ax3 = fig.add_subplot(gs[1, :])
# axs = [ax1,ax2,ax3]
if plot_bool:
fig, axs = plt.subplots(
1, 2, figsize=(2, 1.25), sharey=True, gridspec_kw={"width_ratios": [1, 2]}
)
for alpha_index in range(len(gate_error[0])):
alpha = 1 / alpha_range[alpha_index]
set_color = next(color)
set_marker = next(marker)
#
gate_unit_time = gate_range
c = len([el for el in gate_unit_time if el <= 8])
axs[0].errorbar(
gate_unit_time[:c],
[1 - el for el in np.average(decomp_error, axis=0)[alpha_index][:c]],
yerr=sem(decomp_error, axis=0)[alpha_index][:c],
capsize=1.5,
elinewidth=0.5,
ecolor=set_color,
label=r"$\sqrt[" + str(int(1 / alpha)) + r"]{iSwap}$",
marker=set_marker,
color=set_color,
)
#
gate_unit_time = [el * alpha for el in gate_range]
# gate_unit_time = gate_range
# axs[1].plot(gate_unit_time, np.average(gate_error, axis=0)[alpha_index], label=f"Gate Error {alpha}", linestyle='--', marker='o')
# cutting off values past 2 to make pulse duration plot look nicer
c = len([el for el in gate_unit_time if el <= 2])
c_bottom = len(gate_unit_time) - len(
[el for el in gate_unit_time if el >= 0]
)
# c = len(gate_unit_time)
axs[1].errorbar(
gate_unit_time[c_bottom:c],
[
1 - el
for el in np.average(decomp_error, axis=0)[alpha_index][c_bottom:c]
],
yerr=sem(decomp_error, axis=0)[alpha_index][c_bottom:c],
capsize=1.5,
elinewidth=0.5,
ecolor=set_color,
label=r"$\sqrt[" + str(int(1 / alpha)) + r"]{iSwap}$",
marker=set_marker,
color=set_color,
)
# axs.errorbar(gate_unit_time, np.average(fidelity_error, axis=0)[alpha_index], yerr=sem(fidelity_error, axis=0)[alpha_index], label=f"Total Fidelity{alpha}", marker='^')
# axs[alpha_index].set_xlabel("Gate Unit Time")
# axs[alpha_index].set_title(f"iSwap^(1/{1/alpha})")
# for i, key in enumerate(np.max(np.average(fidelity_error, axis=0),axis=1)):
# axs[i].annotate(key, (i, frequency_list[key]))
# if i >= 3:
# break
axs[0].set_yscale("log")
# axs[1].set_xscale('log')
axs[0].set_xlabel(r"Gate Count ($k$)")
axs[1].set_xlabel(r"Pulse Duration ($k/n$)")
fig.suptitle(r"$\sqrt[n]{iSwap}$ Expected Decomp Fidelity")
# axs[0].legend(bbox_to_anchor=(2,-.2), ncol=2)
handles, labels = axs[0].get_legend_handles_labels()
# fig.legend(handles,labels,bbox_to_anchor=(.95,-.08),ncol=3)
# axs[0].legend(bbox_to_anchor=(1.0,-.2), ncol=2)
# axs[0].yaxis.set_major_locator(plt.LogitLocator(3))
# axs[0].ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
# axs[-1].legend()
axs[0].set_ylabel(r"Avg Infidelity ($1-F_d$)")
axs[0].set_xticks(range(2, 9))
axs[0].minorticks_on()
axs[0].xaxis.set_tick_params(which="minor", bottom=False, top=False)
else: # if plot_bool:
fig, axs = plt.subplots(1, 1, figsize=(2, 1.15), sharey=True)
ydata = []
ysem = []
base_fidelity_list = np.arange(0.9, 1, 0.01)
for bf in base_fidelity_list:
gate_error, decomp_error, fidelity_error = collect_random2q_data(
bf, N=N, mode="random", fn=fn
)
ydata.append(get_max(fidelity_error)[0])
ysem.append(get_max(fidelity_error)[1])
# axs.errorbar([bf]*len(alpha_range), get_max(fidelity_error)[0], yerr=get_max(fidelity_error)[1], capsize=1.5, elinewidth=.5, ecolor='black', linestyle="-", marker=next(marker), label=bf,color=next(color))
for i, n in enumerate(range(len(gate_error[0]))):
alpha = 1 / alpha_range[i]
set_color = next(color)
axs.errorbar(
base_fidelity_list,
[el[i] for el in ydata],
yerr=[el[i] for el in ysem],
capsize=1,
elinewidth=0.5,
ecolor=set_color,
linestyle="-",
marker=next(marker),
label=r"$\sqrt[" + str(int(1 / alpha)) + r"]{iSwap}$",
color=set_color,
)
# axs.set_xlabel(r"$\sqrt[x]{iSwap}$")
axs.set_xlabel(r"$F_b(\texttt{iSwap})$")
axs.invert_xaxis()
axs.set_yscale("linear")
axs.minorticks_on()
axs.xaxis.set_tick_params(which="minor", bottom=False, top=False)
# # axs[1].set_ylabel("Avg fidelity")
# # legend = axs[1].legend(title="iSwap Fidelity", bbox_to_anchor=(1.25,-.22), ncol=2)
axs.legend(bbox_to_anchor=(1.0, -0.22), ncol=3)
# # legend._legend_box.align = "bottoms"
# axs.yaxis.set_major_locator(plt.MaxNLocator(4))
axs.set_xticks(np.linspace(0.9, 1, 5))
# #axs[0].xaxis.set_major_locator(plt.MaxNLocator(integer=True))
# axs[1].ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
# # axs[1].set_title(f"Random 2Q Fidelity vs nth root iswap")
# axs.set_yscale('log')
axs.set_ylabel(r"Avg Total Fidelity $F_t$")
# axs.set_ylabel("Average Fidelity")
axs.set_title(r"$\sqrt[n]{iSwap}$ Expected Total Fidelity")
# axs.minorticks_off()
# axs.set_ylabel("Average Infidelity")
# axs.set_xticks = [2,3,4,5,6,7,8]
# axs.minorticks_off()
# fig.suptitle(f"Random 2Q Fidelity (N={N})")
# plt.axes().xaxis.set_major_locator(plt.MaxNLocator(integer=True))
# fig.tight_layout()
fig.show()
filename = "nuop_experiment"
fig.savefig("{}.svg".format(filename), format="svg", facecolor=None)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_circuit_layout
from qiskit.tools.monitor import job_monitor
from qiskit.providers.fake_provider import FakeVigoV2
import matplotlib.pyplot as plt
ghz = QuantumCircuit(3, 3)
ghz.h(0)
for idx in range(1,3):
ghz.cx(0,idx)
ghz.measure(range(3), range(3))
backend = FakeVigoV2()
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/Tojarieh97/VQE
|
Tojarieh97
|
%load_ext autoreload
%autoreload 2
import nbimporter
from typing import Dict, Tuple, List
import numpy as np
from tqdm import tqdm
QUBITS_NUM = 4
N = 2**QUBITS_NUM
NUM_SHOTS = 1024
NUM_ITERATIONS = 50
CIRCUIT_DEPTH = 3
PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1)
from qiskit import Aer
from qiskit.utils import QuantumInstance, algorithm_globals
seed = 50
algorithm_globals.random_seed = seed
simulator_backend = Aer.get_backend('qasm_simulator')
from scipy.optimize import minimize
from linear_entangelment_and_full_entangelment_ansatz_circuits import *
def get_ansatz_state(thetas, ansatz_entangelment, input_state):
if ansatz_entangelment=="full":
return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state)
if ansatz_entangelment=="linear":
return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state)
def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List:
pauli_operators = hamiltonian.to_pauli_op().settings['oplist']
pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators))
pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators))
return pauli_coeffs, pauli_strings
from qiskit.circuit.library.standard_gates import HGate, SGate
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
reducing_to_pauli_z_mapping = {
'I': 'I',
'Z': 'Z',
'X': 'Z',
'Y': 'Z'
}
def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str:
reduced_pauli_string = ""
for matrix_index in range(QUBITS_NUM):
pauli_matrix = str(pauli_string[matrix_index])
reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix]
reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string
return reduced_pauli_string
def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit):
quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit")
additional_circuit_layer = QuantumCircuit(quantum_registers)
for quantum_register_index, pauli_matrix in enumerate(pauli_string):
if pauli_matrix == "X":
additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]])
if pauli_string == "Y":
additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]])
additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]])
extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer)
return extended_quantum_circuit
def get_probability_distribution(counts: Dict) -> Dict:
proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()}
print(sum(proba_distribution.values()))
return proba_distribution
def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict:
quantum_state_circuit.measure_all()
transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend)
Qobj = assemble(transpiled_quantum_state_circuit)
result = simulator_backend.run(Qobj).result()
counts = result.get_counts(quantum_state_circuit)
print(counts)
return get_probability_distribution(counts)
def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict:
return dict(sorted(proba_distribution.items()))
def reset_power_of_minus_1(power_of_minus_1):
power_of_minus_1 = 0
return power_of_minus_1
def convert_pauli_string_into_str(pauli_string) -> str:
return str(pauli_string)
def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit):
pauli_string_expectation_value = 0
power_of_minus_1 = 0
pauli_string_str = convert_pauli_string_into_str(pauli_string)
extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit)
probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit)
reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string)
sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution)
for qubits_string, proba in sorted_probas_distribuition.items():
for string_index in range(QUBITS_NUM):
if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"):
power_of_minus_1 += 1
pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba
power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1)
return pauli_string_expectation_value
def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings):
total_expection_value = 0
for pauli_coeff, pauli_string in tqdm(zip(pauli_coeffs, pauli_strings)):
total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas(
pauli_string, ansatz_circuit)
return total_expection_value
from qiskit import assemble, transpile
import random
def cost_function(thetas, hamiltonian, ansatz_entangelment):
initial_eigenvector = np.identity(N)[0]
pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian)
ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector)
L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings)
insert_approximated_energy_to_list_of_all_approximated_energies(L)
return L
def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment):
initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=PARAMS_NUM)
optimizer_result = minimize(cost_function,
x0=initial_thetas,
args=(hamiltonian, ansatz_entangelment),
method="COBYLA",
options={"maxiter":NUM_ITERATIONS,
"disp": True})
optimal_thetas = optimizer_result.x
return optimal_thetas
def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment):
optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment)
print(optimal_thetas)
initial_eigenvector = np.identity(N)[0]
optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector)
pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian)
approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings)
return approximated_eigenvalue
from numpy import linalg as LA
def get_approximation_error(exact_eigenvalue, approximated_eigenvalue):
return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue)
def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian):
eigen_values = LA.eigvals(hamiltonian.to_matrix())
print(sorted(eigen_values))
return min(sorted(eigen_values))
def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue):
exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian)
print("Exact Eigenvalue:")
print(exact_eigenvalue)
print("\nApproximated Eigenvalue:")
print(approximated_eigenvalue)
print("\nApproximation Error")
print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue))
plot_convergence_of_optimization_process(exact_eigenvalue, margin=3)
approximated_energies = []
def insert_approximated_energy_to_list_of_all_approximated_energies(energy):
approximated_energies.append(energy)
import matplotlib.pyplot as plt
def plot_convergence_of_optimization_process(exact_eigenvalue, margin):
plt.title("convergence of optimization process to the exact eigenvalue")
plt.margins(0, margin)
plt.plot(approximated_energies[-NUM_ITERATIONS:])
plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-')
plt.grid()
plt.xlabel("# of iterations")
plt.ylabel("Energy")
def plot_fidelity():
plt.plot(LiH_approximated_energies)
plt.xlabel("# of iterations")
plt.ylabel("Energy")
from qiskit.opflow import X, Z, I, H, Y
LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \
-0.0029329964409502266*(X^X^Y^Y) + \
0.0029329964409502266*(X^Y^Y^X) + \
0.01291078027311749*(X^Z^X^I) + \
-0.0013743761078958677*(X^Z^X^Z) + \
0.011536413200774975*(X^I^X^I) + \
0.0029329964409502266*(Y^X^X^Y) + \
-0.0029329964409502266*(Y^Y^X^X) + \
0.01291078027311749*(Y^Z^Y^I) + \
-0.0013743761078958677*(Y^Z^Y^Z) + \
0.011536413200774975*(Y^I^Y^I) + \
0.16199475388004184*(Z^I^I^I) + \
0.011536413200774975*(Z^X^Z^X) + \
0.011536413200774975*(Z^Y^Z^Y) + \
0.12444770133137588*(Z^Z^I^I) + \
0.054130445793298836*(Z^I^Z^I) + \
0.05706344223424907*(Z^I^I^Z) + \
0.012910780273117487*(I^X^Z^X) + \
-0.0013743761078958677*(I^X^I^X) + \
0.012910780273117487*(I^Y^Z^Y) + \
-0.0013743761078958677*(I^Y^I^Y) + \
0.16199475388004186*(I^Z^I^I) + \
0.05706344223424907*(I^Z^Z^I) + \
0.054130445793298836*(I^Z^I^Z) + \
-0.013243698330265966*(I^I^Z^I) + \
0.08479609543670981*(I^I^Z^Z) + \
-0.013243698330265952*(I^I^I^Z)
%%time
LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear")
compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue)
%%time
LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full")
compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue)
H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \
+ 0.1721839326191554 * (I^I^I^Z) \
- 0.22575349222402372 * (I^I^Z^I) \
+ 0.17218393261915543 * (I^Z^I^I) \
- 0.2257534922240237 * (Z^I^I^I) \
+ 0.12091263261776627 * (I^I^Z^Z) \
+ 0.16892753870087907 * (I^Z^I^Z) \
+ 0.045232799946057826 * (Y^Y^Y^Y) \
+ 0.045232799946057826 * (X^X^Y^Y) \
+ 0.045232799946057826 * (Y^Y^X^X) \
+ 0.045232799946057826 * (X^X^X^X) \
+ 0.1661454325638241 * (Z^I^I^Z) \
+ 0.1661454325638241 * (I^Z^Z^I) \
+ 0.17464343068300453 * (Z^I^Z^I) \
+ 0.12091263261776627 * (Z^Z^I^I)
%%time
H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear")
compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue)
%%time
H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full")
compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue)
transverse_ising_4_qubits = 0.0 * (I^I^I^I) \
+ 0.8398088405253477 * (X^I^I^I) \
+ 0.7989496312070936 * (I^X^I^I) \
+ 0.38189710487113193 * (Z^Z^I^I) \
+ 0.057753122422666725 * (I^I^X^I) \
+ 0.5633292636970458 * (Z^I^Z^I) \
+ 0.3152740621483513 * (I^Z^Z^I) \
+ 0.07209487981989715 * (I^I^I^X) \
+ 0.17892334004292654 * (Z^I^I^Z) \
+ 0.2273896497668042 * (I^Z^I^Z) \
+ 0.09762902934216211 * (I^I^Z^Z)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear")
compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full")
compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue)
QUBITS_NUM = 3
N = 2**QUBITS_NUM
NUM_SHOTS = 1024
CIRCUIT_DEPTH = 3
PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1)
from qiskit.opflow import X, Z, I
transverse_ising_3_qubits = 0.0 * (I^I^I) \
+ 0.012764169333459807 * (X^I^I) \
+ 0.7691573729160869 * (I^X^I) \
+ 0.398094746026449 * (Z^Z^I) \
+ 0.15250261906586637 * (I^I^X) \
+ 0.2094051920882264 * (Z^I^Z) \
+ 0.5131291860752999 * (I^Z^Z)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear")
compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full")
compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue)
QUBITS_NUM = 2
N = 2**QUBITS_NUM
NUM_SHOTS = 1024
CIRCUIT_DEPTH = 3
PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1)
transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \
+ 0.43305656297810435 * (X^I) \
+ 0.8538597608997253 * (Z^Z)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear")
compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full")
compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue)
from qiskit.opflow import X, Z, I
H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \
-0.3277380754984016*(Z^I) + \
0.15567463610622564*(Z^Z) + \
-0.3277380754984016*(I^Z)
%%time
H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear")
compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
%%time
H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full")
compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
#!/usr/bin/env python
# coding: utf-8
from qiskit import QuantumCircuit
from qiskit.aqua.components.optimizers import COBYLA, ADAM, SPSA
from qiskit.circuit.library import ZZFeatureMap, RealAmplitudes, ZFeatureMap, PauliFeatureMap
from qiskit.quantum_info import Statevector
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import csv
import warnings
warnings.filterwarnings("ignore")
class Benchmark:
"""
Benchmarking different optimizers, featuremaps and depth of variational circuits
"""
def __init__(self, optimizer, variational_depth, feature_map, X_train, X_test, Y_train, Y_test):
"""
Initial function
:param optimizer: The optimizer to benchmark
:param variational_depth: The depth of the variational circuit
:param feature_map: The featuremap that encodes data
:param X_train: The x data for training
:param X_test: The x data for testing
:param Y_train: The y data for training
:param Y_test: The y data for testing
"""
self.optimizer = optimizer
self.variational_depth = variational_depth
self.feature_map = feature_map
self.no_qubit = 4
self.random_state = 42
self.class_labels = ['yes', 'no']
self.circuit = None
self.var_form = RealAmplitudes(self.no_qubit, reps=self.variational_depth)
self.sv = Statevector.from_label('0' * self.no_qubit)
self.X_train, self.X_test, self.Y_train, self.Y_test = X_train, X_test, Y_train, Y_test
self.cost_list = []
def prepare_circuit(self):
"""
Prepares the circuit. Combines an encoding circuit, feature map, to a variational circuit, RealAmplitudes
:return:
"""
self.circuit = self.feature_map.combine(self.var_form)
# circuit.draw(output='mpl')
def get_data_dict(self, params, x):
"""
Assign the params to the variational circuit and the data to the featuremap
:param params: Parameter for training the variational circuit
:param x: The data
:return parameters:
"""
parameters = {}
for i, p in enumerate(self.feature_map.ordered_parameters):
parameters[p] = x[i]
for i, p in enumerate(self.var_form.ordered_parameters):
parameters[p] = params[i]
return parameters
def assign_label(self, bit_string):
"""
Based on the output from measurements assign no if it odd parity and yes if it is even parity
:param bit_string: The bit string eg 00100
:return class_label: Yes or No
"""
hamming_weight = sum([int(k) for k in list(bit_string)])
is_odd_parity = hamming_weight & 1
if is_odd_parity:
return self.class_labels[1]
else:
return self.class_labels[0]
def return_probabilities(self, counts):
"""
Calculates the probabilities of the class label after assigning the label from the bit string measured
as output
:type counts: dict
:param counts: The counts from the measurement of the quantum circuit
:return result: The probability of each class
"""
shots = sum(counts.values())
result = {self.class_labels[0]: 0, self.class_labels[1]: 0}
for key, item in counts.items():
label = self.assign_label(key)
result[label] += counts[key] / shots
return result
def classify(self, x_list, params):
"""
Assigns the x and params to the quantum circuit the runs a measurement to return the probabilities
of each class
:type params: List
:type x_list: List
:param x_list: The x data
:param params: Parameters for optimizing the variational circuit
:return probs: The probabilities
"""
qc_list = []
for x in x_list:
circ_ = self.circuit.assign_parameters(self.get_data_dict(params, x))
qc = self.sv.evolve(circ_)
qc_list += [qc]
probs = []
for qc in qc_list:
counts = qc.to_counts()
prob = self.return_probabilities(counts)
probs += [prob]
return probs
@staticmethod
def mse_cost(probs, expected_label):
"""
Calculates the mean squared error from the expected values and calculated values
:type expected_label: List
:type probs: List
:param probs: The expected values
:param expected_label: The real values
:return mse: The mean squared error
"""
p = probs.get(expected_label)
actual, pred = np.array(1), np.array(p)
mse = np.square(np.subtract(actual, pred)).mean()
return mse
def cost_function(self, X, Y, params, print_value=False):
"""
This is the cost function and returns cost for optimization
:type print_value: Boolean
:type params: List
:type Y: List
:type X: List
:param X: The x data
:param Y: The label
:param params: The parameters
:param print_value: If you want values to be printed
:return cost:
"""
# map training input to list of labels and list of samples
cost = 0
training_labels = []
training_samples = []
for sample in X:
training_samples += [sample]
for label in Y:
if label == 0:
training_labels += [self.class_labels[0]]
elif label == 1:
training_labels += [self.class_labels[1]]
probs = self.classify(training_samples, params)
# evaluate costs for all classified samples
for i, prob in enumerate(probs):
cost += self.mse_cost(prob, training_labels[i])
cost /= len(training_samples)
# print resulting objective function
if print_value:
print('%.4f' % cost)
# return objective value
self.cost_list.append(cost)
return cost
def test_model(self, X, Y, params):
"""
Test the model based on x test and y test
:type params: List
:type Y: List
:type X: List
:param X: The x test set
:param Y: The y test set
:param params: The parameters
:return:
"""
accuracy = 0
training_samples = []
for sample in X:
training_samples += [sample]
probs = self.classify(training_samples, params)
for i, prob in enumerate(probs):
if (prob.get('yes') >= prob.get('no')) and (Y[i] == 0):
accuracy += 1
elif (prob.get('no') >= prob.get('yes')) and (Y[i] == 1):
accuracy += 1
accuracy /= len(Y)
print("Test accuracy: {}".format(accuracy))
def run(self):
"""
Runs the whole code
1. Prepares the circuit
2. define the objective function
3. Initialize the paramters
4. Optimize the paramters by training the classifier
:return:
"""
self.prepare_circuit()
# define objective function for training
objective_function = lambda params: self.cost_function(self.X_train, self.Y_train, params, print_value=False)
# randomly initialize the parameters
np.random.seed(self.random_state)
init_params = 2 * np.pi * np.random.rand(self.no_qubit * self.variational_depth * 2)
# train classifier
opt_params, value, _ = self.optimizer.optimize(len(init_params), objective_function, initial_point=init_params)
# print results
# print()
# print('opt_params:', opt_params)
# print('opt_value: ', value)
self.test_model(self.X_test, self.Y_test, opt_params)
def get_cost_list(self):
"""
Return the cost list
:return cost list:
"""
return self.cost_list
def normalize_data(dataPath="../../Data/Processed/heartdata.csv"):
"""
Normalizes the data
:return X_train, X_test, Y_train, Y_test:
"""
# Reads the data
data = pd.read_csv(dataPath)
data = shuffle(data, random_state=42)
X, Y = data[['sex', 'cp', 'exang', 'oldpeak']].values, data['num'].values
# normalize the data
scaler = MinMaxScaler(feature_range=(-2 * np.pi, 2 * np.pi))
X = scaler.fit_transform(X)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=42)
return X_train, X_test, Y_train, Y_test
def main():
data = {}
feature_maps = ['ZZFeatureMap(4, reps=1)', 'ZZFeatureMap(4, reps=2)', 'ZZFeatureMap(4, reps=4)',
'ZFeatureMap(4, reps=1)', 'ZFeatureMap(4, reps=2)', 'ZFeatureMap(4, reps=4)',
'PauliFeatureMap(4, reps=1)', 'PauliFeatureMap(4, reps=2)', 'PauliFeatureMap(4, reps=4)']
optimizers = ["COBYLA(maxiter=50)", "SPSA(max_trials=50)", "ADAM(maxiter=50)"]
x_train, x_test, y_train, y_test = normalize_data()
for fe in feature_maps:
for i in [1, 3, 5]:
for opt in optimizers:
print("FE: {}\tDepth: {}\tOpt: {}".format(fe, i, opt))
test_benchmark = Benchmark(optimizer=eval(opt), variational_depth=i, feature_map=eval(fe), X_train=x_train, X_test=x_test, Y_train=y_train, Y_test=y_test)
test_benchmark.run()
data_list = "{} {} vdepth {}".format(fe, opt, i)
data[data_list] = test_benchmark.get_cost_list()
w = csv.writer(open("../../Data/Processed/heartcosts.csv", "w"))
for key, val in data.items():
w.writerow([key, val])
if __name__ == "__main__":
main()
|
https://github.com/if-quantum/pairwise-tomography
|
if-quantum
|
"""
Pairwise tomography circuit generation
"""
# pylint: disable=invalid-name
import numpy as np
from qiskit import ClassicalRegister
from qiskit.ignis.verification.tomography.basis.circuits import _format_registers
def pairwise_state_tomography_circuits(circuit, measured_qubits):
"""
Generates a minimal set of circuits for pairwise state tomography.
This performs measurement in the Pauli-basis resulting in
circuits for an n-qubit state tomography experiment.
Args:
circuit (QuantumCircuit): the state preparation circuit to be
tomographed.
measured_qubits (QuantumRegister): the qubits to be measured.
This can also be a list of whole QuantumRegisters or
individual QuantumRegister qubit tuples.
Returns:
A list of QuantumCircuit objects containing the original circuit
with state tomography measurements appended at the end.
"""
### Initialisation stuff
if isinstance(measured_qubits, list):
# Unroll list of registers
meas_qubits = _format_registers(*measured_qubits)
else:
meas_qubits = _format_registers(measured_qubits)
N = len(meas_qubits)
cr = ClassicalRegister(len(meas_qubits))
### Uniform measurement settings
X = circuit.copy(name=str(('X',)*N))
Y = circuit.copy(name=str(('Y',)*N))
Z = circuit.copy(name=str(('Z',)*N))
X.add_register(cr)
Y.add_register(cr)
Z.add_register(cr)
for bit_index, qubit in enumerate(meas_qubits):
X.h(qubit)
Y.sdg(qubit)
Y.h(qubit)
X.measure(qubit, cr[bit_index])
Y.measure(qubit, cr[bit_index])
Z.measure(qubit, cr[bit_index])
output_circuit_list = [X, Y, Z]
### Heterogeneous measurement settings
# Generation of six possible sequences
sequences = []
meas_bases = ['X', 'Y', 'Z']
for i in range(3):
for j in range(2):
meas_bases_copy = meas_bases[:]
sequence = [meas_bases_copy[i]]
meas_bases_copy.remove(meas_bases_copy[i])
sequence.append(meas_bases_copy[j])
meas_bases_copy.remove(meas_bases_copy[j])
sequence.append(meas_bases_copy[0])
sequences.append(sequence)
# Qubit colouring
nlayers = int(np.ceil(np.log(float(N))/np.log(3.0)))
for layout in range(nlayers):
for sequence in sequences:
meas_layout = circuit.copy()
meas_layout.add_register(cr)
meas_layout.name = ()
for bit_index, qubit in enumerate(meas_qubits):
local_basis = sequence[int(float(bit_index)/float(3**layout))%3]
if local_basis == 'Y':
meas_layout.sdg(qubit)
if local_basis != 'Z':
meas_layout.h(qubit)
meas_layout.measure(qubit, cr[bit_index])
meas_layout.name += (local_basis,)
meas_layout.name = str(meas_layout.name)
output_circuit_list.append(meas_layout)
return output_circuit_list
|
https://github.com/C2QA/bosonic-qiskit
|
C2QA
|
import random
import c2qa
import numpy
import qiskit
def count_nonzero(statevector: qiskit.quantum_info.Statevector):
"""Re-implement numpy.count_nonzero using numpy.isclose()."""
nonzero = len(statevector.data)
for state in statevector.data:
if numpy.isclose(state, 0):
nonzero -= 1
return nonzero
def create_conditional(num_qumodes: int = 2, num_qubits_per_qumode: int = 2):
qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode)
qr = qiskit.QuantumRegister(2)
circuit = c2qa.CVCircuit(qmr, qr)
for qumode in range(num_qumodes):
circuit.cv_initialize(0, qmr[qumode])
circuit.initialize([0, 1], qr[1]) # qr[0] will init to zero
return circuit, qmr, qr
def create_unconditional(num_qumodes: int = 2, num_qubits_per_qumode: int = 3):
qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode)
circuit = c2qa.CVCircuit(qmr)
for qumode in range(num_qumodes):
circuit.cv_initialize(0, qmr[qumode])
return circuit, qmr
def assert_changed(state, result):
assert result.success
# print()
# print(circuit.draw("text"))
# print(state)
# TODO - better understand what the state vector results should be
assert count_nonzero(state) > 1
def assert_unchanged(state, result):
assert result.success
# print()
# print(circuit.draw("text"))
# print(state)
# TODO - better understand what the state vector results should be
assert count_nonzero(state) == 1
def test_no_gates():
circuit, qmr = create_unconditional()
state, result, fock_counts = c2qa.util.simulate(circuit)
assert_unchanged(state, result)
def test_beamsplitter_once():
circuit, qmr = create_unconditional()
phi = random.random()
circuit.cv_bs(phi, qmr[0], qmr[1])
state, result, fock_counts = c2qa.util.simulate(circuit)
# TODO - Beam splitter gate does not change state vector
# Both Strawberry Fields & FockWits are the same, too.
# assert_changed(state, result)
assert_unchanged(state, result)
def test_conditional_beamsplitter():
circuit, qmr, qr = create_conditional()
theta = random.random()
circuit.cv_c_bs(theta, qmr[0], qmr[1], qr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
# TODO - Beam splitter gate does not change state vector
# Both Strawberry Fields & FockWits are the same, too.
# assert_changed(state, result)
assert_unchanged(state, result)
def test_conditional_schwinger():
circuit, qmr, qr = create_conditional()
beta = random.random()
theta_1 = random.random()
phi_1 = random.random()
theta_2 = random.random()
phi_2 = random.random()
circuit.cv_c_schwinger([beta, theta_1, phi_1, theta_2, phi_2], qmr[0], qmr[1], qr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
assert_unchanged(state, result)
def test_beamsplitter_twice():
circuit, qmr = create_unconditional()
phi = random.random()
circuit.cv_bs(phi, qmr[0], qmr[1])
circuit.cv_bs(-phi, qmr[0], qmr[1])
state, result, fock_counts = c2qa.util.simulate(circuit)
assert_unchanged(state, result)
def test_conditonal_displacement():
circuit, qmr, qr = create_conditional()
alpha = random.random()
circuit.cv_c_d(alpha, qmr[0], qr[0])
circuit.cv_c_d(-alpha, qmr[0], qr[0])
circuit.cv_c_d(-alpha, qmr[0], qr[1])
circuit.cv_c_d(alpha, qmr[0], qr[1])
state, result, fock_counts = c2qa.util.simulate(circuit)
assert_unchanged(state, result)
def test_conditonal_squeezing():
circuit, qmr, qr = create_conditional()
alpha = random.random()
circuit.cv_c_sq(alpha, qmr[0], qr[0])
circuit.cv_c_sq(-alpha, qmr[0], qr[0])
circuit.cv_c_sq(-alpha, qmr[0], qr[1])
circuit.cv_c_sq(alpha, qmr[0], qr[1])
state, result, fock_counts = c2qa.util.simulate(circuit)
assert_unchanged(state, result)
def test_displacement_once(capsys):
with capsys.disabled():
circuit, qmr = create_unconditional()
# alpha = random.random()
alpha = 1
circuit.cv_d(alpha, qmr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
assert_changed(state, result)
def test_cv_delay():
circuit, qmr = create_unconditional()
circuit.cv_delay(100,qmr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
def test_displacement_twice():
circuit, qmr = create_unconditional()
alpha = random.random()
circuit.cv_d(alpha, qmr[0])
circuit.cv_d(-alpha, qmr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
assert_unchanged(state, result)
def test_displacement_calibration(capsys):
with capsys.disabled():
qmr = c2qa.QumodeRegister(1, 2)
qr = qiskit.QuantumRegister(1)
cr = qiskit.ClassicalRegister(1)
circuit = c2qa.CVCircuit(qmr, qr, cr)
# qr[0] and cr[0] will init to zero
circuit.cv_initialize(0, qmr[0])
alpha = numpy.sqrt(numpy.pi)
circuit.h(qr[0])
circuit.cv_c_d(alpha, qmr[0], qr[0])
circuit.cv_d(1j * alpha, qmr[0])
circuit.cv_c_d(-alpha, qmr[0], qr[0])
circuit.cv_d(-1j * alpha, qmr[0])
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
assert result.success
state = result.get_statevector(circuit)
counts = result.get_counts(circuit)
assert state.dim > 0
assert counts
# print()
# print(circuit.draw("text"))
# print(state)
# print(counts.int_outcomes())
def test_rotation_once():
circuit, qmr = create_unconditional()
theta = random.random()
circuit.cv_r(theta, qmr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
# TODO - Rotation gate does not change state vector.
# Both Strawberry Fields & FockWits are the same, too.
# assert_changed(state, result)
assert_unchanged(state, result)
def test_rotation_twice():
circuit, qmr = create_unconditional()
theta = random.random()
circuit.cv_r(theta, qmr[0])
circuit.cv_r(-theta, qmr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
assert_unchanged(state, result)
def test_squeezing_once():
circuit, qmr = create_unconditional()
z = random.random()
circuit.cv_sq(z, qmr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
assert_changed(state, result)
def test_squeezing_twice():
circuit, qmr = create_unconditional()
z = random.random()
circuit.cv_sq(z, qmr[0])
circuit.cv_sq(-z, qmr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
assert_unchanged(state, result)
def test_two_mode_squeezing_once():
circuit, qmr = create_unconditional()
z = random.random()
circuit.cv_sq2(z, qmr[0], qmr[1])
state, result, fock_counts = c2qa.util.simulate(circuit)
assert_changed(state, result)
def test_two_mode_squeezing_twice():
circuit, qmr = create_unconditional()
z = random.random()
circuit.cv_sq2(z, qmr[0], qmr[1])
circuit.cv_sq2(-z, qmr[0], qmr[1])
state, result, fock_counts = c2qa.util.simulate(circuit)
assert_unchanged(state, result)
def test_gates():
"""Verify that we can use the gates, not that they are actually working."""
# ===== Constants =====
alpha = 1
phi = numpy.pi / 2
z = 1
circuit, qmr, qr = create_conditional()
# Basic Gaussian Operations on a Resonator
circuit.cv_bs(phi, qmr[0], qmr[1])
circuit.cv_d(alpha, qmr[0])
circuit.cv_r(phi, qmr[0])
circuit.cv_sq(z, qmr[0])
circuit.cv_sq2(z, qmr[0], qmr[1])
# Hybrid qubit-cavity gates
circuit.cv_c_d(alpha, qmr[0], qr[0])
circuit.cv_c_d(alpha, qmr[1], qr[0])
circuit.cv_c_sq(z, qmr[0], qr[0])
circuit.cv_c_sq(z, qmr[1], qr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
assert result.success
def test_snap():
circuit, qmr = create_unconditional()
phi = random.random()
n = 1
circuit.cv_snap(phi, n, qmr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
def test_eswap():
circuit, qmr = create_unconditional()
phi = random.random()
circuit.cv_eswap(phi, qmr[0], qmr[1])
state, result, fock_counts = c2qa.util.simulate(circuit)
def test_multiboson_sampling(capsys):
with capsys.disabled():
num_qubits=1
num_qumodes=2
num_qubits_per_qumode=2
qmrA = c2qa.QumodeRegister(num_qumodes = num_qumodes, num_qubits_per_qumode = num_qubits_per_qumode,name="qmrA_initial")
qmrB = c2qa.QumodeRegister(num_qumodes = num_qumodes, num_qubits_per_qumode = num_qubits_per_qumode,name="qmrB_initial")
qbr = qiskit.QuantumRegister(size=num_qubits,name='qbr_initial')
circuit = c2qa.CVCircuit(qmrA, qmrB, qbr)
circuit.cv_c_multiboson_sampling([0,1,2,3], qmrA[0], qbr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
assert result.success
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumCircuit
import math
qc = QuantumCircuit(4)
qc.rx(math.pi/2, [0,1,2,3])
qc.i(1)
qc.u(math.pi/2, 0, math.pi, 2)
qc.u(0,0, math.pi/4, 3)
qc.draw("mpl")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
%matplotlib inline
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile
from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits per dimension to represent the uncertainty
num_uncertainty_qubits = 2
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# map to higher dimensional distribution
# for simplicity assuming dimensions are independent and identically distributed)
dimension = 2
num_qubits = [num_uncertainty_qubits] * dimension
low = low * np.ones(dimension)
high = high * np.ones(dimension)
mu = mu * np.ones(dimension)
cov = sigma**2 * np.eye(dimension)
# construct circuit
u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high))))
# plot PDF of uncertainty model
x = [v[0] for v in u.values]
y = [v[1] for v in u.values]
z = u.probabilities
# z = map(float, z)
# z = list(map(float, z))
resolution = np.array([2**n for n in num_qubits]) * 1j
grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]]
grid_z = griddata((x, y), z, (grid_x, grid_y))
plt.figure(figsize=(10, 8))
ax = plt.axes(projection="3d")
ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral)
ax.set_xlabel("Spot Price $S_1$ (\$)", size=15)
ax.set_ylabel("Spot Price $S_2$ (\$)", size=15)
ax.set_zlabel("Probability (\%)", size=15)
plt.show()
# determine number of qubits required to represent total loss
weights = []
for n in num_qubits:
for i in range(n):
weights += [2**i]
# create aggregation circuit
agg = WeightedAdder(sum(num_qubits), weights)
n_s = agg.num_sum_qubits
n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price_1 = 3
strike_price_2 = 4
# set the barrier threshold
barrier = 2.5
# map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1}
max_value = 2**n_s - 1
low_ = low[0]
high_ = high[0]
mapped_strike_price_1 = (
(strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
mapped_strike_price_2 = (
(strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1)
# condition and condition result
conditions = []
barrier_thresholds = [2] * dimension
n_aux_conditions = 0
for i in range(dimension):
# target dimension of random distribution and corresponding condition (which is required to be True)
comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False)
n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas)
conditions += [comparator]
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2]
slopes = [0, 1, 0]
offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1]
f_min = 0
f_max = mapped_strike_price_2 - mapped_strike_price_1
objective = LinearAmplitudeFunction(
n_s,
slopes,
offsets,
domain=(0, max_value),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define overall multivariate problem
qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution
qr_obj = QuantumRegister(1, "obj") # to encode the function values
ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum
ar_cond = AncillaRegister(len(conditions) + 1, "conditions")
ar = AncillaRegister(
max(n_aux, n_aux_conditions, objective.num_ancillas), "work"
) # additional qubits
objective_index = u.num_qubits
# define the circuit
asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar)
# load the probability distribution
asian_barrier_spread.append(u, qr_state)
# apply the conditions
for i, cond in enumerate(conditions):
state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))]
asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas])
# aggregate the conditions on a single qubit
asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1])
# apply the aggregation function controlled on the condition
asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux])
# apply the payoff function
asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas])
# uncompute the aggregation
asian_barrier_spread.append(
agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]
)
# uncompute the conditions
asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1])
for j, cond in enumerate(reversed(conditions)):
i = len(conditions) - j - 1
state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))]
asian_barrier_spread.append(
cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]
)
print(asian_barrier_spread.draw())
print("objective qubit index", objective_index)
# plot exact payoff function
plt.figure(figsize=(7, 5))
x = np.linspace(sum(low), sum(high))
y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1)
plt.plot(x, y, "r-")
plt.grid()
plt.title("Payoff Function (for $S_1 = S_2$)", size=15)
plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# plot contour of payoff function with respect to both time steps, including barrier
plt.figure(figsize=(7, 5))
z = np.zeros((17, 17))
x = np.linspace(low[0], high[0], 17)
y = np.linspace(low[1], high[1], 17)
for i, x_ in enumerate(x):
for j, y_ in enumerate(y):
z[i, j] = np.minimum(
np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1
)
if x_ > barrier or y_ > barrier:
z[i, j] = 0
plt.title("Payoff Function", size=15)
plt.contourf(x, y, z)
plt.colorbar()
plt.xlabel("Spot Price $S_1$", size=15)
plt.ylabel("Spot Price $S_2$", size=15)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value
sum_values = np.sum(u.values, axis=1)
payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1)
leq_barrier = [np.max(v) <= barrier for v in u.values]
exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier])
print("exact expected value:\t%.4f" % exact_value)
num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas
print("state qubits: ", num_state_qubits)
transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"])
print("circuit width:", transpiled.width())
print("circuit depth:", transpiled.depth())
asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(asian_barrier_spread_measure)
# evaluate the result
value = 0
probabilities = job.result().quasi_dists[0].binary_probabilities()
for i, prob in probabilities.items():
if prob > 1e-4 and i[-num_state_qubits:][0] == "1":
value += prob
# map value to original range
mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % mapped_value)
print("Exact Expected Payoff: %.4f" % exact_value)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=asian_barrier_spread,
objective_qubits=[objective_index],
post_processing=objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}))
result = ae.estimate(problem)
conf_int = (
np.array(result.confidence_interval_processed)
/ (2**num_uncertainty_qubits - 1)
* (high_ - low_)
)
print("Exact value: \t%.4f" % exact_value)
print(
"Estimated value:\t%.4f"
% (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_))
)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/vm6502q/qiskit-qrack-provider
|
vm6502q
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 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.
"""
QasmSimulator kraus error NoiseModel integration tests
"""
from test.terra.utils.utils import list2dict
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors.standard_errors import amplitude_damping_error
# Backwards compatibility for Terra <= 0.13
if not hasattr(QuantumCircuit, 'i'):
QuantumCircuit.i = QuantumCircuit.iden
# ==========================================================================
# Amplitude damping error
# ==========================================================================
def kraus_gate_error_circuits():
"""Kraus gate error noise model circuits"""
circuits = []
# Repeated amplitude damping to diagonal state
qr = QuantumRegister(1, 'qr')
cr = ClassicalRegister(1, 'cr')
circuit = QuantumCircuit(qr, cr)
circuit.x(qr) # prepare + state
for _ in range(30):
# Add noisy identities
circuit.barrier(qr)
circuit.i(qr)
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
return circuits
def kraus_gate_error_noise_models():
"""Kraus gate error noise models"""
noise_models = []
# Amplitude damping error on "id"
error = amplitude_damping_error(0.75, 0.25)
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error, 'id')
noise_models.append(noise_model)
return noise_models
def kraus_gate_error_counts(shots, hex_counts=True):
"""Kraus gate error circuits reference counts"""
counts_lists = []
# 100% all-qubit Pauli error on "id" gates
counts = [3 * shots / 4, shots / 4, 0, 0]
counts_lists.append(counts)
# Convert to counts dict
return [list2dict(i, hex_counts) for i in counts_lists]
|
https://github.com/TheClintest/QuantumMedianFilter
|
TheClintest
|
# IMPORTS
from PIL import Image
import math
import time
import re
import numpy as np
from qiskit import *
from qiskit.circuit.library import *
from qiskit.providers.aer import *
import matplotlib.pyplot as plt
# UTILITY
def qunion(*qregs: QuantumRegister):
"""
This function returns a list of qubits by their own register variables, useful for Qiskit methods
:param qregs: Input quantum register
:return: A list of qubits, ordered by given args
"""
res = []
for r in qregs:
res += r._bits
return res
# PRINTING
def print_circuit(circuit, filename: str = None):
"""
Prints out a representation of a given circuit.
If "filename" is provided, it saves the visualization in the file system.
:param circuit: Input circuit to visualize
:param filename: Path for the output
"""
style = {
'displaycolor': {
"NEQR": "#FF33FF",
"CS+": "#FF0000",
"CS-": "#FF8888",
"SWAP": "#AAAAFF",
"Neighborhood Preparation": "#33BB33",
"p-values Computation": "#BB3333",
"Median Function": "#BB5555",
"PCN": "#AAAA11",
"ADD": "#55FF55",
"SWPPR": "#55FF55",
"COMP": "#5555FF",
"c_SWAP": "#FF5555",
"SUB": "#FF5555"
},
'fontsize': 12,
'dpi': 300
}
circuit.draw(output="mpl", reverse_bits=False, filename=filename, initial_state=False, style=style, fold=700, vertical_compression="high")
plt.show()
# QASM
qasm_dir = "./qasm/"
def load_qasm(filename, path='./qasm/', verbose=False):
"""
Load a QASM string from a path, returning the corresponding circuit
:param filename: Path to QASM file
:param verbose: Prints out debug info
:return: A QuantumCircuit described in the file
"""
t1 = time.time()
circ = QuantumCircuit.from_qasm_file(f'{path}{filename}')
t2 = time.time()
duration = t2 - t1
if verbose: print(f'QASM loading time for {filename}: {duration}')
return circ
def save_qasm(circuit, filename, path='./qasm/', verbose=False):
"""
Save a circuit/qobj as a QASM file
:param path: Path to the saving directory
:param circuit: Target circuit/qobj to save
:param filename: Name to the file
:param verbose: Prints out debug info
"""
t1 = time.time()
circuit.qasm(filename=f'{path}{filename}')
t2 = time.time()
duration = t2 - t1
if verbose: print(f'QASM saving time: {duration}')
# PATCHER
class ImagePatcher:
"""
An utility class for image decomposition.
It generates 2x2 patches of the image, "wrapped" in a 4x4 image.
Border pixels are repeated to create a sort of frame
"""
original_image = None
original_shape = None
image = None
max_patch = None
def __preprocess(self):
"""
An internal method for image padding
"""
image = self.original_image.copy()
self.max_patch = (image.shape[0], image.shape[1])
image = np.pad(image, ((1, 1), (1, 1)), mode="symmetric") # Total padding
self.image = image
def load_image(self, image_array: np.ndarray = None):
"""
Loads an image array into the patcher and pre-processes it
:param image_array: A NumPy array encoding the image
"""
# TODO: Add image check - minimum (2,2)
self.original_image = image_array
image_shape = image_array.shape
self.__preprocess()
@staticmethod
def pad_image(image_array: np.ndarray):
image = np.pad(image_array, ((1, 1), (1, 1)), mode="symmetric") # Total padding
return image
def extract_image(self):
"""
Returns the original image
:return: A NumPy array encoding the image
"""
result = self.image[1:self.image[0] - 1, 1:self.image[1] - 1]
return result
def get_image(self):
"""
Returns the processed image
:return: A NumPy array encoding the image
"""
return self.image
def get_patches(self):
"""
It generates a dictionary containing all possible patches
:return: A dictionary {pos : patch}
"""
res = dict()
for y in range(0, self.max_patch[0]):
for x in range(0, self.max_patch[1]):
patch_pos = (y, x)
x_start = x * 2
y_start = y * 2
x_end = x_start + 4
y_end = y_start + 4
patch_image = self.image[y_start:y_end, x_start:x_end]
res[patch_pos] = patch_image
return res
def convert_patches(self, patches: dict):
"""
Converts a patch dictionary into the resulting array, according to image original shape
:param patches: A dictionary {pos : patch}
:return: A NumPy array encoding the image
"""
res = self.image.copy()
for pos, patch in patches.items():
y_start = pos[0] * 2 + 1
x_start = pos[1] * 2 + 1
y_end = y_start + 2
x_end = x_start + 2
to_replace = patch[1:3, 1:3]
res[y_start:y_end, x_start:x_end] = to_replace
res = res[1:self.original_shape[0] + 1, 1:self.original_shape[1] + 1]
return res
def check_patch(self, a, b, tolerance):
for x in range(1, 3):
for y in range(1, 3):
val1 = int(a[y][x])
val2 = int(b[y][x])
res = abs(val2 - val1)
if res > tolerance:
# print("CONVERGENCE %d/%d"%(res,tolerance))
return False
return True
def converged_patches(self, old: dict, new: dict, epsilon):
res = dict()
positions = old.keys()
for pos in positions:
res[pos] = self.check_patch(old[pos], new[pos], epsilon)
return res
# CONVERTER
class Converter:
# IMAGE CONVERTER
@staticmethod
def to_array(filename):
"""
Converts a PNG image into a greyscale representation. Returns a NumPy array instance of it
:param filename: Path of input image
:return: A NumPy array representing input image
"""
return np.array(Image.open(filename).convert("L"))
# ARRAY CONVERTER
@staticmethod
def to_image(array, filename):
"""
Converts a Numpy array into a PNG image and saves it as given filename
:param array: Input image array
:param filename: Path of output image
:return:
"""
new_image = Image.fromarray(array)
new_image.save(filename)
# SIMULATION CONVERTER
@staticmethod
def decode_image(answer: dict, target_array, color_size=8):
"""
Process simulator's results to be decoded into an image
:param answer: Simulator results
:param target_array: Array for storing result. Use one of the same shape used for encoding
:param color_size: Size of color registers. Use the value given for the simulated circuit
"""
# Processing
for measure in answer:
m = re.compile(r'\W+').split(measure)
x_coord = int(m[0], 2)
y_coord = int(m[1], 2)
val = int(m[2], 2)
val = val << (8 - color_size)
target_array[y_coord][x_coord] = val
# print("Inserting %d at x:%d y:%d" % (val, x_coord, y_coord))
# Output
return target_array
@staticmethod
def decode_pixel(answer: dict, color_size=8):
"""
Process simulator's results to be decoded into an image
:param answer: Simulator results
:param color_size: Size of color registers. Use the value given for the simulated circuit
"""
# Processing
for measure, num in answer.items():
m = re.compile(r'\W+').split(measure)
val = int(m[0], 2)
val = val << (8 - color_size)
return val
# SIMULATOR
class Simulator:
"""
An Aer Simulator for experimentation.
Default setting is "matrix_product_state"
"""
simulator = None
def __init__(self, mps_max_bond_dimension: int = None):
if mps_max_bond_dimension is not None:
self.simulator = AerSimulator(method="matrix_product_state",
matrix_product_state_max_bond_dimension=mps_max_bond_dimension,
max_parallel_experiments=0,
max_parallel_threads=48,
zero_threshold=1e-50
# mps_log_data=True
)
else:
self.simulator = StatevectorSimulator(max_parallel_experiments=0,
max_parallel_threads=48
)
def transpile(self, circuit: QuantumCircuit, optimization=0, qasm_filename=None, verbose=False):
"""
Transpile circuit
:param circuit: Target circuit to optimize
:param optimization: Optimization level for transpiler (0 to 3)
:param qasm_filename: If path is given, transpiled qobj will be saved as QASM string on file
:return: Transpiled circuit
"""
if verbose:
print(f'Transpiling {circuit.name}')
t1 = time.time()
qobj = transpile(circuit, self.simulator, optimization_level=optimization)
t2 = time.time()
duration = t2 - t1
if verbose: print(f'Transpiling time: {duration}')
if qasm_filename is not None:
if verbose: print(f'Saving circuit as {qasm_filename}')
save_qasm(qobj, filename=qasm_filename)
return qobj
def simulate(self, circuits, shots=1, verbose=False):
"""
Simulate experiment
:param circuits: Quantum circuit(s) to simulate
:param shots: Number of experiments
:param verbose: Debug printing
:return: A dictionary with all results.
"""
t1 = time.time()
results = self.simulator.run(circuits, shots=shots).result()
answer = results.get_counts()
t2 = time.time()
total = t2 - t1
if verbose:
print("---RESULTS---")
print(f"Time:{total}")
print(f"Integrity: {len(answer)}")
print("-------------")
return answer
def simulate_old(self, circuit: QuantumCircuit, shots=1024, verbose=False):
"""
Simulate experiment
:param circuit: A quantum circuit to execute
:param shots: Number of experiments
:param verbose: Debug printing
:return: A dictionary with all results.
"""
if verbose:
print(f'Simulating qobj {circuit.name}')
t1 = time.time()
results = self.simulator.run(circuit, shots=shots).result()
answer = results.get_counts(experiment=None)
t2 = time.time()
total = t2 - t1
if verbose:
print("---RESULTS---")
print(f"Time:{total}")
print(f"Integrity: {len(answer)}/16")
print("-------------")
if len(answer) != 16:
print("## WARNING ##")
return answer
# CIRCUITS
class Circuit:
# Setter
@staticmethod
def setter(number: int, size: int):
num = f'{number:08b}'[::-1]
n = QuantumRegister(size, "n")
circuit = QuantumCircuit(n, name=f'S{number}')
for ix in range(size):
if num[ix] == '1':
circuit.x(n[ix])
return circuit
# NEQR Module
@staticmethod
def __next_x(val: int, bit: int):
"""
FOR INTERNAL USAGE: Find next pixel's coordinates to encode
:param val:
:param bit:
:return:
"""
if (val % (2 ** bit)) == 0:
return bit
else:
return Circuit.__next_x(val, bit - 1)
@staticmethod
def neqr(imageArray, color_num=8, verbose=False):
"""
Encodes the loaded array into a NEQR circuit
:param color_num: Size of color register
:param imageArray: A NumPy Array encoding the input image. To create one, use Converter.to_array(...)
:param verbose: Prints out encoding phase.
:return: A QuantumCircuit class, encoding the NEQR image
"""
# PARAMETERS
if imageArray.shape[0] != imageArray.shape[1]:
raise Exception("Image array must be a square matrix")
size = imageArray.shape[1]
c_qb = color_num # Size of color register
n_qb = int(math.ceil(math.log(size, 2))) # Size of position registers
# REGISTERS
c = QuantumRegister(c_qb, "col")
x = QuantumRegister(n_qb, "x_coor")
y = QuantumRegister(n_qb, "y_coor")
pos = QuantumRegister(bits=qunion(x, y)) # Useful for mcx
qc = QuantumCircuit(c, y, x, name="NEQR")
# ENCODING
# Initialize position registers
qc.x(x)
qc.x(y)
# First barrier
qc.barrier()
# Encoding colors
total = 2 ** (n_qb + n_qb)
val = 0
i = 1
while i <= total:
to_change = Circuit.__next_x(i, n_qb + n_qb - 1)
val = val ^ (2 ** to_change) # XOR to get correct coordinate
x_index = (val >> 0) & (2 ** n_qb) - 1
y_index = (val >> n_qb)
pixel = imageArray[y_index][x_index]
# --debug--
if verbose:
print("Encoding %d at x:%d y:%d" % (pixel, x_index, y_index))
# Set barrier
qc.barrier()
# Set X-Gate
qc.x(pos[to_change])
# Set CX-Gate
for n in range(c_qb):
new_pixel = pixel >> (8 - color_num) # THIS IS WHERE COLOR ENCODING CHANGES!
bit = (new_pixel >> n) & 1
if bit == 1:
qc.mcx(pos, c[n])
# Increase counter
i += 1
# Set last barrier
qc.barrier()
# Reset coordinates
qc.x(x)
qc.x(y)
# RETURN
return qc
@staticmethod
def neqr_new(imageArray, color_num=8, verbose=False):
"""
Encodes the loaded array into a NEQR circuit
:param color_num: Size of color register
:param imageArray: A NumPy Array encoding the input image. To create one, use Converter.to_array(...)
:param verbose: Prints out encoding phase.
:return: A QuantumCircuit class, encoding the NEQR image
"""
# PARAMETERS
if imageArray.shape[0] != imageArray.shape[1]:
raise Exception("Image array must be a square matrix")
size = imageArray.shape[1]
c_qb = color_num # Size of color register
n_qb = int(math.ceil(math.log(size, 2))) # Size of position registers
# REGISTERS
c = QuantumRegister(c_qb, "col")
x = QuantumRegister(n_qb, "x_coor")
y = QuantumRegister(n_qb, "y_coor")
anc = AncillaRegister(1, "anc")
pos = QuantumRegister(bits=qunion(x, y)) # Useful for mcx
qc = QuantumCircuit(c, y, x, anc, name="NEQR")
# ENCODING
# Initialize position registers
qc.x(x)
qc.x(y)
# First barrier
qc.barrier()
# Encoding colors
total = 2 ** (n_qb + n_qb)
val = 0
i = 1
while i <= total:
to_change = Circuit.__next_x(i, n_qb + n_qb - 1)
val = val ^ (2 ** to_change) # XOR to get correct coordinate
x_index = (val >> 0) & (2 ** n_qb) - 1
y_index = (val >> n_qb)
pixel = imageArray[y_index][x_index]
# --debug--
if verbose:
print("Encoding %d at x:%d y:%d" % (pixel, x_index, y_index))
# Set barrier
qc.barrier()
# Set X-Gate
qc.x(pos[to_change])
# Set CX-Gate
qc.mcx(pos, anc)
for n in range(c_qb):
new_pixel = pixel >> (8 - color_num) # THIS IS WHERE COLOR ENCODING CHANGES!
bit = (new_pixel >> n) & 1
if bit == 1:
qc.mcx(anc, c[n])
qc.mcx(pos, anc)
# Increase counter
i += 1
# Set last barrier
qc.barrier()
# Reset coordinates
qc.x(x)
qc.x(y)
# RETURN
return qc
# Cycle-Shift Module
@staticmethod
def __counter(size, reg_name='q', add=True, module_name="CNTR"):
q = QuantumRegister(size, reg_name)
circuit = QuantumCircuit(q, name=f'{module_name}')
order = range(size)
if add:
order = order.__reversed__()
for i in order:
if i == 0:
circuit.x(i)
else:
circuit.mcx([n for n in range(i)], i)
return circuit
@staticmethod
def cycleshift_w(size):
"""
A CycleShift module. Translates Y coordinate up.
:param size: Size of coordinate's register
:return: A QuantumCircuit implementing the module
"""
return Circuit.__counter(size, 'y_coor', add=False, module_name="CSW")
@staticmethod
def cycleshift_a(size):
"""
A CycleShift module. Translates X coordinate left.
:param size: Size of coordinate's register
:return: A QuantumCircuit implementing the module
"""
return Circuit.__counter(size, 'x_coor', add=False, module_name="CSA")
@staticmethod
def cycleshift_s(size):
"""
A CycleShift module. Translates Y coordinate down.
:param size: Size of coordinate's register
:return: A QuantumCircuit implementing the module
"""
return Circuit.__counter(size, 'y_coor', module_name="CSS")
@staticmethod
def cycleshift_d(size):
"""
A CycleShift module. Translates X coordinate right.
:param size: Size of coordinate's register
:return: A QuantumCircuit implementing the module
"""
return Circuit.__counter(size, 'x_coor', module_name="CSD")
@staticmethod
def adder_single():
"""
A 5 qubit circuit with the following logic:
q0 = q0 -- A
q1 = q1 XOR (q2 XOR q0) -- B/Sum
q2 = q2 XOR ((q2 XOR q0) AND (q2 XOR q1)) --Cin/Cout
q3 = 0 -- q2 XOR q0
q4 = 0 -- q2 XOR q1
It adds up the first two qubits (A and B) and the third (C), putting the SUM on q1 and the Cout on q2
:return: A QuantumCircuit implementing the module
"""
circuit = QuantumCircuit(5, name="HA")
circuit.cx(2, 3) # q3 = C
circuit.cx(2, 4) # q4 = C
circuit.cx(0, 2) # q2 = C XOR A
circuit.cx(1, 3) # q3 = C XOR B
circuit.cx(2, 1) # q1 = B XOR ( C XOR A )
circuit.ccx(2, 3, 4) # q4 = C XOR ((C XOR A) AND (C XOR B))
circuit.reset(2) # q2 = 0
circuit.reset(3) # q3 = 0
circuit.cx(4, 2) # q2 = C XOR ((C XOR A) AND (C XOR B))
circuit.reset(4) # q4 = 0
return circuit
@staticmethod
def adder(size):
"""
A full adder mod(2**size)
:param size: Size of addendum registers
:return: A QuantumCircuit implementing the module
"""
a = QuantumRegister(size, name="a")
b = QuantumRegister(size, name="b")
c0 = AncillaRegister(1, name="c0")
c1 = AncillaRegister(1, name="c1")
c2 = AncillaRegister(1, name="c2")
circuit = QuantumCircuit(a, b, c0, c1, c2, name=f'ADD')
add = Circuit.adder_single()
for i in range(size):
circuit.compose(add.to_instruction(), qubits=[a[i], b[i], c0[0], c1[0], c2[0]], inplace=True)
# Cap value to 255 if c0 == 1
circuit.x(c0)
for i in range(size):
circuit.x(b[i])
circuit.ccx(c0[0], b[i], c1[0])
circuit.x(c1[0])
circuit.swap(b[i], c1[0])
circuit.reset(c1)
circuit.reset(c0)
return circuit
@staticmethod
def subtractor(size):
"""
A full subtractor mod(2**size)
:param size: Size of addendum registers
:return: A QuantumCircuit implementing the module
"""
a = QuantumRegister(size, name="a")
b = QuantumRegister(size, name="b")
c0 = AncillaRegister(1, name="c0")
c1 = AncillaRegister(1, name="c1")
c2 = AncillaRegister(1, name="c2")
circuit = QuantumCircuit(a, b, c0, c1, c2, name=f'SUB')
adder = Circuit.adder(size)
circuit.x(a)
circuit.compose(adder, qunion(a, b, c0, c1, c2), inplace=True)
circuit.x(a)
circuit.x(b)
return circuit
# Swap Module
@staticmethod
def swap(size, a_name="a", b_name="b"):
"""
A Swap module. Swaps the value of two given registers
:param size: Size of registers
:param a_name: Name of the first register
:param b_name: Name of the second register
:return: A QuantumCircuit implementing the module
"""
a = QuantumRegister(size, a_name)
b = QuantumRegister(size, b_name)
circuit = QuantumCircuit(a, b, name=f'SWAP')
for i in range(size):
circuit.swap(i, i + size)
return circuit
# Parallel Controlled-NOT Module
@staticmethod
def parallel_controlled_not(size, a_name="a", b_name="b"):
"""
A Parallel Controlled-NOT module. Copy the value of a given register into another
:param size: Size of registers
:param a_name: Name of the original register
:param b_name: Name of the target register
:return: A QuantumCircuit implementing the module
"""
a = QuantumRegister(size, a_name)
b = QuantumRegister(size, b_name)
circuit = QuantumCircuit(a, b, name="PCN")
for i in range(size):
circuit.cx(i, i + size)
return circuit
@staticmethod
def pcn(size, a_name="a", b_name="b"):
"""
A Parallel Controlled-NOT module. Copy the value of a given register into another
:param size: Size of registers
:param a_name: Name of the original register
:param b_name: Name of the target register
:return: A QuantumCircuit implementing the module
"""
return Circuit.parallel_controlled_not(size, a_name, b_name)
# Neighborhood Preparation
@staticmethod
def neighborhood_prep(neighborhood: dict, f: dict, loaded_circuits: dict, color_size=8, verbose=False):
"""
This module process a given image to be prepared for further processing.
It actually stores a 3x3 mask of the given image on 9 ancillary registers.
:param neighborhood: A dictionary containing pixel values
:param color_size: Size of the color registers
:param verbose: For debug usage
:return: A QuantumCircuit implementing the module
"""
# PARAMETERS
col_qb = color_size # Size of color register
f1 = int(abs(f['f1'])) >> (8 - color_size)
f2 = int(abs(f['f2'])) >> (8 - color_size)
f3 = int(abs(f['f3'])) >> (8 - color_size)
f4 = int(abs(f['f4'])) >> (8 - color_size)
f5 = int(abs(f['f5'])) >> (8 - color_size)
# QUANTUM REGISTERS
a1 = QuantumRegister(col_qb, "a1") # Neighbor F1 | |
a2 = QuantumRegister(col_qb, "a2") # Neighbor UP F1 | UP | F2
a3 = QuantumRegister(col_qb, "a3") # Neighbor F2 _ _ | _ | _ _
a4 = QuantumRegister(col_qb, "a4") # Neighbor LFT | |
a5 = QuantumRegister(col_qb, "a5") # Neighbor CNTR LFT | CNTR | RGHT
a6 = QuantumRegister(col_qb, "a6") # Neighbor RGHT _ _ | _ | _ _
a7 = QuantumRegister(col_qb, "a7") # Neighbor F3 | |
a8 = QuantumRegister(col_qb, "a8") # Neighbor DWN F3 | DWN | F4
a9 = QuantumRegister(col_qb, "a9") # Neighbor F4 | |
# ANCILLA REGISTERS
anc = AncillaRegister(3, "anc")
# MAIN CIRCUIT
circuit = QuantumCircuit(a1, a2, a3, a4, a5, a6, a7, a8, a9, anc, name="NBRHD")
# CIRCUITS
add = loaded_circuits["ADD"]
sub = loaded_circuits["SUB"]
q1 = Circuit.setter(f1, col_qb)
q2 = Circuit.setter(neighborhood["UP"], col_qb)
q3 = Circuit.setter(f2, col_qb)
q4 = Circuit.setter(neighborhood["LFT"], col_qb)
q5 = Circuit.setter(neighborhood["CNTR"], col_qb)
q6 = Circuit.setter(neighborhood["RGHT"], col_qb)
q7 = Circuit.setter(f4, col_qb)
q8 = Circuit.setter(neighborhood["DWN"], col_qb)
q9 = Circuit.setter(f5, col_qb)
# COMPOSITING
# 5
if verbose: print("Preparing Pixel:5")
circuit.compose(q5, a5, inplace=True)
# 6
if verbose: print("Preparing Pixel:6")
circuit.compose(q6, a6, inplace=True)
# 3
if verbose: print("Preparing Pixel:3")
circuit.compose(q3, a3, inplace=True)
circuit.compose(add, qunion(a5, a3, anc), inplace=True)
# 2
if verbose: print("Preparing Pixel:2")
circuit.compose(q2, a2, inplace=True)
# 1
if verbose: print("Preparing Pixel:1")
circuit.compose(q1, a1, inplace=True)
circuit.compose(add, qunion(a5, a1, anc), inplace=True)
# 4
if verbose: print("Preparing Pixel:4")
circuit.compose(q4, a4, inplace=True)
# 7
if verbose: print("Preparing Pixel:7")
circuit.compose(q7, a7, inplace=True)
circuit.compose(sub, qunion(a5, a7, anc), inplace=True)
# 8
if verbose: print("Preparing Pixel:8")
circuit.compose(q8, a8, inplace=True)
# 9
if verbose: print("Preparing Pixel:9")
circuit.compose(q9, a9, inplace=True)
circuit.compose(sub, qunion(a5, a9, anc), inplace=True)
# RETURN
if verbose: print("Done!")
return circuit
@staticmethod
def neighborhood_prep_old(img: np.array, f: dict, loaded_circuits: dict, color_size=8, neqr_circuit=None,
verbose=False):
"""
This module process a given image to be prepared for further processing.
It actually stores a 3x3 mask of the given image on 9 ancillary registers.
:param neqr_circuit: If given, will use the given NEQR circuit without having to compose it
:param img: A NumPy array representing the image
:param color_size: Size of the color registers
:param verbose: For debug usage
:return: A QuantumCircuit implementing the module
"""
# PARAMETERS
x_range = img.shape[1] # X size
y_range = img.shape[0] # Y size
col_qb = color_size # Size of color register
pos_qb = int(math.ceil(math.log(x_range, 2))) # Size of position registers
f1 = int(abs(f['f1'])) >> (8 - color_size)
f2 = int(abs(f['f2'])) >> (8 - color_size)
f3 = int(abs(f['f3'])) >> (8 - color_size)
f4 = int(abs(f['f4'])) >> (8 - color_size)
f5 = int(abs(f['f5'])) >> (8 - color_size)
# QUANTUM REGISTERS
c = QuantumRegister(col_qb, "col") # Color
x = QuantumRegister(pos_qb, "x_coor") # X coordinates
y = QuantumRegister(pos_qb, "y_coor") # Y coordinates
a1 = QuantumRegister(col_qb, "a1") # Neighbor 1 | |
a2 = QuantumRegister(col_qb, "a2") # Neighbor 2 1 | 2 | 3
a3 = QuantumRegister(col_qb, "a3") # Neighbor 3 _ _ | _ | _ _
a4 = QuantumRegister(col_qb, "a4") # Neighbor 4 | |
a5 = QuantumRegister(col_qb, "a5") # Neighbor 5 4 | 5 | 6
a6 = QuantumRegister(col_qb, "a6") # Neighbor 6 _ _ | _ | _ _
a7 = QuantumRegister(col_qb, "a7") # Neighbor 7 | |
a8 = QuantumRegister(col_qb, "a8") # Neighbor 8 7 | 8 | 9
a9 = QuantumRegister(col_qb, "a9") # Neighbor 9 | |
# ANCILLA REGISTERS
anc = AncillaRegister(3, "anc")
# MAIN CIRCUIT
circuit = QuantumCircuit(c, y, x, a1, a2, a3, a4, a5, a6, a7, a8, a9, anc, name="NBRHD")
# CIRCUITS
if neqr_circuit is None:
neqr = Circuit.neqr(img, color_num=col_qb, verbose=False)
else:
neqr = neqr_circuit
cs_w = loaded_circuits["CSW"]
cs_a = loaded_circuits["CSA"]
cs_s = loaded_circuits["CSS"]
cs_d = loaded_circuits["CSD"]
swp = loaded_circuits["SWAP"]
add = loaded_circuits["ADD"]
sub = loaded_circuits["SUB"]
q3 = Circuit.setter(f1, col_qb)
q1 = Circuit.setter(f2, col_qb)
q7 = Circuit.setter(f4, col_qb)
q9 = Circuit.setter(f5, col_qb)
# COMPOSITING
circuit.h(y)
circuit.h(x)
circuit.compose(q3, a3, inplace=True)
circuit.compose(q1, a1, inplace=True)
circuit.compose(q7, a7, inplace=True)
circuit.compose(q9, a9, inplace=True)
# 5
if verbose: print("Preparing Pixel:5")
circuit.compose(neqr, qunion(c, y, x), inplace=True)
circuit.compose(swp, qunion(c, a5), inplace=True)
# 6
if verbose: print("Preparing Pixel:6")
circuit.compose(cs_d, qunion(x), inplace=True)
circuit.compose(neqr, qunion(c, y, x), inplace=True)
circuit.compose(swp, qunion(c, a6), inplace=True)
# 3
if verbose: print("Preparing Pixel:3")
circuit.compose(cs_w, qunion(y), inplace=True)
circuit.compose(add, qunion(a5, a3, anc), inplace=True)
# 2
if verbose: print("Preparing Pixel:2")
circuit.compose(cs_a, qunion(x), inplace=True)
circuit.compose(neqr, qunion(c, y, x), inplace=True)
circuit.compose(swp, qunion(c, a2), inplace=True)
# 1
if verbose: print("Preparing Pixel:1")
circuit.compose(cs_a, qunion(x), inplace=True)
circuit.compose(add, qunion(a5, a1, anc), inplace=True)
# 4
if verbose: print("Preparing Pixel:4")
circuit.compose(cs_s, qunion(y), inplace=True)
circuit.compose(neqr, qunion(c, y, x), inplace=True)
circuit.compose(swp, qunion(c, a4), inplace=True)
# 7
if verbose: print("Preparing Pixel:7")
circuit.compose(cs_s, qunion(y), inplace=True)
circuit.compose(sub, qunion(a5, a7, anc), inplace=True)
# 8
if verbose: print("Preparing Pixel:8")
circuit.compose(cs_d, qunion(x), inplace=True)
circuit.compose(neqr, qunion(c, y, x), inplace=True)
circuit.compose(swp, qunion(c, a8), inplace=True)
# 9
if verbose: print("Preparing Pixel:9")
circuit.compose(cs_d, qunion(x), inplace=True)
circuit.compose(sub, qunion(a5, a9, anc), inplace=True)
# Reset
if verbose: print("Restoring...")
circuit.compose(cs_w, qunion(y), inplace=True)
circuit.compose(cs_a, qunion(x), inplace=True)
# RETURN
if verbose: print("Done!")
return circuit
@staticmethod
def neighborhood_prep_patch(img: np.array, pixel: int, f: dict, loaded_circuits: dict, color_size=8, verbose=False):
"""
This module process a given image to be prepared for further processing.
It actually stores a 3x3 mask of the given image on 9 ancillary registers.
:param f:
:param neqr_circuit: If given, will use the given NEQR circuit without having to compose it
:param img: A NumPy array representing the image
:param color_size: Size of the color registers
:param verbose: For debug usage
:return: A QuantumCircuit implementing the module
"""
# PARAMETERS
x_range = img.shape[1] # X size
y_range = img.shape[0] # Y size
col_qb = color_size # Size of color register
pos_qb = int(math.ceil(math.log(x_range, 2))) # Size of position registers
f1 = round(abs(f['f1'])) >> (8 - color_size)
f2 = round(abs(f['f2'])) >> (8 - color_size)
f3 = round(abs(f['f3'])) >> (8 - color_size)
f4 = round(abs(f['f4'])) >> (8 - color_size)
f5 = round(abs(f['f5'])) >> (8 - color_size)
# QUANTUM REGISTERS
c = QuantumRegister(col_qb, "col") # Color
x = QuantumRegister(pos_qb, "x_coor") # X coordinates
y = QuantumRegister(pos_qb, "y_coor") # Y coordinates
a1 = QuantumRegister(col_qb, "a1") # Neighbor UP
a2 = QuantumRegister(col_qb, "a2") # Neighbor RIGHT
a3 = QuantumRegister(col_qb, "a3") # Neighbor DOWN
a4 = QuantumRegister(col_qb, "a4") # Neighbor LEFT
a5 = QuantumRegister(col_qb, "a5") # PIXEL
a6 = QuantumRegister(col_qb, "a6") # F1
a7 = QuantumRegister(col_qb, "a7") # F2
a8 = QuantumRegister(col_qb, "a8") # F4
a9 = QuantumRegister(col_qb, "a9") # F5
# ANCILLA REGISTERS
anc = AncillaRegister(3, "anc")
# MAIN CIRCUIT
circuit = QuantumCircuit(c, y, x, a1, a2, a3, a4, a5, a6, a7, a8, a9, anc, name="NBRHD")
# CIRCUITS
neqr = Circuit.neqr(img, color_num=col_qb, verbose=False)
cs_w = loaded_circuits["CSW"]
cs_a = loaded_circuits["CSA"]
cs_s = loaded_circuits["CSS"]
cs_d = loaded_circuits["CSD"]
swp = loaded_circuits["SWAP"]
add = loaded_circuits["ADD"]
sub = loaded_circuits["SUB"]
q1 = Circuit.setter(f1, col_qb)
q2 = Circuit.setter(f2, col_qb)
q3 = Circuit.setter(pixel, col_qb)
q4 = Circuit.setter(f4, col_qb)
q5 = Circuit.setter(f5, col_qb)
# COMPOSITING
# 1
if verbose: print("Preparing A1")
circuit.compose(neqr, qunion(c, y, x), inplace=True)
circuit.compose(swp, qunion(c, a1), inplace=True)
# 2
if verbose: print("Preparing A2")
circuit.compose(cs_d, qunion(x), inplace=True)
circuit.compose(neqr, qunion(c, y, x), inplace=True)
circuit.compose(swp, qunion(c, a2), inplace=True)
# 3
if verbose: print("Preparing A3")
circuit.compose(cs_s, qunion(y), inplace=True)
circuit.compose(neqr, qunion(c, y, x), inplace=True)
circuit.compose(swp, qunion(c, a3), inplace=True)
# 4
if verbose: print("Preparing A4")
circuit.compose(cs_a, qunion(x), inplace=True)
circuit.compose(neqr, qunion(c, y, x), inplace=True)
circuit.compose(swp, qunion(c, a4), inplace=True)
# 5
if verbose: print("Preparing A5")
circuit.compose(q3, a5, inplace=True)
# 6
if verbose: print("Preparing A6")
circuit.compose(q1, a6, inplace=True)
circuit.compose(add, qunion(a5, a6, anc), inplace=True)
# 7
if verbose: print("Preparing A7")
circuit.compose(q2, a7, inplace=True)
circuit.compose(add, qunion(a5, a7, anc), inplace=True)
# 8
if verbose: print("Preparing A8")
circuit.compose(q4, a8, inplace=True)
circuit.compose(sub, qunion(a5, a8, anc), inplace=True)
# 9
if verbose: print("Preparing A9")
circuit.compose(q5, a9, inplace=True)
circuit.compose(sub, qunion(a5, a9, anc), inplace=True)
# Reset
if verbose: print("Restoring...")
circuit.compose(cs_w, qunion(y), inplace=True)
# RETURN
if verbose: print("Done!")
return circuit
# Comparator
@staticmethod
def comparator_new(size, a_name="a", b_name="b", res_name="e"):
"""
This module compares the binary encoding of two registers and stores the result on a third register.
The result register can result in:
0: A <= B
1: A > B
:param size: Size of the registers
:param a_name: Name of the first register
:param b_name: Name of the second register
:param res_name: Name of the result register
:return: A QuantumCircuit implementing the module
"""
# REGISTERS
a = QuantumRegister(size, a_name)
b = QuantumRegister(size, b_name)
anc = AncillaRegister(1, "anc")
res = AncillaRegister(1, res_name)
circuit = QuantumCircuit(a, b, res, anc, name="COMP")
# COMPOSING
for i in range(size):
circuit.cx(res, anc)
circuit.cx(anc, a[i])
circuit.cx(anc, b[i])
circuit.x(b[i])
circuit.toffoli(b[i], a[i], res)
circuit.x(b[i])
circuit.cx(anc, a[i])
circuit.cx(anc, b[i])
circuit.reset(anc) # 1 ancilla version
# RETURN
return circuit
@staticmethod
def comparator(size, a_name="a", b_name="b", res_name="e"):
"""
This module compares the binary encoding of two registers and stores the result on a third register.
The result register can result in:
00: equal
01: A greater than B
10: B greater than A
:param size: Size of the registers
:param a_name: Name of the first register
:param b_name: Name of the second register
:param res_name: Name of the result register
:return: A QuantumCircuit implementing the module
"""
# REGISTERS
anc_qb = (size - 1) * 2
a = QuantumRegister(size, a_name)
b = QuantumRegister(size, b_name)
anc = AncillaRegister(anc_qb, "anc")
res = AncillaRegister(2, res_name)
circuit = QuantumCircuit(a, b, res, anc, name="COMP")
# COMPOSING
add = []
for i in range(size).__reversed__():
if i != 0:
# Check a > b
circuit.x(b[i])
circuit.mcx([a[i], b[i]] + add, anc[i * 2 - 1])
circuit.mcx([a[i], b[i]] + add, res[0])
circuit.x(b[i])
# Check a < b
circuit.x(a[i])
circuit.mcx([a[i], b[i]] + add, anc[i * 2 - 2])
circuit.mcx([a[i], b[i]] + add, res[1])
circuit.x(a[i])
# Prepare ancilla
circuit.x(anc[i * 2 - 1])
circuit.x(anc[i * 2 - 2])
add.append(anc[i * 2 - 1])
add.append(anc[i * 2 - 2])
else:
mcmt = MCMT(XGate(), 2 + len(add), 1)
# Check a > b
circuit.x(b[i])
circuit.mcx([a[i], b[i]] + add, res[0])
circuit.x(b[i])
# Check b > a
circuit.x(a[i])
circuit.mcx([a[i], b[i]] + add, res[1])
circuit.x(a[i])
# circuit.barrier()
# RETURN
return circuit
# Swapper
@staticmethod
def swapper_new(size, a_name="a", b_name="b"):
"""
A Swapper is a composite module which "swaps" two registers based on their binary encoding:
A > B --> SWAP
A <= B --> PASS
:param size: Size of the register
:param a_name: Name of the first register
:param b_name: Name of the second register
:return: A QuantumCircuit implementing the module
"""
# REGISTERS
a = QuantumRegister(size, a_name)
b = QuantumRegister(size, b_name)
res = AncillaRegister(1, "e")
anc = AncillaRegister(1, "anc")
circuit = QuantumCircuit(a, b, res, anc, name="SWPPR")
# COMPOSING
comp = Circuit.comparator_new(size, a_name, b_name, res.name)
swp = Circuit.swap(size, a_name, b_name).control(1, ctrl_state='1')
circuit.append(comp.to_instruction(), circuit.qubits)
circuit.append(swp, qunion(res, a, b))
# RETURN
return circuit
@staticmethod
def swapper(size, a_name="a", b_name="b"):
"""
A Swapper is a composite module which "swaps" two registers based on their binary encoding:
A > B --> SWAP
A <= B --> PASS
:param size: Size of the register
:param a_name: Name of the first register
:param b_name: Name of the second register
:return: A QuantumCircuit implementing the module
"""
# REGISTERS
anc_qb = (size - 1) * 2
a = QuantumRegister(size, a_name)
b = QuantumRegister(size, b_name)
res = AncillaRegister(2, "e")
anc = AncillaRegister(anc_qb, "anc")
circuit = QuantumCircuit(a, b, res, anc, name="SWPPR")
# COMPOSING
comp = Circuit.comparator(size, a_name, b_name, res.name)
swp = Circuit.swap(size, a_name, b_name).control(2, ctrl_state='01')
circuit.append(comp.to_instruction(), circuit.qubits)
circuit.append(swp, qunion(res, a, b))
# RETURN
return circuit
# Sort Module
@staticmethod
def sort_new(size, a_name="a", b_name="b", c_name="c"):
"""
This module sorts a set of three registers.
:param size: Size of the registers
:param a_name: Name of the first register
:param b_name: Name of the second register
:param c_name: Name of the third register
:return: A QuantumCircuit implementing the module
"""
# REGISTERS
a = QuantumRegister(size, a_name)
b = QuantumRegister(size, b_name)
c = QuantumRegister(size, c_name)
res = AncillaRegister(1, "e")
anc = AncillaRegister(1, "anc")
circuit = QuantumCircuit(a, b, c, res, anc, name="SORT")
# COMPOSING
swppr_ab = Circuit.swapper_new(size, a_name=a_name, b_name=b_name).to_instruction()
swppr_ac = Circuit.swapper_new(size, a_name=a_name, b_name=c_name).to_instruction()
swppr_bc = Circuit.swapper_new(size, a_name=b_name, b_name=c_name).to_instruction()
# Sort A and B
circuit.append(swppr_ab, qunion(a, b, res, anc))
circuit.reset(res)
circuit.reset(anc)
# Sort A and C
circuit.append(swppr_ac, qunion(a, c, res, anc))
circuit.reset(res)
circuit.reset(anc)
# Sort B and C
circuit.append(swppr_bc, qunion(b, c, res, anc))
circuit.reset(res)
circuit.reset(anc)
# RETURN
return circuit
@staticmethod
def sort(size, a_name="a", b_name="b", c_name="c"):
"""
This module sorts a set of three registers.
:param size: Size of the registers
:param a_name: Name of the first register
:param b_name: Name of the second register
:param c_name: Name of the third register
:return: A QuantumCircuit implementing the module
"""
# REGISTERS
anc_qb = (size - 1) * 2
a = QuantumRegister(size, a_name)
b = QuantumRegister(size, b_name)
c = QuantumRegister(size, c_name)
res = AncillaRegister(2, "e")
anc = AncillaRegister(anc_qb, "anc")
circuit = QuantumCircuit(a, b, c, res, anc, name="SORT")
# COMPOSING
swppr_ab = Circuit.swapper(size, a_name=a_name, b_name=b_name).to_instruction()
swppr_ac = Circuit.swapper(size, a_name=a_name, b_name=c_name).to_instruction()
swppr_bc = Circuit.swapper(size, a_name=b_name, b_name=c_name).to_instruction()
# Sort A and B
circuit.append(swppr_ab, qunion(a, b, res, anc))
circuit.reset(res)
circuit.reset(anc)
# Sort A and C
circuit.append(swppr_ac, qunion(a, c, res, anc))
circuit.reset(res)
circuit.reset(anc)
# Sort B and C
circuit.append(swppr_bc, qunion(b, c, res, anc))
circuit.reset(res)
circuit.reset(anc)
# RETURN
return circuit
# Maximum-Median-Minimum Module
@staticmethod
def min_med_max(size):
"""
A module which sorts its input, which median is finally stored in the center register.
:param size: Size of the registers
:return: A QuantumCircuit implementing the module
"""
# REGISTERS
a1 = QuantumRegister(size, "a1")
a2 = QuantumRegister(size, "a2")
a3 = QuantumRegister(size, "a3")
a4 = QuantumRegister(size, "a4")
a5 = QuantumRegister(size, "a5")
a6 = QuantumRegister(size, "a6")
a7 = QuantumRegister(size, "a7")
a8 = QuantumRegister(size, "a8")
a9 = QuantumRegister(size, "a9")
res = AncillaRegister(1, "e")
anc = AncillaRegister(1, "anc")
circuit = QuantumCircuit(a1, a2, a3, a4, a5, a6, a7, a8, a9, res, anc,
name=f'MMM')
# COMPOSING
sort = Circuit.sort_new(size).to_instruction()
# Row sort
circuit.append(sort, qunion(a1, a2, a3, res, anc))
circuit.append(sort, qunion(a4, a5, a6, res, anc))
circuit.append(sort, qunion(a7, a8, a9, res, anc))
# Column sort
circuit.append(sort, qunion(a1, a4, a7, res, anc))
circuit.append(sort, qunion(a2, a5, a8, res, anc))
circuit.append(sort, qunion(a3, a6, a9, res, anc))
# Right diagonal sort
circuit.append(sort, qunion(a3, a5, a7, res, anc))
# RETURN
return circuit
# QUANTUM MEDIAN FILTER
class QuantumMedianFilter:
"""
A Quantum Median Filter.
OUTPUT: X Y C
X is a binary representation of pixel horizontal coordinate
Y is a binary representation of pixel vertical coordinate
C is a binary representation of pixel median value
"""
circuit = None
loaded_circuits = dict()
def generate(self, simulator: Simulator, color_size: int, coordinate_size: int, optimization_level=3):
# Circuits
mmm = Circuit.min_med_max(color_size)
swp = Circuit.swap(color_size)
cs_w = Circuit.cycleshift_w(coordinate_size)
cs_a = Circuit.cycleshift_a(coordinate_size)
cs_s = Circuit.cycleshift_s(coordinate_size)
cs_d = Circuit.cycleshift_d(coordinate_size)
add = Circuit.adder(color_size)
sub = Circuit.subtractor(color_size)
# Transpile and save
self.loaded_circuits["MMM"] = simulator.transpile(mmm, optimization=optimization_level, qasm_filename=mmm.name)
self.loaded_circuits["SWAP"] = simulator.transpile(swp, optimization=optimization_level, qasm_filename=swp.name)
self.loaded_circuits["CSW"] = simulator.transpile(cs_w, optimization=optimization_level,
qasm_filename=cs_w.name)
self.loaded_circuits["CSA"] = simulator.transpile(cs_a, optimization=optimization_level,
qasm_filename=cs_a.name)
self.loaded_circuits["CSS"] = simulator.transpile(cs_s, optimization=optimization_level,
qasm_filename=cs_s.name)
self.loaded_circuits["CSD"] = simulator.transpile(cs_d, optimization=optimization_level,
qasm_filename=cs_d.name)
self.loaded_circuits["ADD"] = simulator.transpile(add, optimization=optimization_level, qasm_filename=add.name)
self.loaded_circuits["SUB"] = simulator.transpile(sub, optimization=optimization_level, qasm_filename=sub.name)
def load_precompiled_circuits(self):
to_load = ["MMM", "SWAP", "CSW", "CSA", "CSS", "CSD", "ADD", "SUB"]
for c in to_load:
print(f"Loading {c} QASM file")
self.loaded_circuits[c] = load_qasm(c)
def prepare(self, neighborhood: dict, lambda_par=1, color_size=8):
"""
Prepare the circuit
:param lambda_par: Lambda parameter for filtering
:param neighborhood: A dictionary containing neighbor pixels
:param color_size: Size of the color registers (defult: 8)
"""
# QC PARAMETERS
col_qb = color_size # Size of color register
# FILTER PARAMETERS
w0_par = 1
u_par = 1 / lambda_par
const_par = (1 / (2 * u_par))
w1_par = 4 * w0_par - 0 * w0_par
w2_par = 3 * w0_par - 1 * w0_par
w3_par = 2 * w0_par - 2 * w0_par
w4_par = 1 * w0_par - 3 * w0_par
w5_par = 0 * w0_par - 4 * w0_par
f = dict()
f['f1'] = const_par * w1_par
f['f2'] = const_par * w2_par
f['f3'] = const_par * w3_par
f['f4'] = const_par * w4_par
f['f5'] = const_par * w5_par
# QUANTUM REGISTERS
a1 = QuantumRegister(col_qb, "a1")
a2 = QuantumRegister(col_qb, "a2")
a3 = QuantumRegister(col_qb, "a3")
a4 = QuantumRegister(col_qb, "a4")
a5 = QuantumRegister(col_qb, "a5")
a6 = QuantumRegister(col_qb, "a6")
a7 = QuantumRegister(col_qb, "a7")
a8 = QuantumRegister(col_qb, "a8")
a9 = QuantumRegister(col_qb, "a9")
# ANCILLA REGISTERS
res = AncillaRegister(1, "e")
anc1 = AncillaRegister(1, "anc1")
anc2 = AncillaRegister(3, "anc2")
# CLASSICAL REGISTERS
cm = ClassicalRegister(col_qb, "cm") # Color Measurement
# MAIN CIRCUIT
circuit = QuantumCircuit(a1, a2, a3, a4, a5, a6, a7, a8, a9, # QUANTUM REGISTERS
res, anc1, anc2, # ANCILLA REGISTERS
cm, # CLASSICAL REGISTERS
name="QuantumMedianFilter" # NAME
)
# CIRCUITS
if len(self.loaded_circuits) == 0:
print("Loading transpiled circuits")
self.load_precompiled_circuits()
prep = Circuit.neighborhood_prep(neighborhood, f, self.loaded_circuits, color_size=color_size)
mmm = self.loaded_circuits["MMM"]
# COMPOSITING
circuit.compose(prep, qunion(a1, a2, a3, a4, a5, a6, a7, a8, a9, anc2), inplace=True)
circuit.barrier()
circuit.compose(mmm, qunion(a1, a2, a3, a4, a5, a6, a7, a8, a9, res, anc1),
inplace=True)
circuit.barrier()
# MEASUREMENT
circuit.measure(a5, cm)
#
self.circuit = circuit
def prepare_old(self, img: np.array, lambda_par=1, color_size=8, neqr_circuit=None):
"""
Prepare the circuit. Uses NEQR
:param neqr_circuit: If given, this NEQR circuit will be used, avoiding to compose one
:param lambda_par: Lambda parameter for filtering
:param img: A NumPy image representation
:param color_size: Size of the color registers (defult: 8)
"""
# IMAGE PARAMETERS
x_range = img.shape[1] # X size
y_range = img.shape[0] # Y size
# QC PARAMETERS
col_qb = color_size # Size of color register
pos_qb = int(math.ceil(math.log(x_range, 2))) # Size of position registers
# FILTER PARAMETERS
w0_par = 1
u_par = 1 / lambda_par
const_par = (1 / (2 * u_par))
w1_par = 4 * w0_par - 0 * w0_par
w2_par = 3 * w0_par - 1 * w0_par
w3_par = 2 * w0_par - 2 * w0_par
w4_par = 1 * w0_par - 3 * w0_par
w5_par = 0 * w0_par - 4 * w0_par
f = dict()
f['f1'] = const_par * w1_par
f['f2'] = const_par * w2_par
f['f3'] = const_par * w3_par
f['f4'] = const_par * w4_par
f['f5'] = const_par * w5_par
# QUANTUM REGISTERS
c = QuantumRegister(col_qb, "col") # Color
x_coord = QuantumRegister(pos_qb, "x_coor") # X coordinates
y_coord = QuantumRegister(pos_qb, "y_coor") # Y coordinates
a1 = QuantumRegister(col_qb, "a1")
a2 = QuantumRegister(col_qb, "a2")
a3 = QuantumRegister(col_qb, "a3")
a4 = QuantumRegister(col_qb, "a4")
a5 = QuantumRegister(col_qb, "a5")
a6 = QuantumRegister(col_qb, "a6")
a7 = QuantumRegister(col_qb, "a7")
a8 = QuantumRegister(col_qb, "a8")
a9 = QuantumRegister(col_qb, "a9")
# ANCILLA REGISTERS
res = AncillaRegister(1, "e")
anc1 = AncillaRegister(1, "anc1")
anc2 = AncillaRegister(3, "anc2")
# CLASSICAL REGISTERS
cm = ClassicalRegister(col_qb, "cm") # Color Measurement (2)
xm = ClassicalRegister(pos_qb, "xm") # X Measurement (1)
ym = ClassicalRegister(pos_qb, "ym") # Y Measurement (0)
# MAIN CIRCUIT
circuit = QuantumCircuit(c, y_coord, x_coord, a1, a2, a3, a4, a5, a6, a7, a8, a9, # QUANTUM REGISTERS
res, anc1, anc2, # ANCILLA REGISTERS
cm, ym, xm, # CLASSICAL REGISTERS
name="QuantumMedianFilter" # NAME
)
# CIRCUITS
if len(self.loaded_circuits) == 0:
print("Loading transpiled circuits")
self.load_precompiled_circuits()
prep = Circuit.neighborhood_prep_old(img, f, self.loaded_circuits, color_size=color_size,
neqr_circuit=neqr_circuit)
mmm = self.loaded_circuits["MMM"]
swp = self.loaded_circuits["SWAP"]
# COMPOSITING
circuit.compose(prep, qunion(c, y_coord, x_coord, a1, a2, a3, a4, a5, a6, a7, a8, a9, anc2), inplace=True)
circuit.barrier()
circuit.compose(mmm, qunion(a1, a2, a3, a4, a5, a6, a7, a8, a9, res, anc1),
inplace=True)
circuit.barrier()
circuit.compose(swp, qunion(c, a5), inplace=True)
circuit.barrier()
# MEASUREMENT
circuit.measure(c, cm)
circuit.measure(y_coord, ym)
circuit.measure(x_coord, xm)
#
self.circuit = circuit
def prepare_patch(self, patch: np.array, pixel, lambda_par=2, color_size=8):
"""
Prepare the circuit. Uses NEQR
:param neqr_circuit: If given, this NEQR circuit will be used, avoiding to compose one
:param lambda_par: Lambda parameter for filtering
:param img: A NumPy image representation
:param color_size: Size of the color registers (defult: 8)
"""
# IMAGE PARAMETERS
x_range = 2 # X size
y_range = 2 # Y size
# QC PARAMETERS
col_qb = color_size # Size of color register
pos_qb = int(math.ceil(math.log(x_range, 2))) # Size of position registers
# FILTER PARAMETERS
w0_par = 1
const_par = lambda_par / 2
w1_par = 4 * w0_par - 0 * w0_par
w2_par = 3 * w0_par - 1 * w0_par
w3_par = 2 * w0_par - 2 * w0_par
w4_par = 1 * w0_par - 3 * w0_par
w5_par = 0 * w0_par - 4 * w0_par
f = dict()
f['f1'] = const_par * w1_par
f['f2'] = const_par * w2_par
f['f3'] = const_par * w3_par
f['f4'] = const_par * w4_par
f['f5'] = const_par * w5_par
# QUANTUM REGISTERS
c = QuantumRegister(col_qb, "col") # Color
x_coord = QuantumRegister(pos_qb, "x_coor") # X coordinates
y_coord = QuantumRegister(pos_qb, "y_coor") # Y coordinates
a1 = QuantumRegister(col_qb, "a1")
a2 = QuantumRegister(col_qb, "a2")
a3 = QuantumRegister(col_qb, "a3")
a4 = QuantumRegister(col_qb, "a4")
a5 = QuantumRegister(col_qb, "a5")
a6 = QuantumRegister(col_qb, "a6")
a7 = QuantumRegister(col_qb, "a7")
a8 = QuantumRegister(col_qb, "a8")
a9 = QuantumRegister(col_qb, "a9")
# ANCILLA REGISTERS
res = AncillaRegister(1, "e")
anc1 = AncillaRegister(1, "anc1")
anc2 = AncillaRegister(3, "anc2")
# CLASSICAL REGISTERS
cm = ClassicalRegister(col_qb, "cm") # Color Measurement
# MAIN CIRCUIT
circuit = QuantumCircuit(c, y_coord, x_coord, a1, a2, a3, a4, a5, a6, a7, a8, a9, # QUANTUM REGISTERS
res, anc1, anc2, # ANCILLA REGISTERS
cm, # CLASSICAL REGISTERS
name="QuantumMedianFilter" # NAME
)
# CIRCUITS
if len(self.loaded_circuits) == 0:
print("Loading transpiled circuits")
self.load_precompiled_circuits()
prep = Circuit.neighborhood_prep_patch(patch, pixel, f, self.loaded_circuits, color_size=color_size)
mmm = self.loaded_circuits["MMM"]
swp = self.loaded_circuits["SWAP"]
# COMPOSITING
circuit.compose(prep, qunion(c, y_coord, x_coord, a1, a2, a3, a4, a5, a6, a7, a8, a9, anc2), inplace=True)
circuit.barrier()
circuit.compose(mmm, qunion(a1, a2, a3, a4, a5, a6, a7, a8, a9, res, anc1),
inplace=True)
circuit.barrier()
# MEASUREMENT
circuit.measure(a5, cm)
#
self.circuit = circuit
def get(self):
"""
If prepared, returns the Quantum Median Filter module
:return: A QuantumCircuit implementing the module
"""
return self.circuit
|
https://github.com/Alice-Bob-SW/qiskit-alice-bob-provider
|
Alice-Bob-SW
|
'''
qiskitpool/job.py
Contains the QJob class
'''
from functools import partial
from qiskit import execute
class QJob():
'''
QJob
Job manager for asynch qiskit backends
'''
def __init__(self, *args, qjob_id=None, **kwargs):
'''
QJob.__init__
Initialiser for a qiksit job
:: *args :: Args for qiskit execute
:: **kwargs :: Kwargs for qiskit execute
'''
self.job_fn = partial(execute, *args, **kwargs)
self.job = None
self.done = False
self.test_count = 10
self.qjob_id = qjob_id
def __call__(self):
'''
QJob.__call__
Wrapper for QJob.run
'''
return self.run()
def run(self):
'''
QJob.run
Send async job to qiskit backend
'''
self.job = self.job_fn()
return self
def poll(self):
'''
QJob.poll
Poll qiskit backend for job completion status
'''
if self.job is not None:
return self.job.done()
return False
def cancel(self):
'''
QJob.cancel
Cancel job on backend
'''
if self.job is None:
return None
return self.job.cancel()
def position(self):
pos = self.job.queue_position()
if pos is None:
return 0
return pos
def status(self):
if self.job is None:
return 'LOCAL QUEUE'
else:
status = self.job.status().value
if 'running' in status:
return 'RUNNING'
if 'run' in status:
return 'COMPLETE'
if 'validated' in status:
return 'VALIDATING'
if 'queued' in status:
pos = self.position()
return f'QISKIT QUEUE: {self.position()}'
def status_short(self):
if self.job is None:
return ' '
else:
status = self.job.status().value
if 'running' in status:
return 'R'
if 'run' in status:
return 'C'
if 'validated' in status:
return 'V'
if 'queued' in status:
return str(self.position())
def result(self):
'''
QJob.result
Get result from backend
Non blocking - returns False if a job is not yet ready
'''
if self.poll():
return self.job.result()
return False
|
https://github.com/matteoacrossi/oqs-jupyterbook
|
matteoacrossi
|
"""
Circuit preparation for the amplitude damping channel
"""
from qiskit import QuantumCircuit
import numpy as np
from scipy.special import xlogy
from scipy.optimize import minimize_scalar
def initial_state(q, sys):
"""Returns a QuantumCircuit implementing the initial condition for the amplitude damping channel
Args:
q (QuantumRegister): the register to use for the circuit
sys (int): index for the system qubit
Returns:
A QuantumCircuit object
"""
# Create circuit
ic = QuantumCircuit(q)
# System in |1>
ic.x(q[sys])
return ic
def initial_state_witness(q, sys, anc):
"""Returns a QuantumCircuit implementing the initial condition for the amplitude damping channel with non-Markovianity witness
Args:
q (QuantumRegister): the register to use for the circuit
sys (int): index for the system qubit
anc (int): index for the ancilla qubit
Returns:
A QuantumCircuit object
"""
# Create circuit
ic = QuantumCircuit(q)
# System and ancilla in |\psi^+>
ic.h(q[sys])
ic.cx(q[sys], q[anc])
return ic
def amplitude_damping_channel(q, c, sys, env, R, t):
"""Returns a QuantumCircuit implementing the amplitude damping channel on the system qubit
Args:
q (QuantumRegister): the register to use for the circuit
c (ClassicalRegister): the register to use for the measurement of the system qubit
sys (int): index for the system qubit
env (int): index for the environment qubit
R (float): value of R = \gamma_0/\lambda
t (float): value of the time variable
Returns:
A QuantumCircuit object
"""
ad = QuantumCircuit(q, c)
# Rotation angle
theta = 2.0 * np.arccos(c1(R, t))
# Channel
ad.cu3(theta, 0.0, 0.0, q[sys], q[env])
ad.cx(q[env], q[sys])
# Masurement in the computational basis
ad.measure(q[sys], c[0])
return ad
def amplitude_damping_channel_witness(q, c, sys, env, anc, observable, R, t):
"""Returns a QuantumCircuit implementing the amplitude damping channel on the system qubit with non-Markovianity witness
Args:
q (QuantumRegister): the register to use for the circuit
c (ClassicalRegister): the register to use for the measurement of the system and ancilla qubits
sys (int): index for the system qubit
env (int): index for the environment qubit
anc (int): index for the ancillary qubit
observable (str): the observable to be measured
R (float): value of R = \gamma_0/\lambda
t (float): value of the time variable
Returns:
A QuantumCircuit object
"""
ad = QuantumCircuit(q, c)
# Rotation angle
theta = 2.0 * np.arccos(c1(R, t))
# Channel
ad.cu3(theta, 0.0, 0.0, q[sys], q[env])
ad.cx(q[env], q[sys])
# Masurement of the corresponding observable
if observable == 'xx':
ad.h(sys)
ad.h(anc)
elif observable == 'yy':
ad.sdg(sys)
ad.h(sys)
ad.sdg(anc)
ad.h(anc)
ad.measure(sys,c[0])
ad.measure(anc,c[1])
return ad
def c1(R,t):
"""Returns the coherence factor in the amplitude damping channel
Args:
R (float): value of R = \gamma_0/\lambda
t (float): value of the time variable
Returns:
A float number
"""
if R < 0.5:
c1 = np.exp(- t / 2.0) * (np.cosh(t * np.sqrt(1.0 - 2.0 * R) / 2.0) + 1.0 / np.sqrt(1.0 - 2.0 * R) * np.sinh(t * np.sqrt(1.0 - 2.0 * R) / 2.0))
else:
c1 = np.exp(- t / 2.0) * (np.cos(t * np.sqrt(2.0 * R - 1.0) / 2.0) + 1.0 / np.sqrt(2.0 * R - 1.0) * np.sin(t * np.sqrt(2.0 * R - 1.0) / 2.0))
return c1
def H2(p):
"""Returns the binary Shannon entropy of its argument
Args:
p (float): value of p, between 0 and 1
Returns:
A float number
"""
H2 = - xlogy(p, p) / np.log(2.0) - xlogy(1.0 - p, 1.0 - p) / np.log(2.0)
return H2
def Qa(c):
"""Returns the quantum channel capacity (Eq. (14) in the paper)
Args:
c (float): value of |c_1(t)|^2
Returns:
A float number
"""
Q = 0.0
if c > 0.5:
f = lambda p: -H2(c * p) + H2((1.0 - c) * p)
Q = -minimize_scalar(f, bounds=(0.0, 1.0), method='Bounded').fun
return Q
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization import QuadraticProgram
problem = QuadraticProgram("sample")
problem.binary_var("x")
problem.binary_var("y")
problem.maximize(linear={"x": 1, "y": -2})
print(problem.prettyprint())
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = NumPyMinimumEigensolver()
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = NumPyMinimumEigensolver()
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
mes = QAOA(optimizer=COBYLA(), quantum_instance=qins)
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
shots = 1000
mes = QAOA(sampler=Sampler(), optimizer=COBYLA())
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
mes = VQE(ansatz=RealAmplitudes(), optimizer=COBYLA(), quantum_instance=qins)
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = SamplingVQE(sampler=Sampler(), ansatz=RealAmplitudes(), optimizer=COBYLA())
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Estimator
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = VQE(estimator=Estimator(), ansatz=RealAmplitudes(), optimizer=COBYLA())
try:
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
except TypeError as ex:
print(ex)
from qiskit import BasicAer
from qiskit.algorithms import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
qaoa = QAOA(optimizer=COBYLA(), quantum_instance=qins)
optimizer = WarmStartQAOAOptimizer(
pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25
)
result = optimizer.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer
qaoa = QAOA(sampler=Sampler(), optimizer=COBYLA())
optimizer = WarmStartQAOAOptimizer(
pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25
)
result = optimizer.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import GroverOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, quantum_instance=qins)
result = optimizer.solve(problem)
print(result)
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import GroverOptimizer
optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, sampler=Sampler())
result = optimizer.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import GroverOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
try:
optimizer = GroverOptimizer(
num_value_qubits=3, num_iterations=3, quantum_instance=qins, sampler=Sampler()
)
# raises an error because both quantum_instance and sampler are set.
except ValueError as ex:
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.72" # Two Hydrogen atoms, 0.72 Angstrom apart
)
molecule = driver.run()
from qiskit_nature.second_q.mappers import QubitConverter, ParityMapper
qubit_converter = QubitConverter(ParityMapper())
hamiltonian = qubit_converter.convert(molecule.second_q_ops()[0])
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
sol = NumPyMinimumEigensolver().compute_minimum_eigenvalue(hamiltonian)
real_solution = molecule.interpret(sol)
real_solution.groundenergy
from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator"
from qiskit.algorithms.minimum_eigensolvers import VQE
# Use RealAmplitudes circuit to create trial states
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=2, reps=2)
# Search for better states using SPSA algorithm
from qiskit.algorithms.optimizers import SPSA
optimizer = SPSA(150)
# Set a starting point for reproduceability
import numpy as np
np.random.seed(6)
initial_point = np.random.uniform(-np.pi, np.pi, 12)
# Create an object to store intermediate results
from dataclasses import dataclass
@dataclass
class VQELog:
values: list
parameters: list
def update(self, count, parameters, mean, _metadata):
self.values.append(mean)
self.parameters.append(parameters)
print(f"Running circuit {count} of ~350", end="\r", flush=True)
log = VQELog([],[])
# Main calculation
with Session(service=service, backend=backend) as session:
options = Options()
options.optimization_level = 3
vqe = VQE(Estimator(session=session, options=options),
ansatz, optimizer, callback=log.update, initial_point=initial_point)
result = vqe.compute_minimum_eigenvalue(hamiltonian)
print("Experiment complete.".ljust(30))
print(f"Raw result: {result.optimal_value}")
if 'simulator' not in backend:
# Run once with ZNE error mitigation
options.resilience_level = 2
vqe = VQE(Estimator(session=session, options=options),
ansatz, SPSA(1), initial_point=result.optimal_point)
result = vqe.compute_minimum_eigenvalue(hamiltonian)
print(f"Mitigated result: {result.optimal_value}")
import matplotlib.pyplot as plt
plt.rcParams["font.size"] = 14
# Plot energy and reference value
plt.figure(figsize=(12, 6))
plt.plot(log.values, label="Estimator VQE")
plt.axhline(y=real_solution.groundenergy, color="tab:red", ls="--", label="Target")
plt.legend(loc="best")
plt.xlabel("Iteration")
plt.ylabel("Energy [H]")
plt.title("VQE energy")
plt.show()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from sympy import *
init_printing(use_unicode=True)
r1,r2,r3,s1,s2,s3 = symbols('r_1 r_2 r_3 s_1 s_2 s_3')
I = Matrix([[1,0],[0,1]]); X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]])
rho = (1/2)*(I+r1*X+r2*Y+r3*Z); sigma = (1/2)*(I+s1*X+s2*Y+s3*Z)
#rho, sigma
def frho(r1,r2,r3):
return (1/2)*(I+r1*X+r2*Y+r3*Z)
def fsigma(s1,s2,s3):
return (1/2)*(I+s1*X+s2*Y+s3*Z)
A = frho(r1,0,r2)*fsigma(0,s2,0)
simplify(A.eigenvals())
A = frho(0,0,r3); B = fsigma(s1,s2,0)
simplify(A*(B**2)*A - B*(A**2)*B)
M = A*B; simplify(M)
simplify(M.eigenvals()) # parecem ser positivos o que esta na raiz e o autovalores
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import re
import itertools
import numpy as np
import random
random.seed(42)
import mitiq
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.ignis.mitigation import expectation_value
# Pauli Twirling
def pauli_twirling(circ: QuantumCircuit) -> QuantumCircuit:
"""
[internal function]
This function takes a quantum circuit and return a new quantum circuit with Pauli Twirling around the CNOT gates.
Args:
circ: QuantumCircuit
Returns:
QuantumCircuit
"""
def apply_pauli(num: int, qb: int) -> str:
if (num == 0):
return f''
elif (num == 1):
return f'x q[{qb}];\n'
elif (num == 2):
return f'y q[{qb}];\n'
else:
return f'z q[{qb}];\n'
paulis = [(i,j) for i in range(0,4) for j in range(0,4)]
paulis.remove((0,0))
paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)]
new_circ = ''
ops = circ.qasm().splitlines(True) #! split the quantum circuit into qasm operators
for op in ops:
if (op[:2] == 'cx'): # add Pauli Twirling around the CNOT gate
num = random.randrange(len(paulis))
qbs = re.findall('q\[(.)\]', op)
new_circ += apply_pauli(paulis[num][0], qbs[0])
new_circ += apply_pauli(paulis[num][1], qbs[1])
new_circ += op
new_circ += apply_pauli(paulis_map[num][0], qbs[0])
new_circ += apply_pauli(paulis_map[num][1], qbs[1])
else:
new_circ += op
return QuantumCircuit.from_qasm_str(new_circ)
def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0], pt = False):
"""
This function outputs the circuit list for zero-noise extrapolation.
Args:
qcs: List[QuantumCircuit], the input quantum circuits.
scale_factors: List[float], to what extent the noise scales are investigated.
pt: bool, whether add Pauli Twirling or not.
Returns:
folded_qcs: List[QuantumCircuit]
"""
folded_qcs = [] #! ZNE用の回路
for qc in qcs:
folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用
folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化
if pt:
folded_qcs = [pauli_twirling(circ) for circ in folded_qcs]
return folded_qcs
def make_stf_basis(n, basis_elements = ["X","Y","Z"]):
"""
[internal function]
This function outputs all the combinations of length n string for given basis_elements.
When basis_elements is X, Y, and Z (default), the output becomes the n-qubit Pauli basis.
Args:
n: int
basis_elements: List[str]
Returns:
basis: List[str]
"""
if n == 1:
return basis_elements
basis = []
for i in basis_elements:
sub_basis = make_stf_basis(n - 1, basis_elements)
basis += [i + j for j in sub_basis]
return basis
def reduce_hist(hist, poses):
"""
[internal function]
This function returns the reduced histogram to the designated positions.
Args:
hist: Dict[str, float]
poses: List[int]
Returns:
ret_hist: Dict[str, float]
"""
n = len(poses)
ret_hist = {format(i, "0" + str(n) + "b"): 0 for i in range(1 << n)}
for k, v in hist.items():
pos = ""
for i in range(n):
pos += k[poses[i]]
ret_hist[pos] += v
return ret_hist
def make_stf_expvals(n, stf_hists):
"""
[internal function]
This function create the expectations under expanded basis, which are used to reconstruct the density matrix.
Args:
n: int, the size of classical register in the measurement results.
stf_hists: List[Dict[str, float]], the input State Tomography Fitter histograms.
Returns:
st_expvals: List[float], the output State Tomography expectation values.
"""
assert len(stf_hists) == 3 ** n
stf_basis = make_stf_basis(n, basis_elements=["X","Y","Z"])
st_basis = make_stf_basis(n, basis_elements=["I","X","Y","Z"])
stf_hists_dict = {basis: hist for basis, hist in zip(stf_basis, stf_hists)}
st_hists_dict = {basis: stf_hists_dict.get(basis, None) for basis in st_basis}
# remaining
for basis in sorted(set(st_basis) - set(stf_basis)):
if basis == "I" * n:
continue
reduction_poses = []
reduction_basis = ""
for i, b in enumerate(basis):
if b != "I":
reduction_poses.append(n - 1 - i) # big endian
reduction_basis += b # こっちはそのまま(なぜならラベルはlittle endianだから)
else:
reduction_basis += "Z"
st_hists_dict[basis] = reduce_hist(stf_hists_dict[reduction_basis], reduction_poses)
st_expvals = dict()
for basis, hist in st_hists_dict.items():
if basis == "I" * n:
st_expvals[basis] = 1.0
continue
st_expvals[basis], _ = expectation_value(hist)
return st_expvals
def zne_decoder(n, result, scale_factors=[1.0, 2.0, 3.0], fac_type="lin"):
"""
This function applies the zero-noise extrapolation to the measured results and output the mitigated zero-noise expectation values.
Args:
n: int, the size of classical register in the measurement results.
result: Result, the returned results from job.
scale_factors: List[float], this should be the same as the zne_wrapper.
fac_type: str, "lin" or "exp", whether to use LinFactory option or ExpFactory option in mitiq, to extrapolate the expectation values.
Returns:
zne_expvals: List[float], the mitigated zero-noise expectation values.
"""
hists = result.get_counts()
num_scale_factors = len(scale_factors)
assert len(hists) % num_scale_factors == 0
scale_wise_expvals = [] # num_scale_factors * 64
for i in range(num_scale_factors):
scale_wise_hists = [hists[3 * j + i] for j in range(len(hists) // num_scale_factors)]
st_expvals = make_stf_expvals(n, scale_wise_hists)
scale_wise_expvals.append( list(st_expvals.values()) )
scale_wise_expvals = np.array(scale_wise_expvals)
linfac = mitiq.zne.inference.LinearFactory(scale_factors)
expfac = mitiq.zne.ExpFactory(scale_factors)
zne_expvals = []
for i in range(4 ** n):
if fac_type == "lin":
zne_expvals.append( linfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) )
else:
zne_expvals.append( expfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) )
return zne_expvals
|
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.
"""
Module defining Amazon Braket conversion extras.
"""
from typing import TYPE_CHECKING
from qbraid_core._import import LazyLoader
from qbraid.transpiler.annotations import requires_extras
qiskit_braket_provider = LazyLoader("qiskit_braket_provider", globals(), "qiskit_braket_provider")
pytket_braket = LazyLoader("pytket_braket", globals(), "pytket.extensions.braket")
if TYPE_CHECKING:
import braket.circuits
import pytket.circuit
import qiskit.circuit
@requires_extras("qiskit_braket_provider")
def braket_to_qiskit(circuit: "braket.circuits.Circuit") -> "qiskit.circuit.QuantumCircuit":
"""Return a Qiskit quantum circuit from a Braket quantum circuit.
Args:
circuit (Circuit): Braket quantum circuit
Returns:
QuantumCircuit: Qiskit quantum circuit
"""
return qiskit_braket_provider.providers.adapter.to_qiskit(circuit)
@requires_extras("pytket.extensions.braket")
def braket_to_pytket(circuit: "braket.circuits.Circuit") -> "pytket.circuit.Circuit":
"""Returns a pytket circuit equivalent to the input Amazon Braket circuit.
Args:
circuit (braket.circuits.Circuit): Braket circuit to convert to a pytket circuit.
Returns:
pytket.circuit.Circuit: PyTKET circuit object equivalent to input Braket circuit.
"""
return pytket_braket.braket_convert.braket_to_tk(circuit)
|
https://github.com/adarshisme/QiskitBiskitGlobal
|
adarshisme
|
!pip install qiskit
!pip install matplotlib
!pip install sympy
from tqdm import tqdm
import numpy as np
import math
import qiskit
from qiskit import circuit
from qiskit.circuit.random import random_circuit
import copy
import matplotlib as mpl
import matplotlib.pyplot as plt
from qiskit.quantum_info import PTM, Chi, Statevector, DensityMatrix, partial_trace
from qiskit import transpile, QuantumCircuit, QuantumRegister
import qiskit.quantum_info as qi
from qiskit.providers.aer import AerSimulator
from qiskit.providers.aer.noise import NoiseModel, amplitude_damping_error
from qiskit.tools.visualization import plot_histogram
import sympy as sp
from sympy import linsolve, sympify, var, Eq, solve, solve_linear_system, Matrix, symbols
import random
def twirl_qubit(circ, dist=None, qubit=0, twirling_gate=None, r=None):
if not twirling_gate:
twirling_gate = (r.choice([i for i in range(4)], size=1, p=dist) if dist else r.choice([i for i in range(4)], size=1))[0]
# twirling_gate = random.randint(0, 3)
if twirling_gate == 1:
circ.x(qubit)
elif twirling_gate == 2:
circ.y(qubit)
elif twirling_gate == 3:
circ.z(qubit)
return twirling_gate
def sim(num_gates=100, noise=False, twirl=False, twirl_dist=[1, 0, 0, 0], circ=None, noise_AD=math.pi/9, noise_dephasing=math.pi/9, circ_seed=1, twirl_seed=1):
# twirl_set = {0: 'I', 1: 'X', 2: 'Y', 3: 'Z'}
np.random.seed(0)
circ_seed = 7654
rand_circ = np.random.RandomState()
rand_twirl = np.random.RandomState()
rand_circ.seed(circ_seed)
rand_twirl.seed(twirl_seed)
if not circ:
circ = QuantumCircuit(2)
circ.initialize([1, 0], 0)
circ.initialize([1, 0], 1)
random_gate_set = [i for i in range(3)] # and whatever other gates you want for the actual circuit
twirl_set = [i for i in range(3)] # and whatever other twirling gates you want
special_reg_AD = 1
special_reg_dephasing = 2
for i in range(num_gates):
random_gate = rand_circ.choice(random_gate_set)
random_theta = rand_circ.uniform(low=0, high=np.pi)
if random_gate == 0:
circ.rx(random_theta, 0)
elif random_gate == 1:
circ.ry(random_theta, 0)
elif random_gate == 2:
circ.rz(random_theta, 0)
#print(random_theta, end=' ')
# random_gate = np.random.choice([i for i in range(4)])
# if random_gate == 0:
# # circ.h(0)
# circ.z(0)
# elif random_gate == 1:
# circ.x(0)
# elif random_gate == 2:
# circ.y(0)
# elif random_gate == 3:
# circ.z(0)
# else:
# circ.s(0)
if noise:
if twirl:
twirling_gate = twirl_qubit(circ, dist=twirl_dist, r=rand_twirl)
# print(twirling_gate, end=' ')
# simulate noise on circuit
circ.cry(noise_AD, 0, special_reg_AD)
circ.cnot(special_reg_AD, 0)
special_reg_AD += 2
if twirl:
twirl_qubit(circ, dist=twirl_dist, twirling_gate=twirling_gate, r=rand_twirl)
twirling_gate = twirl_qubit(circ, dist=twirl_dist, r=rand_twirl)
circ.ry(noise_dephasing, special_reg_dephasing)
circ.cz(special_reg_dephasing, 0)
special_reg_dephasing += 2
if twirl:
twirl_qubit(circ, dist=twirl_dist, twirling_gate=twirling_gate, r=rand_twirl)
# boom
# circ.draw()
return circuit
def state_tomography(p):
I = np.trace(np.matmul(np.array([[1, 0],[0, 1]]), np.array(p)))
X = np.trace(np.matmul(np.array([[0, 1],[1, 0]]), np.array(p)))
Y = np.trace(np.matmul(np.array([[0, 0- 1j],[1j, 0]]), np.array(p)))
Z = np.trace(np.matmul(np.array([[1, 0],[0, -1]]), np.array(p)))
return np.array([I, X, Y, Z])
def equation_PTM(input_list, output_list):
I, X, Y, Z = var('I X Y Z')
I_o, X_o, Y_o, Z_o = var('I_o X_o Y_o Z_o')
eq = sp.Function('eq')
first = float(np.real(input_list[0])).__round__(4)*I
second = float(np.real(input_list[1])).__round__(4)*X
third = float(np.real(input_list[2])).__round__(4)*Y
fourth = float(np.real(input_list[3])).__round__(4)*Z
fifth = float(np.real(output_list[0])).__round__(4)*I_o
sixth = float(np.real(output_list[1])).__round__(4)*X_o
seventh = float(np.real(output_list[2])).__round__(4)*Y_o
eighth = float(np.real(output_list[3])).__round__(4)*Z_o
eq = Eq(first + second + third + fourth, fifth + sixth + seventh + eighth)
return eq
import random
# Function returns a list of 4 random distributions as a list - [i_dist, x_dist, y_dist, z_dist]
def gen_dist():
r = [random.random() for i in range(4)]
r_sum = sum(r)
r = [(i/r_sum) for i in r]
return r
def conjug_dists():
dists = []
for i in range(4):
dist = [0 for _ in range(4)]
dist[i] = 1
dists.append(dist)
return dists
conjug_dists()
runs = 1
noise_AD = math.pi/100
noise_dephasing = math.pi/100
def error():
t = np.array(PTM(True))
f = np.array(PTM(False))
ret = t - f
return ret
def fid(twirl_dist):
twirled, ideal = (PTM(noisy=True, twirl=True, twirl_dist=twirl_dist, noise_AD=noise_AD, noise_dephasing=noise_dephasing, ideal=False))
# print(t[0]) # t is a list of R matrices, of length [runs]
fid_sum = 0
for R_twirled, R_ideal in zip(twirled, ideal):
fid_sum += (np.trace(np.matmul(np.transpose(R_ideal), R_twirled)) + 2) / 6
fid_sum /= runs
# print(fid_sum)
return fid_sum
def ket(k):
k = str(k)
ket_dict = {'0': [1, 0], '1': [0, 1], '+': [1/math.sqrt(2), 1/math.sqrt(2)], '-': [1/math.sqrt(2), -1/math.sqrt(2)], 'i': [1/math.sqrt(2), 1j/math.sqrt(2)], '-i': [1/math.sqrt(2), -1j/math.sqrt(2)]}
return ket_dict[k]
def init_circ(num_qubits=13, qubit_0_init='0'):
circ0 = QuantumCircuit(num_qubits)
circ0.initialize(ket(qubit_0_init), 0)
for i in range(1, num_qubits):
circ0.initialize(ket('0'), i)
return circ0
def run(noisy, state='0', num_qubits=13, twirl=False, twirl_dist=None, noise_AD=0, noise_dephasing=0, circ_seed=1):
# print('state:', state)
partials = np.zeros(shape=(2, 2), dtype='complex128')
n = 0
partials = []
while n < runs:
circ0 = init_circ(num_qubits, qubit_0_init=state)
sim(num_gates=6, noise=noisy, circ=circ0, noise_AD=noise_AD, twirl=twirl, noise_dephasing=noise_dephasing, twirl_dist=twirl_dist, circ_seed=1, twirl_seed=10000+n)
state_in0 = Statevector.from_int(0, 2 ** 13)
state_out0 = state_in0.evolve(circ0)
rho_out0 = DensityMatrix(state_out0)
# print(np.array(partial_trace(rho_out0, [i for i in range(1, 13)])))
partials.append(np.array(partial_trace(rho_out0, [i for i in range(1, 13)])))
n += 1
return partials
def PTM(noisy=False, twirl=False, twirl_dist=None, noise_AD=noise_AD, noise_dephasing=noise_dephasing, ideal=False, circ_seed=1):
#print(locals())
# ket 0
partial_rho_out0s = run(noisy=noisy, state='0', num_qubits=13, twirl=twirl, twirl_dist=twirl_dist, noise_AD=noise_AD, noise_dephasing=noise_dephasing, circ_seed=circ_seed)
partial_rho_in0 = np.array([[1, 0], [0, 0]])
# ket 1
partial_rho_out1s = run(noisy=noisy, state='1', num_qubits=13, twirl=twirl, twirl_dist=twirl_dist, noise_AD=noise_AD, noise_dephasing=noise_dephasing, circ_seed=circ_seed)
partial_rho_in1 = np.array([[0, 0], [0, 1]])
# ket +
partial_rho_outXs = run(noisy=noisy, state='+', num_qubits=13, twirl=twirl, twirl_dist=twirl_dist, noise_AD=noise_AD, noise_dephasing=noise_dephasing, circ_seed=circ_seed)
partial_rho_inX = np.array([[0.5, 0.5], [0.5, 0.5]])
# ket i
partial_rho_outYs = run(noisy=noisy, state='i', num_qubits=13, twirl=twirl, twirl_dist=twirl_dist, noise_AD=noise_AD, noise_dephasing=noise_dephasing, circ_seed=circ_seed)
partial_rho_inY = np.array([[0.5, -0.5j], [0.5j, 0.5]])
eqs = []
for partial_rho_out0, partial_rho_out1, partial_rho_outX, partial_rho_outY in zip(partial_rho_out0s, partial_rho_out1s, partial_rho_outXs, partial_rho_outYs):
Eq1 = equation_PTM(state_tomography(partial_rho_in0), state_tomography(partial_rho_out0))
# print("1", Eq1)
Eq2 = equation_PTM(state_tomography(partial_rho_in1), state_tomography(partial_rho_out1))
# print("2", Eq2)
Eq3 = equation_PTM(state_tomography(partial_rho_inX), state_tomography(partial_rho_outX))
# print("3", Eq3)
Eq4 = equation_PTM(state_tomography(partial_rho_inY), state_tomography(partial_rho_outY))
# print("4", Eq4)
eqs.append((Eq1, Eq2, Eq3, Eq4))
I, X, Y, Z = var('I X Y Z')
I_o, X_o, Y_o, Z_o = var('I_o X_o Y_o Z_o')
solution_set = [linsolve([Eq1, Eq2, Eq3, Eq4], (I, X, Y, Z)) for Eq1, Eq2, Eq3, Eq4 in eqs]
I_o = np.array([[1, 0],[0, 1]])
X_o = np.array([[0, 1],[1, 0]])
Y_o = np.array([[0, 0- 1j],[1j, 0]])
Z_o = np.array([[1, 0],[0, -1]])
R_list = []
for solutions in solution_set:
solutions_list = list(solutions.args[0])
#convert sympy to numpy
solutions_list = eval(str(solutions_list))
# print(solutions_list)
reference_list = [I_o, X_o, Y_o, Z_o]
R = [[0 for i in range(4)] for j in range(4)]
for i in range(4):
for j in range(4):
sol_j = solutions_list[j]
ref_i = reference_list[i]
R[i][j] = 0.5*np.real(np.matmul(solutions_list[j], reference_list[i]).trace())
# print(R)
R_list.append(R)
# print('\nR:')
# print(R)
# print()
if not ideal:
return (R_list, PTM(noisy=True, twirl=True, twirl_dist=twirl_dist, noise_AD=0, noise_dephasing=0, ideal=True))
else:
return R_list
noise_AD *= 5
noise_dephasing *= 5
runs *= 2
data = {}
# runs = 1
# ideal_matrix = PTM(noisy=False, twirl=True, noise_AD=0, noise_dephasing=0, ideal=True)
# ideal_matrix
# dists = [gen_dist() for _ in range(5)]
# dists = conjug_dists() + [[0.25 for _ in range(4)]]
# dists = [[0.25 for i in range(4)]] + conjug_dists()
# for dist in (dists):
# data[tuple(dist)] = fid(dist)
# print(dist, data[tuple(dist)])
# sorted_data = list(map(lambda x: str(x) + ': ' + str(data[x]), reversed(sorted(data.keys(), key=lambda x: data[x]))))
# print(data)
def print_mat(mat):
for row in mat:
print(row)
runs = 1
#seed = 1
matrices = []
storage = []
for circ_seed in range(234, 235):
runs=1
ideal_matrix = PTM(noisy=False, twirl=True, noise_AD=0, noise_dephasing=0, ideal=True)[0]
print('ideal matrix for circ_seed', circ_seed, ':')
print_mat(ideal_matrix)
print()
runs=1
for noise_mult in range(5, 26, 5):
noise_AD = noise_mult * math.pi/100
#print("AD error angle =", noise_mult/100)
for noise_dephase_mult in range(5, 26, 5):
#print("Dephasing error angle=", noise_dephase_mult/100)
noise_dephasing = noise_dephase_mult * math.pi/100
noisy_mat = PTM(noisy=True, twirl=True, noise_AD=noise_AD, noise_dephasing=noise_dephasing, ideal=True)[0]
# just_AD_mat = PTM(noisy=True, twirl=True, noise_AD=noise_AD, noise_dephasing=0, ideal=True)[0]
matrices.append(noisy_mat)
storage.append((matrices[-1]))
#print(matrices[-1])
print(storage)
#returns a data set of matrices and takes in a numpy array a
# x = [1, 2, 3, 4, 5, 6, 7, 8]
# y = [0.6282, 0.5894, 0.485, 0.3457, 0.2083, 0.1015, 0.0366, 0.0079]
# plt.plot(x, y)
# plt.show()
dists = [gen_dist() for _ in range(5)]
for dist in (dists):
data[tuple(dist)] = fid(dist)
# print(dist, data[tuple(dist)])
sorted_data = list(map(lambda x: str(x) + ': ' + str(data[x]), reversed(sorted(data.keys(), key=lambda x: data[x]))))
#print(data)
# training = []
# dists = conjug_dists()
# for seed in range(10):
# for dist in dists:
# training.append(fid(twirl_dist=dist))
# training
|
https://github.com/mickahell/quantum_pokemon-fight
|
mickahell
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute
def quantum_attaq(attacker, defender, qc_type, backend_sim):
def diffuser(qc):
qc.h(qram_q)
qc.z(qram_q)
qc.cz(qram_q[0], qram_q[1])
qc.h(qram_q)
def or_weak(qc):
qc.barrier()
qc.cx(advweak_q[0], weakcheck_q[0])
qc.cx(advweak_q[1], weakcheck_q[0])
qc.ccx(advweak_q[1], advweak_q[0], weakcheck_q[0])
qc.barrier()
def or_resist(qc):
qc.barrier()
qc.cx(advresist_q[0], resistcheck_q[0])
qc.cx(advresist_q[1], resistcheck_q[0])
qc.ccx(advresist_q[1], advresist_q[0], resistcheck_q[0])
qc.barrier()
def immunite(defender, qc):
for i in defender.types:
if i.imunite[0] != "None":
qc.cx(i.imunite[0].qubit, immu_q)
def calcul_resist(defender, qc):
resist_count = 0
for i in defender.types:
for u in i.resistance:
if i.resistance[0] != "None":
qc.cx(u.qubit, advresist_q[resist_count])
resist_count += 1
def calcul_weak(defender, qc):
weak_count = 0
for i in defender.types:
for u in i.weakness:
if i.weakness[0] != "None":
qc.cx(u.qubit, advweak_q[weak_count])
weak_count += 1
def qram_att(attacker, qc):
# 00
qc.x(qram_q)
qc.ccx(qram_q[0], qram_q[1], attacker.attacks[0].type.qubit)
qc.x(qram_q)
# 01
qc.x(qram_q[1])
qc.ccx(qram_q[0], qram_q[1], attacker.attacks[1].type.qubit)
qc.x(qram_q[1])
# 10
qc.x(qram_q[0])
qc.ccx(qram_q[0], qram_q[1], attacker.attacks[2].type.qubit)
qc.x(qram_q[0])
# 11
qc.ccx(qram_q[0], qram_q[1], attacker.attacks[3].type.qubit)
qram_q = QuantumRegister(2, "attacks")
qc_qram = QuantumCircuit(qram_q)
advweak_q = QuantumRegister(2, "weakness_map")
weakcheck_q = QuantumRegister(1, "check_weakness")
advresist_q = QuantumRegister(2, "resistance_map")
resistcheck_q = QuantumRegister(1, "check_resistance")
immu_q = QuantumRegister(1, "immunity")
qc_weak = QuantumCircuit(advweak_q, weakcheck_q, advresist_q, resistcheck_q, immu_q)
check_q = QuantumRegister(1, "check")
out_q = QuantumRegister(1, "flag")
c = ClassicalRegister(2, "c")
qc_c = QuantumCircuit(check_q, out_q, c)
# Circuit final
qc = qc_qram + qc_type + qc_weak + qc_c
# Init
qc.h(qram_q)
qc.x(immu_q)
qc.x(resistcheck_q)
qc.x(out_q)
qc.h(out_q)
qc.barrier()
for i in range(1):
# Compute
qram_att(attacker, qc)
calcul_weak(defender, qc)
calcul_resist(defender, qc)
or_weak(qc)
or_resist(qc)
immunite(defender, qc)
# Flag
qc.mcx([weakcheck_q, resistcheck_q, immu_q], check_q)
qc.cx(check_q, out_q)
qc.mcx([weakcheck_q, resistcheck_q, immu_q], check_q)
# Uncompute
immunite(defender, qc)
or_resist(qc)
or_weak(qc)
calcul_resist(defender, qc)
calcul_weak(defender, qc)
qram_att(attacker, qc)
# Apply generic diffuser
diffuser(qc)
qc.measure(qram_q, c)
# Interprete result
job = execute(qc, backend_sim, shots=512, memory=True)
result_job = job.result().get_counts()
result_memory = job.result().get_memory()
if len(result_job) == 1:
to_return = int(result_memory[0], 2)
else:
to_return = max(result_job, key=result_job.get)
to_return = int(to_return, 2)
return to_return
def quantum_action(defender, attacker, qc_type, backend_sim):
def diffuser(qc):
qc.h(qram_q)
qc.z(qram_q)
qc.cz(qram_q[0], qram_q[1])
qc.h(qram_q)
def immunite(defender, qc):
for i in defender.types:
if i.imunite[0] != "None":
qc.cx(i.imunite[0].qubit, immu_q)
def calcul_resist(defender, qc):
resist_count = 0
for i in defender.types:
for u in i.resistance:
if i.resistance[0] != "None":
qc.cx(u.qubit, resist_q[resist_count])
resist_count += 1
def calcul_weak(defender, qc):
weak_count = 0
for i in defender.types:
for u in i.weakness:
if i.weakness[0] != "None":
qc.cx(u.qubit, weak_q[weak_count])
weak_count += 1
def or_weak(qc):
qc.barrier()
qc.cx(weak_q[0], weakcheck_q[0])
qc.cx(weak_q[1], weakcheck_q[0])
qc.ccx(weak_q[1], weak_q[0], weakcheck_q[0])
qc.barrier()
def qram_att(attacker, qc):
# 00
qc.x(qram_q)
qc.ccx(qram_q[0], qram_q[1], attacker.types[0].qubit)
qc.x(qram_q)
# 11
if len(attacker.types) > 1:
qc.ccx(qram_q[0], qram_q[1], attacker.types[1].qubit)
qram_q = QuantumRegister(2, "attacks")
qc_qram = QuantumCircuit(qram_q)
weak_q = QuantumRegister(2, "weakness_map")
weakcheck_q = QuantumRegister(1, "check_weakness")
resist_q = QuantumRegister(2, "resistance_map")
immu_q = QuantumRegister(1, "immunity")
qc_weak = QuantumCircuit(weak_q, weakcheck_q, resist_q, immu_q)
check_q = QuantumRegister(1, "check")
out_q = QuantumRegister(1, "flag")
c = ClassicalRegister(2, "c")
qc_c = QuantumCircuit(check_q, out_q, c)
# Circuit final
qc = qc_qram + qc_type + qc_weak + qc_c
# Init
qc.h(qram_q)
qc.x(resist_q)
qc.x(immu_q)
qc.x(out_q)
qc.h(out_q)
qc.barrier()
for i in range(1):
# Compute
qram_att(attacker, qc)
calcul_weak(defender, qc)
calcul_resist(defender, qc)
or_weak(qc)
immunite(defender, qc)
# Flag
qc.mcx([weakcheck_q, resist_q[0], resist_q[1], immu_q], check_q)
qc.cx(check_q, out_q)
qc.mcx([weakcheck_q, resist_q[0], resist_q[1], immu_q], check_q)
# Uncompute
immunite(defender, qc)
or_weak(qc)
calcul_resist(defender, qc)
calcul_weak(defender, qc)
qram_att(attacker, qc)
# Apply generic diffuser
diffuser(qc)
qc.measure(qram_q, c)
# Interprete result
job = execute(qc, backend_sim, shots=512, memory=True)
result_job = job.result().get_counts()
if len(result_job) == 1:
to_return = 1
else:
to_return = 0
return to_return
def quantum_switch(attacker, defender, qc_type, backend_sim):
def diffuser(nqubits):
qc = QuantumCircuit(nqubits)
for qubit in range(nqubits):
qc.h(qubit)
for qubit in range(nqubits):
qc.x(qubit)
qc.h(nqubits - 1)
qc.mct(list(range(nqubits - 1)), nqubits - 1)
qc.h(nqubits - 1)
for qubit in range(nqubits):
qc.x(qubit)
for qubit in range(nqubits):
qc.h(qubit)
U_s = qc.to_gate()
U_s.name = "$U_s$"
return qc
def immunite(defender, qc):
for i in defender.types:
if i.imunite[0] != "None":
qc.cx(i.imunite[0].qubit, immu_q)
def calcul_resist(defender, qc):
resist_count = 0
for i in defender.types:
for u in i.resistance:
if i.resistance[0] != "None":
qc.cx(u.qubit, resist_q[resist_count])
resist_count += 1
def calcul_weak(defender, qc):
weak_count = 0
for i in defender.types:
for u in i.weakness:
if i.weakness[0] != "None":
qc.cx(u.qubit, weak_q[weak_count])
weak_count += 1
def or_weak(qc):
qc.barrier()
qc.cx(weak_q[0], weakcheck_q[0])
qc.cx(weak_q[1], weakcheck_q[0])
qc.ccx(weak_q[1], weak_q[0], weakcheck_q[0])
qc.barrier()
def qram_att(attacker, qc):
# 0
qc.x(qrampoke_q)
# 00 0
qc.x(qramatt_q)
qc.mcx(
[qrampoke_q[0], qramatt_q[0], qramatt_q[1]],
attacker[0].attacks[0].type.qubit,
)
qc.x(qramatt_q)
# 01 0
qc.x(qramatt_q[1])
qc.mcx(
[qrampoke_q[0], qramatt_q[0], qramatt_q[1]],
attacker[0].attacks[1].type.qubit,
)
qc.x(qramatt_q[1])
# 10 0
qc.x(qramatt_q[0])
qc.mcx(
[qrampoke_q[0], qramatt_q[0], qramatt_q[1]],
attacker[0].attacks[2].type.qubit,
)
qc.x(qramatt_q[0])
# 11 0
qc.mcx(
[qrampoke_q[0], qramatt_q[0], qramatt_q[1]],
attacker[0].attacks[3].type.qubit,
)
qc.x(qrampoke_q)
# 1
if len(attacker) > 1:
# 00 1
qc.x(qramatt_q)
qc.mcx(
[qrampoke_q[0], qramatt_q[0], qramatt_q[1]],
attacker[1].attacks[0].type.qubit,
)
qc.x(qramatt_q)
# 01 1
qc.x(qramatt_q[1])
qc.mcx(
[qrampoke_q[0], qramatt_q[0], qramatt_q[1]],
attacker[1].attacks[1].type.qubit,
)
qc.x(qramatt_q[1])
# 10 1
qc.x(qramatt_q[0])
qc.mcx(
[qrampoke_q[0], qramatt_q[0], qramatt_q[1]],
attacker[1].attacks[2].type.qubit,
)
qc.x(qramatt_q[0])
# 11 1
qc.mcx(
[qrampoke_q[0], qramatt_q[0], qramatt_q[1]],
attacker[1].attacks[3].type.qubit,
)
qrampoke_q = QuantumRegister(1, "team")
qramatt_q = QuantumRegister(2, "attacks")
qc_qram = QuantumCircuit(qrampoke_q, qramatt_q)
weak_q = QuantumRegister(2, "weakness_map")
weakcheck_q = QuantumRegister(1, "check_weakness")
resist_q = QuantumRegister(2, "resistance_map")
immu_q = QuantumRegister(1, "immunite")
qc_weak = QuantumCircuit(weak_q, weakcheck_q, resist_q, immu_q)
check_q = QuantumRegister(1, "check")
out_q = QuantumRegister(1, "flag")
c = ClassicalRegister(1, "c")
qc_c = QuantumCircuit(check_q, out_q, c)
# Circuit final
qc = qc_qram + qc_type + qc_weak + qc_c
# Init
qc.h(qrampoke_q)
qc.h(qramatt_q)
qc.x(resist_q)
qc.x(immu_q)
qc.x(out_q)
qc.h(out_q)
qc.barrier()
for i in range(1):
# Compute
qram_att(attacker, qc)
calcul_weak(defender, qc)
calcul_resist(defender, qc)
or_weak(qc)
immunite(defender, qc)
# Flag
qc.mcx([weakcheck_q, resist_q[0], resist_q[1], immu_q], check_q)
qc.cx(check_q, out_q)
qc.mcx([weakcheck_q, resist_q[0], resist_q[1], immu_q], check_q)
# Uncompute
immunite(defender, qc)
or_weak(qc)
calcul_resist(defender, qc)
calcul_weak(defender, qc)
qram_att(attacker, qc)
# Apply generic diffuser
qc.append(diffuser(3), [0, 1, 2])
qc.measure(qrampoke_q, c)
# Interprete result
job = execute(qc, backend_sim, shots=512, memory=True)
result_job = job.result().get_counts()
result_memory = job.result().get_memory()
if len(result_job) == 1:
to_return = int(result_memory[0], 2)
else:
to_return = max(result_job, key=result_job.get)
to_return = int(to_return, 2)
return to_return
|
https://github.com/DavidFitzharris/EmergingTechnologies
|
DavidFitzharris
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
# Constant Oracle
const_oracle = QuantumCircuit(n+1)
# Random output
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw()
# Balanced Oracle
balanced_oracle = QuantumCircuit(n+1)
# Binary string length
b_str = "101"
# For each qubit in our circuit
# we place an X-gate if the corresponding digit in b_str is 1
# or do nothing if the digit is 0
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw()
# Creating the controlled-NOT gates
# using each input qubit as a control
# and the output as a target
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Wrapping the controls in X-gates
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw()
# Viewing the output
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a DensityMatrix
state = DensityMatrix(qc)
plot_state_city(state)
|
https://github.com/sooodos/Quantum-Computing-Learning-Gate
|
sooodos
|
from qiskit import QuantumCircuit
from QCLG_lvl3.oracles.cnot_oracle import CnotOracle
class DeutschJosza:
@classmethod
def deutsch_josza(cls, bit_string: str, eval_mode: bool) -> QuantumCircuit:
n = len(bit_string)
dj_circuit = QuantumCircuit(n + 1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put output qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Construct balanced oracle
balanced_oracle = CnotOracle.create_cnot_oracle(bit_string, n, eval_mode)
# Add oracle
dj_circuit += balanced_oracle
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
if not eval_mode:
print(dj_circuit)
# return circuit
return dj_circuit
|
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
Q_program = QuantumProgram()
#Q_program.set_api(Qconfig.APItoken, Qconfig.config['url'])
"Choice of the backend"
backend = 'local_qasm_simulator' #can be very slow when number of shoots increases
#backend = 'ibmqx_hpc_qasm_simulator'
print("Your choice for the backend is: ", backend)
# 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])
#"CIRCUITS"
q = Q_program.create_quantum_register("q", 16)
c = Q_program.create_classical_register("c", 16)
twin = Q_program.create_circuit("twin", [q], [c])
# First W state
twin.x(q[14])
F_gate(twin,q,14,3,3,1)
F_gate(twin,q,3,2,3,2)
twin.cx(q[3],q[14])
twin.cx(q[2],q[3])
#Second W state
twin.x(q[12])
F_gate(twin,q,12,5,3,1)
F_gate(twin,q,5,6,3,2)
cxrv(twin,q,5,12)
twin.cx(q[6],q[5])
#Coin tossing
twin.h(q[0])
twin.h(q[1])
switch1 = Q_program.create_circuit('switch1',[q],[c])
#Stick or switch
switch1.h(q[13])
for i in range (4) :
switch1.measure(q[i] , c[i]);
for i in range (5,7) :
switch1.measure(q[i] , c[i]);
for i in range (12,15) :
switch1.measure(q[i] , c[i]);
Q_program.add_circuit("AliceBob", twin+switch1)
Label = ["left", "central", "right"]
wstates = 0
while wstates != 1:
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print("Alice vs Bob", "backend=", backend, "starting time", time_exp)
result = Q_program.execute("AliceBob", backend=backend, shots=1, max_credits=5, wait=5, timeout=120)
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print("Alice vs Bob", "backend=", backend, " end time", time_exp)
cstr = str(result.get_counts("AliceBob"))
nb_of_cars = int(cstr[3]) + int(cstr[14]) + int(cstr[15])
nb_of_doors = int(cstr[12]) + int(cstr[11]) + int(cstr[5])
wstates = nb_of_cars * nb_of_doors
print(" ")
print('Alice: One car and two goats are now hidden behind these doors.')
print(' Which door do you choose?')
print(" ")
"Chosing the left door"
if int(cstr[5]) == 1:
Doorchosen = 1
"Chosing the center door"
if int(cstr[11]) == 1:
Doorchosen = 2
"Chosing the right door"
if int(cstr[12]) == 1:
Doorchosen = 3
time.sleep(2)
print('Bob: My choice is the',Label[Doorchosen-1], "door")
print(" ")
randomnb = int(cstr[16]) + int(cstr[17]) %2
if cstr[3] == "1": #car behind left door
Doorwinning = 1
if Doorchosen == 1:
Dooropen = 2 + randomnb
Doorswitch = 3 - randomnb
if Doorchosen == 2:
Dooropen = 3
Doorswitch = 1
if Doorchosen == 3:
Dooropen = 2
Doorswitch = 1
if cstr[14] == "1": #car behind central door
Doorwinning = 2
if Doorchosen == 2:
Dooropen = 1 + 2*randomnb
Doorswitch = 3 - 2*randomnb
if Doorchosen == 1:
Dooropen = 3
Doorswitch = 2
if Doorchosen == 3:
Dooropen = 1
Doorswitch = 2
if cstr[15] == "1": #car behind right door
Doorwinning = 3
if Doorchosen == 3:
Dooropen = randomnb + 1
Doorswitch = 2 - randomnb
if Doorchosen == 1:
Dooropen = 2
Doorswitch = 3
if Doorchosen == 2:
Dooropen = 1
Doorswitch = 3
time.sleep(2)
print('Alice: Now I open the', Label[Dooropen-1], 'door and you see a goat')
time.sleep(2)
print(' You get an opportunity to change your choice!')
time.sleep(2)
print(' Do you want to switch for the',Label[Doorswitch-1], "door?")
print(" ")
time.sleep(2)
switch_flag = int(cstr[4])
"BOB STICKS WITH HIS FIRST CHOICE!"
if switch_flag == 0:
Doorfinal = Doorchosen
print('Bob: I stick with my first choice, the',Label[Doorfinal-1], "door")
"BOB CHANGES HIS MIND!"
if switch_flag == 1:
Doorfinal = Doorswitch
print('Bob: I change my mind and choose the',Label[Doorfinal-1], "door")
"FINAL ANNOUNCE"
if Doorfinal == Doorwinning:
endmessage = 'won the car! Congratulations!'
else:
endmessage = 'won a goat! Sorry!'
time.sleep(2)
print()
print('Alice: You opened the',Label[Doorfinal-1],'door and', endmessage)
print("Game over")
#Toffoli gates
Toffoli = Q_program.create_circuit('Toffoli',[q],[c])
Toffoli.ccx(q[3], q[5], q[4])
Toffoli.swap(q[2],q[3])
Toffoli.swap(q[6],q[5])
Toffoli.ccx(q[3], q[5], q[4])
Toffoli.swap(q[3],q[14])
Toffoli.swap(q[12],q[5])
Toffoli.ccx(q[3], q[5], q[4])
# A general solution with 50% switching strategy
switch_fifty_percent = Q_program.create_circuit('switch_fifty_percent',[q],[c])
#switch flag
switch_fifty_percent.h(q[13])
switch_fifty_percent.cx(q[13],q[4])
switch_fifty_percent.measure(q[4] , c[4]);
switch_fifty_percent.measure(q[13] , c[13]);
Q_program.add_circuit("general_solution", twin+Toffoli+switch_fifty_percent)
circuits = ['general_solution']
shots = 1024
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print(backend, "shots", shots, "starting time", time_exp)
result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=30, timeout=600)
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print(backend, "shots", shots, "end time", time_exp)
plot_histogram(result.get_counts("general_solution"))
print(result.get_counts("general_solution"))
observable_stickwon = {'0000000000010000': 1, '0010000000010000': 0, '0010000000000000': 0, '0000000000000000': 0}
observable_switchwon = {'0000000000010000': 0, '0010000000010000': 1, '0010000000000000': 0, '0000000000000000': 0}
observable_stickall = {'0000000000010000': 1, '0010000000010000': 0, '0010000000000000': 0, '0000000000000000': 1}
observable_switchall = {'0000000000010000': 0, '0010000000010000': 1, '0010000000000000': 1, '0000000000000000': 0}
stickwon = result.average_data("general_solution",observable_stickwon)
switchwon = result.average_data("general_solution",observable_switchwon)
stickall = result.average_data("general_solution",observable_stickall)
switchall = result.average_data("general_solution",observable_switchall)
print("Proportion sticking: %6.2f " % stickall)
print("Proportion switching: %6.2f " % switchall)
stickwon_stickall = stickwon/stickall
switchwon_switchall = switchwon/switchall
print("Proportion winning when sticking: %6.2f " % stickwon_stickall)
print("Proportion winning when switching: %6.2f " % switchwon_switchall)
# Illustrating different strategies
xdat = []
ydat = []
observable = {'0000000000000000': 0, '0000000000010000': 1}
shots = 1024
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print(backend, "shots", shots, "starting time", time_exp)
for i in range(9) :
strategies = Q_program.create_circuit('strategies',[q],[c])
Prob = i/8
lambda_s = 2*np.arcsin(np.sqrt(Prob))
strategies.rx(lambda_s,q[13])
strategies.cx(q[13],q[4])
strategies.measure(q[4] , c[4]);
statploti = "statplot"+str(i)
Q_program.create_circuit("statploti",[q],[c])
Q_program.add_circuit("statploti",twin+Toffoli+strategies)
result = Q_program.execute("statploti", backend=backend, shots=shots, max_credits=5, wait=30, timeout=600)
loop_average=(result.average_data("statploti",observable))
print(statploti," Proportion switching: %6.3f" % Prob, " Proportion winning: %6.2f" % loop_average)
ydat.append(loop_average)
xdat.append(Prob)
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print(backend, "shots", shots, "end time", time_exp)
plt.plot(xdat, ydat, 'ro')
plt.grid()
plt.ylabel('Probability of Winning', fontsize=12)
plt.xlabel(r'Probability of Switching', fontsize=12)
plt.show()
print("Our Advice: \n")
y_aver = []
for j in range(0,7,3) :
y_aver.append((ydat[j] + ydat[j+1] +ydat[j+2])/3)
if y_aver[0] == max(y_aver) :
print(" Thou Shalt Not Switch")
elif y_aver[2] == max(y_aver) :
print(" Thou Shalt Not Stick")
else:
print(" Just follow the intuition of the moment")
%run "../version.ipynb"
|
https://github.com/duartefrazao/Quantum-Finance-Algorithms
|
duartefrazao
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 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.
import numpy as np
from functools import reduce
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.quantum_info import Pauli
from qiskit.aqua import Operator
class QAOAVarForm:
"""Global X phases and parameterized problem hamiltonian."""
def __init__(self, cost_operator, p, initial_state=None, mixer_operator=None):
self._cost_operator = cost_operator
self._p = p
self._initial_state = initial_state
self.num_parameters = 2 * p
self.parameter_bounds = [(0, np.pi)] * p + [(0, 2 * np.pi)] * p
self.preferred_init_points = [0] * p * 2
# prepare the mixer operator
v = np.zeros(self._cost_operator.num_qubits)
ws = np.eye(self._cost_operator.num_qubits)
if mixer_operator is None:
self._mixer_operator = reduce(
lambda x, y: x + y,
[
Operator([[1, Pauli(v, ws[i, :])]])
for i in range(self._cost_operator.num_qubits)
]
)
else:
if not type(mixer_operator) == Operator:
raise TypeError('The mixer should be a qiskit.aqua.Operator '
+ 'object, found {} instead'.format(type(mixer_operator)))
self._mixer_operator = mixer_operator
def construct_circuit(self, angles):
if not len(angles) == self.num_parameters:
raise ValueError('Incorrect number of angles: expecting {}, but {} given.'.format(
self.num_parameters, len(angles)
))
circuit = QuantumCircuit()
if self._initial_state:
circuit += self._initial_state.construct_circuit('circuit')
if len(circuit.qregs) == 0:
q = QuantumRegister(self._cost_operator.num_qubits, name='q')
circuit.add_register(q)
elif len(circuit.qregs) == 1:
q = circuit.qregs[0]
else:
raise NotImplementedError
circuit.u2(0, np.pi, q)
for idx in range(self._p):
beta, gamma = angles[idx], angles[idx + self._p]
circuit += self._cost_operator.evolve(
evo_time=gamma, evo_mode='circuit', num_time_slices=1, quantum_registers=q
)
circuit += self._mixer_operator.evolve(
evo_time=beta, evo_mode='circuit', num_time_slices=1, quantum_registers=q
)
return circuit
@property
def setting(self):
ret = "Variational Form: {}\n".format(self.__class__.__name__)
params = ""
for key, value in self.__dict__.items():
if key != "_configuration" and key[0] == "_":
params += "-- {}: {}\n".format(key[1:], value)
ret += "{}".format(params)
return ret
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import *
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit $q_{0}$, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{1}$, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{2}$, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
circ.draw('mpl')
# Import Aer
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = backend.run(circ)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
from qiskit.visualization import plot_state_city
plot_state_city(outputstate)
# Run the quantum circuit on a unitary simulator backend
backend = Aer.get_backend('unitary_simulator')
job = backend.run(circ)
result = job.result()
# Show the results
print(result.get_unitary(circ, decimals=3))
# Create a Quantum Circuit
meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
# map the quantum measurement to the classical bits
meas.measure(range(3), range(3))
# The Qiskit circuit object supports composition using
# the compose method.
circ.add_register(meas.cregs[0])
qc = circ.compose(meas)
#drawing the circuit
qc.draw()
# Use Aer's qasm_simulator
backend_sim = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = backend_sim.run(transpile(qc, backend_sim), shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import NormalDistribution
# can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example.
A = np.eye(2)
b = np.zeros(2)
# specify the number of qubits that are used to represent the different dimenions of the uncertainty model
num_qubits = [2, 2]
# specify the lower and upper bounds for the different dimension
low = [0, 0]
high = [0.12, 0.24]
mu = [0.12, 0.24]
sigma = 0.01 * np.eye(2)
# construct corresponding distribution
bounds = list(zip(low, high))
u = NormalDistribution(num_qubits, mu, sigma, bounds)
# plot contour of probability density function
x = np.linspace(low[0], high[0], 2 ** num_qubits[0])
y = np.linspace(low[1], high[1], 2 ** num_qubits[1])
z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1])
plt.contourf(x, y, z)
plt.xticks(x, size=15)
plt.yticks(y, size=15)
plt.grid()
plt.xlabel("$r_1$ (%)", size=15)
plt.ylabel("$r_2$ (%)", size=15)
plt.colorbar()
plt.show()
# specify cash flow
cf = [1.0, 2.0]
periods = range(1, len(cf) + 1)
# plot cash flow
plt.bar(periods, cf)
plt.xticks(periods, size=15)
plt.yticks(size=15)
plt.grid()
plt.xlabel("periods", size=15)
plt.ylabel("cashflow ($)", size=15)
plt.show()
# estimate real value
cnt = 0
exact_value = 0.0
for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])):
for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])):
prob = u.probabilities[cnt]
for t in range(len(cf)):
# evaluate linear approximation of real value w.r.t. interest rates
exact_value += prob * (
cf[t] / pow(1 + b[t], t + 1)
- (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2)
)
cnt += 1
print("Exact value: \t%.4f" % exact_value)
# specify approximation factor
c_approx = 0.125
# create fixed income pricing application
from qiskit_finance.applications.estimation import FixedIncomePricing
fixed_income = FixedIncomePricing(
num_qubits=num_qubits,
pca_matrix=A,
initial_interests=b,
cash_flow=cf,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=u,
)
fixed_income._objective.draw()
fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits)
# load probability distribution
fixed_income_circ.append(u, range(u.num_qubits))
# apply function
fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits))
fixed_income_circ.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
# construct amplitude estimation
problem = fixed_income.to_estimation_problem()
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (fixed_income.interpret(result)))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### replaced cx gate ###
qc.cy(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/dcavar/q
|
dcavar
|
!pip install -U qiskit
!pip install -U qiskit_ibm_provider
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile
from qiskit_ibm_provider import IBMProvider
from secret import api_key_ibm_q
provider = IBMProvider(token=api_key_ibm_q)
backends = provider.backends()
print(backends)
backend = provider.get_backend('ibm_brisbane')
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
circuit = QuantumCircuit(q,c)
circuit.h(q)
circuit.measure(q,c)
new_circuit = transpile(circuit, backend)
job = backend.run(new_circuit, shots=1, memory=True)
status = backend.status()
print(status.operational)
print(status.pending_jobs)
res = job.result()
print('Result:', res)
|
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
|
ronitd2002
|
# please create a 3 qubit GHZ circuit
# please create a 2 qubit ch gate with only cx and ry gate
# Enter your prompt here - Delete this line
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
# For Jupyter Notebooks
%config InlineBackend.figure_format = 'svg' # Makes the images look nice
from qiskit_textbook.widgets import binary_widget
binary_widget(nbits=5)
n = 8
n_q = n
n_b = n
qc_output = QuantumCircuit(n_q,n_b)
for j in range(n):
qc_output.measure(j,j)
qc_output.draw(output='mpl')
counts = execute(qc_output,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
qc_encode = QuantumCircuit(n)
qc_encode.x(7)
qc_encode.draw(output='mpl')
qc = qc_encode + qc_output
qc.draw(output='mpl',justify='none')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
qc_encode = QuantumCircuit(n)
qc_encode.x(1)
qc_encode.x(5)
qc_encode.draw(output='mpl')
qc_cnot = QuantumCircuit(2)
qc_cnot.cx(0,1)
qc_cnot.draw(output='mpl')
qc = QuantumCircuit(2,2)
qc.x(0)
qc.cx(0,1)
qc.measure(0,0)
qc.measure(1,1)
qc.draw(output='mpl')
qc_ha = QuantumCircuit(4,2)
# encode inputs in qubits 0 and 1
qc_ha.x(0) # For a=0, remove this line. For a=1, leave it.
qc_ha.x(1) # For b=0, remove this line. For b=1, leave it.
qc_ha.barrier()
# use cnots to write the XOR of the inputs on qubit 2
qc_ha.cx(0,2)
qc_ha.cx(1,2)
qc_ha.barrier()
# extract outputs
qc_ha.measure(2,0) # extract XOR value
qc_ha.measure(3,1)
qc_ha.draw(output='mpl')
qc_ha = QuantumCircuit(4,2)
# encode inputs in qubits 0 and 1
qc_ha.x(0) # For a=0, remove the this line. For a=1, leave it.
qc_ha.x(1) # For b=0, remove the this line. For b=1, leave it.
qc_ha.barrier()
# use cnots to write the XOR of the inputs on qubit 2
qc_ha.cx(0,2)
qc_ha.cx(1,2)
# use ccx to write the AND of the inputs on qubit 3
qc_ha.ccx(0,1,3)
qc_ha.barrier()
# extract outputs
qc_ha.measure(2,0) # extract XOR value
qc_ha.measure(3,1) # extract AND value
qc_ha.draw(output='mpl')
counts = execute(qc_ha,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/PAYAL980/Four-Algorithms-in-Qiskit
|
PAYAL980
|
# Importing libraries and necessary tools
from qiskit import *
import numpy as np
import math
import random
from qiskit.visualization import plot_histogram
from qiskit.providers.fake_provider import FakeJakarta, FakeBelem
""" Defining an almost general oracle for the algorithm"""
def oracle(N, case):
# Creating a quantum circuit with N input qubits and 1 helper qubits
qc = QuantumCircuit(N+1)
# Create an oracle based on the type of the function
m = random.randint(0,1) # Creating a random bit to make the decision process random
if(case == 'balanced') and (m == 0):
for iz in range(N):
qc.cx(iz,N) # Balanced function type 1
elif (case == 'balanced') and (m == 1):
qc.x(0)
for iz in range(N):
qc.cx(iz,N) # Balanced oracle flips helper qubit when the 0th qubit is 0
qc.x(0) # Balanced function type 2
elif (case == 'constant') and (m == 0):
qc.x(N) # Applying X gate on the (N+1)th qubit
# Constant function type 1
else:
qc.i(N) # Applying identity on the (N+1)th qubit
# Constant function type 1
return qc
# Checking the oracle function for 2 bits and type of function equal to balanced
cir = oracle(2, 'balanced')
cir.draw('mpl')
""" Defining a function for Deutsch-Jozsa algorithm
Input: N - Number of bits in the input string for the function to be determined
oracle1- black box encoding the function to be determined
Output: qc - the quantum circuit to be run on a simulator to get the final output """
def DJ_algo_gen(N, oracle1):
# Create a quantum circuit of 'N+1' qubits where N is the number of bits in the input bitstring
qc = QuantumCircuit(N+1, N)
# Apply X gate on the helper qubit to change it's state from 0 to 1
qc.x(N)
qc.barrier() # Barrier for better visualization
# Apply Hadamard gates on all qubits to create superposition and access all the possible cases at same time
qc.h(range(0,N+1))
qc.barrier() # Barrier for better visualization
# Apply the oracle for the funtion to the quantum circuit
qc.append(oracle1, range(N+1))
qc.barrier() # Barrier for better visualization
# Apply Hadamard gates to all qubits
qc.h(range(N+1))
qc.barrier() # Barrier for better visualization
# Measure first N qubits to find if the function is constant or balanced
qc.measure(range(N), range(N))
return qc
# Testing the algorithm for n=2 and constant function
ora = oracle(2, 'constant')
q1 = DJ_algo_gen(2, ora)
q1.draw('mpl')
# Running on non-noisy simulator 1
backend = Aer.get_backend('aer_simulator')
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
plot_histogram(counts)
# Running on non-noisy simulator 2
backend = Aer.get_backend('qasm_simulator')
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
plot_histogram(counts)
# Running on noisy simulator 1
backend = FakeJakarta()
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
plot_histogram(counts)
# Running on noisy simulator 2
backend = FakeBelem()
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
plot_histogram(counts)
# Defining a function that gives the output directly without running many cells
# N - number of bits in input bit string
# case - type of function to be given as a string either 'constant' or 'balanced'
# sim: simulator on which you want to run the algorithm
#. - 1: non-noisy aer simulator
# 2: non-noisy qasm simulator
# 3: noisy simulator FakeJakarta
# 4: noisy simulator FakeBelem
# Output: counts, if maximum counts is for '0'*N, the function is constant
# if maximum counts is for '1'*N, the function is balanced
def run(N, case, sim):
oracle_1 = oracle(N, case)
q1 = DJ_algo_gen(N, oracle_1)
count = 0
if sim==1:
backend = Aer.get_backend('aer_simulator')
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
count = counts
elif sim == 2:
backend = Aer.get_backend('qasm_simulator')
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
count = counts
elif sim == 3:
backend = FakeJakarta()
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
count = counts
else:
backend = FakeBelem()
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
count = counts
return count
# Testing the algorithm for N=3 and balanced function on all 4 simulators
plot_histogram(run(3, 'balanced', 1))
plot_histogram(run(3, 'balanced', 2))
plot_histogram(run(3, 'balanced', 3))
plot_histogram(run(3, 'balanced', 4))
# Testing the algorithm for N=6 and Balanced functon on noisy simulator
plot_histogram(run(6, 'balanced', 3))
# Testing the algorithm for N=6 and Balanced functon on non - noisy simulator
plot_histogram(run(6, 'balanced', 2))
plot_histogram(run(6, 'balanced', 4))
plot_histogram(run(8, 'balanced', 3))
plot_histogram(run(8, 'balanced', 1))
plot_histogram(run(1000, 'balanced', 1))
plot_histogram(run(1000, 'balanced', 2))
|
https://github.com/Raunak-Singh-Inventor/quantum_algorithms_in_qiskit
|
Raunak-Singh-Inventor
|
from qiskit import *
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
secretnumber = "101001"
circuit = QuantumCircuit(6+1, 6)
circuit.h([0, 1, 2, 3, 4, 5])
circuit.x(6)
circuit.h(6)
circuit.barrier()
circuit.cx(5, 6)
circuit.cx(3, 6)
circuit.cx(0, 6)
circuit.barrier()
circuit.h([0, 1, 2, 3, 4, 5])
circuit.barrier()
circuit.measure([0,1,2,3,4,5], [0,1,2,3,4,5])
circuit.draw("mpl")
simulator = Aer.get_backend("qasm_simulator")
result = execute(circuit, backend = simulator, shots = 1).result()
counts = result.get_counts()
print(counts)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
from qiskit.tools.visualization import plot_histogram
q0 = QuantumRegister(1); q1 = QuantumRegister(1)
c0 = ClassicalRegister(1); c1 = ClassicalRegister(1)
qc = QuantumCircuit(q0,q1,c0,c1)
qc.h(q0); qc.cx(q0,q1) # emaranhamento compartilhado entre Alice e Bob
qc.barrier()
qc.x(q0); qc.sdg(q0); qc.h(q0); qc.measure(q0,c0) # Medida de Alice
qc.barrier()
qc.z(q1).c_if(c0, 1) # acao de Bob condicionada no cbit enviado por Alice
qc.barrier()
qc.sdg(q1); qc.h(q1); qc.measure(q1,c1) # passa da base circular pra computacional
qc.draw(output='mpl')
jobS = execute(qc, backend = simulator, shots = nshots)
plot_histogram(jobS.result().get_counts(qc))
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
import unittest
import numpy as np
import hypothesis.strategies as st
from hypothesis import given, settings
from qiskit import QuantumCircuit, Aer, execute
from qiskit.circuit.library import QFT
from math import pi, degrees
# importing sys
import sys
from sympy import false
# adding Folder_2 to the system path
import pathlib
sys.path.insert(0, str(pathlib.Path().resolve())+f"/Property_Assertion")
from QuantumAssertions import assertPhase
#####################################################################################
### Change the file to import from, in order to test a mutant version of the code ###
#####################################################################################
### e.g. from Add_mutant_1 import remove_garbage, generate_binary, encode_message, measure_message
#####################################################################################
from QuantumPhaseEstimation import generalised_qpe
###########################################################################
## Define composite strategies to generate lists of ints in equal length ##
###########################################################################
@st.composite
def draw_a_small_and_bigger_number_theta(draw):
small = draw(st.integers(min_value=1, max_value=5))
big = draw(st.integers(min_value=small+1, max_value=7))
theta = draw(st.floats(min_value=0, max_value=1, exclude_max=True))
return(small,big, theta)
@st.composite
def draw_a_qubit_size_and_theta(draw):
size = draw(st.integers(min_value=2, max_value=7))
theta = draw(st.floats(min_value=0, max_value=1, exclude_max=True))
return(size, theta)
##########################
## test generate binary ##
##########################
@given(draw_a_small_and_bigger_number_theta())
@settings(deadline=None)
def more_qubits_better_estimation(vals):
small = vals[0]
big = vals[1]
theta = vals[2]
smallEst = generalised_qpe(small, theta*2*pi, shots=10000)
bigEst = generalised_qpe(big, theta*2*pi, shots=10000)
print("---")
print(smallEst)
print(bigEst)
print(theta)
print(abs(smallEst - theta))
print(abs(bigEst - theta))
assert(abs(smallEst - theta) <= abs(smallEst - theta))
@given(draw_a_qubit_size_and_theta())
@settings(deadline=None)
def accurate_to_2_minus_n_radians(vals):
size = vals[0]
theta = vals[1]
est = generalised_qpe(size, theta*2*pi, shots=10000)
if est == 0:
if abs(1 - theta) < abs(0 - theta):
est = 1
print("---")
print(f"size {size}")
print(f"est {est}")
print(f"theta {theta}")
print(f"abs(est - theta) {abs(est - theta)}")
print(2**-size)
assert(abs(est - theta) <= 2**-size)
if __name__ == "__main__":
more_qubits_better_estimation()
accurate_to_2_minus_n_radians()
|
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
|
Sanjay-995
|
from qiskit import QuantumCircuit # imports only QuantumCircuit function from qiskit
# from qiskit import * --> import all the fuction defined under qiskit library including QuantumCircuit
# Creating an empty quantum circuit object with 3 qubits and 3 classical bits
qc = QuantumCircuit(3,3)
qc.draw()
# For better visualization use matplotlib as 'mpl'
qc.draw(output = "mpl")
qc_trial = QuantumCircuit(3,3)
qc_trial.draw(output = "mpl")
qc_trial.measure_all()
qc_trial.draw(output = "mpl")
qc_trial2 = QuantumCircuit(3)
qc_trial2.draw(output = "mpl")
qc_trial2.measure_all()
qc_trial2.draw(output = "mpl")
qc_trial3 = QuantumCircuit(3,3)
# if you get bored typing QuantumCircuit all the time try this: from qiskit import QuantumCircuit as qc
qc_trial3.draw(output = "mpl")
qc_trial3.measure(0,0) # measure(qubit,clbit)
qc_trial3.draw(output = "mpl")
# alternative to give a command to measure multiple qubits at the same time
qc_trial3 = QuantumCircuit(3,3)
qc_trial3.measure([0,2],[0,2])# measure([qubits],[clbits]), order matters,here qubit0-->clbit0,qubit2 --> clbit2
qc_trial3.draw( output = "mpl")
#To demonstrate significance of order
qc_trial3 = QuantumCircuit(3,3)
qc_trial3.measure([0,1],[0,2])# measure([qubits],[clbits]), order here qubit0-->clbit0,qubit1 --> clbit2
qc_trial3.draw( output = "mpl")
# To measure all the qubits
qc_trial3 = QuantumCircuit(3,3)
qc_trial3.measure([0,1,2],[0,1,2])# measure([qubits],[clbits]), order here qubit0-->clbit0,qubit1 --> clbit1,qubit2 --> clbit2
qc_trial3.draw( output = "mpl")
#measure() requires pre-written classical register
qc_trial4 = QuantumCircuit(3)
qc_trial4.measure([0,1,2],[0,1,2])
qc_trial4.draw(output = "mpl")
qc_trial5 = QuantumCircuit(3,3)
qc_trial5.measure(0,1,2)
qc_trial5.draw(output = "mpl")
# We can also use"range" function
qc_trial5 = QuantumCircuit(3,3)
qc_trial5.measure(range(3),range(3))
qc_trial5.draw(output = "mpl")
qc.draw(output = "mpl")
qc.measure([0,1,2], [0,1,2])
qc.draw(output = "mpl")
qc_op2 = QuantumCircuit(3,3)
qc_op2.measure([0,0], [1,1], [2,2])
qc_op2.measure([0,0], [1,1])
qc_op2.draw(output = "mpl")
# It just implemented 2 measurements on the same qubit as the instruction read [(qubit0,qubit0),(clbit1,clbit1)]
# so qubit0 --> clbit0, and again qubit0--> clbit1
qc_op3 = QuantumCircuit(3,3)
qc_op3.measure_all()
qc_op3.draw(output = "mpl")
# Two classical registers('c' and 'meas')
qc_op4 = QuantumCircuit(3,3)
qc_op4.measure(0,1,2)
qc_op4.draw(output = "mpl")
|
https://github.com/AsishMandoi/VRP-explorations
|
AsishMandoi
|
from utils import random_routing_instance
from TSP.classical.gps import GPS as GPSc
from TSP.quantum.gps import GPS as GPSq
from TSP.quantum.fqs import FQS as FQSq
n=8
cost, xc, yc = random_routing_instance(n, seed=0)
GPSc(n, cost, xc, yc)
fqs = FQSq(n, cost, xc, yc)
res = fqs.solve()
fqs.visualize()
gps = GPSq(n, cost, xc, yc)
res = gps.solve()
gps.visualize()
|
https://github.com/Soumyo2121/Basic-Quantum-Algorithms
|
Soumyo2121
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
secretnumber = '11100011'
circuit = QuantumCircuit(len(secretnumber)+1,len(secretnumber))
circuit.h(range(len(secretnumber)))
circuit.x(len(secretnumber))
circuit.h(len(secretnumber))
circuit.barrier()
for ii, yesno in enumerate(reversed(secretnumber)):
if yesno == '1':
circuit.cx(ii,len(secretnumber))
circuit.barrier()
circuit.h(range(len(secretnumber)))
circuit.barrier()
circuit.measure(range(len(secretnumber)),range(len(secretnumber)))
circuit.draw(output = 'mpl')
|
https://github.com/peiyong-addwater/Hackathon-QNLP
|
peiyong-addwater
|
import collections
import pickle
import warnings
warnings.filterwarnings("ignore")
import os
from random import shuffle
import random
from discopy.tensor import Tensor
from discopy import Word
from discopy.rigid import Functor
from discopy import grammar
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from jax import numpy as np
import numpy
from lambeq import AtomicType, IQPAnsatz, remove_cups, NumpyModel, spiders_reader
from lambeq import BobcatParser, TreeReader, cups_reader, DepCCGParser, TreeReaderMode
from lambeq import Dataset
from lambeq import QuantumTrainer, SPSAOptimizer
from lambeq import TketModel
from lambeq import Rewriter
from pytket.extensions.qiskit import AerBackend
import seaborn as sns
import matplotlib.pyplot as plt
from pytket.circuit.display import render_circuit_jupyter
pd.set_option('display.width', 1000)
pd.options.display.max_colwidth=80
print(os.getcwd())
warnings.filterwarnings("ignore")
os.environ["TOKENIZERS_PARALLELISM"] = "false"
BATCH_SIZE = 50
EPOCHS = 200
SEED = 0
TRAIN_INDEX_RATIO = 0.08
VAL_INDEX_RATIO = TRAIN_INDEX_RATIO + 0.01
TEST_INDEX_RATIO = VAL_INDEX_RATIO + 0.01
assert TEST_INDEX_RATIO <= 1
def load_pickled_dict_to_df(filename):
saved_dict = pickle.load(open(filename, 'rb'))
df = pd.DataFrame.from_dict(saved_dict)
df = df.sample(frac=1, random_state=SEED).reset_index(drop=True)
sentiment = []
for i in df['target']:
if i == "Positive":
sentiment.append(1)
else:
sentiment.append(0)
df["Sentiment"] = sentiment
return df
cleaned_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data.pkl')
cleaned_lemmatized_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data_lematize.pkl')
cleaned_lemmatized_stemmed_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data_stem_lematize.pkl')
cleaned_qnlp = load_pickled_dict_to_df(cleaned_qnlp_filename)
cleaned_lemmatized_qnlp = load_pickled_dict_to_df(cleaned_lemmatized_qnlp_filename)
cleaned__lemmatized_stemmed_qnlp = load_pickled_dict_to_df(cleaned_lemmatized_stemmed_qnlp_filename)
cleaned_qnlp.head(10)
cleaned_qnlp.info()
sns.countplot(x = "target", data = cleaned_qnlp)
cleaned_lemmatized_qnlp.head(10)
cleaned_lemmatized_qnlp.info()
sns.countplot(x='target', data = cleaned_lemmatized_qnlp)
cleaned__lemmatized_stemmed_qnlp.head(10)
cleaned__lemmatized_stemmed_qnlp.info()
sns.countplot(x='target', data = cleaned__lemmatized_stemmed_qnlp)
# parser = BobcatParser(verbose='text')
# parser = DepCCGParser(root_cats=['S[dcl]'])
# parser = spiders_reader
parser = TreeReader(mode=TreeReaderMode.RULE_TYPE)
NUM_DATA = 2578
loss = lambda y_hat, y: -np.sum(y * np.log(y_hat)) / len(y) # binary cross-entropy loss
acc = lambda y_hat, y: np.sum(np.round(y_hat) == y) / len(y) / 2 # half due to double-counting
rewriter = Rewriter(['prepositional_phrase', 'determiner', 'auxiliary', 'connector',
'coordination', 'object_rel_pronoun', 'subject_rel_pronoun',
'postadverb', 'preadverb'])
def rewrite(diagram):
# diagram = rewriter(diagram)
return remove_cups(diagram)
def create_diagrams_and_labels(total_df, NUM_DATA = 2578):
total_text = total_df['data'].tolist()
total_labels = total_df["Sentiment"].tolist()
total_labels = [[t, 1-t] for t in total_labels] # [1, 0] for positive, [0, 1] for negative
train_diagrams = parser.sentences2diagrams(total_text[:round(NUM_DATA*TRAIN_INDEX_RATIO)])
train_labels = total_labels[:round(NUM_DATA*TRAIN_INDEX_RATIO)]
dev_diagrams = parser.sentences2diagrams(total_text[round(NUM_DATA*TRAIN_INDEX_RATIO):round(NUM_DATA*VAL_INDEX_RATIO)])
dev_labels = total_labels[round(NUM_DATA*TRAIN_INDEX_RATIO):round(NUM_DATA*VAL_INDEX_RATIO)]
test_diagrams = parser.sentences2diagrams(total_text[round(NUM_DATA*VAL_INDEX_RATIO):round(NUM_DATA*TEST_INDEX_RATIO)])
test_labels = total_labels[round(NUM_DATA*VAL_INDEX_RATIO):round(NUM_DATA*TEST_INDEX_RATIO)]
return train_diagrams, train_labels, dev_diagrams, dev_labels, test_diagrams, test_labels
data = cleaned__lemmatized_stemmed_qnlp
raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(data)
print(len(raw_train_diagrams_1))
raw_train_diagrams_1[0].draw(figsize=(12,3))
train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1]
dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1]
test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1]
train_diagrams_1[0].draw(figsize=(6,5))
alternate_parser = BobcatParser(verbose='text')
dig_0 = alternate_parser.sentence2diagram(cleaned__lemmatized_stemmed_qnlp['data'].tolist()[0])
grammar.draw(dig_0, figsize=(14,3), fontsize=12)
ansatz_1 = IQPAnsatz({AtomicType.NOUN: 1, AtomicType.SENTENCE: 1, AtomicType.PREPOSITIONAL_PHRASE: 1, AtomicType.NOUN_PHRASE:1, AtomicType.CONJUNCTION:1}, n_layers=1, n_single_qubit_params=3)
train_circuits_1 = [ansatz_1(diagram) for diagram in train_diagrams_1]
dev_circuits_1 = [ansatz_1(diagram) for diagram in dev_diagrams_1]
test_circuits_1 = [ansatz_1(diagram) for diagram in test_diagrams_1]
train_circuits_1[0].draw(figsize=(9, 12))
# train_circuits_1[0].draw(figsize=(9, 12))
render_circuit_jupyter(train_circuits_1[0].to_tk())
[(s, s.size) for s in train_circuits_1[0].free_symbols]
all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1
model_1 = NumpyModel.from_diagrams(all_circuits_1, use_jit=True)
# model_1 = TketModel.from_diagrams(all_circuits_1, backend_config=backend_config)
trainer_1 = QuantumTrainer(
model_1,
loss_function=loss,
epochs=EPOCHS,
optimizer=SPSAOptimizer,
optim_hyperparams={'a': 0.2, 'c': 0.06, 'A':0.01*EPOCHS},
evaluate_functions={'acc': acc},
evaluate_on_train=True,
verbose = 'text',
seed=0
)
train_dataset_1 = Dataset(
train_circuits_1,
train_labels_1,
batch_size=BATCH_SIZE)
val_dataset_1 = Dataset(dev_circuits_1, dev_labels_1, shuffle=False)
trainer_1.fit(train_dataset_1, val_dataset_1, logging_step=1)
fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(12, 8))
ax_tl.set_title('Training set')
ax_tr.set_title('Development set')
ax_bl.set_xlabel('Iterations')
ax_br.set_xlabel('Iterations')
ax_bl.set_ylabel('Accuracy')
ax_tl.set_ylabel('Loss')
colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color'])
ax_tl.plot(trainer_1.train_epoch_costs, color=next(colours))
ax_bl.plot(trainer_1.train_results['acc'], color=next(colours))
ax_tr.plot(trainer_1.val_costs, color=next(colours))
ax_br.plot(trainer_1.val_results['acc'], color=next(colours))
test_acc_1 = acc(model_1(test_circuits_1), test_labels_1)
print('Test accuracy:', test_acc_1)
data = cleaned_lemmatized_qnlp
raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(data)
print(len(raw_train_diagrams_1))
raw_train_diagrams_1[0].draw(figsize=(12,3))
train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1]
dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1]
test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1]
train_diagrams_1[0].draw(figsize=(6,5))
ansatz_1 = IQPAnsatz({AtomicType.NOUN: 1, AtomicType.SENTENCE: 1, AtomicType.PREPOSITIONAL_PHRASE: 1, AtomicType.NOUN_PHRASE:1, AtomicType.CONJUNCTION:1}, n_layers=1, n_single_qubit_params=3)
train_circuits_1 = [ansatz_1(diagram) for diagram in train_diagrams_1]
dev_circuits_1 = [ansatz_1(diagram) for diagram in dev_diagrams_1]
test_circuits_1 = [ansatz_1(diagram) for diagram in test_diagrams_1]
train_circuits_1[0].draw(figsize=(9, 12))
render_circuit_jupyter(train_circuits_1[0].to_tk())
all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1
model_1 = NumpyModel.from_diagrams(all_circuits_1, use_jit=True)
trainer_1 = QuantumTrainer(
model_1,
loss_function=loss,
epochs=EPOCHS,
optimizer=SPSAOptimizer,
optim_hyperparams={'a': 0.2, 'c': 0.06, 'A':0.01*EPOCHS},
evaluate_functions={'acc': acc},
evaluate_on_train=True,
verbose = 'text',
seed=0
)
train_dataset_1 = Dataset(
train_circuits_1,
train_labels_1,
batch_size=BATCH_SIZE)
val_dataset_1 = Dataset(dev_circuits_1, dev_labels_1, shuffle=False)
trainer_1.fit(train_dataset_1, val_dataset_1, logging_step=1)
fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(12, 8))
ax_tl.set_title('Training set')
ax_tr.set_title('Development set')
ax_bl.set_xlabel('Iterations')
ax_br.set_xlabel('Iterations')
ax_bl.set_ylabel('Accuracy')
ax_tl.set_ylabel('Loss')
colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color'])
ax_tl.plot(trainer_1.train_epoch_costs, color=next(colours))
ax_bl.plot(trainer_1.train_results['acc'], color=next(colours))
ax_tr.plot(trainer_1.val_costs, color=next(colours))
ax_br.plot(trainer_1.val_results['acc'], color=next(colours))
test_acc_1 = acc(model_1(test_circuits_1), test_labels_1)
print('Test accuracy:', test_acc_1)
data = cleaned_qnlp
raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(data)
print(len(raw_train_diagrams_1))
raw_train_diagrams_1[0].draw(figsize=(12,3))
train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1]
dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1]
test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1]
train_diagrams_1[0].draw(figsize=(6,5))
render_circuit_jupyter(train_circuits_1[0].to_tk())
all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1
model_1 = NumpyModel.from_diagrams(all_circuits_1, use_jit=True)
trainer_1 = QuantumTrainer(
model_1,
loss_function=loss,
epochs=EPOCHS,
optimizer=SPSAOptimizer,
optim_hyperparams={'a': 0.2, 'c': 0.06, 'A':0.01*EPOCHS},
evaluate_functions={'acc': acc},
evaluate_on_train=True,
verbose = 'text',
seed=0
)
train_dataset_1 = Dataset(
train_circuits_1,
train_labels_1,
batch_size=BATCH_SIZE)
val_dataset_1 = Dataset(dev_circuits_1, dev_labels_1, shuffle=False)
trainer_1.fit(train_dataset_1, val_dataset_1, logging_step=1)
fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(12, 8))
ax_tl.set_title('Training set')
ax_tr.set_title('Development set')
ax_bl.set_xlabel('Iterations')
ax_br.set_xlabel('Iterations')
ax_bl.set_ylabel('Accuracy')
ax_tl.set_ylabel('Loss')
colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color'])
ax_tl.plot(trainer_1.train_epoch_costs, color=next(colours))
ax_bl.plot(trainer_1.train_results['acc'], color=next(colours))
ax_tr.plot(trainer_1.val_costs, color=next(colours))
ax_br.plot(trainer_1.val_results['acc'], color=next(colours))
test_acc_1 = acc(model_1(test_circuits_1), test_labels_1)
print('Test accuracy:', test_acc_1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import RealAmplitudes
from qiskit.algorithms.optimizers import COBYLA
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, SamplingVQE
from qiskit.primitives import Sampler
from qiskit_optimization.converters import LinearEqualityToPenalty
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.translators import from_docplex_mp
from qiskit.utils import algorithm_globals
import numpy as np
import matplotlib.pyplot as plt
from docplex.mp.model import Model
algorithm_globals.random_seed = 123456
# prepare problem instance
n = 6 # number of assets
q = 0.5 # risk factor
budget = n // 2 # budget
penalty = 2 * n # scaling of penalty term
# instance from [1]
mu = np.array([0.7313, 0.9893, 0.2725, 0.8750, 0.7667, 0.3622])
sigma = np.array(
[
[0.7312, -0.6233, 0.4689, -0.5452, -0.0082, -0.3809],
[-0.6233, 2.4732, -0.7538, 2.4659, -0.0733, 0.8945],
[0.4689, -0.7538, 1.1543, -1.4095, 0.0007, -0.4301],
[-0.5452, 2.4659, -1.4095, 3.5067, 0.2012, 1.0922],
[-0.0082, -0.0733, 0.0007, 0.2012, 0.6231, 0.1509],
[-0.3809, 0.8945, -0.4301, 1.0922, 0.1509, 0.8992],
]
)
# or create random instance
# mu, sigma = portfolio.random_model(n, seed=123) # expected returns and covariance matrix
# create docplex model
mdl = Model("portfolio_optimization")
x = mdl.binary_var_list(range(n), name="x")
objective = mdl.sum([mu[i] * x[i] for i in range(n)])
objective -= q * mdl.sum([sigma[i, j] * x[i] * x[j] for i in range(n) for j in range(n)])
mdl.maximize(objective)
mdl.add_constraint(mdl.sum(x[i] for i in range(n)) == budget)
# case to
qp = from_docplex_mp(mdl)
# solve classically as reference
opt_result = MinimumEigenOptimizer(NumPyMinimumEigensolver()).solve(qp)
print(opt_result.prettyprint())
# we convert the problem to an unconstrained problem for further analysis,
# otherwise this would not be necessary as the MinimumEigenSolver would do this
# translation automatically
linear2penalty = LinearEqualityToPenalty(penalty=penalty)
qp = linear2penalty.convert(qp)
_, offset = qp.to_ising()
# set classical optimizer
maxiter = 100
optimizer = COBYLA(maxiter=maxiter)
# set variational ansatz
ansatz = RealAmplitudes(n, reps=1)
m = ansatz.num_parameters
# set sampler
sampler = Sampler()
# run variational optimization for different values of alpha
alphas = [1.0, 0.50, 0.25] # confidence levels to be evaluated
# dictionaries to store optimization progress and results
objectives = {alpha: [] for alpha in alphas} # set of tested objective functions w.r.t. alpha
results = {} # results of minimum eigensolver w.r.t alpha
# callback to store intermediate results
def callback(i, params, obj, stddev, alpha):
# we translate the objective from the internal Ising representation
# to the original optimization problem
objectives[alpha].append(np.real_if_close(-(obj + offset)))
# loop over all given alpha values
for alpha in alphas:
# initialize SamplingVQE using CVaR
vqe = SamplingVQE(
sampler=sampler,
ansatz=ansatz,
optimizer=optimizer,
aggregation=alpha,
callback=lambda i, params, obj, stddev: callback(i, params, obj, stddev, alpha),
)
# initialize optimization algorithm based on CVaR-SamplingVQE
opt_alg = MinimumEigenOptimizer(vqe)
# solve problem
results[alpha] = opt_alg.solve(qp)
# print results
print("alpha = {}:".format(alpha))
print(results[alpha].prettyprint())
print()
# plot resulting history of objective values
plt.figure(figsize=(10, 5))
plt.plot([0, maxiter], [opt_result.fval, opt_result.fval], "r--", linewidth=2, label="optimum")
for alpha in alphas:
plt.plot(objectives[alpha], label="alpha = %.2f" % alpha, linewidth=2)
plt.legend(loc="lower right", fontsize=14)
plt.xlim(0, maxiter)
plt.xticks(fontsize=14)
plt.xlabel("iterations", fontsize=14)
plt.yticks(fontsize=14)
plt.ylabel("objective value", fontsize=14)
plt.show()
# evaluate and sort all objective values
objective_values = np.zeros(2**n)
for i in range(2**n):
x_bin = ("{0:0%sb}" % n).format(i)
x = [0 if x_ == "0" else 1 for x_ in reversed(x_bin)]
objective_values[i] = qp.objective.evaluate(x)
ind = np.argsort(objective_values)
# evaluate final optimal probability for each alpha
for alpha in alphas:
probabilities = np.fromiter(
results[alpha].min_eigen_solver_result.eigenstate.binary_probabilities().values(),
dtype=float,
)
print("optimal probability (alpha = %.2f): %.4f" % (alpha, probabilities[ind][-1:]))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
def trotter_gate(dt, to_instruction = True):
qc = QuantumCircuit(2)
qc.rx(2 * dt, 0)
qc.rz(2 * dt, 1)
qc.h(1)
qc.cx(1, 0)
qc.rz(-2 * dt, 0)
qc.rx(-2 * dt, 1)
qc.rz(2 * dt, 1)
qc.cx(1, 0)
qc.h(1)
qc.rz(2 * dt, 0)
return qc.to_instruction() if to_instruction else qc
dt = Parameter('(-2t/n)')
trotter_gate(dt, to_instruction=False).draw("mpl")
dt = Parameter('2t/n')
mdt = Parameter('-2t/n')
qc = QuantumCircuit(2)
qc.rx(dt, 0)
qc.rz(dt, 1)
qc.h(1)
qc.cx(1, 0)
qc.rz(mdt, 0)
qc.rx(mdt, 1)
qc.rz(dt, 1)
qc.cx(1, 0)
qc.h(1)
qc.rz(dt, 0)
qc.draw("mpl")
dt = Parameter('2t/n')
mdt = Parameter('-2t/n')
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
qc.rz(mdt, 0)
qc.rx(mdt, 1)
qc.rz(dt, 1)
qc.cx(1, 0)
qc.h(1)
qc.rx(dt, 1)
qc.draw("mpl")
trotter_gate(np.pi / 6, to_instruction=False).draw("mpl")
def make_initial_state(qc, initial_state):
"""
logical qubit index
little endian
"""
for i, state in enumerate(initial_state):
if state == "1":
qc.x(i)
qc = QuantumCircuit(3)
make_initial_state(qc, "110")
qc.draw("mpl")
def subspace_encoder(qc, targets):
"""
naive method, can be optimized for init state |110>
little endian
"""
n = qc.num_qubits
qc.cx(targets[2],targets[1])
qc.cx(targets[1],targets[0])
def subspace_encoder_init110(qc, targets):
"""
optimized encoder for init state |110>
endian: |q_0, q_1, q_2> (little endian)
encode |110> to |0>|10>
"""
n = qc.num_qubits
qc.x(targets[0])
def subspace_decoder(qc, targets):
"""
naive method
little endian
"""
n = qc.num_qubits
qc.cx(targets[1], targets[0])
qc.cx(targets[2], targets[1])
qc = QuantumCircuit(3)
make_initial_state(qc, "110")
subspace_encoder_init110(qc, targets=[0,1,2])
qc.draw("mpl")
def trotterize(qc, trot_gate, num_steps, targets):
for _ in range(num_steps):
qc.append(trot_gate, qargs = targets)
qc = QuantumCircuit(3)
make_initial_state(qc, "110")
subspace_encoder_init110(qc, targets=[0,1,2])
qc.barrier()
trotterize(qc, trotter_gate(np.pi / 6), 1, targets=[1, 2])
qc = transpile(qc, optimization_level = 3, basis_gates=["sx", "rz", "cx"])
qc.draw("mpl")
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
st_qcs_list = []
# Number of trotter steps
max_trotter_step = 50 ### CAN BE >= 4
trotter_steps = list(range(1, max_trotter_step + 1, 3))
for num_steps in trotter_steps:
print("trotter step: ", num_steps)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder(qc, targets=[0,1,2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
st_qcs_list.append(t3_st_qcs)
st_qcs_list[-1][-1].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
jobs = []
shots = 1 << 13
# Number of trotter steps
for i, num_steps in enumerate(trotter_steps):
print("trotter step: ", num_steps)
# execute: reps = 1
job = execute(st_qcs_list[i], backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
print()
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
results = []
for job in jobs:
results.append( job.result() )
mit_results = []
for job in jobs:
mit_results.append( meas_fitter.filter.apply(job.result()) )
print(len(results), len(mit_results))
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Compute tomography fidelities for each repetition
raw_fids = []
for result in results:
fid = state_tomo(result, st_qcs)
raw_fids.append(fid)
# print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
# Compute tomography fidelities for each repetition
fids = []
for result in mit_results:
fid = state_tomo(result, st_qcs)
fids.append(fid)
# print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
plt.clf()
plt.style.use('ggplot')
plt.figure(dpi=200)
plt.title("state fidelity from Trotter step 1 to "+str(trotter_steps))
plt.plot(trotter_steps, raw_fids, label="raw fidelity")
plt.plot(trotter_steps, fids, label="fidelity after QREM")
plt.xlabel("number of trotter steps")
plt.ylabel("fidelity")
plt.grid(linestyle='dotted')
for step, fid in zip(trotter_steps, raw_fids):
print(step, fid)
for step, fid in zip(trotter_steps, fids):
print(step, fid)
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# let's define both vectors
u = [-3,-2,0,-1,4]
v = [-1,-1,2,-3,5]
uv = 0; # summation is initially zero
for i in range(len(u)): # iteratively access every pair with the same indices
print("pairwise multiplication of the entries with index",i,"is",u[i]*v[i])
uv = uv + u[i]*v[i] # i-th entries are multiplied and then added to summation
print() # print an empty line
print("The dot product of",u,'and',v,'is',uv)
#
# your solution is here
#
#
# your solution is here
#
# let's find the dot product of v and u
v = [-4,0]
u = [0,-5]
result = 0;
for i in range(2):
result = result + v[i]*u[i]
print("the dot product of u and v is",result)
# we can use the same code
v = [-4,3]
u = [-3,-4]
result = 0;
for i in range(2):
result = result + v[i]*u[i]
print("the dot product of u and v is",result)
# you may consider to write a function in Python for dot product
#
# your solution is here
#
#
# your solution is here
#
|
https://github.com/mhlr/qiskit-meetup
|
mhlr
|
#%pip install qiskit-aqua qiskit
from qiskit.visualization import iplot_histogram, plot_histogram
%pylab inline
import qiskit as qk
qr = qk.QuantumRegister(2)
cr = qk.ClassicalRegister(2)
qc = qk.QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.draw(output='mpl')
qc.cx(qr[0], qr[1])
qc.draw(output='mpl')
qc.measure(qr,cr)
qc.draw(output='mpl')
qk.Aer.backends()
sim = qk.Aer.get_backend('qasm_simulator')
res = qk.execute(qc, sim).result()
res
plot_histogram(res.get_counts())
from qiskit import IBMQ
IBMQ.delete_account()
IBMQ.save_account('4fd56...',
overwrite=True) # the token you obtained above
IBMQ.load_account()
provider = IBMQ.get_provider()
procs=provider.backends(operational=True, simulator=False)
procs
from qiskit.tools.jupyter import *
%qiskit_backend_overview
from qiskit.tools import monitor
backend = qk.providers.ibmq.least_busy([p for p in procs if len(p.properties().qubits) >= 2])
from qiskit.tools.monitor import backend_overview, backend_monitor
backend_monitor(backend)
#%%qiskit_job_status
#%%qiskit_progress_bar
%time job = qk.execute(qc, backend=backend, shots=2**10)
#mon = monitor.job_monitor(job)
%time res2 = job.result()
plot_histogram(res2.get_counts(qc))
res2.get_counts(qc)
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/we-taper/qiskit-pyzx
|
we-taper
|
from functools import singledispatch
from math import pi
from typing import Dict
import pyzx.circuit.gates as pyzx_g
import qiskit.extensions.standard as qk_g
from qiskit.circuit import Measure, Qubit, Reset
import pyzx
# from .barrier import Barrier
# from .cswap import FredkinGate
# from .cy import CyGate
# from .u0 import U0Gate
# from .cu1 import Cu1Gate
# from .ch import CHGate
# from .cu3 import Cu3Gate
# from .rzz import RZZGate
# from .crz import CrzGate
# from .u1 import U1Gate
# from .u2 import U2Gate
# from .u3 import U3Gate
from qiskit.dagcircuit import DAGCircuit
@singledispatch
def to_pyzx_gate(qiskit_gate, targets, gatelist: list, **kwargs):
raise NotImplementedError(
f"The gate {type(qiskit_gate)} have not been implemented.")
@to_pyzx_gate.register(qk_g.ToffoliGate)
def to_pyzx_gate_1(qiskit_gate, targets, gatelist: list, **kwargs):
return gatelist.append(
pyzx_g.Tofolli(ctrl1=targets[0], ctrl2=targets[1], target=targets[2]))
@to_pyzx_gate.register(qk_g.CnotGate)
def to_pyzx_gate_2(qiskit_gate, targets, gatelist: list, **kwargs):
return gatelist.append(pyzx_g.CNOT(control=targets[0], target=targets[1]))
# TODO: what is the diff btw cxbase and cnotgate?
@to_pyzx_gate.register(qk_g.CXBase)
def to_pyzx_gate_3(qiskit_gate, targets, gatelist: list, **kwargs):
return gatelist.append(pyzx_g.CNOT(control=targets[0], target=targets[1]))
@to_pyzx_gate.register(qk_g.CyGate)
def to_pyzx_gate_4(qiskit_gate, targets, gatelist: list, **kwargs):
raise NotImplementedError(
f"TODO: implement the rule from CY to CXCZCPhase")
@to_pyzx_gate.register(qk_g.CzGate)
def to_pyzx_gate_5(qiskit_gate, targets, gatelist: list, **kwargs):
gatelist.append(pyzx_g.CZ(control=targets[0], target=targets[1]))
@to_pyzx_gate.register(qk_g.SwapGate)
def to_pyzx_gate_6(qiskit_gate, targets, gatelist: list, **kwargs):
gatelist.append(pyzx_g.SWAP(control=targets[0], target=targets[1]))
@to_pyzx_gate.register(qk_g.HGate)
def to_pyzx_gate_7(qiskit_gate, targets, gatelist: list, **kwargs):
gatelist.append(pyzx_g.HAD(target=targets[0]))
@to_pyzx_gate.register(qk_g.IdGate)
def to_pyzx_gate_7(qiskit_gate, targets, gatelist: list, **kwargs):
pass
@to_pyzx_gate.register(qk_g.SGate)
def to_pyzx_gate_8(qiskit_gate, targets, gatelist: list, **kwargs):
gatelist.append(pyzx_g.S(target=targets[0]))
@to_pyzx_gate.register(qk_g.SdgGate)
def to_pyzx_gate_9(qiskit_gate, targets, gatelist: list, **kwargs):
gatelist.append(pyzx_g.S(target=targets[0], adjoint=True))
@to_pyzx_gate.register(qk_g.TGate)
def to_pyzx_gate_9(qiskit_gate, targets, gatelist: list, **kwargs):
gatelist.append(pyzx_g.T(target=targets[0]))
@to_pyzx_gate.register(qk_g.TdgGate)
def to_pyzx_gate_9(qiskit_gate, targets, gatelist: list, **kwargs):
gatelist.append(pyzx_g.T(target=targets[0], adjoint=True))
@to_pyzx_gate.register(qk_g.XGate)
def to_pyzx_gate_9(qiskit_gate, targets, gatelist: list, **kwargs):
gatelist.append(pyzx_g.XPhase(target=targets[0], phase=1))
@to_pyzx_gate.register(qk_g.YGate)
def to_pyzx_gate_9(qiskit_gate, targets, gatelist: list, **kwargs):
gatelist.extend([
pyzx_g.XPhase(target=targets[0], phase=1),
pyzx_g.Z(target=targets[0])
])
@to_pyzx_gate.register(qk_g.ZGate)
def to_pyzx_gate_9(qiskit_gate, targets, gatelist: list, **kwargs):
gatelist.append(pyzx_g.Z(target=targets[0]))
@to_pyzx_gate.register(qk_g.RXGate)
def to_pyzx_gate_9(qiskit_gate: qk_g.RXGate, targets, gatelist: list, **kwargs):
gatelist.append(
pyzx_g.XPhase(target=targets[0],
phase=get_angle(qiskit_gate.params[0])))
@to_pyzx_gate.register(qk_g.RYGate)
def to_pyzx_gate_9(qiskit_gate: qk_g.RYGate, targets, gatelist: list, **kwargs):
# YRot = SRx(theta)Sdg
gatelist.extend([
pyzx_g.S(target=targets[0]),
pyzx_g.XPhase(target=targets[0],
phase=get_angle(qiskit_gate.params[0])),
pyzx_g.S(target=targets[0], adjoint=True),
])
@to_pyzx_gate.register(qk_g.RZGate)
def to_pyzx_gate_9(qiskit_gate: qk_g.RZGate, targets, gatelist: list, **kwargs):
gatelist.append(
pyzx_g.ZPhase(target=targets[0],
phase=get_angle(qiskit_gate.params[0])))
@to_pyzx_gate.register(qk_g.U3Gate)
def to_pyzx_gate_9(qiskit_gate: qk_g.RZGate, targets, gatelist: list, **kwargs):
gatelist.append(
pyzx_g.U3(target=targets[0],
phases=list(map(get_angle, qiskit_gate.params))))
@to_pyzx_gate.register(Measure)
def to_pyzx_gate_9(qiskit_gate: Measure, targets, gatelist: list, **kwargs):
clbits = kwargs['clbits']
# TODO classically controlled measurement?
stored_data = {'clbits': clbits, 'gate': qiskit_gate}
gatelist.append(
pyzx_g.Nonunitary(target=targets[0],
stored_data=stored_data))
@to_pyzx_gate.register(Reset)
def to_pyzx_gate_9(qiskit_gate: Reset, targets, gatelist: list, **kwargs):
stored_data = {'gate': qiskit_gate}
gatelist.append(
pyzx_g.Nonunitary(target=targets[0],
stored_data=stored_data))
def get_angle(angle):
# 1. qiskit stores angle in Sympy.Float, which is not allowed by PyZX
# 2. angle in pyZX is in ratios of pi
angle = float(angle)
angle /= pi
return angle
def check_classical_control(
qiskit_gate, targets, gatelist: list, **kwargs):
"""
Check for classical control for this gate.
If there is a classical control, it appneds the gatelist with a dummy gate for this classical control, and then return True.
If not, then this function returns False.
:param qiskit_gate: The qiskit gate.
:param targets: A list of integers.
The target qregs of this quantum gate.
:param gatelist: The list of gates for PyZX's Circuit
:param kwargs: contains,
clbits (Qiskit's clbits)
condition: A tuple: (ClassicalRegister, int index)
:return: bool
"""
control = kwargs['condition']
if control is None:
return False
else:
stored_data = {'gate': qiskit_gate, 'control': control}
gatelist.append(
pyzx_g.Nonunitary(target=targets[0],
stored_data=stored_data))
return True
def add_non_unitary_gate(
gate: pyzx.gates.Gate,
pyreg_to_qubit: Dict[int, Qubit],
dagcircuit: DAGCircuit):
if not isinstance(gate, pyzx.gates.Nonunitary):
return False
qargs = [pyreg_to_qubit[gate.target]]
if hasattr(gate, 'control'):
qargs.insert(0, gate.control)
if hasattr(gate, 'ctrl2'):
qargs.insert(0, gate.ctrl1)
if hasattr(gate, 'ctrl1'):
qargs.insert(0, gate.ctrl1)
dagcircuit.apply_operation_back(
op=gate.stored_data['gate'],
qargs=qargs,
cargs=gate.stored_data.get('clbits'),
condition=gate.stored_data.get('control'),
)
return True
|
https://github.com/mickahell/quantum_pokemon-fight
|
mickahell
|
import math
from qiskit import QuantumCircuit, execute
def quantum_fight(psi, backend_sim):
qc = QuantumCircuit(1, 1)
qc.rx(math.pi * psi, 0)
qc.measure(0, 0)
job = execute(qc, backend_sim, shots=1, memory=True)
result_job = job.result().get_memory()
to_return = int(result_job[0], 2)
return to_return
def calcul_dommage(attac, pokemon_att, pokemon_def, backend_sim):
quantum_precision = quantum_fight(attac.precision, backend_sim)
if quantum_precision == 1:
STAB = 1
RESISTANCE = 1
CRIT = 1
if attac.type in pokemon_att.types:
STAB = 1.5
for i in pokemon_def.types:
if attac.type in i.weakness:
RESISTANCE *= 2
elif attac.type in i.resistance:
RESISTANCE *= 0.5
elif attac.type in i.imunite:
RESISTANCE *= 0
quantum_crit = quantum_fight(0.0417, backend_sim)
if quantum_crit == 1:
CRIT = 1.5
print("critical hit !")
if attac.status == "physical":
dommages = (
(
(
((100 * 0.4 + 2) * pokemon_att.points_attack * attac.power)
/ (pokemon_def.points_defense * 50)
)
+ 2
)
* STAB
* RESISTANCE
* CRIT
)
else:
dommages = (
(
(
((100 * 0.4 + 2) * pokemon_att.points_att_sp * attac.power)
/ (pokemon_def.points_def_sp * 50)
)
+ 2
)
* STAB
* RESISTANCE
* CRIT
)
if RESISTANCE > 1:
print("It's super efficient !")
if RESISTANCE < 1:
if RESISTANCE == 0:
print("{} is not affected by this attack !".format(pokemon_def.name))
else:
print("It is not very effective !")
if attac.type.name == "Poison" and RESISTANCE > 0:
if quantum_fight(0.3, backend_sim) == 1 and pokemon_def.malus == "None":
pokemon_def.malus = "poison"
print("{} is poisoned.".format(pokemon_def.name))
if attac.type.name == "Fire" and RESISTANCE > 0:
if quantum_fight(0.1, backend_sim) == 1 and pokemon_def.malus == "None":
pokemon_def.malus = "burn"
pokemon_def.points_attack *= 0.5
print("{} is burnt.".format(pokemon_def.name))
if attac.type.name == "Ice" and RESISTANCE > 0:
if quantum_fight(0.1, backend_sim) == 1 and pokemon_def.malus == "None":
pokemon_def.malus = "freeze"
print("{} is frozen.".format(pokemon_def.name))
if attac.type.name == "Electric" and RESISTANCE > 0:
if quantum_fight(0.3, backend_sim) == 1 and pokemon_def.malus == "None":
pokemon_def.malus = "paralysis"
pokemon_def.speed *= 0.5
print("{} is paralyzed.".format(pokemon_def.name))
else:
print("{} miss !".format(pokemon_att.name))
dommages = 0
return dommages
def action_attack(attaque, player_att, player_def, backend_sim):
player_att.action = 0
thaw = 1
paralysis = 1
if player_att.pokemon.malus == "freeze":
thaw = quantum_fight(0.2, backend_sim)
if thaw == 1:
print("{} is thawed.".format(player_att.pokemon.name))
player_att.pokemon.malus = "None"
else:
print("{} is still frozen.".format(player_att.pokemon.name))
if player_att.pokemon.malus == "paralysis":
paralysis = quantum_fight(0.75, backend_sim)
if paralysis == 0:
print("{} is paralyzed, he cannot attack.".format(player_att.pokemon.name))
if thaw == 1 and paralysis == 1:
print("{} is using {}".format(player_att.pokemon.name, attaque.name))
player_def.pokemon.dommages = player_def.pokemon.dommages + calcul_dommage(
attaque, player_att.pokemon, player_def.pokemon, backend_sim
)
if round(player_def.pokemon.pv - player_def.pokemon.dommages) < 0:
print(
"{} - 0 / {} pv".format(player_def.pokemon.name, player_def.pokemon.pv)
)
else:
print(
"{} - {} / {} pv".format(
player_def.pokemon.name,
round(player_def.pokemon.pv - player_def.pokemon.dommages),
player_def.pokemon.pv,
)
)
if player_def.pokemon.dommages >= player_def.pokemon.pv:
player_def.pokemon.status = 0
player_def.action = 0
def control_input(options, input_ctl):
if input_ctl is not None:
if 0 <= input_ctl < options:
return True
print("Please give a number between 0 and {}.".format(options - 1))
return False
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import *
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit $q_{0}$, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{1}$, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{2}$, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
circ.draw('mpl')
# Import Aer
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = backend.run(circ)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
from qiskit.visualization import plot_state_city
plot_state_city(outputstate)
# Run the quantum circuit on a unitary simulator backend
backend = Aer.get_backend('unitary_simulator')
job = backend.run(circ)
result = job.result()
# Show the results
print(result.get_unitary(circ, decimals=3))
# Create a Quantum Circuit
meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
# map the quantum measurement to the classical bits
meas.measure(range(3), range(3))
# The Qiskit circuit object supports composition using
# the compose method.
circ.add_register(meas.cregs[0])
qc = circ.compose(meas)
#drawing the circuit
qc.draw()
# Use Aer's qasm_simulator
backend_sim = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = backend_sim.run(transpile(qc, backend_sim), shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# let's define the vectors
v=[-3,4,-5,6]
u=[4,3,6,5]
vu = 0
for i in range(len(v)):
vu = vu + v[i]*u[i]
print(v,u,vu)
u = [-3,-4]
uu = u[0]*u[0] + u[1]*u[1]
print(u,u,uu)
u = [-3,-4]
neg_u=[3,4]
v=[-4,3]
neg_v=[4,-3]
# let's define a function for inner product
def dot(v_one,v_two):
summation = 0
for i in range(len(v_one)):
summation = summation + v_one[i]*v_two[i] # adding up pairwise multiplications
return summation # return the inner product
print("the dot product of u and -v (",u," and ",neg_v,") is",dot(u,neg_v))
print("the dot product of -u and v (",neg_u," and ",v,") is",dot(neg_u,v))
print("the dot product of -u and -v (",neg_u," and ",neg_v,") is",dot(neg_u,neg_v))
# let's define a function for inner product
def dot(v_one,v_two):
summation = 0
for i in range(len(v_one)):
summation = summation + v_one[i]*v_two[i] # adding up pairwise multiplications
return summation # return the inner product
v = [-1,2,-3,4]
v_neg_two=[2,-4,6,-8]
u=[-2,-1,5,2]
u_three=[-6,-3,15,6]
print("the dot product of v and u is",dot(v,u))
print("the dot product of -2v and 3u is",dot(v_neg_two,u_three))
|
https://github.com/sohrabganjian/Quantum-Information-Science
|
sohrabganjian
|
import random
from qiskit import QuantumCircuit, QuantumRegister, execute, Aer
from qiskit.extensions import UnitaryGate
import numpy as np
# Generate a random bit
random_bit = random.randint(0, 1)
# Print the random bit
print(random_bit)
# Charlie to Alice bit
CA = random.randint(0, 1)
# Charlie to Bob bit
CB = random.randint(0, 1)
print(CA,CB)
# Alice to Charlie bit
AC = 0
# Bob to Charlie bit
BC = 0
# Charlie checks
(CA and CB) == (AC or BC)
classical_wins = 0
number_of_rounds = 10000
for i in range(number_of_rounds):
CA = random.randint(0, 1)
CB = random.randint(0, 1)
AC, BC = 0, 0
if (CA and CB) == (AC or BC):
classical_wins += 1
print(classical_wins/number_of_rounds)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
# qc.measure(0,0)
# Measure both qubits and store the results in classical registers
qc.measure([0, 1], [0, 1])
# Execute the circuit on a simulator backend
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=10)
result = job.result()
# Get the counts of each measurement outcome
counts = result.get_counts(qc)
print(counts)
CA, CB = 0,0
# Create a quantum circuit with two qubits and two classical registers
qc = QuantumCircuit(2, 2)
# Prepare an entangled state of the two qubits
qc.h(0)
qc.cx(0,1)
# Apply Alice's measurement
if CA == 1:
qc.h(0)
Bob_0_unitary = np.array([[np.cos(np.pi/8), np.sin(np.pi/8)], [-np.sin(np.pi/8), np.cos(np.pi/8)]])
Bob_1_unitary = np.array(
[[np.cos(np.pi/8), -np.sin(np.pi/8)],[np.sin(np.pi/8), np.cos(np.pi/8)]]
)
if CB == 0:
qc.unitary(Bob_0_unitary, [1])
if CB == 1:
qc.unitary(Bob_1_unitary, [1])
# Measure both qubits in the computational basis
qc.measure([0, 1], [0, 1])
qc.draw('mpl')
def CHSH_strategy(CA, CB):
# Create a quantum circuit with two qubits and two classical registers
qc = QuantumCircuit(2, 2)
# Prepare an entangled state of the two qubits
qc.h(0)
qc.cx(0,1)
# Apply Alice's measurement
if CA == 1:
qc.h(0)
Bob_0_unitary = np.array([[np.cos(np.pi/8), np.sin(np.pi/8)], [-np.sin(np.pi/8), np.cos(np.pi/8)]])
Bob_1_unitary = np.array(
[[np.cos(np.pi/8), -np.sin(np.pi/8)],[np.sin(np.pi/8), np.cos(np.pi/8)]]
)
if CB == 0:
qc.unitary(Bob_0_unitary, [1])
if CB == 1:
qc.unitary(Bob_1_unitary, [1])
# Measure both qubits in the computational basis
qc.measure([0, 1], [0, 1])
drawing = qc.draw('mpl')
# Execute the circuit on a simulator backend
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1)
result = job.result()
# Get the counts of each measurement outcome
counts = result.get_counts(qc)
# Compute the XOR of the keys
xor_values = [int(k[0]) ^ int(k[1]) for k in counts.keys()]
return xor_values[0]
# Test the CHSH strategy
quantum_wins = 0
number_of_rounds = 100
for i in range(number_of_rounds):
CA = random.randint(0, 1)
CB = random.randint(0, 1)
output_bit = CHSH_strategy(CA,CB)
if (CA and CB) == output_bit:
quantum_wins += 1
print(quantum_wins/number_of_rounds)
|
https://github.com/IvanIsCoding/Quantum
|
IvanIsCoding
|
from qiskit import *
from qiskit.visualization import plot_histogram
simulator = Aer.get_backend("qasm_simulator")
circuit = QuantumCircuit(1, 1)
circuit.measure(0, 0)
circuit.draw(output="mpl")
job = execute(circuit, backend=simulator, shots=2**15)
result = job.result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
circuit = QuantumCircuit(1, 1)
circuit.x(0)
circuit.measure(0, 0)
circuit.draw(output="mpl")
counts = execute(circuit, backend=simulator, shots=2**15).result().get_counts()
plot_histogram(counts)
circuit = QuantumCircuit(1, 1)
circuit.h(0)
circuit.measure(0, 0)
circuit.draw(output="mpl")
counts = execute(circuit, backend=simulator, shots=2**15).result().get_counts()
plot_histogram(counts)
# Circuit to generate -|0>
circuit = QuantumCircuit(1, 1)
circuit.x(0)
circuit.z(0)
circuit.x(0)
circuit.measure(0, 0)
circuit.draw(output="mpl")
counts = execute(circuit, backend=simulator, shots=2**15).result().get_counts()
plot_histogram(counts)
# Circuit to generate i|0>
circuit = QuantumCircuit(1, 1)
circuit.x(0)
circuit.y(0)
circuit.measure(0, 0)
circuit.draw(output="mpl")
counts = execute(circuit, backend=simulator, shots=2**15).result().get_counts()
plot_histogram(counts)
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.aer import QasmSimulator
# use Aer's qasm_simulator
simulator = QasmSimulator()
# create quantum circute acting on the q register
circuit = QuantumCircuit(2,2)
# add a H gate on qubit 0
circuit.h(0)
# add a cx (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0,1)
# map the quantum measurement to the classical bits
circuit.measure([0,1],[0,1])
# compile the circuit down to low-level QASM instructions
# supported by the backend (not needed for simple circuits)
compiled_circuit = transpile(circuit, simulator)
# execute the circuit on the qasm simulator
job = simulator.run(compiled_circuit, shots=1024)
# grad results from the job
result = job.result()
# return counts
counts = result.get_counts(compiled_circuit)
print('total count for 00 and 11 are: ',counts)
# draw circuit
circuit.draw(output='mpl')
# plot histogram
plot_histogram(counts)
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.providers.aer import AerSimulator
backend = AerSimulator()
circuit = QuantumCircuit(2)
theta = Parameter('theta')
circuit.rx(234, 0)
circuit.draw(output='mpl')
backend = AerSimulator()
circuit = QuantumCircuit(2)
# theta = Parameter('theta')
circuit.rx(20, 0)
circuit.x(0)
circuit.h(1)
result = execute(circuit, backend=backend, shots=1024).result()
# counts=result.get_counts()
# print(counts)
circuit.draw(output='mpl')
|
https://github.com/riddheshMarkandeya/shors-algorithm-quantum
|
riddheshMarkandeya
|
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
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
from math import gcd
from numpy.random import randint
import pandas as pd
from fractions import Fraction
print("Imports Successful")
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
#defining the U gates for mod 63
def c_amod63(a, power):
"""Controlled multiplication by a mod 63"""
if a not in [2, 4, 5, 8, 10, 11, 13, 16, 17, 19, 20, 22, 23, 25, 26, 29, 31, 32, 34, 37, 38, 40, 41, 43, 44, 46, 47, 50, 52, 53, 55, 58, 59, 61, 62]:
raise ValueError("'a' must be 2, 4, 5, 8, 10, 11, 13, 16, 17, 19, 20, 22, 23, 25, 26, 29, 31, 32, 34, 37, 38, 40, 41, 43, 44, 46, 47, 50, 52, 53, 55, 58, 59, 61, or 62")
#the number of qubits used is 6
U = QuantumCircuit(6)
#implementing the swap gates for rotation
#we implement every number and see common behaivor between the numbers
for iteration in range(power):
if a in [2,61]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
U.swap(3,4)
U.swap(4,5)
if a in [4, 59]:
U.swap(0,2)
U.swap(1,3)
U.swap(2,4)
U.swap(3,5)
if a in [5, 58]:
U.swap(0,2)
U.swap(1,3)
U.swap(0,4)
U.swap(1,5)
if a in [8, 55]:
U.swap(0,3)
U.swap(1,4)
U.swap(2,5)
if a in [10, 53]:
U.swap(0,2)
U.swap(1,3)
U.swap(0,4)
U.swap(1,5)
U.swap(0,2)
U.swap(1,3)
U.swap(0,4)
U.swap(1,5)
if a in [11, 52]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
U.swap(3,4)
U.swap(4,5)
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
U.swap(3,4)
U.swap(4,5)
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
U.swap(3,4)
U.swap(4,5)
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
U.swap(3,4)
U.swap(4,5)
if a in [13, 50]:
U.swap(0,5)
U.swap(1,5)
U.swap(2,5)
U.swap(3,5)
U.swap(4,5)
if a in [16, 47]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
U.swap(3,4)
U.swap(4,5)
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
U.swap(3,4)
U.swap(4,5)
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
U.swap(3,4)
U.swap(4,5)
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
U.swap(3,4)
U.swap(4,5)
# if a in [17, 46]:
# if a in [19, 44]:
if a in [20, 43]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
U.swap(3,4)
U.swap(4,5)
if a in [22, 41]:
U.swap(0,5)
U.swap(1,5)
U.swap(2,5)
U.swap(3,5)
U.swap(4,5)
if a in [23, 40]:
U.swap(0,2)
U.swap(1,3)
U.swap(2,4)
U.swap(3,5)
if a in [25, 38]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
U.swap(3,4)
U.swap(4,5)
# if a in [26, 37]:
if a in [29, 34]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
U.swap(3,4)
U.swap(4,5)
if a in [31, 32]:
U.swap(0,5)
U.swap(1,5)
U.swap(2,5)
U.swap(3,5)
U.swap(4,5)
if a in [62]:
U.swap(0,3)
U.swap(1,4)
U.swap(2,5)
if a in [5, 11, 13, 17, 19, 23, 25, 29, 31, 37, 41, 43, 47, 53, 55, 59, 61]:
for q in range(6):
U.x(q)
U = U.to_gate()
U.name = "%i^%i mod 63" % (a, power)
c_U = U.control()
return c_U
# Specify variables
n_count = 10 # number of counting qubits
a = 13
def qft_dagger(n):
"""n-qubit QFTdagger the first n qubits in circ"""
qc = QuantumCircuit(n)
# Don't forget the Swaps!
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-np.pi/float(2**(j-m)), m, j)
qc.h(j)
qc.name = "QFT†"
return qc
# Create QuantumCircuit with n_count counting qubits
# plus 4 qubits for U to act on
qc = QuantumCircuit(n_count + 10, n_count)
# Initialize counting qubits
# in state |+>
for q in range(n_count):
qc.h(q)
# And auxiliary register in state |1>
qc.x(3+n_count)
# Do controlled-U operations
for q in range(n_count):
qc.append(c_amod63(a, 2**q),
[q] + [i+n_count for i in range(6)])
# Do inverse-QFT
qc.append(qft_dagger(n_count), range(n_count))
# Measure circuit
qc.measure(range(n_count), range(n_count))
qc.draw(fold=-1) # -1 means 'do not fold'
aer_sim = Aer.get_backend('aer_simulator')
t_qc = transpile(qc, aer_sim)
qobj = assemble(t_qc)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
rows, measured_phases = [], []
for output in counts:
decimal = int(output, 2) # Convert (base 2) string to decimal
phase = decimal/(2**n_count) # Find corresponding eigenvalue
measured_phases.append(phase)
# Add these values to the rows in our table:
rows.append([f"{output}(bin) = {decimal:>3}(dec)",
f"{decimal}/{2**n_count} = {phase:.2f}"])
# Print the rows in a table
headers=["Register Output", "Phase"]
df = pd.DataFrame(rows, columns=headers)
print(df)
Fraction(0.666)
# Get fraction that most closely resembles 0.666
# with denominator < 63
Fraction(0.666).limit_denominator(63)
rows = []
for phase in measured_phases:
frac = Fraction(phase).limit_denominator(63)
rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator])
# Print as a table
headers=["Phase", "Fraction", "Guess for r"]
df = pd.DataFrame(rows, columns=headers)
print(df)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.library import QFT
def create_qpe_circuit(theta, num_qubits):
'''Creates a QPE circuit given theta and num_qubits.'''
# Step 1: Create a circuit with two quantum registers and one classical register.
first = QuantumRegister(size=num_qubits, name='first') # the first register for phase estimation
second = QuantumRegister(size=1, name='second') # the second register for storing eigenvector |psi>
classical = ClassicalRegister(size=num_qubits, name='readout') # classical register for readout
qpe_circuit = QuantumCircuit(first, second, classical)
# Step 2: Initialize the qubits.
# All qubits are initialized in |0> by default, no extra code is needed to initialize the first register.
qpe_circuit.x(second) # Initialize the second register with state |psi>, which is |1> in this example.
# Step 3: Create superposition in the first register.
qpe_circuit.barrier() # Add barriers to separate each step of the algorithm for better visualization.
qpe_circuit.h(first)
# Step 4: Apply a controlled-U^(2^j) black box.
qpe_circuit.barrier()
for j in range(num_qubits):
qpe_circuit.cp(theta*2*np.pi*(2**j), j, num_qubits) # Theta doesn't contain the 2 pi factor.
# Step 5: Apply an inverse QFT to the first register.
qpe_circuit.barrier()
qpe_circuit.compose(QFT(num_qubits, inverse=True), inplace=True)
# Step 6: Measure the first register.
qpe_circuit.barrier()
qpe_circuit.measure(first, classical)
return qpe_circuit
num_qubits = 4
qpe_circuit_fixed_phase = create_qpe_circuit(1/2, num_qubits) # Create a QPE circuit with fixed theta=1/2.
qpe_circuit_fixed_phase.draw('mpl')
from qiskit.circuit import Parameter
theta = Parameter('theta') # Create a parameter `theta` whose values can be assigned later.
qpe_circuit_parameterized = create_qpe_circuit(theta, num_qubits)
qpe_circuit_parameterized.draw('mpl')
number_of_phases = 21
phases = np.linspace(0, 2, number_of_phases)
individual_phases = [[ph] for ph in phases] # Phases need to be expressed as a list of lists.
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
results = Sampler().run(
[qpe_circuit_parameterized]*len(individual_phases),
parameter_values=individual_phases
).result()
from qiskit.tools.visualization import plot_histogram
idx = 6
plot_histogram(results.quasi_dists[idx].binary_probabilities(), legend=[f'$\\theta$={phases[idx]:.3f}'])
def most_likely_bitstring(results_dict):
'''Finds the most likely outcome bit string from a result dictionary.'''
return max(results_dict, key=results_dict.get)
def find_neighbors(bitstring):
'''Finds the neighbors of a bit string.
Example:
For bit string '1010', this function returns ('1001', '1011')
'''
if bitstring == len(bitstring)*'0':
neighbor_left = len(bitstring)*'1'
else:
neighbor_left = format((int(bitstring,2)-1), '0%sb'%len(bitstring))
if bitstring == len(bitstring)*'1':
neighbor_right = len(bitstring)*'0'
else:
neighbor_right = format((int(bitstring,2)+1), '0%sb'%len(bitstring))
return (neighbor_left, neighbor_right)
def estimate_phase(results_dict):
'''Estimates the phase from a result dictionary of a QPE circuit.'''
# Find the most likely outcome bit string N1 and its neighbors.
num_1_key = most_likely_bitstring(results_dict)
neighbor_left, neighbor_right = find_neighbors(num_1_key)
# Get probabilities of N1 and its neighbors.
num_1_prob = results_dict.get(num_1_key)
neighbor_left_prob = results_dict.get(neighbor_left)
neighbor_right_prob = results_dict.get(neighbor_right)
# Find the second most likely outcome N2 and its probability P2 among the neighbors.
if neighbor_left_prob is None:
# neighbor_left doesn't exist
if neighbor_right_prob is None:
# both neighbors don't exist, N2 is N1
num_2_key = num_1_key
num_2_prob = num_1_prob
else:
# If only neighbor_left doesn't exist, N2 is neighbor_right.
num_2_key = neighbor_right
num_2_prob = neighbor_right_prob
elif neighbor_right_prob is None:
# If only neighbor_right doesn't exist, N2 is neighbor_left.
num_2_key = neighbor_left
num_2_prob = neighbor_left_prob
elif neighbor_left_prob > neighbor_right_prob:
# Both neighbors exist and neighbor_left has higher probability, so N2 is neighbor_left.
num_2_key = neighbor_left
num_2_prob = neighbor_left_prob
else:
# Both neighbors exist and neighbor_right has higher probability, so N2 is neighor_right.
num_2_key = neighbor_right
num_2_prob = neighbor_right_prob
# Calculate the estimated phases for N1 and N2.
num_qubits = len(num_1_key)
num_1_phase = (int(num_1_key, 2) / 2**num_qubits)
num_2_phase = (int(num_2_key, 2) / 2**num_qubits)
# Calculate the weighted average phase from N1 and N2.
phase_estimated = (num_1_phase * num_1_prob + num_2_phase * num_2_prob) / (num_1_prob + num_2_prob)
return phase_estimated
qpe_solutions = []
for idx, result_dict in enumerate(results.quasi_dists):
qpe_solutions.append(estimate_phase(result_dict.binary_probabilities()))
ideal_solutions = np.append(
phases[:(number_of_phases-1)//2], # first period
np.subtract(phases[(number_of_phases-1)//2:-1], 1) # second period
)
ideal_solutions = np.append(ideal_solutions, np.subtract(phases[-1], 2)) # starting point of the third period
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 6))
plt.plot(phases, ideal_solutions, '--', label='Ideal solutions')
plt.plot(phases, qpe_solutions, 'o', label='QPE solutions')
plt.title('Quantum Phase Estimation Algorithm')
plt.xlabel('Input Phase')
plt.ylabel('Output Phase')
plt.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXDebugging(), backend=FakeBoeblingen())
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
## The Sender entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Sender(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Encode the message (values) using a quantum circuit
def encode_quantum_message(self):
encoded_message = []
for i in range(len(self.axes)):
qc = QuantumCircuit(1, 1)
if self.values[i] == 1:
qc.x(0)
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
encoded_message.append(qc)
return encoded_message
|
https://github.com/sohrabganjian/Quantum-Information-Science
|
sohrabganjian
|
from qiskit import QuantumCircuit, QuantumRegister
# approach 1:
qr = QuantumRegister(1) # QuantumRegister(1) would output QuantumRegister(1, 'q0')
qr
QuantumCircuit(qr)
type(QuantumCircuit(qr))
QuantumCircuit(qr).draw() # better than nothing - but it looks empty for now as we are
# applying any gates to it
QuantumCircuit(1).draw() # this has the same effect
QuantumCircuit(1,1).draw()
# Create a quantum register with one qubit
qr = QuantumRegister(1)
# Create a quantum circuit with the quantum register
circuit = QuantumCircuit(qr)
# Apply the X gate to the first qubit
circuit.x(qr[0])
# Draw the circuit
circuit.draw('mpl') # what does mpl do?
# mpl: images with color rendered purely in Python using matplotlib.
qc = QuantumCircuit(1,0)
qc.x(0)
qc.draw('mpl')
qc = QuantumCircuit(1,1) # adding a classical bit
qc.x(0)
qc.draw('mpl')
qc = QuantumCircuit(1)
qc.y(0)
qc.draw('mpl')
qc = QuantumCircuit(1)
qc.z(0)
qc.draw('mpl')
qc = QuantumCircuit(2,0)
qc.draw()
qc.h(0)
qc.draw()
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
qc.draw('mpl')
from qiskit.visualization import plot_bloch_vector, visualize_transition
from math import sqrt, pi
coords = [1,pi/2,0] # [Radius, Theta, Phi]
plot_bloch_vector(coords, coord_type='spherical')
qc = QuantumCircuit(1)
qc.y(0)
qc.h(0)
qc.z(0)
qc.draw('mpl')
## Takes 30s # uncomment to run
# %%time ## takes a long time to run this cell, about 30 seconds!
# ## it creates a useful animation that shows the effect of quantum gates over time
# visualize_transition(qc)
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import numpy as np
from linear_solver_float import LinearSolverFloat
# set floating point accuracy
R = 4
# first example
M = np.array([[1/2,3/2],
[3/2,1/2]])
Y_1 = np.array([1,0])
Y_2 = np.array([0,1])
M_inv = np.linalg.inv(M)
M_inv.dot(Y_1), M_inv.dot(Y_2)
num_reads = 1000
lsf = LinearSolverFloat(M,Y_1,R=R,num_reads=num_reads)
sampleset = lsf.sample()
sampleset.to_pandas_dataframe()
min_occurence = num_reads / 20
solutions = lsf.getSolutions(min_occurence)
list(solutions)
lsf.setY(Y_2)
lsf.sample() # 050d68cf-b1d7-4ba5-acdb-688140e88c15
list(lsf.getSolutions(min_occurence))
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# 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.
"""Test RemoveDiagonalGatesBeforeMeasure pass"""
import unittest
from copy import deepcopy
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit.library import U1Gate, CU1Gate
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import RemoveDiagonalGatesBeforeMeasure, DAGFixedPoint
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TesRemoveDiagonalGatesBeforeMeasure(QiskitTestCase):
"""Test remove_diagonal_gates_before_measure optimizations."""
def test_optimize_1rz_1measure(self):
"""Remove a single RZGate
qr0:-RZ--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1z_1measure(self):
"""Remove a single ZGate
qr0:--Z--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.z(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1t_1measure(self):
"""Remove a single TGate, SGate, TdgGate, SdgGate, U1Gate
qr0:--T--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.t(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1s_1measure(self):
"""Remove a single SGate
qr0:--S--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.s(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1tdg_1measure(self):
"""Remove a single TdgGate
qr0:-Tdg-m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.tdg(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1sdg_1measure(self):
"""Remove a single SdgGate
qr0:-Sdg--m-- qr0:--m-
| |
qr1:------|-- ==> qr1:--|-
| |
cr0:------.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.sdg(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1u1_1measure(self):
"""Remove a single U1Gate
qr0:--U1-m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(U1Gate(0.1), [qr[0]])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1rz_1z_1measure(self):
"""Remove a single RZ and leave the other Z
qr0:-RZ--m-- qr0:----m-
| |
qr1:--Z--|-- ==> qr1:--Z-|-
| |
cr0:-----.-- cr0:----.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[0])
circuit.z(qr[1])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.z(qr[1])
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_simple_if_else(self):
"""Test that the pass recurses into an if-else."""
pass_ = RemoveDiagonalGatesBeforeMeasure()
base_test = QuantumCircuit(1, 1)
base_test.z(0)
base_test.measure(0, 0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
test = QuantumCircuit(1, 1)
test.if_else(
(test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits
)
expected = QuantumCircuit(1, 1)
expected.if_else(
(expected.clbits[0], True),
base_expected.copy(),
base_expected.copy(),
expected.qubits,
expected.clbits,
)
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the pass recurses into nested control flow."""
pass_ = RemoveDiagonalGatesBeforeMeasure()
base_test = QuantumCircuit(2, 1)
base_test.cz(0, 1)
base_test.measure(0, 0)
base_expected = QuantumCircuit(2, 1)
base_expected.measure(1, 0)
body_test = QuantumCircuit(2, 1)
body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits)
body_expected = QuantumCircuit(2, 1)
body_expected.for_loop(
(0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits
)
test = QuantumCircuit(2, 1)
test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits)
expected = QuantumCircuit(2, 1)
expected.while_loop(
(expected.clbits[0], True), body_expected, expected.qubits, expected.clbits
)
self.assertEqual(pass_(test), expected)
class TesRemoveDiagonalControlGatesBeforeMeasure(QiskitTestCase):
"""Test remove diagonal control gates before measure."""
def test_optimize_1cz_2measure(self):
"""Remove a single CZGate
qr0:--Z--m--- qr0:--m---
| | |
qr1:--.--|-m- ==> qr1:--|-m-
| | | |
cr0:-----.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1crz_2measure(self):
"""Remove a single CRZGate
qr0:-RZ--m--- qr0:--m---
| | |
qr1:--.--|-m- ==> qr1:--|-m-
| | | |
cr0:-----.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.crz(0.1, qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1cu1_2measure(self):
"""Remove a single CU1Gate
qr0:-CU1-m--- qr0:--m---
| | |
qr1:--.--|-m- ==> qr1:--|-m-
| | | |
cr0:-----.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU1Gate(0.1), [qr[0], qr[1]])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1rzz_2measure(self):
"""Remove a single RZZGate
qr0:--.----m--- qr0:--m---
|zz | |
qr1:--.----|-m- ==> qr1:--|-m-
| | | |
cr0:-------.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rzz(0.1, qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
class TestRemoveDiagonalGatesBeforeMeasureOveroptimizations(QiskitTestCase):
"""Test situations where remove_diagonal_gates_before_measure should not optimize"""
def test_optimize_1cz_1measure(self):
"""Do not remove a CZGate because measure happens on only one of the wires
Compare with test_optimize_1cz_2measure.
qr0:--Z--m---
| |
qr1:--.--|---
|
cr0:-----.---
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = deepcopy(dag)
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(expected, after)
def test_do_not_optimize_with_conditional(self):
"""Diagonal gates with conditionals on a measurement target.
See https://github.com/Qiskit/qiskit-terra/pull/2208#issuecomment-487238819
░ ┌───┐┌─┐
qr_0: |0>────────────░─┤ H ├┤M├
┌─────────┐ ░ └───┘└╥┘
qr_1: |0>┤ Rz(0.1) ├─░───────╫─
└─┬──┴──┬─┘ ░ ║
cr_0: 0 ══╡ = 1 ╞═══════════╩═
└─────┘
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[1]).c_if(cr, 1)
circuit.barrier()
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = deepcopy(dag)
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(expected, after)
class TestRemoveDiagonalGatesBeforeMeasureFixedPoint(QiskitTestCase):
"""Test remove_diagonal_gates_before_measure optimizations in
a transpiler, using fixed point."""
def test_optimize_rz_z(self):
"""Remove two swaps that overlap
qr0:--RZ-Z--m-- qr0:--m--
| |
cr0:--------.-- cr0:--.--
"""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[0])
circuit.z(qr[0])
circuit.measure(qr[0], cr[0])
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_manager = PassManager()
pass_manager.append(
[RemoveDiagonalGatesBeforeMeasure(), DAGFixedPoint()],
do_while=lambda property_set: not property_set["dag_fixed_point"],
)
after = pass_manager.run(circuit)
self.assertEqual(expected, after)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
with pulse.build(name='my_example') as my_program:
# Add instructions here
pass
my_program
from qiskit.pulse import DriveChannel
channel = DriveChannel(0)
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend=backend, name='backend_aware') as backend_aware_program:
channel = pulse.drive_channel(0)
print(pulse.num_qubits())
# Raises an error as backend only has 5 qubits
#pulse.drive_channel(100)
with pulse.build(backend) as delay_5dt:
pulse.delay(5, channel)
from qiskit.pulse import library
amp = 1
sigma = 10
num_samples = 128
gaus = pulse.library.Gaussian(num_samples, amp, sigma,
name="Parametric Gaus")
gaus.draw()
import numpy as np
times = np.arange(num_samples)
gaussian_samples = np.exp(-1/2 *((times - num_samples / 2) ** 2 / sigma**2))
gaus = library.Waveform(gaussian_samples, name="WF Gaus")
gaus.draw()
gaus = library.gaussian(duration=num_samples, amp=amp, sigma=sigma, name="Lib Gaus")
gaus.draw()
with pulse.build() as schedule:
pulse.play(gaus, channel)
schedule.draw()
with pulse.build() as schedule:
pulse.play([0.001*i for i in range(160)], channel)
schedule.draw()
with pulse.build(backend) as schedule:
pulse.set_frequency(4.5e9, channel)
with pulse.build(backend) as schedule:
pulse.shift_phase(np.pi, channel)
from qiskit.pulse import Acquire, AcquireChannel, MemorySlot
with pulse.build(backend) as schedule:
pulse.acquire(1200, pulse.acquire_channel(0), MemorySlot(0))
with pulse.build(backend, name='Left align example') as program:
with pulse.align_left():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='Right align example') as program:
with pulse.align_right():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='example') as program:
gaussian_pulse = library.gaussian(100, 0.5, 20)
with pulse.align_equispaced(2*gaussian_pulse.duration):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='example') as program:
with pulse.align_sequential():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='Offset example') as program:
with pulse.phase_offset(3.14, pulse.drive_channel(0)):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
with pulse.frequency_offset(10e6, pulse.drive_channel(0)):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
program.draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/conradhaupt/Qiskit-Bayesian-Inference-Module-QCA19-
|
conradhaupt
|
# Import major packages
import qiskit as qk
import qinfer as qf
import numpy as np
import matplotlib as mpl
# Qiskit imports for IQPE
from qiskit import IBMQ
from qiskit.aqua.algorithms.single_sample import IQPE,QPE
from qiskit.aqua.components import iqfts
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.aqua.algorithms import ExactEigensolver
from qiskit.aqua.components.initial_states import Custom
from qiskit import Aer,execute
from qiskit.aqua import QuantumInstance
from qiskit.providers.aer import noise
# QInfer imports for modelling the IQPE algorithm
from qinfer import distributions
from qinfer.smc import SMCUpdater # The QInfer Sequantial Monte-Carlo Sampler
from qinfer import FiniteOutcomeModel
# Tertiary imports
import matplotlib.pyplot as plt
import time
# Intial setup
IBMQ.load_account()
ibmqx_provider = IBMQ.get_provider(hub='ibm-q-wits', group='internal', project='default')
mpl.rc('text', usetex=True)
# Function definitions for the entire notebook
EPS = 1e-15
def chop(value):
if np.abs(value) <= EPS:
return 0
else:
return value
def radiandiff(a,b):
FULL_ROTATION = 2 * np.pi
return np.min(np.abs([a - b, b - a, a - b + FULL_ROTATION, b - a + FULL_ROTATION]))
def complexfromangle(angle):
real = chop(np.real(np.exp(1.j * angle)))
imag = chop(np.imag(np.exp(1.j * angle)))
return real,imag
# Set-up unitary with specified phase
angle = 4 * np.pi / 5
real,imag = complexfromangle(angle)
PAULI_DICT_ZZ = {
'paulis': [
{"coeff": {"imag": imag, "real": real}, "label": "ZZ"}
]
}
QUBIT_OP_ZZ = WeightedPauliOperator.from_dict(PAULI_DICT_ZZ)
eigen_results = ExactEigensolver(QUBIT_OP_ZZ,4).run()
eigen_value = eigen_results['eigvals'][0]
eigen_vector = eigen_results['eigvecs'][0]
print('Eigenvalues',eigen_results['eigvals'])
print('Phase is %.4f radians' %(angle))
# Setup initial state as eigenvector
state_in = Custom(QUBIT_OP_ZZ.num_qubits, state_vector=eigen_vector)
# Use QASM Simulator for testing
simulator = Aer.get_backend('qasm_simulator')
# Construct IQPE circuit and simulate
iqpe_builder = IQPE(
QUBIT_OP_ZZ,
state_in,
num_iterations=1,
num_time_slices=1,
expansion_mode='suzuki',
expansion_order=1,
shallow_circuit_concat=True)
# This is required to setup iqpe_builder so we can call construct_circuit() later on
iqpe_results = iqpe_circ = iqpe_builder.run(simulator,shots=1)
# Extend the QInfer FiniteOutcomeModel as IQPE has only one bit per measure
class IQPEModel(FiniteOutcomeModel):
def __init__(self):
super(IQPEModel, self).__init__()
# Number of parameters overwhich to conduct the Bayesian Inference
@property
def n_modelparams(self):
# phi
return 1
# Number of parameters that are needed for the simulation but are known.
# i.e. do not need to be inferred
@property
def expparams_dtype(self):
return [('theta','float64'), ('m','int64')]
@property
def is_n_outcomes_constant(self):
return True
# This function will verify whether the new inferred model parameters are valid for our model.
@staticmethod
def are_models_valid(modelparams):
# NOTE: If T2 is included as a model parameter, restrict it to positive
return np.logical_and(modelparams[:] >= -2*np.pi, modelparams[:]<=2*np.pi, modelparams[:] > 0).all(axis=1)
def n_outcomes(self, expparams):
return 2
# This function implements our probability for reading a 0 or 1 on our IQPE circuit.
# These equations are taken from [1] and are used by the updater/sampler to modify the posterior
def likelihood(self, outcomes, modelparams, expparams):
super(IQPEModel, self).likelihood(outcomes, modelparams, expparams)
# Probability of getting 0 for IQPE is
# P(0) = (1 + cos(M(theta - phi)))/2
# P(1) = (1 - cos(M(theta - phi)))/2
# This is the probability of getting a 0 with T2 depolarisation noise from [1].
# Not currently used.
# pr0 = np.exp(-expparams['m'] / expparams['T2']) * (1 + np.cos(expparams['m'] * (expparams['theta'] - modelparams[:]))) / 2 + (1 - np.exp(-expparams['m'] / expparams['T2']))/2
pr0 = (1 + np.cos(expparams['m'] * (expparams['theta'] - modelparams[:]))) / 2
return FiniteOutcomeModel.pr0_to_likelihood_array(outcomes, pr0)
# As our model parameter is an angle, ensure we have the circular mean for the distribution so we allow
# for wraparound. This is done by converting angles to x,y points on a unit circle, averaging over
# x and y independently, and then combining the resulting average x and y values to create a new
# vector. If the resulting magnitude is 0, there is no circular average as all points are equi-distant.
# The resulting angle is approximately the circular average of the collection of angles/phases.
class PhaseSMCUpdater(SMCUpdater):
@staticmethod
def particle_mean(weights,locations):
locs = [complexfromangle(a) for a in locations.flatten()]
loc_x = []
loc_y = []
for x,y in locs:
loc_x.append(x)
loc_y.append(y)
avg_x = np.average(loc_x,weights=weights)
avg_y = np.average(loc_y,weights=weights)
avg_angle = np.angle(avg_x + 1.j*avg_y)
avg_mag = np.sqrt(avg_x**2 + avg_y**2)
return avg_angle
# Bayesien Inference Parameters
N_PARTICLES = 5000 # number of samples for PhaseSMCUpdater
N_EXP = 25 # Number of times to choose a new theta
USE_QISKIT_QASM_SIMULATOR = True # Toggle parameter if we don't want to run any circuit simulations
SIM_N_SHOTS=1024 # number of shots for the circuit execution
# DType list for experiment metric logging
performance_dtype = [
('outcome', 'i1'),
('est_mean', 'f8'), ('est_cov_mat', 'f8'),
('true_err', 'f8'), ('resample_count', 'i8'),
('elapsed_time', 'f8'),
('like_count', 'i8'), ('sim_count', 'i8'),
('bme', 'f8'),
('var', 'f8'),
('bme_err', 'f8')
]
performance = np.empty((N_EXP), dtype=performance_dtype)
# Set-up initial prior and QInfer model
# prior = distributions.UniformDistribution([0, 2 * np.pi])
prior = distributions.NormalDistribution(angle,np.pi/4)
model = IQPEModel()
# Use IBMQX Rochester as the base device for the partially ideal noise-model. We
backend_device = ibmqx_provider.get_backend('ibmq_rochester')
partially_ideal_model = noise.device.basic_device_noise_model(
backend_device.properties(),gate_error=False,readout_error=False,
thermal_relaxation=False,standard_gates=True)
data_backend = Aer.get_backend('qasm_simulator')
# Create a Bayesian Inference Updater
updater = PhaseSMCUpdater(model, N_PARTICLES, prior,zero_weight_policy='skip')
# Set-up initial experimental parameters
THETA = prior.sample()[0][0]
M = 1
T2 = 100
posterior_marginal = []
##############################################
# Run for each experiment we defined earlier #
##############################################
for idx_exp in range(N_EXP):
# Define experimental parameters
expparams = np.array([(M,THETA)], dtype=model.expparams_dtype)
# Simulate IQPE circuit and get results for inference
circuit = iqpe_builder.construct_circuit(k=M,omega=THETA,measurement=True)
results = execute(circuit,simulator,shots=SIM_N_SHOTS,memory=True,noise_model=ideal_model)
counts = results.result().get_counts()
memory = results.result().get_memory()
# Start by simulating and recording the data. #
# Retrieve the outcome of the simulation either from the circuit simulation or a model simulation
if USE_QISKIT_QASM_SIMULATOR:
outcomes = np.array([[int(m) for m in memory]])
else:
outcomes = model.simulate_experiment(np.array([[angle]]),expparams,repeat=SIM_N_SHOTS)
outcomes = outcomes.reshape((1,outcomes.shape[0]))
model._sim_count = 0
model._call_count = 0
# Time the update process
# tic = toc = None
# tic = time.time()
# Update the posterior particles using the result of the circuit simulation
updater.batch_update(outcomes, expparams)
# performance[idx_exp]['elapsed_time'] = time.time() - tic
# Record the performance of this updater.
est_mean = updater.est_mean()
performance[idx_exp]['est_mean'] = est_mean
performance[idx_exp]['true_err'] = radiandiff(est_mean,angle) ** 2
performance[idx_exp]['est_cov_mat'] = updater.est_covariance_mtx()
performance[idx_exp]['resample_count'] = updater.resample_count
performance[idx_exp]['like_count'] = model.call_count
performance[idx_exp]['sim_count'] = model.sim_count
# Log
print(idx_exp,'/',N_EXP,'[',M,THETA,est_mean,']')
# Re-evaluate experiment parameters
uniform_draw_01 = np.random.uniform(low=0.05,high=0.95)
# uniform_draw_01 = np.random.uniform()
cumsum_particles = np.cumsum(updater.particle_weights)
draw_index = (cumsum_particles<= uniform_draw_01).argmin()
THETA = updater.particle_locations[draw_index]
# current_variance = updater.est_covariance_mtx()[0][0]
# M=idx_exp % 6 + 1
posterior_marginal.append((updater.posterior_marginal()))
print('Inference completed')
# Plot for each iteration
print(angle)
fig_iter = plt.figure()
ax_iter = plt.subplot(111)
for x in posterior_marginal:
# print(x[0],x[1])
_ = ax_iter.plot(x[0],x[1])
ax_iter.vlines(angle,ymin=0,ymax=2)
_ = ax_iter.legend(['Iter ' + str(x) for x in range(len(posterior_marginal))])
_ = plt.grid()
_ = plt.ylabel('PDF')
_ = plt.xlabel(r'$\phi$')
_ = plt.title('Posterior Marginal for some iterations')
ax_qinfer = updater.plot_posterior_marginal(smoothing=0)
plt.vlines(angle,ymin=0,ymax=3)
plt.grid()
_ = plt.ylabel('PDF')
_ = plt.xlabel(r'$\phi$')
_ = plt.title('IQPE Posterior')
fig_true_err = plt.figure()
ax_true_err = plt.subplot(111)
ax_true_err.semilogy(performance['true_err'])
ax_true_err.grid()
_ = plt.xlabel('Iteration count')
_ = plt.ylabel('True Error')
_ = plt.title('True Error over each Iteration')
fig_est_mean = plt.figure()
ax_est_mean = plt.subplot(111)
ax_est_mean.plot(performance['est_mean'])
ax_est_mean.grid()
ax_est_mean.hlines(angle,xmin=0,xmax=N_EXP)
_ = plt.xlabel('Iteration count')
_ = plt.ylabel('Estimated $\phi$ (mean)')
_ = plt.title('Estimated Mean for each Iteration')
|
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
|
nahumsa
|
import qiskit as qsk
import numpy as np
import matplotlib.pyplot as plt
def measure_X(circuit,n):
circuit.barrier(n)
circuit.h(n)
circuit.measure(n,n)
return circuit
def measure_Y(circuit,n):
circuit.barrier(n)
circuit.sdg(n)
circuit.h(n)
circuit.measure(n,n)
return circuit
def tomography(circuit):
""" Tomography of a one qubit Circuit.
"""
qc_list = []
base = ['X', 'Y', 'Z']
for basis in base:
Q = qsk.QuantumCircuit(1,1)
Q.append(circuit, [0])
if basis == 'X':
measure_X(Q, 0)
qc_list.append(Q)
if basis == 'Y':
measure_Y(Q, 0)
qc_list.append(Q)
if basis == 'Z':
Q.measure(0,0)
qc_list.append(Q)
return qc_list, base
qc = qsk.QuantumCircuit(1)
qc.h(0)
qcs, bases = tomography(qc)
backend_sim = qsk.Aer.get_backend('qasm_simulator')
job = qsk.execute(qcs, backend_sim, shots=5000)
result = job.result()
for index, circuit in enumerate(qcs):
print(result.get_counts(circuit))
print(f'Base measured {bases[index]}\n')
def get_density_matrix(measurements,circuits):
"""Get density matrix from tomography measurements.
"""
density_matrix = np.eye(2, dtype=np.complex128)
sigma_x = np.array([[0,1],[1,0]])
sigma_y = np.array([[0,-1j],[1j,0]])
sigma_z = np.array([[1,0],[0,-1]])
basis = [sigma_x, sigma_y, sigma_z]
for index in range(len(circuits)):
R = measurements.get_counts(index)
if '0' in R.keys() and '1' in R.keys():
zero = R['0']
one = R['1']
elif '1' in R.keys():
zero = 0
one = R['1']
elif '0' in R.keys():
zero = R['0']
one = 0
total = sum(list(R.values()))
expected = (zero - one)/total
density_matrix += expected * basis[index]
return 0.5*density_matrix
density = get_density_matrix(result,qcs)
print(density)
def plot_density_matrix(DM):
"""Helper function to plot density matrices.
Parameters
----------------------------------------------
DM(np.array): Density Matrix.
"""
from matplotlib.ticker import MaxNLocator
fig = plt.figure(figsize=(16,10))
gs = fig.add_gridspec(1, 2)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
im = ax1.imshow(np.real(DM), cmap='Greys')
ax1.yaxis.set_major_locator(MaxNLocator(integer=True))
ax1.xaxis.set_major_locator(MaxNLocator(integer=True))
ax1.set_title('Real Part',size=16)
plt.colorbar(im, ax=ax1)
im = ax2.imshow(np.imag(DM), cmap='Greys')
plt.colorbar(im, ax=ax2)
ax2.yaxis.set_major_locator(MaxNLocator(integer=True))
ax2.xaxis.set_major_locator(MaxNLocator(integer=True))
ax2.set_title('Imaginary Part',size=16)
plt.show()
plot_density_matrix(density)
from qiskit.ignis.verification.tomography import state_tomography_circuits
tomography_circuits = state_tomography_circuits(qc, [0], meas_labels='Pauli', meas_basis='Pauli')
tomography_circuits[1].draw('mpl')
backend_sim = qsk.Aer.get_backend('qasm_simulator')
job = qsk.execute(tomography_circuits, backend_sim, shots=5000)
result = job.result()
from qiskit.ignis.verification.tomography import StateTomographyFitter
state_fitter = StateTomographyFitter(result, tomography_circuits, meas_basis='Pauli')
density_matrix = state_fitter.fit(method='lstsq')
print(density_matrix)
plot_density_matrix(density_matrix)
qc = qsk.QuantumCircuit(3)
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.draw('mpl')
from qiskit.ignis.verification.tomography import state_tomography_circuits
tomography_circuits = state_tomography_circuits(qc, [0,1,2],
meas_labels='Pauli',
meas_basis='Pauli')
backend_sim = qsk.Aer.get_backend('qasm_simulator')
job = qsk.execute(tomography_circuits, backend_sim, shots=5000)
result = job.result()
from qiskit.ignis.verification.tomography import StateTomographyFitter
state_fitter = StateTomographyFitter(result, tomography_circuits, meas_basis='Pauli')
density_matrix = state_fitter.fit(method='lstsq')
plot_density_matrix(density_matrix)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can make the bars more transparent to better see the ones that are behind
# if they overlap.
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
state = Statevector(qc)
plot_state_city(state, alpha=0.6)
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
import pandas as pd
import math
import numpy as np
import scipy.stats as sci
from qiskit import execute
from qiskit.circuit import ClassicalRegister
def returnPhase(backend, quantumCircuit, qubits_to_assert, expected_phases, measurements_to_make, tolerance):
## if "qubits to assert" is just a single value, convert it to a list containing the single value
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
## if "expected phases" is just a single value, convert it to a list containing the single value
if (not isinstance(expected_phases, list)):
expected_phases = [expected_phases]
## needs to make at least 2 measurements, one for x axis, one for y axis
## realistically we need more for any statistical significance
if (measurements_to_make < 2):
raise ValueError("Must make at least 2 measurements")
## classical register must be of same length as amount of qubits to assert
## if there is no classical register, add one
if (quantumCircuit.num_clbits == 0):
quantumCircuit.add_register(ClassicalRegister(len(qubits_to_assert)))
elif (quantumCircuit.num_clbits != len(qubits_to_assert)):
raise ValueError("QuantumCircuit classical register length not equal to qubits to assert")
## divide measurements to make by 2 as we need to run measurements twice, one for x and one for y
measurements_to_make = measurements_to_make // 2
## copy the circit and set measurement to y axis
yQuantumCircuit = measure_y(quantumCircuit.copy(), qubits_to_assert)
## measure the x axis
xQuantumCircuit = measure_x(quantumCircuit, qubits_to_assert)
## get y axis results
yJob = execute(yQuantumCircuit, backend, shots=measurements_to_make, memory=True)
yCounts = yJob.result().get_counts()
## get x axis results
xJob = execute(xQuantumCircuit, backend, shots=measurements_to_make, memory=True)
xCounts = xJob.result().get_counts()
## make a df to keep track of the predicted angles
resDf = pd.DataFrame(columns=['+','i','-','-i'])
## fill the df with the x and y results of each qubit that is being asserted
classical_qubit_index = 1
for qubit in qubits_to_assert:
plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0
for experiment in xCounts:
if (experiment[len(qubits_to_assert)-classical_qubit_index] == '0'):
plus_amount += xCounts[experiment]
else:
minus_amount += xCounts[experiment]
for experiment in yCounts:
if (experiment[len(qubits_to_assert)-classical_qubit_index] == '0'):
i_amount += yCounts[experiment]
else:
minus_i_amount += yCounts[experiment]
df = {'+':plus_amount, 'i':i_amount,
'-':minus_amount, '-i':minus_i_amount}
resDf = resDf.append(df, ignore_index = True)
classical_qubit_index+=1
## convert the columns to a strict numerical type
resDf['+'] = resDf['+'].astype(int)
resDf['i'] = resDf['i'].astype(int)
resDf['-'] = resDf['-'].astype(int)
resDf['-i'] = resDf['-i'].astype(int)
## make a dataframe that contains p values of chi square tests to analyse results
## if x and y counts are both 25/25/25/25, it means that we cannot calculate a phase
## we assume that a qubit that is in |0> or |1> position to have 50% chance to fall
## either way, like a coin toss: We treat X and Y results like coin tosses
pValues = pd.DataFrame(columns=['X','Y'])
pValues['X'] = resDf.apply(lambda row: applyChiSquareX(row, measurements_to_make/2), axis=1)
pValues['Y'] = resDf.apply(lambda row: applyChiSquareY(row, measurements_to_make/2), axis=1)
## check p values on chi square test, we use a low value to be sure that
## we only except if we are certain there is an issue with the x, y results
pValues = pValues > 0.00001
## if both pvalues are more than 0.00001, we are pretty certain that the results follow an even distribution
## likely that the qubit is not in the fourier basis (very likely in the |0> or |1> state)
pValues.apply(lambda row: assertIfBothTrue(row), axis=1)
## this sequence of operations converts from measured results
## into an angle for phase:
## with 0 ( 0 rad) signifying the |+> state
## with 90 ( pi/2 rad) signifying the |i> state
## with 180 ( pi rad) signifying the |-> state
## with 270 (3 * pi/2 rad) signifying the |-i> state
resDf = resDf / measurements_to_make
resDf = resDf * 2
resDf = resDf - 1
resDf = np.arccos(resDf)
resDf = resDf * 180
resDf = resDf / math.pi
## to get a final result for phase on each qubit:
## we must get the lowest 2 values for each column
lowestDf = pd.DataFrame(columns=['lowest','lowest-location','second-lowest','second-lowest-location','estimated-phase'])
## store the lowest value as well as what column it is from
lowestDf['lowest'] = resDf.min(axis=1)
lowestDf['lowest-location'] = resDf.idxmin(axis=1)
## remove the lowest value from the dataframe
lowestDf = lowestDf.apply(lambda row: setLowestCellToNan(row, resDf), axis=1)
## store the second lowest value from the dataframe as well as the column
lowestDf['second-lowest'] = resDf.min(axis=1)
lowestDf['second-lowest-location'] = resDf.idxmin(axis=1)
## estimate the phase and put it in a new column
lowestDf['estimated-phase'] = lowestDf.apply(lambda row: setPhaseEstimate(row, resDf), axis=1)
## check that the estimated phase fits in the tolerance
lowestDf.apply(lambda row: assertIfExpectedDoNotFitTolerance(row, expected_phases, tolerance), axis=1)
return(lowestDf['estimated-phase'][0])
#return(lowestDf['estimated-phase'][0])
def measure_x(circuit, qubitIndexes):
cBitIndex = 0
for index in qubitIndexes:
circuit.h(index)
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def measure_y(circuit, qubit_indexes):
cBitIndex = 0
for index in qubit_indexes:
circuit.sdg(index)
circuit.h(index)
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def setLowestCellToNan(row, resDf):
for col in row.index:
resDf.iloc[row.name][row[col]] = np.nan
return row
def setPhaseEstimate(row, resDf):
overallPhase = 0
if(row['lowest-location'] == '+'):
if(row['second-lowest-location'] == 'i'):
overallPhase = 0 + row['lowest']
elif (row['second-lowest-location'] == '-i'):
overallPhase = 360 - row['lowest']
if (row['lowest'] == 0):
overallPhase = 0
elif(row['lowest-location'] == 'i'):
if(row['second-lowest-location'] == '+'):
overallPhase = 90 - row['lowest']
elif (row['second-lowest-location'] == '-'):
overallPhase = 90 + row['lowest']
elif(row['lowest-location'] == '-'):
if(row['second-lowest-location'] == 'i'):
overallPhase = 180 - row['lowest']
elif (row['second-lowest-location'] == '-i'):
overallPhase = 180 + row['lowest']
elif(row['lowest-location'] == '-i'):
if(row['second-lowest-location'] == '+'):
overallPhase = 270 + row['lowest']
elif (row['second-lowest-location'] == '-'):
overallPhase = 270 - row['lowest']
return overallPhase
def applyChiSquareX(row, expected_amount):
observed = [row['+'],row['-']]
expected = [expected_amount,expected_amount]
return(sci.chisquare(f_obs=observed, f_exp=expected)[1])
def applyChiSquareY(row, expected_amount):
observed = [row['i'],row['-i']]
expected = [expected_amount,expected_amount]
return(sci.chisquare(f_obs=observed, f_exp=expected)[1])
def assertIfBothTrue(row):
if row.all():
#raise AssertionError("Qubit does not appear to have a phase applied to it!")
pass
def assertIfExpectedDoNotFitTolerance(row, expected, tolerance):
deltaAngle = (row['estimated-phase'] - expected[row.name] + 180 + 360) % 360 - 180
#print('observed: ' + str(row['estimated-phase']))
#print('predicted: ' + str(expected[row.name]))
#print('diff: ' + str(deltaAngle))
if (abs(deltaAngle) > tolerance):
#raise AssertionError(f"The estimated angle ({row['estimated-phase']}) is off the prediction ({expected[row.name]}) +- tolerance value ({tolerance}) specified")
pass
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
def trotter_gate(dt, to_instruction = True):
qc = QuantumCircuit(2)
qc.rx(2*dt,0)
qc.rz(2*dt,1)
qc.h(1)
qc.cx(1,0)
qc.rz(-2*dt, 0)
qc.rx(-2*dt, 1)
qc.rz(2*dt, 1)
qc.cx(1,0)
qc.h(1)
qc.rz(2*dt, 0)
return qc.to_instruction() if to_instruction else qc
trotter_gate(np.pi / 6, to_instruction=False).draw("mpl")
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
Trot_gate = trotter_gate(dt)
# Number of trotter steps
trotter_steps = 15 ### CAN BE >= 4
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(5)
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
qc.x([2]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, [qr[1], qr[2]])
qc.cx(qr[1], qr[0])
qc.cx(qr[2], qr[1])
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time/trotter_steps})
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(t3_qc, [qr[0], qr[1], qr[2]])
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw("mpl") # only view trotter gates
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_quito")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3)
print('Job ID', cal_job.job_id())
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = []
for job in jobs:
mit_results.append( meas_fitter.filter.apply(job.result()) )
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Compute tomography fidelities for each repetition
fids = []
for result in mit_results:
fid = state_tomo(result, st_qcs)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# we may break lines when defining our list
M = [
[8 , 0 , -1 , 0 , 2],
[-2 , -3 , 1 , 1 , 4],
[0 , 0 , 1 , -7 , 1],
[1 , 4 , -2 , 5 , 9]
]
# let's print matrix M
print(M)
# let's print M in matrix form, row by row
for i in range(4): # there are 4 rows
print(M[i])
M = [
[8 , 0 , -1 , 0 , 2],
[-2 , -3 , 1 , 1 , 4],
[0 , 0 , 1 , -7 , 1],
[1 , 4 , -2 , 5 , 9]
]
#let's print the element of M in the 1st row and the 1st column.
print(M[0][0])
#let's print the element of M in the 3rd row and the 4th column.
print(M[2][3])
#let's print the element of M in the 4th row and the 5th column.
print(M[3][4])
# we use double nested for-loops
N =[] # the result matrix
for i in range(4): # for each row
N.append([]) # create an empty sub-list for each row in the result matrix
for j in range(5): # in row (i+1), we do the following for each column
N[i].append(M[i][j]*-2) # we add new elements into the i-th sub-list
# let's print M and N, and see the results
print("I am M:")
for i in range(4):
print(M[i])
print()
print("I am N:")
for i in range(4):
print(N[i])
# create an empty list for the result matrix
K=[]
for i in range(len(M)): # len(M) return the number of rows in M
K.append([]) # we create a new row for K
for j in range(len(M[0])): # len(M[0]) returns the number of columns in M
K[i].append(M[i][j]+N[i][j]) # we add new elements into the i-th sublist/rows
# print each matrix in a single line
print("M=",M)
print("N=",N)
print("K=",K)
from random import randrange
#
# your solution is here
#
M = [
[-2,3,0,4],
[-1,1,5,9]
]
N =[
[1,2,3],
[4,5,6],
[7,8,9]
]
#
# your solution is here
#
# matrix M
M = [
[-1,0,1],
[-2,-3,4],
[1,5,6]
]
# vector v
v = [1,-3,2]
# the result vector u
u = []
# for each row, we do an inner product
for i in range(3):
# inner product for one row is initiated
inner_result = 0 # this variable keeps the summation of the pairwise multiplications
for j in range(3): # the elements in the i-th row
inner_result = inner_result + M[i][j] * v[j]
# inner product for one row is completed
u.append(inner_result)
print("M is")
for i in range(len(M)):
print(M[i])
print()
print("v=",v)
print()
print("u=",u)
#
# your solution is here
#
# matrix M
M = [
[-1,0,1],
[-2,-1,2],
[1,2,-2]
]
# matrix N
M = [
[0,2,1],
[3,-1,-2],
[-1,1,0]
]
# matrix K
K = []
#
# your solution is here
#
#
# your solution is here
#
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
https://github.com/infiniteregrets/QiskitBot
|
infiniteregrets
|
LIB_IMPORT="""
from qiskit import QuantumCircuit
from qiskit import execute, Aer
from qiskit.visualization import *"""
CIRCUIT_SCRIPT="""
circuit = build_state()
circuit.measure_all()
figure = circuit.draw('mpl')
output = figure.savefig('circuit.png')"""
PLOT_SCRIPT="""
backend = Aer.get_backend("qasm_simulator")
job = execute(circuit,backend=backend, shots =1000)
counts = job.result().get_counts()
plot_histogram(counts).savefig('plot.png', dpi=100, quality=90)"""
ASCII_CIRCUIT_SCRIPT="""
circuit = build_state()
print(circuit)
"""
|
https://github.com/abbarreto/qiskit3
|
abbarreto
| |
https://github.com/abhik-99/Qiskit-Summer-School
|
abhik-99
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import transpile
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc_basis = transpile(qc, backend)
qc_basis.draw(output='mpl')
|
https://github.com/vm6502q/qiskit-qrack-provider
|
vm6502q
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 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.
"""
QasmSimulator Integration Tests
"""
import multiprocessing
import psutil
from qiskit import execute, QuantumCircuit
from qiskit.circuit.library import QuantumVolume
from qiskit.providers.qrack import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors.standard_errors import pauli_error
from test.terra.decorators import requires_omp, requires_multiprocessing
# pylint: disable=no-member
class QasmThreadManagementTests:
"""QasmSimulator thread tests."""
SIMULATOR = QasmSimulator()
BACKEND_OPTS = {}
def backend_options_parallel(self,
total_threads=None,
state_threads=None,
shot_threads=None,
exp_threads=None):
"""Backend options with thread manangement."""
opts = self.BACKEND_OPTS.copy()
if total_threads:
opts['max_parallel_threads'] = total_threads
else:
opts['max_parallel_threads'] = 0
if shot_threads:
opts['max_parallel_shots'] = shot_threads
if state_threads:
opts['max_parallel_state_update'] = state_threads
if exp_threads:
opts['max_parallel_experiments'] = exp_threads
return opts
def dummy_noise_model(self):
"""Return dummy noise model for dummy circuit"""
noise_model = NoiseModel()
error = pauli_error([('X', 0.25), ('I', 0.75)])
noise_model.add_all_qubit_quantum_error(error, 'x')
return noise_model
def dummy_circuit(self, num_qubits):
"""Dummy circuit for testing thread settings"""
circ = QuantumCircuit(num_qubits, num_qubits)
circ.x(range(num_qubits))
circ.measure(range(num_qubits), range(num_qubits))
return circ
def measure_in_middle_circuit(self, num_qubits):
"""Dummy circuit for testing thread settings"""
circ = QuantumCircuit(num_qubits, num_qubits)
circ.measure(range(num_qubits), range(num_qubits))
circ.x(range(num_qubits))
circ.measure(range(num_qubits), range(num_qubits))
return circ
def threads_used(self, result):
"""Return a list of threads used for each execution"""
exp_threads = getattr(result, 'metadata', {}).get('parallel_experiments', 1)
threads = []
for exp_result in getattr(result, 'results', []):
exp_meta = getattr(exp_result, 'metadata', {})
shot_threads = exp_meta.get('parallel_shots', 1)
state_threads = exp_meta.get('parallel_state_update', 1)
threads.append({
'experiments': exp_threads,
'shots': shot_threads,
'state_update': state_threads,
'total': exp_threads * shot_threads * state_threads
})
return threads
def test_max_memory_settings(self):
"""test max memory configuration"""
# 4-qubit quantum circuit
shots = 100
circuit = QuantumVolume(4, 1, seed=0)
circuit.measure_all()
system_memory = int(psutil.virtual_memory().total / 1024 / 1024)
# Test defaults
opts = self.backend_options_parallel()
result = execute(circuit, self.SIMULATOR, shots=shots,
**opts).result()
max_mem_result = result.metadata.get('max_memory_mb')
self.assertGreaterEqual(max_mem_result, int(system_memory / 2),
msg="Default 'max_memory_mb' is too small.")
self.assertLessEqual(max_mem_result, system_memory,
msg="Default 'max_memory_mb' is too large.")
# Test custom value
max_mem_target = 128
opts = self.backend_options_parallel()
opts['max_memory_mb'] = max_mem_target
result = execute(circuit, self.SIMULATOR, shots=shots,
**opts).result()
max_mem_result = result.metadata.get('max_memory_mb')
self.assertEqual(max_mem_result, max_mem_target,
msg="Custom 'max_memory_mb' is not being set correctly.")
def available_threads(self):
""""Return the threads reported by the simulator"""
opts = self.backend_options_parallel()
result = execute(self.dummy_circuit(1),
self.SIMULATOR,
shots=1,
**opts).result()
return self.threads_used(result)[0]['total']
@requires_omp
@requires_multiprocessing
def test_parallel_thread_defaults(self):
"""Test parallel thread assignment defaults"""
opts = self.backend_options_parallel()
max_threads = self.available_threads()
# Test single circuit, no noise
# Parallel experiments and shots should always be 1
result = execute(self.dummy_circuit(1),
self.SIMULATOR,
shots=10*max_threads,
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': 1,
'state_update': max_threads,
'total': max_threads
}
self.assertEqual(threads, target)
# Test single circuit, with noise
# Parallel experiments should always be 1
# parallel shots should be greater than 1
result = execute(self.dummy_circuit(1),
self.SIMULATOR,
shots=10*max_threads,
noise_model=self.dummy_noise_model(),
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': max_threads,
'state_update': 1,
'total': max_threads
}
self.assertEqual(threads, target)
# Test single circuit, with measure in middle, no noise
# Parallel experiments should always be 1
# parallel shots should be greater than 1
result = execute(self.measure_in_middle_circuit(1),
self.SIMULATOR,
shots=10*max_threads,
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': max_threads,
'state_update': 1,
'total': max_threads
}
self.assertEqual(threads, target)
# Test multiple circuit, no noise
# Parallel experiments always be 1
# parallel shots should always be 1
result = execute(max_threads*[self.dummy_circuit(1)],
self.SIMULATOR,
shots=10*max_threads,
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': 1,
'state_update': max_threads,
'total': max_threads
}
self.assertEqual(threads, target)
# Test multiple circuits, with noise
# Parallel experiments should always be 1
# parallel shots should be greater than 1
result = execute(max_threads*[self.dummy_circuit(1)],
self.SIMULATOR,
shots=10*max_threads,
noise_model=self.dummy_noise_model(),
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': max_threads,
'state_update': 1,
'total': max_threads
}
self.assertEqual(threads, target)
# Test multiple circuit, with measure in middle, no noise
# Parallel experiments should always be 1
# parallel shots should be greater than 1
result = execute(max_threads*[self.measure_in_middle_circuit(1)],
self.SIMULATOR,
shots=10*max_threads,
noise_model=self.dummy_noise_model(),
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': max_threads,
'state_update': 1,
'total': max_threads
}
self.assertEqual(threads, target)
@requires_omp
@requires_multiprocessing
def test_parallel_thread_assignment_priority(self):
"""Test parallel thread assignment priority"""
# If we set all values to max test output
# We intentionally set the max shot and experiment threads to
# twice the max threads to check they are limited correctly
for custom_max_threads in [0, 1, 2, 4]:
opts = self.backend_options_parallel()
opts['max_parallel_threads'] = custom_max_threads
opts['max_parallel_experiments'] = 2 * custom_max_threads
opts['max_parallel_shots'] = 2 * custom_max_threads
# Calculate actual max threads from custom max and CPU number
max_threads = self.available_threads()
if custom_max_threads > 0:
max_threads = min(max_threads, custom_max_threads)
# Test single circuit, no noise
# Parallel experiments and shots should always be 1
result = execute(self.dummy_circuit(1),
self.SIMULATOR,
shots=10*max_threads,
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': 1,
'state_update': max_threads,
'total': max_threads
}
self.assertEqual(threads, target)
# Test single circuit, with noise
# Parallel experiments should always be 1
# parallel shots should be greater than 1
result = execute(self.dummy_circuit(1),
self.SIMULATOR,
shots=10*max_threads,
noise_model=self.dummy_noise_model(),
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': max_threads,
'state_update': 1,
'total': max_threads
}
self.assertEqual(threads, target)
# Test single circuit, with measure in middle, no noise
# Parallel experiments should always be 1
# parallel shots should be greater than 1
result = execute(self.measure_in_middle_circuit(1),
self.SIMULATOR,
shots=10*max_threads,
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': max_threads,
'state_update': 1,
'total': max_threads
}
self.assertEqual(threads, target)
# Test multiple circuit, no noise
# Parallel experiments always be greater than 1
# parallel shots should always be 1
result = execute(max_threads*[self.dummy_circuit(1)],
self.SIMULATOR,
shots=10*max_threads,
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': max_threads,
'shots': 1,
'state_update': 1,
'total': max_threads
}
self.assertEqual(threads, target)
# Test multiple circuits, with noise
# Parallel experiments always be greater than 1
# parallel shots should always be 1
result = execute(max_threads*[self.dummy_circuit(1)],
self.SIMULATOR,
shots=10*max_threads,
noise_model=self.dummy_noise_model(),
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': max_threads,
'shots': 1,
'state_update': 1,
'total': max_threads
}
self.assertEqual(threads, target)
# Test multiple circuit, with measure in middle, no noise
# Parallel experiments always be greater than 1
# parallel shots should always be 1
result = execute(max_threads*[self.measure_in_middle_circuit(1)],
self.SIMULATOR,
shots=10*max_threads,
noise_model=self.dummy_noise_model(),
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': max_threads,
'shots': 1,
'state_update': 1,
'total': max_threads
}
self.assertEqual(threads, target)
@requires_omp
@requires_multiprocessing
def test_parallel_experiment_thread_assignment(self):
"""Test parallel experiment thread assignment"""
max_threads = self.available_threads()
opts = self.backend_options_parallel(exp_threads=max_threads)
# Test single circuit
# Parallel experiments and shots should always be 1
result = execute(self.dummy_circuit(1),
self.SIMULATOR,
shots=10*max_threads,
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': 1,
'state_update': max_threads,
'total': max_threads
}
self.assertEqual(threads, target)
# Test multiple circuit, no noise
# Parallel experiments should take priority
result = execute(max_threads*[self.dummy_circuit(1)],
self.SIMULATOR,
shots=10*max_threads,
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': max_threads,
'shots': 1,
'state_update': 1,
'total': max_threads
}
self.assertEqual(threads, target)
# Test multiple circuits, with noise
# Parallel experiments should take priority
result = execute(max_threads*[self.dummy_circuit(1)],
self.SIMULATOR,
shots=10*max_threads,
noise_model=self.dummy_noise_model(),
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': max_threads,
'shots': 1,
'state_update': 1,
'total': max_threads
}
self.assertEqual(threads, target)
# Test multiple circuit, with measure in middle, no noise
# Parallel experiments should take priority
result = execute(max_threads*[self.measure_in_middle_circuit(1)],
self.SIMULATOR,
shots=10*max_threads,
noise_model=self.dummy_noise_model(),
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': max_threads,
'shots': 1,
'state_update': 1,
'total': max_threads
}
self.assertEqual(threads, target)
# Test multiple circuits, with memory limitation
# NOTE: this assumes execution on statevector simulator
# which required approx 2 MB for 16 qubit circuit.
opts['max_memory_mb'] = 1
circuit = QuantumVolume(16, 1, seed=0)
circuit.measure_all()
result = execute(2 * [circuit],
self.SIMULATOR,
shots=10*max_threads,
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': 1,
'state_update': max_threads,
'total': max_threads
}
self.assertEqual(threads, target)
@requires_omp
@requires_multiprocessing
def test_parallel_shot_thread_assignment(self):
"""Test parallel shot thread assignment"""
max_threads = self.available_threads()
opts = self.backend_options_parallel(shot_threads=max_threads)
# Test single circuit
# Parallel experiments and shots should always be 1
result = execute(self.dummy_circuit(1),
self.SIMULATOR,
shots=10*max_threads,
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': 1,
'state_update': max_threads,
'total': max_threads
}
self.assertEqual(threads, target)
# Test multiple circuit, no noise
# Parallel experiments and shots should always be 1
result = execute(max_threads*[self.dummy_circuit(1)],
self.SIMULATOR,
shots=10*max_threads,
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': 1,
'state_update': max_threads,
'total': max_threads
}
self.assertEqual(threads, target)
# Test multiple circuits, with noise
# Parallel shots should take priority
result = execute(max_threads*[self.dummy_circuit(1)],
self.SIMULATOR,
shots=10*max_threads,
noise_model=self.dummy_noise_model(),
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': max_threads,
'state_update': 1,
'total': max_threads
}
self.assertEqual(threads, target)
# Test multiple circuit, with measure in middle, no noise
# Parallel shots should take priority
result = execute(max_threads*[self.measure_in_middle_circuit(1)],
self.SIMULATOR,
shots=10*max_threads,
noise_model=self.dummy_noise_model(),
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': max_threads,
'state_update': 1,
'total': max_threads
}
self.assertEqual(threads, target)
# Test multiple circuits, with memory limitation
# NOTE: this assumes execution on statevector simulator
# which required approx 2 MB for 16 qubit circuit.
opts['max_memory_mb'] = 1
circuit = QuantumVolume(16, 1, seed=0)
circuit.measure_all()
result = execute(2 * [circuit],
self.SIMULATOR,
shots=10*max_threads,
**opts).result()
for threads in self.threads_used(result):
target = {
'experiments': 1,
'shots': 1,
'state_update': max_threads,
'total': max_threads
}
self.assertEqual(threads, target)
@requires_omp
@requires_multiprocessing
def _test_qasm_explicit_parallelization(self):
"""test disabling parallel shots because max_parallel_shots is 1"""
# Test circuit
shots = multiprocessing.cpu_count()
circuit = QuantumVolume(16, 1, seed=0)
circuit.measure_all()
backend_opts = self.backend_options_parallel(shot_threads=1, exp_threads=1)
backend_opts['noise_model'] = self.dummy_noise_model()
backend_opts['_parallel_experiments'] = 2
backend_opts['_parallel_shots'] = 3
backend_opts['_parallel_state_update'] = 4
result = execute(
circuit, self.SIMULATOR, shots=shots,
**backend_opts).result()
if result.metadata['omp_enabled']:
self.assertEqual(
result.metadata['parallel_experiments'],
2,
msg="parallel_experiments should be 2")
self.assertEqual(
result.to_dict()['results'][0]['metadata']['parallel_shots'],
3,
msg="parallel_shots must be 3")
self.assertEqual(
result.to_dict()['results'][0]['metadata']
['parallel_state_update'],
4,
msg="parallel_state_update should be 4")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier, VQC
from qiskit_machine_learning.algorithms.regressors import NeuralNetworkRegressor, VQR
from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN
algorithm_globals.random_seed = 42
num_inputs = 2
num_samples = 20
X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1
y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1}
y = 2 * y01 - 1 # in {-1, +1}
y_one_hot = np.zeros((num_samples, 2))
for i in range(num_samples):
y_one_hot[i, y01[i]] = 1
for x, y_target in zip(X, y):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
# construct QNN
qc = QuantumCircuit(2)
feature_map = ZZFeatureMap(2)
ansatz = RealAmplitudes(2)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
qc.draw(output="mpl")
estimator_qnn = EstimatorQNN(
circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters
)
# QNN maps inputs to [-1, +1]
estimator_qnn.forward(X[0, :], algorithm_globals.random.random(estimator_qnn.num_weights))
# callback function that draws a live plot when the .fit() method is called
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
# construct neural network classifier
estimator_classifier = NeuralNetworkClassifier(
estimator_qnn, optimizer=COBYLA(maxiter=60), callback=callback_graph
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
estimator_classifier.fit(X, y)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
estimator_classifier.score(X, y)
# evaluate data points
y_predict = estimator_classifier.predict(X)
# plot results
# red == wrongly classified
for x, y_target, y_p in zip(X, y, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if y_target != y_p:
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
estimator_classifier.weights
# construct feature map
feature_map = ZZFeatureMap(num_inputs)
# construct ansatz
ansatz = RealAmplitudes(num_inputs, reps=1)
# construct quantum circuit
qc = QuantumCircuit(num_inputs)
qc.append(feature_map, range(num_inputs))
qc.append(ansatz, range(num_inputs))
qc.decompose().draw(output="mpl")
# parity maps bitstrings to 0 or 1
def parity(x):
return "{:b}".format(x).count("1") % 2
output_shape = 2 # corresponds to the number of classes, possible outcomes of the (parity) mapping.
# construct QNN
sampler_qnn = SamplerQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=output_shape,
)
# construct classifier
sampler_classifier = NeuralNetworkClassifier(
neural_network=sampler_qnn, optimizer=COBYLA(maxiter=30), callback=callback_graph
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
sampler_classifier.fit(X, y01)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
sampler_classifier.score(X, y01)
# evaluate data points
y_predict = sampler_classifier.predict(X)
# plot results
# red == wrongly classified
for x, y_target, y_p in zip(X, y01, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if y_target != y_p:
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
sampler_classifier.weights
# construct feature map, ansatz, and optimizer
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs, reps=1)
# construct variational quantum classifier
vqc = VQC(
feature_map=feature_map,
ansatz=ansatz,
loss="cross_entropy",
optimizer=COBYLA(maxiter=30),
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
vqc.fit(X, y_one_hot)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
vqc.score(X, y_one_hot)
# evaluate data points
y_predict = vqc.predict(X)
# plot results
# red == wrongly classified
for x, y_target, y_p in zip(X, y_one_hot, y_predict):
if y_target[0] == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if not np.all(y_target == y_p):
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
from sklearn.datasets import make_classification
from sklearn.preprocessing import MinMaxScaler
X, y = make_classification(
n_samples=10,
n_features=2,
n_classes=3,
n_redundant=0,
n_clusters_per_class=1,
class_sep=2.0,
random_state=algorithm_globals.random_seed,
)
X = MinMaxScaler().fit_transform(X)
plt.scatter(X[:, 0], X[:, 1], c=y)
y_cat = np.empty(y.shape, dtype=str)
y_cat[y == 0] = "A"
y_cat[y == 1] = "B"
y_cat[y == 2] = "C"
print(y_cat)
vqc = VQC(
num_qubits=2,
optimizer=COBYLA(maxiter=30),
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
vqc.fit(X, y_cat)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
vqc.score(X, y_cat)
predict = vqc.predict(X)
print(f"Predicted labels: {predict}")
print(f"Ground truth: {y_cat}")
num_samples = 20
eps = 0.2
lb, ub = -np.pi, np.pi
X_ = np.linspace(lb, ub, num=50).reshape(50, 1)
f = lambda x: np.sin(x)
X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb
y = f(X[:, 0]) + eps * (2 * algorithm_globals.random.random(num_samples) - 1)
plt.plot(X_, f(X_), "r--")
plt.plot(X, y, "bo")
plt.show()
# construct simple feature map
param_x = Parameter("x")
feature_map = QuantumCircuit(1, name="fm")
feature_map.ry(param_x, 0)
# construct simple ansatz
param_y = Parameter("y")
ansatz = QuantumCircuit(1, name="vf")
ansatz.ry(param_y, 0)
# construct a circuit
qc = QuantumCircuit(1)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
# construct QNN
regression_estimator_qnn = EstimatorQNN(
circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters
)
# construct the regressor from the neural network
regressor = NeuralNetworkRegressor(
neural_network=regression_estimator_qnn,
loss="squared_error",
optimizer=L_BFGS_B(maxiter=5),
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit to data
regressor.fit(X, y)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score the result
regressor.score(X, y)
# plot target function
plt.plot(X_, f(X_), "r--")
# plot data
plt.plot(X, y, "bo")
# plot fitted line
y_ = regressor.predict(X_)
plt.plot(X_, y_, "g-")
plt.show()
regressor.weights
vqr = VQR(
feature_map=feature_map,
ansatz=ansatz,
optimizer=L_BFGS_B(maxiter=5),
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit regressor
vqr.fit(X, y)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score result
vqr.score(X, y)
# plot target function
plt.plot(X_, f(X_), "r--")
# plot data
plt.plot(X, y, "bo")
# plot fitted line
y_ = vqr.predict(X_)
plt.plot(X_, y_, "g-")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- 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__
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.