repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
---|---|---|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
n = 1000
circ = QuantumCircuit(n,n)
circ.h(0)
for i in range(1,n):
circ.cx(0,i)
circ.measure(range(n),range(n))
backend = Aer.get_backend("qasm_simulator")
job = execute(circ,backend)
print(job.result().get_counts())
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 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.
"""
Maximum-Likelihood estimation quantum process tomography fitter
"""
import numpy as np
from qiskit import QiskitError
from qiskit.quantum_info.operators import Choi
from .base_fitter import TomographyFitter
from .cvx_fit import cvxpy, cvx_fit
from .lstsq_fit import lstsq_fit
class ProcessTomographyFitter(TomographyFitter):
"""Maximum-Likelihood estimation process tomography fitter."""
def fit(self, method='auto', standard_weights=True, beta=0.5, **kwargs):
"""
Reconstruct a quantum channel using CVXPY convex optimization.
Args:
method (str): The fitter method 'auto', 'cvx' or 'lstsq'.
standard_weights (bool, optional): Apply weights
to tomography data
based on count probability
(default: True)
beta (float): hedging parameter for converting counts
to probabilities (default: 0.5)
**kwargs (optional): kwargs for fitter method.
Returns:
Choi: The fitted Choi-matrix J for the channel that maximizes
||basis_matrix * vec(J) - data||_2. The Numpy matrix can be
obtained from `Choi.data`.
Additional Information:
Choi matrix
-----------
The Choi matrix object is a QuantumChannel representation which
may be converted to other representations using the classes
`SuperOp`, `Kraus`, `Stinespring`, `PTM`, `Chi` from the module
`qiskit.quantum_info.operators`. The raw matrix data for the
representation may be obtained by `channel.data`.
Fitter method
-------------
The 'cvx' fitter method used CVXPY convex optimization package.
The 'lstsq' method uses least-squares fitting (linear inversion).
The 'auto' method will use 'cvx' if the CVXPY package is found on
the system, otherwise it will default to 'lstsq'.
Objective function
------------------
This fitter solves the constrained least-squares minimization:
minimize: ||a * x - b ||_2
subject to: x >> 0 (PSD)
trace(x) = dim (trace)
partial_trace(x) = identity (trace_preserving)
where:
a is the matrix of measurement operators a[i] = vec(M_i).H
b is the vector of expectation value data for each projector
b[i] ~ Tr[M_i.H * x] = (a * x)[i]
x is the vectorized Choi-matrix to be fitted
PSD constraint
--------------
The PSD keyword constrains the fitted matrix to be
postive-semidefinite.
For the 'lstsq' fitter method the fitted matrix is
rescaled using the
method proposed in Reference [1].
For the 'cvx' fitter method the convex constraint makes the
optimization problem a SDP. If PSD=False the
fitted matrix will still
be constrained to be Hermitian, but not PSD. In this case the
optimization problem becomes a SOCP.
Trace constraint
----------------
The trace keyword constrains the trace of the fitted matrix. If
trace=None there will be no trace constraint on the fitted matrix.
This constraint should not be used for process tomography and the
trace preserving constraint should be used instead.
Trace preserving (TP) constraint
--------------------------------
The trace_preserving keyword constrains the fitted
matrix to be TP.
This should only be used for process tomography,
not state tomography.
Note that the TP constraint implicitly enforces
the trace of the fitted
matrix to be equal to the square-root of the
matrix dimension. If a
trace constraint is also specified that differs f
rom this value the fit
will likely fail. Note that this can
only be used for the CVX method.
CVXPY Solvers:
-------
Various solvers can be called in CVXPY using the `solver` keyword
argument. Solvers included in CVXPY are:
'CVXOPT': SDP and SOCP (default solver)
'SCS' : SDP and SOCP
'ECOS' : SOCP only
See the documentation on CVXPY for more information on solvers.
References:
[1] J Smolin, JM Gambetta, G Smith, Phys. Rev. Lett. 108, 070502
(2012). Open access: arXiv:1106.5458 [quant-ph].
"""
# Get fitter data
data, basis_matrix, weights = self._fitter_data(standard_weights,
beta)
# Calculate trace of Choi-matrix from projector length
_, cols = np.shape(basis_matrix)
dim = int(np.sqrt(np.sqrt(cols)))
if dim ** 4 != cols:
raise ValueError("Input data does not correspond "
"to a process matrix.")
# Choose automatic method
if method == 'auto':
if cvxpy is None:
method = 'lstsq'
else:
method = 'cvx'
if method == 'lstsq':
return Choi(lstsq_fit(data, basis_matrix, weights=weights,
trace=dim, **kwargs))
if method == 'cvx':
return Choi(cvx_fit(data, basis_matrix, weights=weights, trace=dim,
trace_preserving=True, **kwargs))
raise QiskitError('Unrecognised fit method {}'.format(method))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.visualization.timeline import draw as timeline_draw
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeBoeblingen
backend = FakeBoeblingen()
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
circ = transpile(ghz, backend, scheduling_method="asap")
timeline_draw(circ)
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
import qiskit
from qiskit import QuantumCircuit
# creating a quantum circuit
qc = QuantumCircuit(3)
qc.z(0)
qc.s(1)
qc.t(2)
qc.cx(0,1)
qc.h(2)
qc.ccx(0, 1, 2)
qc.draw(output='mpl')
# inverse of the quantum circuit
inverse_qc = qc.inverse()
# to draw the quantum circuit
inverse_qc.draw(output='mpl')
# If we measure the quantum circuit's each qubit's states
qc.measure()
# to draw the quantum circuit
qc.draw(output='mpl')
# inverse of the measured quantum circuit's qubit is not possible
inverse_qc = qc.inverse()
qc.measure()
# to draw the quantum circuit
inverse_qc.draw(output='mpl')
# creating a quantum circuit
m_circuit = QuantumCircuit(3)
m_circuit.h(2)
m_circuit.ccx(0, 1, 2)
m_circuit.cz(2, 1)
# draw the circuit
m_circuit.draw(output='mpl')
m_gate = m_circuit.to_gate()
type(m_gate)
new_circuit = QuantumCircuit(5)
new_circuit.append(m_gate, [1, 2, 4])
new_circuit.draw(output='mpl')
#decompose the circuit
new_circuit.decompose().draw(output='mpl')
from qiskit import QuantumCircuit, transpile, Aer
my_circuit = QuantumCircuit(3)
my_circuit.t(1)
my_circuit.h(0)
my_circuit.ccx(2,1,0)
my_circuit.s(2)
my_circuit.t(0)
my_circuit.draw()
my_gate = my_circuit.to_gate()
my_gate
my_inv_gate = my_gate.inverse()
my_inv_gate
my_inv_gate.name = 'My Inverse Gate'
new_circuit = QuantumCircuit(3)
new_circuit.append(my_inv_gate, [0,1,2])
new_circuit.draw()
new_circuit.decompose().draw()
my_circuit = QuantumCircuit(2)
my_circuit.cx(1,0)
my_circuit.cx(0,1)
my_circuit.cx(1,0)
my_circuit.draw()
my_gate = my_circuit.to_gate()
my_gate.name = "My Gate"
my_controlled_gate = my_gate.control()
new_circuit = QuantumCircuit(3)
new_circuit.append(my_controlled_gate, [0, 1, 2])
new_circuit.draw()
new_circuit.decompose().draw()
from qiskit import Aer, IBMQ, QuantumCircuit, execute, transpile, assemble
from qiskit.providers.aer.noise import NoiseModel
from qiskit.visualization import histogram
my_qc = QuantumCircuit(5)
my_qc.h(0)
for q in range(4):
my_qc.cx(0, q+1)
my_qc.measure_all()
my_qc.draw()
## What is the qsphere ?
## What is the unitary simulator ?
## How can i convert a Unitary Matrix to a set of One and Two Qubit gates ?
## How can i change qiskit's defoult behaviour ?
## How do i use parameterization circuit in Qiskit ?
## Why does qiskit order it's qubit the way it does ?
## How i combine two quantum circuits ?
## What is the difference between gates and instructions ?
## How can i use a specific version of qiskit ?
## How can i implement a multi controlled Toffoli Gate ?
## How can i monitor a job send to IBM Quantum ?
## How can i convert a quantum circuit to QASM ?
my_circuit = QuantumCircuit(3)
my_circuit.t(1)
my_circuit.h(0)
my_circuit.ccx(2,1,0)
my_circuit.s(2)
my_circuit.t(0)
my_circuit.draw('latex')
my_circuit.draw('latex_source')
print(my_circuit.draw('latex_source'))
## How can i bundle several circuit into a single job ?
## How can i save circuit Drawings to Different File Types ?
## How can i contruct a quantum volume circuit ?
## What trick can i do with draw methods ?
## How i can find reduced quantum states using qiskit ?
## In What different ways can i draw a quantum circuit ?
## How can i use a classical register for quantum compuation ?
## What is circuit depth and how can i calculate it ?
## How can i choose initial layout for the traspiler ?
## What are the Ancillary Qubits and how are they usefull ?
## What are registers ?
## How can i create a custom gate from matrix ?
## How can i find expectation value for an operator ?
## How can i measure the qubit midway through a quantum circuit ?
## How can i transpile a quantum circuit ?
## How can i make a noise model with qiskit ?
## How can i create a custome controlled gate ?
## How can i choose the best backend from a provider ?
## How can i perform state tomography ?
## How can i reset a qubit in a quantum circuit
## How do i perform a unitary projection in a quantum circuit ?
## How do i debuge an issue in transpiler ?
## How can i estimate Pi using a quantum computer ?
## How do i initialize a mixed states ?
## What is gate fidelity and how do i canculate it ?
## How do i check the state fedility with noisy simulator ?
## How do i change the fitter algorithm in a state tomography experiment ?
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import qiskit_alt
qiskit_alt.project.ensure_init(calljulia="juliacall", compile=False)
julia = qiskit_alt.project.julia
Main = julia.Main
julia.Main.zeros(3)
type(julia.Main.zeros(3))
from qiskit_nature.drivers import UnitsType, Molecule
from qiskit_nature.drivers.second_quantization import ElectronicStructureDriverType, ElectronicStructureMoleculeDriver
# Specify the geometry of the H_2 molecule
geometry = [['H', [0., 0., 0.]],
['H', [0., 0., 0.735]]]
basis = 'sto3g'
molecule = Molecule(geometry=geometry,
charge=0, multiplicity=1)
driver = ElectronicStructureMoleculeDriver(molecule, basis=basis, driver_type=ElectronicStructureDriverType.PYSCF)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
es_problem = ElectronicStructureProblem(driver)
second_q_op = es_problem.second_q_ops()
fermionic_hamiltonian = second_q_op[0]
qubit_converter = QubitConverter(mapper=JordanWignerMapper())
nature_qubit_op = qubit_converter.convert(fermionic_hamiltonian)
nature_qubit_op.primitive
import qiskit_alt.electronic_structure
fermi_op = qiskit_alt.electronic_structure.fermionic_hamiltonian(geometry, basis)
pauli_op = qiskit_alt.electronic_structure.jordan_wigner(fermi_op)
pauli_op.simplify() # The Julia Pauli operators use a different sorting convention; we sort again for comparison.
%run ../bench/jordan_wigner_nature_time.py
nature_times
%run ../bench/jordan_wigner_alt_time.py
alt_times
[t_nature / t_qk_alt for t_nature, t_qk_alt in zip(nature_times, alt_times)]
%run ../bench/fermionic_nature_time.py
nature_times
%run ../bench/fermionic_alt_time.py
alt_times
[t_nature / t_qk_alt for t_nature, t_qk_alt in zip(nature_times, alt_times)]
from qiskit_alt.pauli_operators import QuantumOps, PauliSum_to_SparsePauliOp
import numpy as np
m = np.random.rand(2**3, 2**3) # 3-qubit operator
m = Main.convert(Main.Matrix, m) # Convert PythonCall.PyArray to a native Julia type
pauli_sum = QuantumOps.PauliSum(m) # This is a wrapped Julia object
PauliSum_to_SparsePauliOp(pauli_sum) # Convert to qiskit.quantum_info.SparsePauliOp
%run ../bench/from_matrix_quantum_info.py
%run ../bench/from_matrix_alt.py
[t_pyqk / t_qk_alt for t_pyqk, t_qk_alt in zip(pyqk_times, qk_alt_times)]
%run ../bench/pauli_from_list_qinfo.py
%run ../bench/pauli_from_list_alt.py
[x / y for x,y in zip(quantum_info_times, qkalt_times)]
import qiskit.tools.jupyter
d = qiskit.__qiskit_version__._version_dict
d['qiskit_alt'] = qiskit_alt.__version__
%qiskit_version_table
# %load_ext julia.magic
# %julia using Random: randstring
#%julia pauli_strings = [randstring("IXYZ", 10) for _ in 1:1000]
# None;
# %julia import Pkg; Pkg.add("BenchmarkTools")
#%julia using BenchmarkTools: @btime
#%julia @btime QuantumOps.PauliSum($pauli_strings)
#None;
#%julia pauli_sum = QuantumOps.PauliSum(pauli_strings);
#%julia println(length(pauli_sum))
#%julia println(pauli_sum[1])
#6.9 * 2.29 / .343 # Ratio of time to construct PauliSum via qiskit_alt to time in pure Julia
|
https://github.com/madmen2/QASM
|
madmen2
|
import qiskit.quantum_info as qi
from qiskit.circuit.library import FourierChecking
from qiskit.tools.visualization import plot_histogram
#Fourier checking algoirthm
f=[1,-1,-1,-1]
g=[1,1,-1,-1]
#if probability of fouriere checking f,g > 0 = correlation
circ = FourierChecking(f=f,g=g)
circ.draw()
zero = qi.Statevector.from_label('00')
sv = zero.evolve(circ)
probs = sv.probabilities_dict()
plot_histogram(probs)
# fourier transform of function g is correlated
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.tools.visualization import plot_histogram, plot_state_city
# List Aer backends
Aer.backends()
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator
# Construct quantum circuit
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(2, 'cr')
circ = QuantumCircuit(qr, cr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.measure(qr, cr)
# Select the QasmSimulator from the Aer provider
simulator = Aer.get_backend('qasm_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
# Construct quantum circuit
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(2, 'cr')
circ = QuantumCircuit(qr, cr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.measure(qr, cr)
# Select the QasmSimulator from the Aer provider
simulator = Aer.get_backend('qasm_simulator')
# Execute and get memory
result = execute(circ, simulator, shots=10, memory=True).result()
memory = result.get_memory(circ)
print(memory)
# Construct an empty quantum circuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circ = QuantumCircuit(qr, cr)
circ.measure(qr, cr)
# Set the initial state
opts = {"initial_statevector": np.array([1, 0, 0, 1] / np.sqrt(2))}
# Select the QasmSimulator from the Aer provider
simulator = Aer.get_backend('qasm_simulator')
# Execute and get counts
result = execute(circ, simulator, backend_options=opts).result()
counts = result.get_counts(circ)
plot_histogram(counts, title="Bell initial statevector")
# Construct quantum circuit without measure
qr = QuantumRegister(2, 'qr')
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
# Select the StatevectorSimulator from the Aer provider
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
statevector = result.get_statevector(circ)
plot_state_city(statevector, title='Bell state')
# Construct quantum circuit with measure
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(2, 'cr')
circ = QuantumCircuit(qr, cr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.measure(qr, cr)
# Select the StatevectorSimulator from the Aer provider
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
statevector = result.get_statevector(circ)
plot_state_city(statevector, title='Bell state post-measurement')
# Construct an empty quantum circuit
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.iden(qr)
# Set the initial state
opts = {"initial_statevector": np.array([1, 0, 0, 1] / np.sqrt(2))}
# Select the StatevectorSimulator from the Aer provider
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(circ, simulator, backend_options=opts).result()
statevector = result.get_statevector(circ)
plot_state_city(statevector, title="Bell initial statevector")
# Construct an empty quantum circuit
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
unitary = result.get_unitary(circ)
print("Circuit unitary:\n", unitary)
# Construct an empty quantum circuit
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.iden(qr)
# Set the initial unitary
opts = {"initial_unitary": np.array([[ 1, 1, 0, 0],
[ 0, 0, 1, -1],
[ 0, 0, 1, 1],
[ 1, -1, 0, 0]] / np.sqrt(2))}
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator, backend_options=opts).result()
unitary = result.get_unitary(circ)
unitary = result.get_unitary(circ)
print("Initial Unitary:\n", unitary)
|
https://github.com/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (C) Copyright IBM 2020.
#
# 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 json
from typing import Any, Callable, Optional, Tuple, Union
from urllib.parse import urljoin
from qiskit import QuantumCircuit, execute
from qiskit.providers import JobStatus
from qiskit.providers.ibmq.job import IBMQJob
from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint
from .exercises import get_question_id
from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate
def _circuit_criteria(
circuit: QuantumCircuit,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[int], Optional[int]]:
if max_qubits is not None and circuit.num_qubits > max_qubits:
print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.')
print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.')
return None, None
try:
if check_gates and not uses_multiqubit_gate(circuit):
print('Your circuit appears to not use any multi-quibit gates.')
print('Please review your circuit and try again.')
return None, None
cost = compute_cost(circuit)
if min_cost is not None and cost < min_cost:
print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n'
'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.')
return None, None
return circuit.num_qubits, cost
except Exception as err:
print(f'Unable to compute cost: {err}')
return None, None
def _circuit_grading(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
payload = None
server = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or '
'the grading servers are down right now.')
return None, None
else:
server = None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
payload = {
'answer': circuit_to_json(circuit)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _job_grading(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str):
print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}')
print(f'Please submit a job as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading '
'servers are down right now.')
return None, None
else:
server = None
job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id
if not job:
print('An invalid or non-existent job was specified.')
return None, None
job_status = job.status()
if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]:
print(f'Job did not successfully complete: {job_status.value}.')
return None, None
elif job_status is not JobStatus.DONE:
print(f'Job has not yet completed: {job_status.value}.')
print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.')
return None, None
header = job.result().header.to_dict()
if 'qc_cost' not in header:
if is_submit:
print('An unprepared answer was specified. '
'Please prepare() and grade() answer before submitting.')
else:
print('An unprepared answer was specified. Please prepare() answer before grading.')
return None, None
download_url, result_url = get_job_urls(job)
if not download_url or not result_url:
print('Unable to obtain job URLs')
return None, None
payload = {
'answer': json.dumps({
'download_url': download_url,
'result_url': result_url
})
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _number_grading(
answer: int,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(answer, int):
print(f'Expected a integer, but was given {type(answer)}')
print(f'Please provide a number as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server '
'or the grading servers are down right now.')
return None, None
else:
server = None
payload = {
'answer': str(answer)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def prepare_circuit(
circuit: QuantumCircuit,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit.')
return None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiment. Please wait...')
job = execute(
circuit,
qobj_header={
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def prepare_solver(
solver_func: Callable,
lab_id: str,
ex_id: str,
problem_set: Optional[Any] = None,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not callable(solver_func):
print(f'Expected a function, but was given {type(solver_func)}')
print(f'Please provide a function that returns a QuantumCircuit.')
return None
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading servers are down right now.')
return
endpoint = server + 'problem-set'
index, value = get_problem_set(lab_id, ex_id, endpoint)
print(f'Running {solver_func.__name__}...')
qc_1 = solver_func(problem_set)
_, cost = _circuit_criteria(
qc_1,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if value and index is not None and index >= 0 and cost is not None:
qc_2 = solver_func(value)
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiments. Please wait...')
job = execute(
[qc_1, qc_2],
qobj_header={
'qc_index': [None, index],
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def grade_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, server = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=False,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_job(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str
) -> bool:
payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def submit_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, _ = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=True,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_job(
job_or_id: IBMQJob,
lab_id: str,
ex_id: str,
) -> bool:
payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def get_problem_set(
lab_id: str, ex_id: str, endpoint: str
) -> Tuple[Optional[int], Optional[Any]]:
problem_set_response = None
try:
payload = {'question_id': get_question_id(lab_id, ex_id)}
problem_set_response = send_request(endpoint, query=payload, method='GET')
except Exception as err:
print('Unable to obtain the problem set')
if problem_set_response:
status = problem_set_response.get('status')
if status == 'valid':
try:
index = problem_set_response.get('index')
value = json.loads(problem_set_response.get('value'))
return index, value
except Exception as err:
print(f'Problem set could not be processed: {err}')
else:
cause = problem_set_response.get('cause')
print(f'Problem set failed: {cause}')
return None, None
def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool:
try:
answer_response = send_request(endpoint, body=payload)
status = answer_response.get('status', None)
cause = answer_response.get('cause', None)
score = cost if cost else answer_response.get('score', None)
handle_grade_response(status, score=score, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def submit_answer(payload: dict) -> bool:
try:
access_token = get_access_token()
baseurl = get_submission_endpoint()
endpoint = urljoin(baseurl, './challenges/answers')
submit_response = send_request(
endpoint,
body=payload,
query={'access_token': access_token}
)
status = submit_response.get('status', None)
if status is None:
status = submit_response.get('valid', None)
cause = submit_response.get('cause', None)
handle_submit_response(status, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def handle_grade_response(
status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None
) -> None:
if status == 'valid':
print('\nCongratulations 🎉! Your answer is correct.')
if score is not None:
print(f'Your score is {score}.')
elif status == 'invalid':
print(f'\nOops 😕! {cause}')
print('Please review your answer and try again.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete then try again.')
else:
print(f'Failed: {cause}')
print('Unable to grade your answer.')
def handle_submit_response(
status: Union[str, bool], cause: Optional[str] = None
) -> None:
if status == 'valid' or status is True:
print('\nSuccess 🎉! Your answer has been submitted.')
elif status == 'invalid' or status is False:
print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}')
print('Make sure your answer is correct and successfully graded before submitting.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete, grade it, and then try to submit again.')
else:
print(f'Failed: {cause}')
print('Unable to submit your answer at this time.')
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
import pylab
import numpy as np
from qiskit import BasicAer
from qiskit.tools.visualization import plot_histogram
from qiskit.aqua import QuantumInstance
from qiskit.aqua import run_algorithm
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle
input_3sat_instance = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
oracle = LogicalExpressionOracle(input_3sat_instance)
grover = Grover(oracle)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
result = grover.run(quantum_instance)
print(result['result'])
plot_histogram(result['measurement'])
params = {
'problem': {
'name': 'search',
},
'algorithm': {
'name': 'Grover'
},
'oracle': {
'name': 'LogicalExpressionOracle',
'expression': input_3sat_instance
},
'backend': {
'shots': 1000,
},
}
result_dict = run_algorithm(params, backend=backend)
plot_histogram(result_dict['measurement'])
expression = '(w ^ x) & ~(y ^ z) & (x & y & z)'
oracle = LogicalExpressionOracle(expression)
grover = Grover(oracle)
result = grover.run(QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024))
plot_histogram(result['measurement'])
truthtable = '1000000000000001'
oracle = TruthTableOracle(truthtable)
grover = Grover(oracle)
result = grover.run(QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024))
plot_histogram(result['measurement'])
#solution
from hide_toggle import hide_toggle
hide_toggle(for_next=True)
sat_cnf = '''
c prova.cnf
c
p cnf 2 2
1 -2 0
-1 2 0
'''
print(sat_cnf)
oracle_2 = LogicalExpressionOracle(sat_cnf)
my_grover = Grover(oracle_2)
backend = BasicAer.get_backend('qasm_simulator')
quantum_grover = QuantumInstance(backend, shots=1024)
result = grover.run(quantum_grover)
print(result['result'])
|
https://github.com/tushdon2/Qiskit_Hackathon_IITR_2021
|
tushdon2
|
# importing required libraries
from tensorflow import keras
import os
from pathlib import Path
# downloading the ImageNet model with output layer removed and input shape (224, 224, 3)
base_model = keras.applications.VGG16(
weights = 'imagenet',
input_shape = (224, 224, 3),
include_top = False)
base_model.summary()
# Freeze base model
base_model.trainable = False
# Create inputs with correct shape
inputs = keras.Input(shape=(224, 224, 3))
x = base_model(inputs, training=False)
# Add pooling layer or flatten layer
x = keras.layers.GlobalAveragePooling2D()(x)
# Add final dense layer
outputs = keras.layers.Dense(6, activation = 'softmax')(x)
# Combine inputs and outputs to create model
model = keras.Model(inputs, outputs)
model.summary()
# compile the model
model.compile(loss='categorical_crossentropy', metrics=['accuracy'])
# Augment the Data
datagen = keras.preprocessing.image.ImageDataGenerator(
samplewise_center = True, # set each sample mean to 0
rotation_range = 10, # randomly rotate images in the range (degrees, 0 to 180)
zoom_range = 0.1, # Randomly zoom image
width_shift_range = 0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range = 0.1, # randomly shift images vertically (fraction of total height)
horizontal_flip = True, # randomly flip images
vertical_flip = True)
# load and iterate training dataset
dirPath = os.path.join(Path(os.path.realpath("__file__")).parent.parent, "assets/data")
train_it = datagen.flow_from_directory(dirPath + "/train",
target_size = (224, 224),
color_mode = 'rgb',
class_mode = "categorical",
batch_size = 8)
# load and iterate validation dataset
valid_it = datagen.flow_from_directory(dirPath + "/valid",
target_size = (224, 224),
color_mode = 'rgb',
class_mode = "categorical",
batch_size = 8)
# Train the Model
model.fit(train_it,
validation_data = valid_it,
steps_per_epoch = train_it.samples/train_it.batch_size,
validation_steps = valid_it.samples/valid_it.batch_size,
epochs = 15)
# # Unfreeze the base model
# base_model.trainable = True
# # Compile the model with a low learning rate
# model.compile(optimizer=keras.optimizers.RMSprop(learning_rate = 0.0001),
# loss='categorical_crossentropy', metrics=['accuracy'])
# model.fit(train_it,
# validation_data = valid_it,
# steps_per_epoch = train_it.samples/train_it.batch_size,
# validation_steps = valid_it.samples/valid_it.batch_size,
# epochs = 8)
# saving the trained model
dirPath = os.path.join(Path(os.path.realpath("__file__")).parent.parent, "assets/model")
if not os.path.exists(dirPath): os.makedirs(dirPath)
model.save(dirPath + "/hand_gesture_classify_model.h5")
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import time, os, logging, warnings
import numpy as np
from qiskit import IBMQ
from qiskit.test.mock import FakeMumbai
from qiskit.providers.aer import AerSimulator
from qiskit.providers.aer.noise import NoiseModel
from qiskit_optimization.algorithms import CplexOptimizer
from qiskit_optimization.algorithms.optimization_algorithm import OptimizationResultStatus
from utilities.helpers import create_qaoa_meo, create_quadratic_programs_from_paths
TEST_DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y") + "/SPARSE/"
RES_DIR = 'RESULTS' + "/" + time.strftime("%d_%m_%Y") + "/SPARSE/"
os.makedirs(RES_DIR, exist_ok=True)
TEST_DIR
logger = logging.getLogger()
max_iter = 5 # set maximum number of optimizer iterations
def qaoa_callback(eval_ct: int, opt_pars: np.ndarray, mean: float, stdev: float) -> None:
"""Print number of iteration in QAOA and log."""
print("Evaluation count:", eval_ct)
logger.info(f"\n Evaluation count {eval_ct} with parameters {opt_pars} and mean {mean:.2f}")
if eval_ct == max_iter:
logger.info(" reached maximum number of evaluations \n")
# select linear programs to solve
qps = create_quadratic_programs_from_paths(TEST_DIR)
# init local backend simulator with noise model
device = FakeMumbai()
local = AerSimulator.from_backend(device)
noise_model = NoiseModel.from_backend(device)
conf = device.configuration()
# init IBM Q Experience Simulator
IBMQ.load_account()
ibmq = IBMQ.get_provider(hub='ibm-q').get_backend('simulator_statevector')
# init Optimizers
cplex = CplexOptimizer()
quantum_instance_kwargs = {"shots": 4096, "noise_model": noise_model, "optimization_level": 3}
qaoa_local_sim = create_qaoa_meo(backend=local, max_iter=max_iter, **quantum_instance_kwargs)
qaoa_ibmq_sim = create_qaoa_meo(backend=ibmq, coupling_map=conf.coupling_map, basis_gates=conf.basis_gates,
max_iter=max_iter, qaoa_callback=qaoa_callback, **quantum_instance_kwargs)
# set online job informations in IBM Q Experience
qaoa_ibmq_sim.min_eigen_solver.quantum_instance.backend_options["job_tags"] = ["qaoa", "sparse", "mumbai"]
def set_job_name(qp):
qaoa_ibmq_sim.min_eigen_solver.quantum_instance.backend_options["job_name"] = "qaoa_sparse_5_" \
+ qp.name + "_" + str(qp.get_num_vars())
warnings.filterwarnings("ignore", category=DeprecationWarning)
logger.setLevel(logging.INFO)
count_fail_qaoa = 0
for qp_name, qp in qps.items() :
print(qp_name)
print("number of qubits: ", qp.get_num_vars())
output_file_handler = logging.FileHandler(filename=RES_DIR + qp.name + ".log")
logger.addHandler(output_file_handler)
if qp.get_num_vars() >= 15:
set_job_name(qp)
qaoa = qaoa_ibmq_sim
logstring = "ibmq_simulator_statevector"
else:
qaoa = qaoa_local_sim
logstring = "local_qasm_simulator"
with open(RES_DIR + qp.name + '.res', 'w') as file:
file.write(str("Start " + qp.name + "\n " + str(qp.get_num_vars()) + " qubits needed"))
file.write("\n " + logstring + " \n")
logger.info("\n " + logstring + " \n")
print(logstring)
try:
res_classic = cplex.solve(qp)
res_quantum = qaoa.solve(qp)
if res_quantum.status != OptimizationResultStatus.SUCCESS:
print("QAOA minimum eigen solver found no solution.")
file.write("\n QAOA minimum eigen solver found no solution. \n")
count_fail_qaoa = count_fail_qaoa + 1
if count_fail_qaoa == 3:
file.write("\n Stop testing \n")
break
else:
print("QAOA minimum eigen solver successful!")
count_fail_qaoa = 0
if res_quantum.fval == res_classic.fval:
file.write("\n QAOA found optimal solution\n")
else:
print("\n optimal value QAOA "+str(res_quantum.fval) \
+ " , cplex:"+ str(res_classic.fval))
file.write("\n QAOA:\n")
file.write(str(res_quantum))
file.write("\n CPLEX:\n")
file.write(str(res_classic))
except Exception as ex:
print(qp_name, " ", type(ex).__name__, " : ", ex)
file.write("\n Cplex or QAOA solver produced an exception:\n")
file.write(str(ex))
count_fail_qaoa = count_fail_qaoa + 1
if count_fail_qaoa == 3:
file.write("\n Stop testing because of Exception! \n")
break
logger.removeHandler(output_file_handler)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization import QuadraticProgram
qp = QuadraticProgram()
qp.binary_var("x")
qp.binary_var("y")
qp.integer_var(lowerbound=0, upperbound=7, name="z")
qp.maximize(linear={"x": 2, "y": 1, "z": 1})
qp.linear_constraint(linear={"x": 1, "y": 1, "z": 1}, sense="LE", rhs=5.5, name="xyz_leq")
qp.linear_constraint(linear={"x": 1, "y": 1, "z": 1}, sense="GE", rhs=2.5, name="xyz_geq")
print(qp.prettyprint())
from qiskit_optimization.converters import InequalityToEquality
ineq2eq = InequalityToEquality()
qp_eq = ineq2eq.convert(qp)
print(qp_eq.prettyprint())
print(qp_eq.prettyprint())
from qiskit_optimization.converters import IntegerToBinary
int2bin = IntegerToBinary()
qp_eq_bin = int2bin.convert(qp_eq)
print(qp_eq_bin.prettyprint())
print(qp_eq_bin.prettyprint())
from qiskit_optimization.converters import LinearEqualityToPenalty
lineq2penalty = LinearEqualityToPenalty()
qubo = lineq2penalty.convert(qp_eq_bin)
print(qubo.prettyprint())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This program sets up the Half Adder and the Full Adder and creates a .tex file
with the gate geometry. It also evaluates the result with a qasm quantum
simulator
'''
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, \
execute, result, Aer
import os
import shutil
import numpy as np
import lib.adder as adder
import lib.quantum_logic as logic
LaTex_folder_Adder_gates = str(os.getcwd())+'/Latex_quantum_gates/Adder-gates/'
if not os.path.exists(LaTex_folder_Adder_gates):
os.makedirs(LaTex_folder_Adder_gates)
else:
shutil.rmtree(LaTex_folder_Adder_gates)
os.makedirs(LaTex_folder_Adder_gates)
qubit_space = ['0','1']
## Half Adder (my version)
print("Test Half Adder (my version",'\n')
for add0 in qubit_space: # loop over all possible additions
for add1 in qubit_space:
q = QuantumRegister(3, name = 'q')
c = ClassicalRegister(2, name = 'c')
qc = QuantumCircuit(q,c)
for qubit in q:
qc.reset(qubit)
# initialisation
if(add0== '1'):
qc.x(q[0])
if(add1 == '1'):
qc.x(q[1])
adder.Half_Adder(qc, q[0],q[1],q[2])
qc.measure(q[0], c[0])
qc.measure(q[2], c[1])
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
results = job.result()
count = results.get_counts()
print('|0', add0, '>', '+', '|0', add1, '>', '\t', count)
## Plot a sketch of the gate
q = QuantumRegister(3, name = 'q')
c = ClassicalRegister(2, name = 'c')
qc = QuantumCircuit(q,c)
qc.reset(q[2])
adder.Half_Adder(qc, q[0],q[1],q[2])
qc.measure(q[1], c[0])
qc.measure(q[2], c[1])
LaTex_code = qc.draw(output='latex_source',
justify=None) # draw the circuit
f_name = 'Half_Adder_gate_Benjamin.tex'
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
## Half Adder for two qubits (Beyond Classical book version)
print("Test Half Adder Beyond Classical")
for add0 in qubit_space: # loop over all possible additions
for add1 in qubit_space:
q = QuantumRegister(5, name = 'q')
c = ClassicalRegister(2, name = 'c')
qc = QuantumCircuit(q,c)
# initialisation
if(add0 == '1'):
qc.x(q[0])
if(add1 == '1'):
qc.x(q[1])
logic.XOR(qc, q[0],q[1],q[2])
qc.barrier(q)
logic.AND(qc, q[0], q[1], q[3])
qc.barrier(q)
qc.measure(q[2], c[0])
qc.measure(q[3], c[1])
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
results = job.result()
count = results.get_counts()
print('|0', add0, '>', '+', '|0', add1, '>', '\t', count)
if(add0=='0' and add1=='1'):
LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit
f_name = 'Half_Adder_gate_Beyond_Classical.tex'
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
## Full Adder for addition of two-qubits |q1>, |q2>, and a carry bit |qd>
# from another calculation using a anxiliary bit |q0> with a carry qubit |cq>
# which is initialised to |0>
# iteration over all possible values for |q1>, |q2>, and |qd>
print('\n',"Full Adder Test (my version)")
for qubit_2 in qubit_space:
for qubit_1 in qubit_space:
for qubit_d in qubit_space:
string_q1 = str(qubit_1)
string_q2 = str(qubit_2)
string_qd = str(qubit_d)
q1 = QuantumRegister(1, name ='q1')
q2 = QuantumRegister(1, name = 'q2')
qd = QuantumRegister(1, name = 'qd')
q0 = QuantumRegister(1, name = 'q0')
c = ClassicalRegister(2, name = 'c')
qc = QuantumCircuit(q1,q2,qd,q0,c)
for qubit in q1:
qc.reset(qubit)
for qubit in q2:
qc.reset(qubit)
for qubit in qd:
qc.reset(qubit)
for qubit in q0:
qc.reset(qubit)
# initialise qubits which should be added
for i, qubit in enumerate(q1):
if(string_q1[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
for i, qubit in enumerate(q2):
if(string_q2[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
for i, qubit in enumerate(qd):
if(string_qd[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
adder.Full_Adder(qc, q1, q2, qd, q0, c[0])
qc.measure(q0, c[1])
# check the results
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
results = job.result()
count = results.get_counts()
print('|', qubit_1, '>', '+', '|', qubit_2, '>', '+', '|', qubit_d, '> = ' , '\t', count)
if(qubit_1 == '0' and qubit_2 == '0' and qubit_d == '0'):
LaTex_code = qc.draw(output='latex_source') # draw the circuit
f_name = 'Full_Adder_gate_Benjamin.tex'
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
## Test for adding two two-qubit numbers |q1> and |q2>
for qubit1_0 in qubit_space:
for qubit1_1 in qubit_space:
for qubit2_0 in qubit_space:
for qubit2_1 in qubit_space:
string_q1 = str(qubit1_1)+str(qubit1_0)
string_q2 = str(qubit2_1)+str(qubit2_0)
q1 = QuantumRegister(2, name ='q1')
q2 = QuantumRegister(2, name = 'q2')
# qubit to store carry over for significiant bit
q0 = QuantumRegister(1, name = 'q0')
c = ClassicalRegister(3, name = 'c')
qc = QuantumCircuit(q1,q2,q0,c)
for qubit in q1:
qc.reset(qubit)
qc.reset(q2)
qc.reset(q0)
# initialise qubits which should be added
for i, qubit in enumerate(q1):
if(string_q1[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
for i, qubit in enumerate(q2):
if(string_q2[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
adder.Half_Adder(qc,q1[-1],q2[-1],q0)
qc.measure(q2[-1],c[0])
adder.Full_Adder(qc, q1[-2],q2[-2], q0, q2[-1], c[1])
qc.measure(q2[-1], c[2])
# check the results
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
results = job.result()
count = results.get_counts()
print('|', qubit1_1, qubit1_0, '>', '+', '|', qubit2_1,
qubit2_0, '> = ' , '\t', count)
if(qubit1_1 == '0' and qubit1_0 == '1'
and qubit2_1 == '0' and qubit2_0 == '0'):
LaTex_code = qc.draw(output='latex_source') # draw the circuit
# export QASM code
qc.qasm(filename="one_plus_one.qasm")
f_name = 'Adder_gate_for_two_two-qubit_numbers.tex'
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
## Adder for two arbitrary binary numbers
# randomly draw number of bits from the numbers to add
bit_number_q1 = int(np.ceil(10*np.random.rand()))+2
bit_number_q2 = int(np.ceil(10*np.random.rand()))+2
# prepare two random binary numbers
string_q1 = []
string_q2 = []
for i in range(bit_number_q1):
#string_q1.append(1)
string_q1.append(int(np.round(np.random.rand())))
for i in range(bit_number_q2):
string_q2.append(int(np.round(np.random.rand())))
while(len(string_q1)<len(string_q2)):
string_q1 = np.insert(string_q1, 0, 0, axis=0)
while(len(string_q1)>len(string_q2)):
string_q2 = np.insert(string_q2, 0, 1, axis=0)
string_q1 = np.array(string_q1)
string_q2 = np.array(string_q2)
q1 = QuantumRegister(len(string_q1), name = 'q1')
q2 = QuantumRegister(len(string_q2), name = 'q2')
# qubit to store carry over for initial half adder
q0 = QuantumRegister(1, name = 'q0')
c = ClassicalRegister(len(string_q1)+1, name = 'c')
qc = QuantumCircuit(q1,q2,q0,c)
for qubit in q1:
qc.reset(qubit)
for qubit in q2:
qc.reset(qubit)
qc.reset(q0)
# initialise qubits which should be added
for i, qubit in enumerate(q1):
if(string_q1[i] == 1):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\n',end="")
for i, qubit in enumerate(q2):
if(string_q2[i] == 1):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\n')
# initial addition of least significant bits and determining carry bit
adder.Half_Adder(qc, q1[-1], q2[-1], q0)
qc.measure(q2[-1], c[0])
# adding of next significant bits
adder.Full_Adder(qc, q1[-2], q2[-2], q0, q2[-1], c[1])
# adding of other digits by full adder cascade
for i in range(2, len(string_q1)):
adder.Full_Adder(qc,
q1[-i-1], # bit to add
q2[-i-1], # bit to add
#(and to measure as next significant bit)
q2[-i+1], # carry from last calculation
q2[-i], # carry for next calculation
c[i])
qc.measure(q2[-len(string_q1)+1], c[len(string_q1)])
# check the results
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=10)
results = job.result()
count = results.get_counts()
print(count)
LaTex_code = qc.draw(output='latex_source') # draw the circuit
f_name = 'Adder_gate_for_'+str(string_q1)+'_and_'+str(string_q2)+'.tex'
print(f_name)
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
|
https://github.com/mballarin97/mps_qnn
|
mballarin97
|
# This code is part of qcircha.
#
# 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.
"""
Functions to create and manage QNNs, in addition to some pre-defined structures.
It is used as an intermediate step to create QNNs using the definitions
in the script `circuit.py`. Circuits for the `ZZFeatureMap` and `TwoLocal`
schemes with all possible entangling topologies are defined.
"""
# Import necessary modules
from qiskit import QuantumCircuit
from qiskit.circuit.library import ZZFeatureMap, TwoLocal
from qcircha.circuits import *
def pick_circuit(num_qubits, num_reps, feature_map = 'ZZFeatureMap',
var_ansatz = 'TwoLocal', alternate=True):
"""
Select a circuit with a feature map and a variational block. Examples below.
Each block must have reps = 1, and then specify the correct number of repetitions
is ensured by the :py:func:`general_qnn`.
Available circuits:
- 'ZZFeatureMap' : circuit with linear entanglement, used as feature map in the Power of Quantum Neural networks by Abbas et al.
- 'TwoLocal' : circuit with linear entanglement, used as ansatz in the Power of Quantum Neural networks by Abbas et al.
- 'Circuit15' : circuit with ring entanglement, defined in (n.15 from Kim et al.)
- 'Circuit12' : circuit with linear entanglement and a piramidal structure, defined in (n.12 from Kim et al.)
- 'Circuit1' : circuit without entanglement with two single qubits rotations per qubit (n.1 from Kim et al.)
- 'Identity' : identity circuit
- 'Circuit9' : circuit n. 9 from Kim et al.
- variations of TwoLocal structures are present.
Parameters
----------
num_qubits : int
Number of qubits
num_reps : int
Number of repetitions
feature_map : str or :py:class:`QuantumCircuit`, optional
Type of feature map. Available options in the description. If a
:py:class:`QuantumCircuit` it is used instead of the default ones.
Default to 'ZZFeatureMap'.
ansatz : str or :py:class:`QuantumCircuit`, optional
Type of feature map. Available options in the description. If a
:py:class:`QuantumCircuit` it is used instead of the default ones.
Default to 'TwoLocal'.
alternate : bool, optional
If the feature map and the variational ansatz should be alternated in the
disposition (True) or if first apply ALL the feature map repetitions and
then all the ansatz repetitions (False). Default to True.
Return
------
:py:class:`QuantumCircuit`
quantum circuit with the correct structure
"""
feature_map = _select_circ(num_qubits, feature_map)
var_ansatz = _select_circ(num_qubits, var_ansatz)
# Build the PQC
ansatz = general_qnn(num_reps, feature_map=feature_map,
var_ansatz=var_ansatz, alternate=alternate, barrier=True)
return ansatz
def _select_circ(num_qubits, circ = 'ZZFeatureMap'):
"""
Select the circuit based on the possibilities
Available circuits:
- 'ZZFeatureMap' : circuit with linear entanglement, used as feature map
in the Power of Quantum Neural networks by Abbas et al.
- 'TwoLocal' : circuit with linear entanglement, used as ansatz in
the Power of Quantum Neural networks by Abbas et al.
- 'Circuit15' : circuit with ring entanglement, defined in
(n.15 from Kim et al.)
- 'Circuit12' : circuit with linear entanglement and a piramidal
structure, defined in (n.12 from Kim et al.)
- 'Circuit1' : easy circuit without entanglement (n.1 from Kim et al.)
- 'circuit9' : circuit n. 9 from Kim et al.
Parameters
----------
num_qubits : int
Number of qubits
circ : str or :py:class:`QuantumCircuit`, optional
Type of circuit. Available options in the description. If a
:py:class:`QuantumCircuit` it is used instead of the default ones.
Default to 'ZZFeatureMap'.
Return
------
:py:class:`QuantumCircuit`
Selected quantum circuit
"""
# If it is a quantum circuit, directly return that.
# Otherwise, go through the list
if not isinstance(circ, QuantumCircuit):
circ = circ.lower()
if circ == 'zzfeaturemap':
circ = ZZFeatureMap(num_qubits, reps=1, entanglement='linear')
elif circ == 'twolocal':
circ = TwoLocal(num_qubits, 'ry', 'cx', 'linear', reps=1, skip_final_rotation_layer=True)
elif circ == 'twolocalx':
circ = TwoLocal(num_qubits, 'rx', 'cx', 'linear', reps=1, skip_final_rotation_layer=True, name = "TwoLocalX")
elif circ == 'twolocalz':
circ = TwoLocal(num_qubits, 'rz', 'cx', 'linear', reps=1, skip_final_rotation_layer=True, name="TwoLocalZ")
elif circ == 'zzfeaturemap_ring':
circ = ZZFeatureMap(num_qubits, reps=1, entanglement='circular')
elif circ == 'twolocal_ring':
circ = TwoLocal(num_qubits, 'ry', 'cx', 'circular', reps=1, skip_final_rotation_layer=True)
elif circ == 'zzfeaturemap_full':
circ = ZZFeatureMap(num_qubits, reps=1, entanglement='full')
elif circ == 'twolocal_full':
circ = TwoLocal(num_qubits, 'ry', 'cx', 'full', reps=1, skip_final_rotation_layer=True)
elif circ == 'twolocal_plus':
circ = TwoLocal(num_qubits, ['rz', 'ry'], 'cx', 'linear', reps=1, skip_final_rotation_layer=True, name = 'TwoLocal_plus')
elif circ == 'twolocal_plus_ring':
circ = TwoLocal(num_qubits, ['rz', 'ry'], 'cx', 'circular', reps=1, skip_final_rotation_layer=True, name='TwoLocal_plus')
elif circ == 'twolocal_plus_full':
circ = TwoLocal(num_qubits, ['rz', 'ry'], 'cx', 'full', reps=1, skip_final_rotation_layer=True, name='TwoLocal_plus')
elif circ == 'twolocal_parametric2q':
circ = TwoLocal(num_qubits, 'ry', 'crz', 'linear', reps=1, skip_final_rotation_layer=True, name='TwoLocal_parametricRz')
elif circ == 'twolocal_parametric2q_ring':
circ = TwoLocal(num_qubits, 'ry', 'crz', 'circular', reps=1, skip_final_rotation_layer=True, name='TwoLocal_parametricRz')
elif circ == 'twolocal_parametric2q_full':
circ = TwoLocal(num_qubits, 'ry', 'crz', 'full', reps=1, skip_final_rotation_layer=True, name='TwoLocal_parametricRz')
elif circ == 'twolocal_h_parametric2q':
circ = TwoLocal(num_qubits, 'h', 'crx', 'linear', reps=1, skip_final_rotation_layer=True, name='TwoLocal_h_parametricRz')
elif circ == 'twolocal_h_parametric2q_ring':
circ = TwoLocal(num_qubits, 'h', 'crx', 'circular', reps=1, skip_final_rotation_layer=True, name='TwoLocal_h_parametricRz')
elif circ == 'twolocal_h_parametric2q_full':
circ = TwoLocal(num_qubits, 'h', 'crx', 'full', reps=1, skip_final_rotation_layer=True, name='TwoLocal_h_parametricRz')
elif circ == 'circuit15':
circ = circuit15(num_qubits, num_reps=1, barrier=False)
elif circ == 'circuit12':
circ = circuit12(num_qubits, num_reps=1, piramidal=True, barrier=False)
elif circ == 'circuit9':
circ = circuit9(num_qubits, num_reps=1, barrier = False)
elif circ == 'circuit10':
circ = circuit10(num_qubits, num_reps=1, barrier=False)
elif circ == 'circuit1':
circ = circuit1(num_qubits, num_reps = 1, barrier = False)
elif circ == 'identity':
circ = identity(num_qubits)
elif circ == 'mps':
circ = mps_circ(num_qubits)
else:
raise ValueError(f'Circuit {circ} is not implemented.')
return circ
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
pw_approximation._build()
qc = QuantumCircuit(pw_approximation.num_qubits)
qc.h(list(range(num_state_qubits)))
qc.append(pw_approximation.to_instruction(), qc.qubits)
qc.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
config = backend.configuration()
# Basic Features
print("This backend is called {0}, and is on version {1}. It has {2} qubit{3}. It "
"{4} OpenPulse programs. The basis gates supported on this device are {5}."
"".format(config.backend_name,
config.backend_version,
config.n_qubits,
'' if config.n_qubits == 1 else 's',
'supports' if config.open_pulse else 'does not support',
config.basis_gates))
config.dt # units of seconds
config.meas_levels
config.dtm
config.meas_map
config.drive(0)
config.measure(0)
config.acquire(0)
props = backend.properties()
def describe_qubit(qubit, properties):
"""Print a string describing some of reported properties of the given qubit."""
# Conversion factors from standard SI units
us = 1e6
ns = 1e9
GHz = 1e-9
print("Qubit {0} has a \n"
" - T1 time of {1} microseconds\n"
" - T2 time of {2} microseconds\n"
" - U2 gate error of {3}\n"
" - U2 gate duration of {4} nanoseconds\n"
" - resonant frequency of {5} GHz".format(
qubit,
properties.t1(qubit) * us,
properties.t2(qubit) * us,
properties.gate_error('sx', qubit),
properties.gate_length('sx', qubit) * ns,
properties.frequency(qubit) * GHz))
describe_qubit(0, props)
defaults = backend.defaults()
q0_freq = defaults.qubit_freq_est[0] # Hz
q0_meas_freq = defaults.meas_freq_est[0] # Hz
GHz = 1e-9
print("DriveChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_freq * GHz))
print("MeasureChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_meas_freq * GHz))
calibrations = defaults.instruction_schedule_map
print(calibrations)
measure_schedule = calibrations.get('measure', range(config.n_qubits))
measure_schedule.draw(backend=backend)
# You can use `has` to see if an operation is defined. Ex: Does qubit 3 have an x gate defined?
calibrations.has('x', 3)
# Some circuit operations take parameters. U1 takes a rotation angle:
calibrations.get('u1', 0, P0=3.1415)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/JackHidary/quantumcomputingbook
|
JackHidary
|
# install release containing NeutralAtomDevice and IonDevice classes
!pip install cirq~=0.5.0
import cirq
import numpy as np
import cirq.ion as ci
from cirq import Simulator
import itertools
import random
### number of qubits
qubit_num = 5
### define your qubits as line qubits for a linear ion trap
qubit_list = cirq.LineQubit.range(qubit_num)
### make your ion trap device with desired gate times and qubits
us = 1000*cirq.Duration(nanos=1)
ion_device = ci.IonDevice(measurement_duration=100*us,
twoq_gates_duration=200*us,
oneq_gates_duration=10*us,
qubits=qubit_list)
# Single Qubit Z rotation by Pi/5 radians
ion_device.validate_gate(cirq.Rz(np.pi/5))
# Single Qubit X rotation by Pi/7 radians
ion_device.validate_gate(cirq.Rx(np.pi/7))
# Molmer-Sorensen gate by Pi/4
ion_device.validate_gate(cirq.MS(np.pi/4))
#Controlled gate with non-integer exponent (rotation angle must be a multiple of pi)
ion_device.validate_gate(cirq.TOFFOLI)
### length of your hidden string
string_length = qubit_num-1
### generate all possible strings of length string_length, and randomly choose one as your hidden string
all_strings = ["".join(seq) for seq in itertools.product("01", repeat=string_length)]
hidden_string = random.choice(all_strings)
### make the circuit for BV with clifford gates
circuit = cirq.Circuit()
circuit.append([cirq.X(qubit_list[qubit_num-1])])
for i in range(qubit_num):
circuit.append([cirq.H(qubit_list[i])])
for i in range(qubit_num-1):
if hidden_string[i] == '1':
circuit.append([cirq.CNOT(qubit_list[i], qubit_list[qubit_num-1])])
for i in range(qubit_num - 1):
circuit.append([cirq.H(qubit_list[i])])
circuit.append([cirq.measure(qubit_list[i])])
print("Doing Bernstein-Vazirani algorithm with hidden string",
hidden_string, "\n")
print("Clifford Circuit:\n")
print(circuit, "\n")
### convert the clifford circuit into circuit with ion trap native gates
ion_circuit = ion_device.decompose_circuit(circuit)
print(repr(ion_circuit))
print("Iontrap Circuit: \n", ion_circuit, "\n")
### convert the clifford circuit into circuit with ion trap native gates
ion_circuit = ion_device.decompose_circuit(circuit)
optimized_ion_circuit=cirq.merge_single_qubit_gates_into_phased_x_z(ion_circuit)
print("Iontrap Circuit: \n", ion_circuit, "\n")
### run the ion trap circuit
simulator = Simulator()
clifford_result = simulator.run(circuit)
result = simulator.run(ion_circuit)
measurement_results = ''
for i in range(qubit_num-1):
if result.measurements[str(i)][0][0]:
measurement_results += '1'
else:
measurement_results += '0'
print("Hidden string is:", hidden_string)
print("Measurement results are:", measurement_results)
print("Found answer using Bernstein-Vazirani:", hidden_string == measurement_results)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
pw_approximation._build()
qc = QuantumCircuit(pw_approximation.num_qubits)
qc.h(list(range(num_state_qubits)))
qc.append(pw_approximation.to_instruction(), qc.qubits)
qc.draw(output='mpl')
|
https://github.com/renatawong/quantum-maxcut
|
renatawong
|
'''
(C) Renata Wong (CGU-CoIC, NCTS-NTU) 2023
This is the accompanying code for the paper
"Bioinspired Quantum Oracle Circuits for Biomolecular Solutions of the Maximum Cut Problem"
by Weng-Long Chang, Renata Wong, Yu-Hao Chen, Wen-Yu Chung, Ju-Chin Chen, and Athanasios V. Vasilakos
'''
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import numpy as np
'''
Create the quantum circuit for the 3-vertex example
num_vertices = n = number of vertices
num_enges = m = number of edges
'''
'''
PLEASE FILL IN THE EDGE LIST FOR YOUR GRAPH IN THE LINE BELOW
'''
permanent_edge_list = [[0,1], [1,2]]
# t is the maximum possible number of edges in a cut and is assumed to be known upfront
t = 2
num_vertices = len({x for l in permanent_edge_list for x in l})
num_edges = len(permanent_edge_list)
range_z = (num_edges * (num_edges + 3)) / 2
range_r = 2 * num_edges
range_s = num_edges
aux = QuantumRegister(1, 'aux')
z_reg = QuantumRegister(range_z, 'z_reg')
s_reg = QuantumRegister(range_s, 's_reg')
r_reg = QuantumRegister(range_r, 'r_reg')
x_reg = QuantumRegister(num_vertices, 'x_reg')
readout = ClassicalRegister(num_vertices, 'out')
qc = QuantumCircuit(x_reg, r_reg, s_reg, z_reg, aux, readout)
system_size = qc.num_qubits
print('System size:', system_size)
'''
Create r_matrix to store indices of the register r_reg
'''
r_matrix = [ [0 for j in range(2)] for i in range(num_edges)]
rij = 0
for i in range(num_edges):
for j in range(2):
r_matrix[i][j] = rij
rij += 1
#print('r matrix', r_matrix)
'''
Create z_matrix to store indices of z_reg
Note that i starts with index 1, not 0.
'''
z_matrix = [ [ 0 for j in range(num_edges + 1) ] for i in range(num_edges + 1) ]
zij = 0
for i in range(1, num_edges + 1):
for j in range(i + 1):
z_matrix[i][j] = zij
zij += 1
#print('z matrix', z_matrix)
'''
Define the EIIAC subcircuit
'''
sq = QuantumRegister(5,'sq')
sc = QuantumCircuit(sq, name='EIIAC')
sc.x(sq[1])
sc.ccx(sq[0], sq[1], sq[2])
sc.x(sq[1])
sc.x(sq[0])
sc.ccx(sq[0], sq[1], sq[3])
sc.x(sq[0])
sc.x(sq[2])
sc.x(sq[3])
sc.ccx(sq[2], sq[3], sq[4])
sc.x(sq[2])
sc.x(sq[3])
eiiac = sc.to_instruction()
'''
Initialize the system and set it in a uniform superpostion
'''
for qubit in s_reg:
qc.x(qubit)
for qubit in x_reg:
qc.h(qubit)
qc.x(aux)
qc.h(aux)
#qc.barrier()
'''
NOTE: There will always be an even number of solutions, since under maximum cut 101 is the same as 010.
For Fig. 1 in the paper, we set the number of solutions to 2.
YOU MAY NEED TO ADJUST THE NUMBER OF SOLUTIONS.
'''
num_solutions = 2
num_runs = int(np.ceil(np.pi * np.sqrt((2**num_vertices) / num_solutions)) / 4)
print('Number of iterations:', num_runs)
'''
Amplitude amplification
'''
for run in range(num_runs):
# Apply EIIAC
# It is assumed that the two vertices in the x_reg share an edge
edge_list = permanent_edge_list.copy()
for index, edge in enumerate(edge_list):
[index_v1, index_v2] = edge
cfe_qubits = []
cfe_qubits += [x_reg[index_v1]]
cfe_qubits += [x_reg[index_v2]]
cfe_qubits += [r_reg[k] for k in range(2*index, 2*index+2)]
cfe_qubits += [s_reg[index]]
qc.append(eiiac, cfe_qubits)
#qc.barrier()
# Apply INO
if t > 0:
qc.cx(s_reg[0], z_reg[1])
# Apply PNO
if t < num_edges:
qc.x(s_reg[0])
qc.cx(s_reg[0], z_reg[0])
qc.x(s_reg[0])
# Apply CIO and CPO
for i in range(1, num_edges):
for j in reversed(range(i+1)):
if j+1 <= t and num_edges-i+j == t:
qc.ccx(s_reg[i], z_reg[z_matrix[i][j]], z_reg[z_matrix[i+1][j+1]])
if j <= t and num_edges-i+j-1 == t:
qc.x(s_reg[i])
qc.ccx(s_reg[i], z_reg[z_matrix[i][j]], z_reg[z_matrix[i+1][j+1]])
qc.x(s_reg[i])
'''
Which qubit of register z_reg is used here depends on how many edges are there in the cut.
For the example in Fig. 1 we expect 2 edges, and therefore we choose qubit 2 (counting from 0, 1, 2, etc.).
This qubit should be in the state 1.
YOU MAY NEED TO ADJUST THE CONTROL QUBIT IN THE CX GATE.
'''
#qc.barrier()
qc.cx(z_reg[z_matrix[num_edges][t]], aux)
#qc.barrier()
'''
Uncomputing CIO, CPO, PNO, INO, and EIIAC,
'''
# uncompute CIO and CPO
for i in range(1, num_edges):
for j in reversed(range(i+1)):
if j+1 <= t and num_edges-i+j == t:
qc.ccx(s_reg[i], z_reg[z_matrix[i][j]], z_reg[z_matrix[i+1][j+1]])
if j <= t and num_edges-i+j-1 == t:
qc.x(s_reg[i])
qc.ccx(s_reg[i], z_reg[z_matrix[i][j]], z_reg[z_matrix[i+1][j+1]])
qc.x(s_reg[i])
# Uncompute PNO
if t < num_edges:
qc.x(s_reg[0])
qc.cx(s_reg[0], z_reg[0])
qc.x(s_reg[0])
# Uncompute INO
if t > 0:
qc.cx(s_reg[0], z_reg[1])
# Uncompute EIIAC
index = len(edge_list) - 1
for edge in reversed(edge_list):
[index_v1, index_v2] = edge
cfe_qubits = []
cfe_qubits += [x_reg[index_v1]]
cfe_qubits += [x_reg[index_v2]]
cfe_qubits += [r_reg[k] for k in range(2*index, 2*index+2)]
cfe_qubits += [s_reg[index]]
index -= 1
qc.append(eiiac.inverse(), cfe_qubits)
'''
Diffusion operations
'''
qc.barrier()
for qubit in x_reg:
qc.h(qubit)
qc.x(qubit)
qc.h(x_reg[len(x_reg) - 1])
multiplexer = [x_reg[i] for i in range(len(x_reg) - 1)]
qc.mcx(multiplexer, x_reg[len(x_reg) - 1])
qc.h(x_reg[len(x_reg) - 1])
for qubit in x_reg:
qc.x(qubit)
qc.h(qubit)
#qc.barrier()
'''
Measurement
'''
cuts = []
for i in range(len(x_reg)):
cuts.append(x_reg[i])
# Reverse the order in which the output is shown so that it can be read from left to right.
cuts.reverse()
qc.measure(cuts, readout)
from qiskit import Aer, execute
from qiskit.visualization import plot_histogram
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 1024).result()
counts = result.get_counts()
# Uncomment to save the output
#plot_histogram(counts).savefig('example.svg')
plot_histogram(counts)
qc.draw('mpl')
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- 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.
"""
This module contains the definition of a base class for
feature map. Several types of commonly used approaches.
"""
from collections import OrderedDict
import copy
import itertools
import logging
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import Pauli
from qiskit.qasm import pi
from sympy.core.numbers import NaN, Float
from qiskit.aqua import Operator
from qiskit.aqua.components.feature_maps import FeatureMap, self_product
logger = logging.getLogger(__name__)
class PauliExpansion(FeatureMap):
"""
Mapping data with the second order expansion followed by entangling gates.
Refer to https://arxiv.org/pdf/1804.11326.pdf for details.
"""
CONFIGURATION = {
'name': 'PauliExpansion',
'description': 'Pauli expansion for feature map (any order)',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'Pauli_Expansion_schema',
'type': 'object',
'properties': {
'depth': {
'type': 'integer',
'default': 2,
'minimum': 1
},
'entangler_map': {
'type': ['array', 'null'],
'default': None
},
'entanglement': {
'type': 'string',
'default': 'full',
'oneOf': [
{'enum': ['full', 'linear']}
]
},
'paulis': {
'type': ['array'],
"items": {
"type": "string"
},
'default': ['Z', 'ZZ']
}
},
'additionalProperties': False
}
}
def __init__(self, feature_dimension, depth=2, entangler_map=None,
entanglement='full', paulis=['Z', 'ZZ'], data_map_func=self_product):
"""Constructor.
Args:
feature_dimension (int): number of features
depth (int): the number of repeated circuits
entangler_map (list[list]): describe the connectivity of qubits, each list describes
[source, target], or None for full entanglement.
Note that the order is the list is the order of
applying the two-qubit gate.
entanglement (str): ['full', 'linear'], generate the qubit connectivitiy by predefined
topology
paulis (str): a comma-seperated string for to-be-used paulis
data_map_func (Callable): a mapping function for data x
"""
self.validate(locals())
super().__init__()
self._num_qubits = self._feature_dimension = feature_dimension
self._depth = depth
if entangler_map is None:
self._entangler_map = self.get_entangler_map(entanglement, feature_dimension)
else:
self._entangler_map = self.validate_entangler_map(entangler_map, feature_dimension)
self._pauli_strings = self._build_subset_paulis_string(paulis)
self._data_map_func = data_map_func
self._magic_num = np.nan
self._param_pos = OrderedDict()
self._circuit_template = self._build_circuit_template()
def _build_subset_paulis_string(self, paulis):
# fill out the paulis to the number of qubits
temp_paulis = []
for pauli in paulis:
len_pauli = len(pauli)
for possible_pauli_idx in itertools.combinations(range(self._num_qubits), len_pauli):
string_temp = ['I'] * self._num_qubits
for idx in range(len(possible_pauli_idx)):
string_temp[-possible_pauli_idx[idx] - 1] = pauli[-idx - 1]
temp_paulis.append(''.join(string_temp))
# clean up string that can not be entangled.
final_paulis = []
for pauli in temp_paulis:
where_z = np.where(np.asarray(list(pauli[::-1])) != 'I')[0]
if len(where_z) == 1:
final_paulis.append(pauli)
else:
is_valid = True
for src, targ in itertools.combinations(where_z, 2):
if [src, targ] not in self._entangler_map:
is_valid = False
break
if is_valid:
final_paulis.append(pauli)
else:
logger.warning("Due to the limited entangler_map,"
" {} is skipped.".format(pauli))
logger.info("Pauli terms include: {}".format(final_paulis))
return final_paulis
def _build_circuit_template(self):
x = np.asarray([self._magic_num] * self._num_qubits)
qr = QuantumRegister(self._num_qubits, name='q')
qc = self.construct_circuit(x, qr)
for index in range(len(qc.data)):
gate_param = qc.data[index][0].params
param_sub_pos = []
for x in range(len(gate_param)):
if isinstance(gate_param[x], NaN):
param_sub_pos.append(x)
if param_sub_pos != []:
self._param_pos[index] = param_sub_pos
return qc
def _extract_data_for_rotation(self, pauli, x):
where_non_i = np.where(np.asarray(list(pauli[::-1])) != 'I')[0]
return x[where_non_i]
def _construct_circuit_with_template(self, x):
coeffs = [self._data_map_func(self._extract_data_for_rotation(pauli, x))
for pauli in self._pauli_strings] * self._depth
qc = copy.deepcopy(self._circuit_template)
data_idx = 0
for key, value in self._param_pos.items():
new_param = coeffs[data_idx]
for pos in value:
qc.data[key].params[pos] = Float(2. * new_param) # rotation angle is 2x
data_idx += 1
return qc
def construct_circuit(self, x, qr=None, inverse=False):
"""
Construct the second order expansion based on given data.
Args:
x (numpy.ndarray): 1-D to-be-transformed data.
qr (QauntumRegister): the QuantumRegister object for the circuit, if None,
generate new registers with name q.
inverse (bool): whether or not inverse the circuit
Returns:
QuantumCircuit: a quantum circuit transform data x.
"""
if not isinstance(x, np.ndarray):
raise TypeError("x must be numpy array.")
if x.ndim != 1:
raise ValueError("x must be 1-D array.")
if x.shape[0] != self._num_qubits:
raise ValueError("number of qubits and data dimension must be the same.")
if qr is None:
qc = self._construct_circuit_with_template(x)
else:
qc = QuantumCircuit(qr)
for _ in range(self._depth):
for i in range(self._num_qubits):
qc.u2(0, pi, qr[i])
for pauli in self._pauli_strings:
coeff = self._data_map_func(self._extract_data_for_rotation(pauli, x))
p = Pauli.from_label(pauli)
qc += Operator.construct_evolution_circuit([[coeff, p]], 1, 1, qr)
if inverse:
qc = qc.inverse()
return qc
|
https://github.com/aaghazaly/quantum-project-using-qiskit
|
aaghazaly
|
from argparse import ArgumentParser, Namespace, BooleanOptionalAction
from qiskit import QuantumCircuit as qc
from qiskit import QuantumRegister as qr
from qiskit import transpile
from qiskit_aer import AerSimulator
from qiskit.result import Counts
from matplotlib.pyplot import show, subplots, xticks, yticks
from math import pi, sqrt
from heapq import nlargest
class GroversAlgorithm:
def __init__(self,
title: str = "Grover's Algorithm",
n_qubits: int = 5,
search: set[int] = { 11, 9, 0, 3 },
shots: int = 1000,
fontsize: int = 10,
print: bool = False,
combine_states: bool = False) -> None:
"""
_summary_
Args:
title (str, optional): Window title. Defaults to "Grover's Algorithm".
n_qubits (int, optional): Number of qubits. Defaults to 5.
search (set[int], optional): Set of nonnegative integers to search for using Grover's algorithm. Defaults to { 11, 9, 0, 3 }.
shots (int, optional): Amount of times the algorithm is simulated. Defaults to 10000.
fontsize (int, optional): Histogram's font size. Defaults to 10.
print (bool, optional): Whether or not to print quantum circuit(s). Defaults to False.
combine_states (bool, optional): Whether to combine all non-winning states into 1 bar labeled "Others" or not. Defaults to False.
"""
# Parsing command line arguments
self._parser: ArgumentParser = ArgumentParser(description = "Run grover's algorithm via command line", add_help = False)
self._init_parser(title, n_qubits, search, shots, fontsize, print, combine_states)
self._args: Namespace = self._parser.parse_args()
# Set of nonnegative ints to search for
self.search: set[int] = set(self._args.search)
# Set of m N-qubit binary strings representing target state(s) (i.e. self.search in base 2)
self._targets: set[str] = { f"{s:0{self._args.n_qubits}b}" for s in self.search }
# N-qubit quantum register
self._qubits: qr = qr(self._args.n_qubits, "qubit")
def _print_circuit(self, circuit: qc, name: str) -> None:
"""Print quantum circuit.
Args:
circuit (qc): Quantum circuit to print.
name (str): Quantum circuit's name.
"""
print(f"\n{name}:\n{circuit}")
def _oracle(self, targets: set[str]) -> qc:
"""Mark target state(s) with negative phase.
Args:
targets (set[str]): N-qubit binary string(s) representing target state(s).
Returns:
qc: Quantum circuit representation of oracle.
"""
# Create N-qubit quantum circuit for oracle
oracle = qc(self._qubits, name = "Oracle")
for target in targets:
# Reverse target state since Qiskit uses little-endian for qubit ordering
target = target[::-1]
# Flip zero qubits in target
for i in range(self._args.n_qubits):
if target[i] == "0":
# Pauli-X gate
oracle.x(i)
# Simulate (N - 1)-control Z gate
# 1. Hadamard gate
oracle.h(self._args.n_qubits - 1)
# 2. (N - 1)-control Toffoli gate
oracle.mcx(list(range(self._args.n_qubits - 1)), self._args.n_qubits - 1)
# 3. Hadamard gate
oracle.h(self._args.n_qubits - 1)
# Flip back to original state
for i in range(self._args.n_qubits):
if target[i] == "0":
# Pauli-X gate
oracle.x(i)
# Display oracle, if applicable
if self._args.print: self._print_circuit(oracle, "ORACLE")
return oracle
def _diffuser(self) -> qc:
"""Amplify target state(s) amplitude, which decreases the amplitudes of other states
and increases the probability of getting the correct solution (i.e. target state(s)).
Returns:
qc: Quantum circuit representation of diffuser (i.e. Grover's diffusion operator).
"""
# Create N-qubit quantum circuit for diffuser
diffuser = qc(self._qubits, name = "Diffuser")
# Hadamard gate
diffuser.h(self._qubits)
# Oracle with all zero target state
diffuser.append(self._oracle({"0" * self._args.n_qubits}), list(range(self._args.n_qubits)))
# Hadamard gate
diffuser.h(self._qubits)
# Display diffuser, if applicable
if self._args.print: self._print_circuit(diffuser, "DIFFUSER")
return diffuser
def _grover(self) -> qc:
"""Create quantum circuit representation of Grover's algorithm,
which consists of 4 parts: (1) state preparation/initialization,
(2) oracle, (3) diffuser, and (4) measurement of resulting state.
Steps 2-3 are repeated an optimal number of times (i.e. Grover's
iterate) in order to maximize probability of success of Grover's algorithm.
Returns:
qc: Quantum circuit representation of Grover's algorithm.
"""
# Create N-qubit quantum circuit for Grover's algorithm
grover = qc(self._qubits, name = "Grover Circuit")
# Intialize qubits with Hadamard gate (i.e. uniform superposition)
grover.h(self._qubits)
# # Apply barrier to separate steps
grover.barrier()
# Apply oracle and diffuser (i.e. Grover operator) optimal number of times
for _ in range(int((pi / 4) * sqrt((2 ** self._args.n_qubits) / len(self._targets)))):
grover.append(self._oracle(self._targets), list(range(self._args.n_qubits)))
grover.append(self._diffuser(), list(range(self._args.n_qubits)))
# Measure all qubits once finished
grover.measure_all()
# Display grover circuit, if applicable
if self._args.print: self._print_circuit(grover, "GROVER CIRCUIT")
return grover
def _outcome(self, winners: list[str], counts: Counts) -> None:
"""Print top measurement(s) (state(s) with highest frequency)
and target state(s) in binary and decimal form, determine
if top measurement(s) equals target state(s), then print result.
Args:
winners (list[str]): State(s) (N-qubit binary string(s))
with highest probability of being measured.
counts (Counts): Each state and its respective frequency.
"""
print("WINNER(S):")
print(f"Binary = {winners}\nDecimal = {[ int(key, 2) for key in winners ]}\n")
print("TARGET(S):")
print(f"Binary = {self._targets}\nDecimal = {self.search}\n")
if not all(key in self._targets for key in winners): print("Target(s) not found...")
else:
winners_frequency, total = 0, 0
for value, frequency in counts.items():
if value in winners:
winners_frequency += frequency
total += frequency
print(f"Target(s) found with {winners_frequency / total:.2%} accuracy!")
def _show_histogram(self, histogram_data) -> None:
"""Print outcome and display histogram of simulation results.
Args:
data: Each state and its respective frequency.
"""
# State(s) with highest count and their frequencies
winners = { winner : histogram_data.get(winner) for winner in nlargest(len(self._targets), histogram_data, key = histogram_data.get) }
# Print outcome
self._outcome(list(winners.keys()), histogram_data)
# X-axis and y-axis value(s) for winners, respectively
winners_x_axis = [ str(winner) for winner in [*winners] ]
winners_y_axis = [ *winners.values() ]
# All other states (i.e. non-winners) and their frequencies
others = { state : frequency for state, frequency in histogram_data.items() if state not in winners }
# X-axis and y-axis value(s) for all other states, respectively
other_states_x_axis = "Others" if self._args.combine else [*others]
other_states_y_axis = [ sum([*others.values()]) ] if self._args.combine else [ *others.values() ]
# Create histogram for simulation results
figure, axes = subplots(num = "Grover's Algorithm — Results", layout = "constrained")
axes.bar(winners_x_axis, winners_y_axis, color = "green", label = "Target")
axes.bar(other_states_x_axis, other_states_y_axis, color = "red", label = "Non-target")
axes.legend(fontsize = self._args.fontsize)
axes.grid(axis = "y", ls = "dashed")
axes.set_axisbelow(True)
# Set histogram title, x-axis title, and y-axis title respectively
axes.set_title(f"Outcome of {self._args.shots} Simulations", fontsize = int(self._args.fontsize * 1.45))
axes.set_xlabel("States (Qubits)", fontsize = int(self._args.fontsize * 1.3))
axes.set_ylabel("Frequency", fontsize = int(self._args.fontsize * 1.3))
# Set font properties for x-axis and y-axis labels respectively
xticks(fontsize = self._args.fontsize, family = "monospace", rotation = 0 if self._args.combine else 70)
yticks(fontsize = self._args.fontsize, family = "monospace")
# Set properties for annotations displaying frequency above each bar
annotation = axes.annotate("",
xy = (0, 0),
xytext = (5, 5),
xycoords = "data",
textcoords = "offset pixels",
ha = "center",
va = "bottom",
family = "monospace",
weight = "bold",
fontsize = self._args.fontsize,
bbox = dict(facecolor = "white", alpha = 0.4, edgecolor = "None", pad = 0)
)
def _hover(event) -> None:
"""Display frequency above each bar upon hovering over it.
Args:
event: Matplotlib event.
"""
visibility = annotation.get_visible()
if event.inaxes == axes:
for bars in axes.containers:
for bar in bars:
cont, _ = bar.contains(event)
if cont:
x, y = bar.get_x() + bar.get_width() / 2, bar.get_y() + bar.get_height()
annotation.xy = (x, y)
annotation.set_text(y)
annotation.set_visible(True)
figure.canvas.draw_idle()
return
if visibility:
annotation.set_visible(False)
figure.canvas.draw_idle()
# Display histogram
id = figure.canvas.mpl_connect("motion_notify_event", _hover)
show()
figure.canvas.mpl_disconnect(id)
def run(self) -> None:
"""
Run Grover's algorithm simulation.
"""
# Simulate Grover's algorithm locally
backend = AerSimulator(method = "density_matrix")
# Generate optimized grover circuit for simulation
transpiled_circuit = transpile(self._grover(), backend, optimization_level = 2)
# Run Grover's algorithm simulation
job = backend.run(transpiled_circuit, shots = self._args.shots)
# Get simulation results
results = job.result()
# Get each state's histogram data (including frequency) from simulation results
data = results.get_counts()
# Display simulation results
self._show_histogram(data)
def _init_parser(self,
title: str,
n_qubits: int,
search: set[int],
shots: int,
fontsize: int,
print: bool,
combine_states: bool) -> None:
"""
Helper method to initialize command line argument parser.
Args:
title (str): Window title.
n_qubits (int): Number of qubits.
search (set[int]): Set of nonnegative integers to search for using Grover's algorithm.
shots (int): Amount of times the algorithm is simulated.
fontsize (int): Histogram's font size.
print (bool): Whether or not to print quantum circuit(s).
combine_states (bool): Whether to combine all non-winning states into 1 bar labeled "Others" or not.
"""
self._parser.add_argument("-H, --help",
action = "help",
help = "show this help message and exit")
self._parser.add_argument("-T, --title",
type = str,
default = title,
dest = "title",
metavar = "<title>",
help = f"window title (default: \"{title}\")")
self._parser.add_argument("-n, --n-qubits",
type = int,
default = n_qubits,
dest = "n_qubits",
metavar = "<n_qubits>",
help = f"number of qubits (default: {n_qubits})")
self._parser.add_argument("-s, --search",
default = search,
type = int,
nargs = "+",
dest = "search",
metavar = "<search>",
help = f"nonnegative integers to search for with Grover's algorithm (default: {search})")
self._parser.add_argument("-S, --shots",
type = int,
default = shots,
dest = "shots",
metavar = "<shots>",
help = f"amount of times the algorithm is simulated (default: {shots})")
self._parser.add_argument("-f, --font-size",
type = int,
default = fontsize,
dest = "fontsize",
metavar = "<font_size>",
help = f"histogram's font size (default: {fontsize})")
self._parser.add_argument("-p, --print",
action = BooleanOptionalAction,
type = bool,
default = print,
dest = "print",
help = f"whether or not to print quantum circuit(s) (default: {print})")
self._parser.add_argument("-c, --combine",
action = BooleanOptionalAction,
type = bool,
default = combine_states,
dest = "combine",
help = f"whether to combine all non-winning states into 1 bar labeled \"Others\" or not (default: {combine_states})")
if __name__ == "__main__":
GroversAlgorithm().run()
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### added h gate ###
qc.h(1)
qc.cx(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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can show the phase of each state and use
# degrees instead of radians
from qiskit.quantum_info import DensityMatrix
import numpy as np
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
qc.z(1)
matrix = DensityMatrix(qc)
plot_state_qsphere(matrix,
show_state_phases = True, use_degrees = True)
|
https://github.com/mspronesti/qlearnkit
|
mspronesti
|
# TODO: uncomment the next line after release qlearnkit 0.2.0
#!pip install qlearnkit
!pip install matplotlib
import numpy as np
from qlearnkit.algorithms.qsvm import QSVClassifier
from sklearn.preprocessing import MinMaxScaler
from sklearn.datasets import load_iris
from sklearn.svm import SVC
from matplotlib import pyplot as plt
from qiskit import BasicAer
from qiskit.circuit.library import PauliFeatureMap
from qiskit.utils import QuantumInstance
# import some data to play with
iris = load_iris()
mms = MinMaxScaler()
X = iris.data[:, :2] # we only take the first two features. We could
# avoid this ugly slicing by using a two-dim dataset
X = mms.fit_transform(X)
y = iris.target
seed = 42
encoding_map = PauliFeatureMap(2)
quantum_instance = QuantumInstance(BasicAer.get_backend('statevector_simulator'),
shots=1024,
optimization_level=1,
seed_simulator=seed,
seed_transpiler=seed)
svc = SVC(kernel='linear')
qsvc = QSVClassifier(encoding_map=encoding_map, quantum_instance=quantum_instance)
svc.fit(X,y)
qsvc.fit(X,y)
h = 0.1 # step size in the mesh
# create a mesh to plot in
x_min, x_max = X[:, 0].min() - 0.2, X[:, 0].max() + 0.2
y_min, y_max = X[:, 1].min() - 0.2, X[:, 1].max() + 0.2
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
# title for the plots
titles = ['SVC with linear kernel',
'QSVC with Pauli feature map']
for i, clf in enumerate((svc, qsvc)):
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, x_max]x[y_min, y_max].
plt.subplot(2, 1, i + 1)
plt.subplots_adjust(wspace=0.4, hspace=0.4)
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap="RdBu", alpha=0.8)
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=y, cmap="RdBu",edgecolor="grey" )
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.xticks(())
plt.yticks(())
plt.title(titles[i])
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Checking the version of PYTHON; we only support > 3.5
import sys
if sys.version_info < (3,5):
raise Exception('Please use Python version 3.5 or greater.')
# useful additional packages
import numpy as np
import random
import re # regular expressions module
# importing the QISKit
from qiskit import QuantumCircuit, QuantumProgram
#import Qconfig
# Quantum program setup
Q_program = QuantumProgram()
#Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url
# Creating registers
qr = Q_program.create_quantum_register("qr", 2)
cr = Q_program.create_classical_register("cr", 4)
singlet = Q_program.create_circuit('singlet', [qr], [cr])
singlet.x(qr[0])
singlet.x(qr[1])
singlet.h(qr[0])
singlet.cx(qr[0],qr[1])
## Alice's measurement circuits
# measure the spin projection of Alice's qubit onto the a_1 direction (X basis)
measureA1 = Q_program.create_circuit('measureA1', [qr], [cr])
measureA1.h(qr[0])
measureA1.measure(qr[0],cr[0])
# measure the spin projection of Alice's qubit onto the a_2 direction (W basis)
measureA2 = Q_program.create_circuit('measureA2', [qr], [cr])
measureA2.s(qr[0])
measureA2.h(qr[0])
measureA2.t(qr[0])
measureA2.h(qr[0])
measureA2.measure(qr[0],cr[0])
# measure the spin projection of Alice's qubit onto the a_3 direction (standard Z basis)
measureA3 = Q_program.create_circuit('measureA3', [qr], [cr])
measureA3.measure(qr[0],cr[0])
## Bob's measurement circuits
# measure the spin projection of Bob's qubit onto the b_1 direction (W basis)
measureB1 = Q_program.create_circuit('measureB1', [qr], [cr])
measureB1.s(qr[1])
measureB1.h(qr[1])
measureB1.t(qr[1])
measureB1.h(qr[1])
measureB1.measure(qr[1],cr[1])
# measure the spin projection of Bob's qubit onto the b_2 direction (standard Z basis)
measureB2 = Q_program.create_circuit('measureB2', [qr], [cr])
measureB2.measure(qr[1],cr[1])
# measure the spin projection of Bob's qubit onto the b_3 direction (V basis)
measureB3 = Q_program.create_circuit('measureB3', [qr], [cr])
measureB3.s(qr[1])
measureB3.h(qr[1])
measureB3.tdg(qr[1])
measureB3.h(qr[1])
measureB3.measure(qr[1],cr[1])
## Lists of measurement circuits
aliceMeasurements = [measureA1, measureA2, measureA3]
bobMeasurements = [measureB1, measureB2, measureB3]
# Define the number of singlets N
numberOfSinglets = 500
aliceMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b of Alice
bobMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b' of Bob
circuits = [] # the list in which the created circuits will be stored
for i in range(numberOfSinglets):
# create the name of the i-th circuit depending on Alice's and Bob's measurement choices
circuitName = str(i) + ':A' + str(aliceMeasurementChoices[i]) + '_B' + str(bobMeasurementChoices[i])
# create the joint measurement circuit
# add Alice's and Bob's measurement circuits to the singlet state curcuit
Q_program.add_circuit(circuitName,
singlet + # singlet state circuit
aliceMeasurements[aliceMeasurementChoices[i]-1] + # measurement circuit of Alice
bobMeasurements[bobMeasurementChoices[i]-1] # measurement circuit of Bob
)
# add the created circuit to the circuits list
circuits.append(circuitName)
print(circuits[0])
result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240)
print(result)
result.get_counts(circuits[0])
abPatterns = [
re.compile('..00$'), # search for the '..00' output (Alice obtained -1 and Bob obtained -1)
re.compile('..01$'), # search for the '..01' output
re.compile('..10$'), # search for the '..10' output (Alice obtained -1 and Bob obtained 1)
re.compile('..11$') # search for the '..11' output
]
aliceResults = [] # Alice's results (string a)
bobResults = [] # Bob's results (string a')
for i in range(numberOfSinglets):
res = list(result.get_counts(circuits[i]).keys())[0] # extract the key from the dict and transform it to str; execution result of the i-th circuit
if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(-1) # Bob got the result -1
if abPatterns[1].search(res):
aliceResults.append(1)
bobResults.append(-1)
if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(1) # Bob got the result 1
if abPatterns[3].search(res):
aliceResults.append(1)
bobResults.append(1)
aliceKey = [] # Alice's key string k
bobKey = [] # Bob's key string k'
# comparing the stings with measurement choices
for i in range(numberOfSinglets):
# if Alice and Bob have measured the spin projections onto the a_2/b_1 or a_3/b_2 directions
if (aliceMeasurementChoices[i] == 2 and bobMeasurementChoices[i] == 1) or (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 2):
aliceKey.append(aliceResults[i]) # record the i-th result obtained by Alice as the bit of the secret key k
bobKey.append(- bobResults[i]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k'
keyLength = len(aliceKey) # length of the secret key
abKeyMismatches = 0 # number of mismatching bits in Alice's and Bob's keys
for j in range(keyLength):
if aliceKey[j] != bobKey[j]:
abKeyMismatches += 1
# function that calculates CHSH correlation value
def chsh_corr(result):
# lists with the counts of measurement results
# each element represents the number of (-1,-1), (-1,1), (1,-1) and (1,1) results respectively
countA1B1 = [0, 0, 0, 0] # XW observable
countA1B3 = [0, 0, 0, 0] # XV observable
countA3B1 = [0, 0, 0, 0] # ZW observable
countA3B3 = [0, 0, 0, 0] # ZV observable
for i in range(numberOfSinglets):
res = list(result.get_counts(circuits[i]).keys())[0]
# if the spins of the qubits of the i-th singlet were projected onto the a_1/b_1 directions
if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 1):
for j in range(4):
if abPatterns[j].search(res):
countA1B1[j] += 1
if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 3):
for j in range(4):
if abPatterns[j].search(res):
countA1B3[j] += 1
if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 1):
for j in range(4):
if abPatterns[j].search(res):
countA3B1[j] += 1
# if the spins of the qubits of the i-th singlet were projected onto the a_3/b_3 directions
if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 3):
for j in range(4):
if abPatterns[j].search(res):
countA3B3[j] += 1
# number of the results obtained from the measurements in a particular basis
total11 = sum(countA1B1)
total13 = sum(countA1B3)
total31 = sum(countA3B1)
total33 = sum(countA3B3)
# expectation values of XW, XV, ZW and ZV observables (2)
expect11 = (countA1B1[0] - countA1B1[1] - countA1B1[2] + countA1B1[3])/total11 # -1/sqrt(2)
expect13 = (countA1B3[0] - countA1B3[1] - countA1B3[2] + countA1B3[3])/total13 # 1/sqrt(2)
expect31 = (countA3B1[0] - countA3B1[1] - countA3B1[2] + countA3B1[3])/total31 # -1/sqrt(2)
expect33 = (countA3B3[0] - countA3B3[1] - countA3B3[2] + countA3B3[3])/total33 # -1/sqrt(2)
corr = expect11 - expect13 + expect31 + expect33 # calculate the CHSC correlation value (3)
return corr
corr = chsh_corr(result) # CHSH correlation value
# CHSH inequality test
print('CHSH correlation value: ' + str(round(corr, 3)))
# Keys
print('Length of the key: ' + str(keyLength))
print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n')
# measurement of the spin projection of Alice's qubit onto the a_2 direction (W basis)
measureEA2 = Q_program.create_circuit('measureEA2', [qr], [cr])
measureEA2.s(qr[0])
measureEA2.h(qr[0])
measureEA2.t(qr[0])
measureEA2.h(qr[0])
measureEA2.measure(qr[0],cr[2])
# measurement of the spin projection of Allice's qubit onto the a_3 direction (standard Z basis)
measureEA3 = Q_program.create_circuit('measureEA3', [qr], [cr])
measureEA3.measure(qr[0],cr[2])
# measurement of the spin projection of Bob's qubit onto the b_1 direction (W basis)
measureEB1 = Q_program.create_circuit('measureEB1', [qr], [cr])
measureEB1.s(qr[1])
measureEB1.h(qr[1])
measureEB1.t(qr[1])
measureEB1.h(qr[1])
measureEB1.measure(qr[1],cr[3])
# measurement of the spin projection of Bob's qubit onto the b_2 direction (standard Z measurement)
measureEB2 = Q_program.create_circuit('measureEB2', [qr], [cr])
measureEB2.measure(qr[1],cr[3])
# lists of measurement circuits
eveMeasurements = [measureEA2, measureEA3, measureEB1, measureEB2]
# list of Eve's measurement choices
# the first and the second elements of each row represent the measurement of Alice's and Bob's qubits by Eve respectively
eveMeasurementChoices = []
for j in range(numberOfSinglets):
if random.uniform(0, 1) <= 0.5: # in 50% of cases perform the WW measurement
eveMeasurementChoices.append([0, 2])
else: # in 50% of cases perform the ZZ measurement
eveMeasurementChoices.append([1, 3])
circuits = [] # the list in which the created circuits will be stored
for j in range(numberOfSinglets):
# create the name of the j-th circuit depending on Alice's, Bob's and Eve's choices of measurement
circuitName = str(j) + ':A' + str(aliceMeasurementChoices[j]) + '_B' + str(bobMeasurementChoices[j] + 2) + '_E' + str(eveMeasurementChoices[j][0]) + str(eveMeasurementChoices[j][1] - 1)
# create the joint measurement circuit
# add Alice's and Bob's measurement circuits to the singlet state curcuit
Q_program.add_circuit(circuitName,
singlet + # singlet state circuit
eveMeasurements[eveMeasurementChoices[j][0]-1] + # Eve's measurement circuit of Alice's qubit
eveMeasurements[eveMeasurementChoices[j][1]-1] + # Eve's measurement circuit of Bob's qubit
aliceMeasurements[aliceMeasurementChoices[j]-1] + # measurement circuit of Alice
bobMeasurements[bobMeasurementChoices[j]-1] # measurement circuit of Bob
)
# add the created circuit to the circuits list
circuits.append(circuitName)
result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240)
print(result)
print(str(circuits[0]) + '\t' + str(result.get_counts(circuits[0])))
ePatterns = [
re.compile('00..$'), # search for the '00..' result (Eve obtained the results -1 and -1 for Alice's and Bob's qubits)
re.compile('01..$'), # search for the '01..' result (Eve obtained the results 1 and -1 for Alice's and Bob's qubits)
re.compile('10..$'),
re.compile('11..$')
]
aliceResults = [] # Alice's results (string a)
bobResults = [] # Bob's results (string a')
# list of Eve's measurement results
# the elements in the 1-st column are the results obtaned from the measurements of Alice's qubits
# the elements in the 2-nd column are the results obtaned from the measurements of Bob's qubits
eveResults = []
# recording the measurement results
for j in range(numberOfSinglets):
res = list(result.get_counts(circuits[j]).keys())[0] # extract a key from the dict and transform it to str
# Alice and Bob
if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(-1) # Bob got the result -1
if abPatterns[1].search(res):
aliceResults.append(1)
bobResults.append(-1)
if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(1) # Bob got the result 1
if abPatterns[3].search(res):
aliceResults.append(1)
bobResults.append(1)
# Eve
if ePatterns[0].search(res): # check if the key is '00..'
eveResults.append([-1, -1]) # results of the measurement of Alice's and Bob's qubits are -1,-1
if ePatterns[1].search(res):
eveResults.append([1, -1])
if ePatterns[2].search(res):
eveResults.append([-1, 1])
if ePatterns[3].search(res):
eveResults.append([1, 1])
aliceKey = [] # Alice's key string a
bobKey = [] # Bob's key string a'
eveKeys = [] # Eve's keys; the 1-st column is the key of Alice, and the 2-nd is the key of Bob
# comparing the strings with measurement choices (b and b')
for j in range(numberOfSinglets):
# if Alice and Bob measured the spin projections onto the a_2/b_1 or a_3/b_2 directions
if (aliceMeasurementChoices[j] == 2 and bobMeasurementChoices[j] == 1) or (aliceMeasurementChoices[j] == 3 and bobMeasurementChoices[j] == 2):
aliceKey.append(aliceResults[j]) # record the i-th result obtained by Alice as the bit of the secret key k
bobKey.append(-bobResults[j]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k'
eveKeys.append([eveResults[j][0], -eveResults[j][1]]) # record the i-th bits of the keys of Eve
keyLength = len(aliceKey) # length of the secret skey
abKeyMismatches = 0 # number of mismatching bits in the keys of Alice and Bob
eaKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Alice
ebKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Bob
for j in range(keyLength):
if aliceKey[j] != bobKey[j]:
abKeyMismatches += 1
if eveKeys[j][0] != aliceKey[j]:
eaKeyMismatches += 1
if eveKeys[j][1] != bobKey[j]:
ebKeyMismatches += 1
eaKnowledge = (keyLength - eaKeyMismatches)/keyLength # Eve's knowledge of Bob's key
ebKnowledge = (keyLength - ebKeyMismatches)/keyLength # Eve's knowledge of Alice's key
corr = chsh_corr(result)
# CHSH inequality test
print('CHSH correlation value: ' + str(round(corr, 3)) + '\n')
# Keys
print('Length of the key: ' + str(keyLength))
print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n')
print('Eve\'s knowledge of Alice\'s key: ' + str(round(eaKnowledge * 100, 2)) + ' %')
print('Eve\'s knowledge of Bob\'s key: ' + str(round(ebKnowledge * 100, 2)) + ' %')
|
https://github.com/minminjao/qiskit1
|
minminjao
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
circ=QuantumCircuit(2)
circ.h(0)
circ.cx(0,1)
meas=QuantumCircuit(2,2)
meas.barrier(range(2))
circ.add_register(meas.cregs[0])
qc=circ.compose(meas)
circ.draw('mpl')
meas.measure(range(2),range(2))
circ.draw('mpl')
job=backend.run(circ)
|
https://github.com/mett29/Shor-s-Algorithm
|
mett29
|
from qiskit import QuantumCircuit, Aer, execute, IBMQ
from qiskit.utils import QuantumInstance
import numpy as np
from qiskit.algorithms import Shor
IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here
provider = IBMQ.get_provider(hub='ibm-q')
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1000)
my_shor = Shor(quantum_instance)
result_dict = my_shor.factor(15)
print(result_dict)
|
https://github.com/yaelbh/qiskit-projectq-provider
|
yaelbh
|
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Example use of the ProjectQ based simulators
"""
import os
from qiskit_addon_projectq import ProjectQProvider
from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister
def use_projectq_backends():
ProjectQ = ProjectQProvider()
qasm_sim = ProjectQ.get_backend('projectq_qasm_simulator')
sv_sim = ProjectQ.get_backend('projectq_statevector_simulator')
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(2, 'cr')
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
# ProjectQ statevector simulator
result = execute(qc, backend=sv_sim).result()
print("final quantum amplitude vector: ")
print(result.get_statevector(qc))
qc.measure(qr, cr)
# ProjectQ simulator
result = execute(qc, backend=qasm_sim, shots=100).result()
print("counts: ")
print(result.get_counts(qc))
if __name__ == "__main__":
use_projectq_backends()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
#!/usr/bin/env python3
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021
#
# 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.
"""Utility to check that slow imports are not used in the default path."""
import subprocess
import sys
# This is not unused: importing it sets up sys.modules
import qiskit # pylint: disable=unused-import
def _main():
optional_imports = [
"networkx",
"sympy",
"pydot",
"pygments",
"ipywidgets",
"scipy.stats",
"matplotlib",
"qiskit.providers.aer",
"qiskit.providers.ibmq",
"qiskit.ignis",
"qiskit.aqua",
"docplex",
]
modules_imported = []
for mod in optional_imports:
if mod in sys.modules:
modules_imported.append(mod)
if not modules_imported:
sys.exit(0)
res = subprocess.run(
[sys.executable, "-X", "importtime", "-c", "import qiskit"],
capture_output=True,
encoding="utf8",
check=True,
)
import_tree = [
x.split("|")[-1]
for x in res.stderr.split("\n")
if "RuntimeWarning" not in x or "warnings.warn" not in x
]
indent = -1
matched_module = None
for module in import_tree:
line_indent = len(module) - len(module.lstrip())
module_name = module.strip()
if module_name in modules_imported:
if indent > 0:
continue
indent = line_indent
matched_module = module_name
if indent > 0:
if line_indent < indent:
print(f"ERROR: {matched_module} is imported via {module_name}")
indent = -1
matched_module = None
sys.exit(len(modules_imported))
if __name__ == "__main__":
_main()
|
https://github.com/hugoecarl/TSP-Problem-Study
|
hugoecarl
|
with open('in-exemplo.txt', 'r') as f:
print(f.read())
with open('out-exemplo.txt', 'r') as f:
print(f.read())
import time
import matplotlib.pyplot as plt
import pandas as pd
import os
import subprocess
%matplotlib inline
#Roda entradas
def roda_com_entrada(executavel, arquivo_in, envs = '1', deb = '0'):
with open(arquivo_in) as f:
start = time.perf_counter()
a = f.read()
proc = subprocess.run([executavel], input=a, text=True, capture_output=True, env=dict(OMP_NUM_THREADS=envs, DEBUG=deb, **os.environ))
end = time.perf_counter()
f.close()
ret = ''
for i in a:
if i == "\n":
break
ret += i
return (proc.stdout, end - start, int(ret))
#retorna tamanho do tour apartir do stdout
def tamanho_tour(out):
buf = ''
for i in out:
if i == " ":
return float(buf)
buf += i
#Cria resultados
tamanho_entradas = []
tempos = []
tempos_1 = []
tempos_2 = []
resultados1 = []
resultados2 = []
resultados3 = []
#Usando as mesmas entradas
for i in range(8):
print("Rodando entrada: "+str(i))
a = roda_com_entrada('./busca_local_antigo','busca-exaustiva/in-'+str(i)+'.txt')
b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt')
c = roda_com_entrada('./heuristico/heuristico','busca-exaustiva/in-'+str(i)+'.txt')
tempos.append(a[1])
tempos_1.append(b[1])
tempos_2.append(c[1])
tamanho_entradas.append(a[2])
resultados1.append(tamanho_tour(a[0]))
resultados2.append(tamanho_tour(b[0]))
resultados3.append(tamanho_tour(c[0]))
#Teste com entrada um pouco maior
print("Rodando entrada: 8")
tempos.append(roda_com_entrada('./busca_local_antigo','maior.txt')[1])
tempos_1.append(roda_com_entrada('./busca-exaustiva/busca-exaustiva','maior.txt')[1])
tempos_2.append(roda_com_entrada('./heuristico/heuristico','maior.txt')[1])
tamanho_entradas.append(roda_com_entrada('./busca-local/busca-local','maior.txt')[2])
resultados1.append(tamanho_tour(roda_com_entrada('./busca_local_antigo','maior.txt')[0]))
resultados2.append(tamanho_tour(roda_com_entrada('./busca-exaustiva/busca-exaustiva','maior.txt')[0]))
resultados3.append(tamanho_tour(roda_com_entrada('./heuristico/heuristico','maior.txt')[0]))
plt.title("Comparacao Desempenho")
plt.ylabel("Tempo (s)")
plt.xlabel("Tamanho entradas")
plt.plot(tamanho_entradas, tempos_1)
plt.plot(tamanho_entradas, tempos)
plt.plot(tamanho_entradas, tempos_2)
plt.legend(["busca-exaustiva", "busca-local","heuristico"])
plt.show()
plt.title("Comparacao Desempenho")
plt.ylabel("Tempo (s)")
plt.xlabel("Tamanho entradas")
plt.plot(tamanho_entradas, tempos)
plt.plot(tamanho_entradas, tempos_2)
plt.legend(["busca-local","heuristico"])
plt.show()
df = pd.DataFrame()
df["Tamanho Entrada"] = pd.Series(tamanho_entradas)
df["busca-local-tempo"] = pd.Series(tempos)
df["busca-exaustiva-tempo"] = pd.Series(tempos_1)
df["heuristica-tempo"] = pd.Series(tempos_2)
df["busca-local-resultado"] = pd.Series(resultados1)
df["busca-exaustiva-resultado"] = pd.Series(resultados2)
df["heuristica-resultado"] = pd.Series(resultados3)
df
df.describe()
#Cria resultados
tamanho_entradas = []
tempos = []
tempos_1 = []
tempos_2 = []
tempos_3 = []
tempos_4 = []
tempos_5 = []
#Usando as mesmas entradas
for i in range(7):
print("Rodando entrada: "+str(i))
a = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt')
b = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','2')
c = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','3')
d = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','4')
e = roda_com_entrada('./busca_local_antigo','busca-local/in-'+str(i)+'.txt')
f = roda_com_entrada('./busca-local/busca-local-gpu','busca-local/in-'+str(i)+'.txt')
tempos.append(a[1])
tempos_1.append(b[1])
tempos_2.append(c[1])
tempos_3.append(d[1])
tempos_4.append(e[1])
tempos_5.append(f[1])
tamanho_entradas.append(a[2])
plt.title("Comparacao Desempenho Busca Local")
plt.ylabel("Tempo (s)")
plt.xlabel("Tamanho entradas")
plt.plot(tamanho_entradas, tempos)
plt.plot(tamanho_entradas, tempos_1)
plt.plot(tamanho_entradas, tempos_2)
plt.plot(tamanho_entradas, tempos_3)
plt.legend(["1 thread otimizado", "2 threads otimizado","3 threads otimizado", "4 threads otimizado", "Sem otimizações"])
plt.show()
plt.title("Comparacao Desempenho Busca Local")
plt.ylabel("Tempo (s)")
plt.xlabel("Tamanho entradas")
plt.plot(tamanho_entradas, tempos_3)
plt.plot(tamanho_entradas, tempos_5)
plt.legend(["4 thread otimizado", "GPU"])
plt.show()
plt.title("Comparacao Desempenho Busca Local")
plt.ylabel("Tempo (s)")
plt.xlabel("Tamanho entradas")
plt.plot(tamanho_entradas, tempos)
plt.plot(tamanho_entradas, tempos_4)
plt.legend(["1 thread otimizado", "Sem otimizações"])
plt.show()
df = pd.DataFrame()
df["Tamanho Entrada"] = pd.Series(tamanho_entradas)
df["busca-local-1-thread"] = pd.Series(tempos)
df["busca-local-2-threads"] = pd.Series(tempos_1)
df["busca-local-3-threads"] = pd.Series(tempos_2)
df["busca-local-4-threads"] = pd.Series(tempos_3)
df["busca-local-gpu"] = pd.Series(tempos_5)
df["busca-local-semopt"] = pd.Series(tempos_4)
df
#Cria resultados
tamanho_entradas = []
tempos = []
tempos_1 = []
#Usando as mesmas entradas
for i in range(7):
print("Rodando entrada: "+str(i))
a = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '1', '1')
b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '1', '0')
tempos.append(a[1])
tempos_1.append(b[1])
tamanho_entradas.append(a[2])
plt.title("Comparacao Desempenho Busca Exaustiva")
plt.ylabel("Tempo (s)")
plt.xlabel("Tamanho entradas")
plt.plot(tamanho_entradas, tempos)
plt.plot(tamanho_entradas, tempos_1)
plt.legend(["Exaustivo Simples", "Exaustivo Branch and Bound"])
plt.show()
df = pd.DataFrame()
df["Tamanho Entrada"] = pd.Series(tamanho_entradas)
df["busca-exaustiva-simples"] = pd.Series(tempos)
df["busca-exaustiva-branchnbound"] = pd.Series(tempos_1)
df
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import *
from qiskit.quantum_info import Statevector
from math import pi
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.ccx(0,1,2)
qc.ry(pi,0)
qc.ch(1,2)
qc.tdg(2)
qc.cx(1,0)
qc.measure_all()
qc.draw(output="mpl")
qc.size()
qc.width()
qc.depth()
qc.num_qubits
qc.count_ops()
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.ccx(0,1,2)
qc.ry(pi,0)
qc.ch(1,2)
qc.tdg(2)
qc.cx(1,0)
qc.measure_all()
qc.draw(output="mpl")
qc.size()
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.ccx(0,1,2)
qc.ry(pi,0)
qc.ch(1,2)
qc.tdg(2)
qc.cx(1,0)
qc.measure_all()
qc.draw(output="mpl")
qc.width()
qc.qregs
qc.qubits
qc.num_qubits
qc.cregs
qc.clbits
qc.num_clbits
qc=QuantumCircuit(1)
qc.h(0)
qc.draw(output="mpl")
qc.depth()
qc=QuantumCircuit(1)
qc.h(0)
qc.y(0)
qc.draw(output="mpl")
qc.depth()
#Let's apply a barrier gate with no arguments
qc=QuantumCircuit(1)
qc.h(0)
qc.h(0)
qc.y(0)
qc.draw(output="mpl")
qc.depth()
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.draw(output="mpl")
qc.depth()
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.ccx(0,1,2)
qc.draw(output="mpl")
qc.depth()
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.ccx(0,1,2)
qc.ry(pi,0)
qc.ch(1,2)
qc.draw(output="mpl")
qc.depth()
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.ccx(0,1,2)
qc.ry(pi,0)
qc.ch(1,2)
qc.tdg(2)
qc.draw(output="mpl")
qc.depth()
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.ccx(0,1,2)
qc.ry(pi,0)
qc.ch(1,2)
qc.tdg(2)
qc.cx(1,0)
qc.draw(output="mpl")
qc.depth()
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.barrier()
qc.ccx(0,1,2)
qc.barrier()
qc.ry(pi,0)
qc.ch(1,2)
qc.barrier()
qc.tdg(2)
qc.cx(1,0)
qc.draw(output="mpl")
qc.depth()
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.barrier()
qc.ccx(0,1,2)
qc.barrier()
qc.ry(pi,0)
qc.ch(1,2)
qc.barrier()
qc.tdg(2)
qc.barrier()
qc.cx(1,0)
qc.draw(output="mpl")
qc.depth()
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.barrier()
qc.ccx(0,1,2)
qc.barrier()
qc.ry(pi,0)
qc.ch(1,2)
qc.barrier()
qc.tdg(2)
qc.cx(1,0)
qc.measure_all()
qc.draw(output="mpl")
qc.depth()
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.barrier()
qc.ccx(0,1,2)
qc.barrier()
qc.ry(pi,0)
qc.ch(1,2)
qc.barrier()
qc.tdg(2)
qc.cx(1,0)
qc.measure_all()
qc.draw(output="mpl")
qc.qubits
qc.num_qubits
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.barrier()
qc.ccx(0,1,2)
qc.barrier()
qc.ry(pi,0)
qc.ch(1,2)
qc.barrier()
qc.tdg(2)
qc.cx(1,0)
qc.measure_all()
qc.draw(output="mpl")
qc.count_ops()
|
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__
|
https://github.com/mlvqc/Byskit
|
mlvqc
|
from qiskit import IBMQ
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = IBMQ.get_provider(hub='ibm-q-oxford', group='on-boarding', project='on-boarding-proj')
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
%matplotlib inline
from byskit import byskit,gen_random_weights
n_parent = 3
n_child = 3
parents,children = gen_random_weights(n_parent,n_child)
b = byskit(backend,parents,children)
b.circ.draw(output='mpl')
results = b.execute_circ()
plot_histogram(results.get_counts(b.circ))
n_parent = 2
n_child = 4
parents,children = gen_random_weights(n_parent,n_child)
b = byskit(backend,parents,children)
b.circ.draw(output='mpl')
results = b.execute_circ()
plot_histogram(results.get_counts(b.circ))
|
https://github.com/GabrielPontolillo/QiskitPBT
|
GabrielPontolillo
|
import random
import numpy as np
from qiskit import QuantumCircuit
from QiskitPBT.case_studies.grovers_algorithm.grovers_algorithm import grovers_algorithm
from QiskitPBT.case_studies.grovers_algorithm.grovers_algorithm_helpers import RandomGroversOracleMarkedStatesPairGenerator
from QiskitPBT.property import Property
class GroversAlgorithmLowerRegisterMinus(Property):
# specify the inputs that are to be generated
def get_input_generators(self):
return [RandomGroversOracleMarkedStatesPairGenerator(4, 6)]
# specify the preconditions for the test
def preconditions(self, oracle_pair):
oracle, marked_states = oracle_pair
if len(marked_states) == 0 or len(marked_states) > 2**(oracle.num_qubits - 1) - 1:
return False
return True
# specify the operations to be performed on the input
def operations(self, oracle_pair):
oracle, marked_states = oracle_pair
# one qubit is workspace
N = 2**(oracle.num_qubits-1)
# number of marked states is used to identify the number of grover iterations to apply
M = len(marked_states)
# src Nielsen and Chuang, quantum computation and quantum information
n_iterations = int(np.floor((np.pi/4) * np.sqrt((N/M))))
circ = grovers_algorithm(oracle, n_iterations)
# should be -
baseline = QuantumCircuit(1, 1)
baseline.x(0)
baseline.h(0)
self.statistical_analysis.assert_equal(self, [circ.num_qubits - 1], circ, [0], baseline)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.sdg(0)
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.cx(0,1)
qc.x(0)
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
#
#
# FILL YOUR CODE IN HERE
#
#
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.y(1)
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
oraclenr = 4 # determines the oracle (can range from 1 to 5)
oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles
oracle.name = "DJ-Oracle"
def dj_classical(n, input_str):
# build a quantum circuit with n qubits and 1 classical readout bit
dj_circuit = QuantumCircuit(n+1,1)
# Prepare the initial state corresponding to your input bit string
for i in range(n):
if input_str[i] == '1':
dj_circuit.x(i)
# append oracle
dj_circuit.append(oracle, range(n+1))
# measure the fourth qubit
dj_circuit.measure(n,0)
return dj_circuit
n = 4 # number of qubits
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
dj_circuit.draw() # draw the circuit
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit, qasm_sim)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def lab1_ex7():
min_nr_inputs = 2
max_nr_inputs = 9
return [min_nr_inputs, max_nr_inputs]
from qc_grader import grade_lab1_ex7
# Note that the grading function is expecting a list of two integers
grade_lab1_ex7(lab1_ex7())
n=4
def psi_0(n):
qc = QuantumCircuit(n+1,n)
# Build the state (|00000> - |10000>)/sqrt(2)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(4)
qc.h(4)
return qc
dj_circuit = psi_0(n)
dj_circuit.draw()
def psi_1(n):
# obtain the |psi_0> = |00001> state
qc = psi_0(n)
# create the superposition state |psi_1>
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
#
#
qc.barrier()
return qc
dj_circuit = psi_1(n)
dj_circuit.draw()
def psi_2(oracle,n):
# circuit to obtain psi_1
qc = psi_1(n)
# append the oracle
qc.append(oracle, range(n+1))
return qc
dj_circuit = psi_2(oracle, n)
dj_circuit.draw()
def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25])
qc = psi_2(oracle, n)
# apply n-fold hadamard gate
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
# add the measurement by connecting qubits to classical bits
#
#
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
#
#
return qc
dj_circuit = lab1_ex8(oracle, n)
dj_circuit.draw()
from qc_grader import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit with measurements
grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n))
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/abhik-99/Qiskit-Summer-School
|
abhik-99
|
# import SymPy and define symbols
import sympy as sp
sp.init_printing(use_unicode=True)
wr = sp.Symbol('\omega_r') # resonator frequency
wq = sp.Symbol('\omega_q') # qubit frequency
g = sp.Symbol('g', real=True) # vacuum Rabi coupling
Delta = sp.Symbol('Delta', real=True) # wr - wq; defined later
# import operator relations and define them
from sympy.physics.quantum.boson import BosonOp
a = BosonOp('a') # resonator photon annihilation operator
from sympy.physics.quantum import pauli, Dagger, Commutator
from sympy.physics.quantum.operatorordering import normal_ordered_form
# Pauli matrices
sx = pauli.SigmaX()
sy = pauli.SigmaY()
sz = pauli.SigmaZ()
# qubit raising and lowering operators
splus = pauli.SigmaPlus()
sminus = pauli.SigmaMinus()
# define J-C Hamiltonian in terms of diagonal and non-block diagonal terms
H0 = wr*Dagger(a)*a - (1/2)*wq*sz;
H1 = 0
H2 = g*(Dagger(a)*sminus + a*splus);
HJC = H0 + H1 + H2; HJC # print
# using the above method for finding the ansatz
eta = Commutator(H0, H2); eta
pauli.qsimplify_pauli(normal_ordered_form(eta.doit().expand()))
A = sp.Symbol('A')
B = sp.Symbol('B')
eta = A * Dagger(a) * sminus - B * a * splus;
pauli.qsimplify_pauli(normal_ordered_form(Commutator(H0, eta).doit().expand()))
H2
S1 = eta.subs(A, g/Delta)
S1 = S1.subs(B, g/Delta); S1.factor()
Heff = H0 + H1 + 0.5*pauli.qsimplify_pauli(normal_ordered_form(Commutator(H2, S1).doit().expand())).simplify(); Heff
from qiskit.tools.jupyter import *
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibmq_armonk')
backend_config = backend.configuration()
assert backend_config.open_pulse, "Backend doesn't support Pulse"
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
backend_defaults = backend.defaults()
import numpy as np
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
kHz = 1.0e3
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
# We will find the qubit frequency for the following qubit.
qubit = 0
# The sweep will be centered around the estimated qubit frequency.
center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz
# warning: this will change in a future release
print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.")
# scale factor to remove factors of 10 from the data
scale_factor = 1e-14
# We will sweep 40 MHz around the estimated frequency
frequency_span_Hz = 40 * MHz
# in steps of 1 MHz.
frequency_step_Hz = 1 * MHz
# We will sweep 20 MHz above and 20 MHz below the estimated frequency
frequency_min = center_frequency_Hz - frequency_span_Hz / 2
frequency_max = center_frequency_Hz + frequency_span_Hz / 2
# Construct an np array of the frequencies for our experiment
frequencies_GHz = np.arange(frequency_min / GHz,
frequency_max / GHz,
frequency_step_Hz / GHz)
print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz \
in steps of {frequency_step_Hz / MHz} MHz.")
from qiskit import pulse # This is where we access all of our Pulse features!
inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure', qubits=[qubit])
x_pulse = inst_sched_map.get('x', qubits=[qubit])
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Create the base schedule
# Start with drive pulse acting on the drive channel
schedule = pulse.Schedule(name='Frequency sweep')
schedule += x_pulse
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
schedule += measure << schedule.duration
# Create the frequency settings for the sweep (MUST BE IN HZ)
frequencies_Hz = frequencies_GHz*GHz
schedule_frequencies = [{drive_chan: freq} for freq in frequencies_Hz]
schedule.draw(label=True, scaling=0.8)
from qiskit import assemble
frequency_sweep_program = assemble(schedule,
backend=backend,
meas_level=1,
meas_return='avg',
shots=1024,
schedule_los=schedule_frequencies)
# RUN the job on a real device
job = backend.run(frequency_sweep_program)
print(job.job_id())
from qiskit.tools.monitor import job_monitor
job_monitor(job)
# OR retreive result from previous run
# job = backend.retrieve_job('5ef3b081fbc24b001275b03b')
frequency_sweep_results = job.result()
import matplotlib.pyplot as plt
plt.style.use('dark_background')
sweep_values = []
for i in range(len(frequency_sweep_results.results)):
# Get the results from the ith experiment
res = frequency_sweep_results.get_memory(i)*scale_factor
# Get the results for `qubit` from this experiment
sweep_values.append(res[qubit])
plt.scatter(frequencies_GHz, np.real(sweep_values), color='white') # plot real part of sweep values
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured signal [a.u.]")
plt.show()
from scipy.optimize import curve_fit
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
fit_params, y_fit = fit_function(frequencies_GHz,
np.real(sweep_values),
lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C,
[5, 4.975, 1, 3] # initial parameters for curve_fit
)
plt.scatter(frequencies_GHz, np.real(sweep_values), color='white')
plt.plot(frequencies_GHz, y_fit, color='red')
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
# Create the schedules for 0 and 1
schedule_0 = pulse.Schedule(name='0')
schedule_0 += measure
schedule_1 = pulse.Schedule(name='1')
schedule_1 += x_pulse
schedule_1 += measure << schedule_1.duration
schedule_0.draw()
schedule_1.draw()
frequency_span_Hz = 320 * kHz
frequency_step_Hz = 8 * kHz
center_frequency_Hz = backend_defaults.meas_freq_est[qubit]
print(f"Qubit {qubit} has an estimated readout frequency of {center_frequency_Hz / GHz} GHz.")
frequency_min = center_frequency_Hz - frequency_span_Hz / 2
frequency_max = center_frequency_Hz + frequency_span_Hz / 2
frequencies_GHz = np.arange(frequency_min / GHz,
frequency_max / GHz,
frequency_step_Hz / GHz)
print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz\
in steps of {frequency_step_Hz / MHz} MHz.")
num_shots_per_frequency = 2048
frequencies_Hz = frequencies_GHz*GHz
schedule_los = [{meas_chan: freq} for freq in frequencies_Hz]
cavity_sweep_0 = assemble(schedule_0,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_frequency,
schedule_los=schedule_los)
cavity_sweep_1 = assemble(schedule_1,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_frequency,
schedule_los=schedule_los)
# RUN the job on a real device
#job_0 = backend.run(cavity_sweep_0)
#job_monitor(job_0)
#job_0.error_message()
#job_1 = backend.run(cavity_sweep_1)
#job_monitor(job_1)
#job_1.error_message()
# OR retreive result from previous run
job_0 = backend.retrieve_job('5efa5b447c0d6800137fff1c')
job_1 = backend.retrieve_job('5efa6b2720eee10013be46b4')
cavity_sweep_0_results = job_0.result()
cavity_sweep_1_results = job_1.result()
scale_factor = 1e-14
sweep_values_0 = []
for i in range(len(cavity_sweep_0_results.results)):
res_0 = cavity_sweep_0_results.get_memory(i)*scale_factor
sweep_values_0.append(res_0[qubit])
sweep_values_1 = []
for i in range(len(cavity_sweep_1_results.results)):
res_1 = cavity_sweep_1_results.get_memory(i)*scale_factor
sweep_values_1.append(res_1[qubit])
plotx = frequencies_Hz/kHz
ploty_0 = np.abs(sweep_values_0)
ploty_1 = np.abs(sweep_values_1)
plt.plot(plotx, ploty_0, color='blue', marker='.') # plot real part of sweep values
plt.plot(plotx, ploty_1, color='red', marker='.') # plot real part of sweep values
plt.legend([r'$\vert0\rangle$', r'$\vert1\rangle$'])
plt.grid()
plt.xlabel("Frequency [kHz]")
plt.ylabel("Measured signal [a.u.]")
plt.yscale('log')
plt.show()
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The shadow is constructed based on derandomized Hamiltonian.
The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g).
The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer.primitives import Estimator as AerEstimator
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
'''
DEFINING DRIVERS FOR THE MOLECULES
'''
H2_driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
LiH_driver = PySCFDriver(
atom="Li 0 0 0; H 0 0 1.599",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
BeH2_driver = PySCFDriver(
atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
H2O_driver = PySCFDriver(
atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
NH3_driver = PySCFDriver(
atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
'''
FORMATTING HAMILTONIAN
'''
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
'''
COST FUNCTION AND HELPER FUNCTIONS
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
EXPERIMENTS
'''
start_time = time.time()
all_molecules_rmse_errors = []
# CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN
MOLECULES = ['LiH']
for molecule in MOLECULES:
rmse_errors = []
if molecule == 'H2':
problem = H2_driver.run()
if molecule == 'LiH':
problem = LiH_driver.run()
if molecule == 'BeH2':
problem = BeH2_driver.run()
if molecule == 'H2O':
problem = H2O_driver.run()
if molecule == 'NH3':
problem = NH3_driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper() #(num_particles=problem.num_particles) #BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
#print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian)
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
'''
VARIATIONAL ANSATZ
'''
ansatz = UCCSD(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
initial_state=HartreeFock(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
),
)
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
#estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
#estimator.set_options(shots = None)
#estimator = AerEstimator()
#estimator.set_options(approximation=False, shots=None)
#vqe_solver = VQE(estimator, ansatz, SLSQP())
vqe_solver = VQE(Estimator(), ansatz, SLSQP())
vqe_solver.initial_point = np.zeros(ansatz.num_parameters)
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
#print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
derandomized_hamiltonian = derandomized_classical_shadow(observables_xyz, 50,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
print('Original derandomized Hamiltonian', counts)
# derandomized classical shadow will usually either undergenerate or overgenerate derandomized operators
# adjusting for this issue:
while sum(counts.values()) != num_operators:
for key, value in zip(counts.keys(), counts.values()):
sum_counts = sum(counts.values())
if sum_counts == num_operators:
break
if sum_counts < num_operators:
# generate additional operators from the existing ones by increasing the number of counts
counts[key] += 1
if sum_counts > num_operators:
# remove the element with highest count
max_element_key = [k for k, v in counts.items() if v == max(counts.values())][0]
counts[max_element_key] -= 1
print('Size-adjusted derandomized Hamiltonian', counts)
# translate the Counter to a set of derandomized operators
new_derandomized_hamiltonian = []
for key, value in counts.items():
for _ in range(value):
new_derandomized_hamiltonian.append(list(key))
#print('Size-adjusted derandomized Hamiltonian', new_derandomized_hamiltonian)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(new_derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
all_molecules_rmse_errors.append(rmse_errors)
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
import matplotlib.pyplot as plt
points = measurement_range
num_points = len(points)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='derandomized classical shadow')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Qiskit utility functions."""
from functools import partial
from typing import Optional, Tuple
import numpy as np
import numpy.typing as npt
import qiskit
from qiskit import QuantumCircuit
from qiskit.providers import Backend
from qiskit_aer import AerSimulator
# Noise simulation packages
from qiskit_aer.noise import NoiseModel
from qiskit_aer.noise.errors.standard_errors import depolarizing_error
from mitiq import Executor, MeasurementResult, Observable
def initialized_depolarizing_noise(noise_level: float) -> NoiseModel:
"""Initializes a depolarizing noise Qiskit NoiseModel.
Args:
noise_level: The noise strength as a float, e.g., 0.01 is 1%.
Returns:
A Qiskit depolarizing NoiseModel.
"""
# initialize a qiskit noise model
noise_model = NoiseModel()
# we assume the same depolarizing error for each
# gate of the standard IBM basis
noise_model.add_all_qubit_quantum_error(
depolarizing_error(noise_level, 1), ["u1", "u2", "u3"]
)
noise_model.add_all_qubit_quantum_error(
depolarizing_error(noise_level, 2), ["cx"]
)
return noise_model
def execute(circuit: QuantumCircuit, obs: npt.NDArray[np.complex64]) -> float:
"""Simulates a noiseless evolution and returns the
expectation value of some observable.
Args:
circuit: The input Qiskit circuit.
obs: The observable to measure as a NumPy array.
Returns:
The expectation value of obs as a float.
"""
return execute_with_noise(circuit, obs, noise_model=None)
def execute_with_shots(
circuit: QuantumCircuit, obs: npt.NDArray[np.complex64], shots: int
) -> float:
"""Simulates the evolution of the circuit and returns
the expectation value of the observable.
Args:
circuit: The input Qiskit circuit.
obs: The observable to measure as a NumPy array.
shots: The number of measurements.
Returns:
The expectation value of obs as a float.
"""
return execute_with_shots_and_noise(
circuit,
obs,
noise_model=None,
shots=shots,
)
def execute_with_noise(
circuit: QuantumCircuit,
obs: npt.NDArray[np.complex64],
noise_model: NoiseModel,
) -> float:
"""Simulates the evolution of the noisy circuit and returns
the exact expectation value of the observable.
Args:
circuit: The input Qiskit circuit.
obs: The observable to measure as a NumPy array.
noise_model: The input Qiskit noise model.
Returns:
The expectation value of obs as a float.
"""
# Avoid mutating circuit
circ = circuit.copy()
circ.save_density_matrix()
if noise_model is None:
basis_gates = None
else:
basis_gates = noise_model.basis_gates + ["save_density_matrix"]
# execution of the experiment
backend = AerSimulator(method="density_matrix", noise_model=noise_model)
exec_circuit = qiskit.transpile(
circ,
backend=backend,
basis_gates=basis_gates,
# we want all gates to be actually applied,
# so we skip any circuit optimization
optimization_level=0,
)
job = backend.run(exec_circuit, shots=1)
rho = job.result().data()["density_matrix"]
expectation = np.real(np.trace(rho @ obs))
return expectation
def execute_with_shots_and_noise(
circuit: QuantumCircuit,
obs: npt.NDArray[np.complex64],
noise_model: NoiseModel,
shots: int,
seed: Optional[int] = None,
) -> float:
"""Simulates the evolution of the noisy circuit and returns
the statistical estimate of the expectation value of the observable.
Args:
circuit: The input Qiskit circuit.
obs: The observable to measure as a NumPy array.
noise_model: The input Qiskit noise model.
shots: The number of measurements.
seed: Optional seed for qiskit simulator.
Returns:
The expectation value of obs as a float.
"""
# Avoid mutating circuit
circ = circuit.copy()
# we need to modify the circuit to measure obs in its eigenbasis
# we do this by appending a unitary operation
# obtains a U s.t. obs = U diag(eigvals) U^dag
eigvals, U = np.linalg.eigh(obs)
circ.unitary(np.linalg.inv(U), qubits=range(circ.num_qubits))
circ.measure_all()
if noise_model is None:
basis_gates = None
else:
basis_gates = noise_model.basis_gates
# execution of the experiment
backend = AerSimulator(method="density_matrix", noise_model=noise_model)
exec_circuit = qiskit.transpile(
circ,
backend=backend,
basis_gates=basis_gates,
# we want all gates to be actually applied,
# so we skip any circuit optimization
optimization_level=0,
)
job = backend.run(exec_circuit, shots=shots, seed_simulator=seed)
counts = job.result().get_counts()
expectation = 0
for bitstring, count in counts.items():
expectation += (
eigvals[int(bitstring[0 : circ.num_qubits], 2)] * count / shots
)
return expectation
def sample_bitstrings(
circuit: QuantumCircuit,
backend: Optional[Backend] = None,
noise_model: Optional[NoiseModel] = None,
shots: int = 10000,
measure_all: bool = False,
qubit_indices: Optional[Tuple[int]] = None,
) -> MeasurementResult:
"""Returns measurement bitstrings obtained from executing the input circuit
on a Qiskit backend (passed as an argument).
Note that the input circuit must contain measurement gates
(unless ``measure_all`` is ``True``).
Args:
circuit: The input Qiskit circuit.
backend: A real or fake Qiskit backend. The input circuit
should be transpiled into a compatible gate set.
It may be necessary to set ``optimization_level=0`` when
transpiling.
noise_model: A valid Qiskit ``NoiseModel`` object. This option is used
if and only if ``backend`` is ``None``. In this case a default
density matrix simulator is used with ``optimization_level=0``.
shots: The number of measurements.
measure_all: If True, measurement gates are applied to all qubits.
qubit_indices: Optional qubit indices associated to bitstrings.
Returns:
The measured bitstrings casted as a Mitiq :class:`.MeasurementResult`
object.
"""
if measure_all:
circuit = circuit.measure_all(inplace=False)
if backend:
job = backend.run(circuit, shots=shots)
elif noise_model:
backend = AerSimulator(
method="density_matrix", noise_model=noise_model
)
exec_circuit = qiskit.transpile(
circuit,
backend=backend,
basis_gates=noise_model.basis_gates,
# we want all gates to be actually applied,
# so we skip any circuit optimization
optimization_level=0,
)
job = backend.run(exec_circuit, shots=shots)
else:
raise ValueError(
"Either a backend or a noise model must be given as input."
)
counts = job.result().get_counts(circuit)
bitstrings = []
for key, val in counts.items():
bitstring = [int(c) for c in key]
for _ in range(val):
bitstrings.append(bitstring)
return MeasurementResult(
result=bitstrings,
qubit_indices=qubit_indices,
)
def compute_expectation_value_on_noisy_backend(
circuit: QuantumCircuit,
obs: Observable,
backend: Optional[Backend] = None,
noise_model: Optional[NoiseModel] = None,
shots: int = 10000,
measure_all: bool = False,
qubit_indices: Optional[Tuple[int]] = None,
) -> complex:
"""Returns the noisy expectation value of the input Mitiq observable
obtained from executing the input circuit on a Qiskit backend.
Args:
circuit: The input Qiskit circuit.
obs: The Mitiq observable to compute the expectation value of.
backend: A real or fake Qiskit backend. The input circuit
should be transpiled into a compatible gate set.
noise_model: A valid Qiskit ``NoiseModel`` object. This option is used
if and only if ``backend`` is ``None``. In this case a default
density matrix simulator is used with ``optimization_level=0``.
shots: The number of measurements.
measure_all: If True, measurement gates are applied to all qubits.
qubit_indices: Optional qubit indices associated to bitstrings.
Returns:
The noisy expectation value.
"""
execute = partial(
sample_bitstrings,
backend=backend,
noise_model=noise_model,
shots=shots,
measure_all=measure_all,
qubit_indices=qubit_indices,
)
executor = Executor(execute)
return executor.evaluate(circuit, obs)[0]
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# External imports
from pylab import cm
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
# Qiskit imports
from qiskit import QuantumCircuit
from qiskit.circuit import ParameterVector
from qiskit.visualization import circuit_drawer
from qiskit.algorithms.optimizers import SPSA
from qiskit.circuit.library import ZZFeatureMap
from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel
from qiskit_machine_learning.kernels.algorithms import QuantumKernelTrainer
from qiskit_machine_learning.algorithms import QSVC
from qiskit_machine_learning.datasets import ad_hoc_data
class QKTCallback:
"""Callback wrapper class."""
def __init__(self) -> None:
self._data = [[] for i in range(5)]
def callback(self, x0, x1=None, x2=None, x3=None, x4=None):
"""
Args:
x0: number of function evaluations
x1: the parameters
x2: the function value
x3: the stepsize
x4: whether the step was accepted
"""
self._data[0].append(x0)
self._data[1].append(x1)
self._data[2].append(x2)
self._data[3].append(x3)
self._data[4].append(x4)
def get_callback_data(self):
return self._data
def clear_callback_data(self):
self._data = [[] for i in range(5)]
adhoc_dimension = 2
X_train, y_train, X_test, y_test, 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,
)
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],
)
plt.scatter(
X_train[np.where(y_train[:] == 0), 0],
X_train[np.where(y_train[:] == 0), 1],
marker="s",
facecolors="w",
edgecolors="b",
label="A train",
)
plt.scatter(
X_train[np.where(y_train[:] == 1), 0],
X_train[np.where(y_train[:] == 1), 1],
marker="o",
facecolors="w",
edgecolors="r",
label="B train",
)
plt.scatter(
X_test[np.where(y_test[:] == 0), 0],
X_test[np.where(y_test[:] == 0), 1],
marker="s",
facecolors="b",
edgecolors="w",
label="A test",
)
plt.scatter(
X_test[np.where(y_test[:] == 1), 0],
X_test[np.where(y_test[:] == 1), 1],
marker="o",
facecolors="r",
edgecolors="w",
label="B test",
)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for classification")
plt.show()
# Create a rotational layer to train. We will rotate each qubit the same amount.
training_params = ParameterVector("θ", 1)
fm0 = QuantumCircuit(2)
fm0.ry(training_params[0], 0)
fm0.ry(training_params[0], 1)
# Use ZZFeatureMap to represent input data
fm1 = ZZFeatureMap(2)
# Create the feature map, composed of our two circuits
fm = fm0.compose(fm1)
print(circuit_drawer(fm))
print(f"Trainable parameters: {training_params}")
# Instantiate quantum kernel
quant_kernel = TrainableFidelityQuantumKernel(feature_map=fm, training_parameters=training_params)
# Set up the optimizer
cb_qkt = QKTCallback()
spsa_opt = SPSA(maxiter=10, callback=cb_qkt.callback, learning_rate=0.05, perturbation=0.05)
# Instantiate a quantum kernel trainer.
qkt = QuantumKernelTrainer(
quantum_kernel=quant_kernel, loss="svc_loss", optimizer=spsa_opt, initial_point=[np.pi / 2]
)
# Train the kernel using QKT directly
qka_results = qkt.fit(X_train, y_train)
optimized_kernel = qka_results.quantum_kernel
print(qka_results)
# Use QSVC for classification
qsvc = QSVC(quantum_kernel=optimized_kernel)
# Fit the QSVC
qsvc.fit(X_train, y_train)
# Predict the labels
labels_test = qsvc.predict(X_test)
# Evalaute the test accuracy
accuracy_test = metrics.balanced_accuracy_score(y_true=y_test, y_pred=labels_test)
print(f"accuracy test: {accuracy_test}")
plot_data = cb_qkt.get_callback_data() # callback data
K = optimized_kernel.evaluate(X_train) # kernel matrix evaluated on the training samples
plt.rcParams["font.size"] = 20
fig, ax = plt.subplots(1, 2, figsize=(14, 5))
ax[0].plot([i + 1 for i in range(len(plot_data[0]))], np.array(plot_data[2]), c="k", marker="o")
ax[0].set_xlabel("Iterations")
ax[0].set_ylabel("Loss")
ax[1].imshow(K, cmap=cm.get_cmap("bwr", 20))
fig.tight_layout()
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import numpy as np
n_samples = 100
p_1 = 0.2
x_data = np.random.binomial(1, p_1, (n_samples,))
print(x_data)
frequency_of_zeros, frequency_of_ones = 0, 0
for x in x_data:
if x:
frequency_of_ones += 1/n_samples
else:
frequency_of_zeros += 1/n_samples
print(frequency_of_ones+frequency_of_zeros)
import matplotlib.pyplot as plt
%matplotlib inline
p_0 = np.linspace(0, 1, 100)
p_1 = 1-p_0
fig, ax = plt.subplots()
ax.set_xlim(-1.2, 1.2)
ax.set_ylim(-1.2, 1.2)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.set_xlabel("$p_0$")
ax.xaxis.set_label_coords(1.0, 0.5)
ax.set_ylabel("$p_1$")
ax.yaxis.set_label_coords(0.5, 1.0)
plt.plot(p_0, p_1)
p = np.array([[0.8], [0.2]])
np.linalg.norm(p, ord=1)
Π_0 = np.array([[1, 0], [0, 0]])
np.linalg.norm(Π_0 @ p, ord=1)
Π_1 = np.array([[0, 0], [0, 1]])
np.linalg.norm(Π_1 @ p, ord=1)
p = np.array([[.5], [.5]])
M = np.array([[0.7, 0.6], [0.3, 0.4]])
np.linalg.norm(M @ p, ord=1)
ϵ = 10e-10
p_0 = np.linspace(ϵ, 1-ϵ, 100)
p_1 = 1-p_0
H = -(p_0*np.log2(p_0) + p_1*np.log2(p_1))
fig, ax = plt.subplots()
ax.set_xlim(0, 1)
ax.set_ylim(0, -np.log2(0.5))
ax.set_xlabel("$p_0$")
ax.set_ylabel("$H$")
plt.plot(p_0, H)
plt.axvline(x=0.5, color='k', linestyle='--')
# %pip install qiskit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit_aer import AerSimulator
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit.primitives import BackendEstimator, BackendSampler
import numpy as np
π = np.pi
backend = AerSimulator(method='statevector')
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
circuit.measure(q, c)
circuit.draw(output='mpl')
sampler = BackendSampler(backend=backend)
result = sampler.run(circuit).result()
print(result.quasi_dists[0])
# get the statevcector
from qiskit.quantum_info import Statevector
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
state = Statevector.from_instruction(circuit)
print(state)
plot_bloch_multivector(state)
circuit = QuantumCircuit(q, c)
circuit.ry(π/2, q[0])
circuit.measure(q, c)
circuit.draw(output='mpl')
job = sampler.run(circuit)
result = job.result()
print(result.quasi_dists[0])
plot_histogram(result.quasi_dists[0])
circuit = QuantumCircuit(q, c)
circuit.ry(π/2, q[0])
# get statevector
state = Statevector.from_instruction(circuit)
print(state)
plot_bloch_multivector(state)
circuit = QuantumCircuit(q, c)
circuit.x(q[0])
circuit.ry(π/2, q[0])
# get statevector
state = Statevector.from_instruction(circuit)
print(state)
plot_bloch_multivector(state)
circuit.measure(q, c)
job = sampler.run(circuit)
result = job.result()
print(result.quasi_dists[0])
plot_histogram(result.quasi_dists[0])
circuit = QuantumCircuit(q, c)
circuit.ry(π/2, q[0])
circuit.ry(π/2, q[0])
circuit.measure(q, c)
job = sampler.run(circuit)
result = job.result()
print(result.quasi_dists[0])
plot_histogram(result.quasi_dists[0])
q0 = np.array([[1], [0]])
q1 = np.array([[1], [0]])
np.kron(q0, q1)
q = QuantumRegister(2)
c = ClassicalRegister(2)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.cx(q[0], q[1])
circuit.measure(q, c)
job = sampler.run(circuit)
result = job.result()
print(result.quasi_dists[0])
plot_histogram(result.quasi_dists[0])
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
import qiskit
qiskit.__qiskit_version__
from qiskit import IBMQ
IBMQ.save_account('TOKEN HERE')
# Replace your API token with 'TOKEN HERE'
IBMQ.load_account()
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
#Assign these values as per your requirements.
global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion
min_qubits=4
max_qubits=15 #reference files are upto 12 Qubits only
skip_qubits=2
max_circuits=3
num_shots=4092
gate_counts_plots = True
Noise_Inclusion = False
saveplots = False
Memory_utilization_plot = True
Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2"
backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends
#Change your Specification of Simulator in Declaring Backend Section
#By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2()
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute
from qiskit.opflow import PauliTrotterEvolution, Suzuki
from qiskit.opflow.primitive_ops import PauliSumOp
import time,os,json
import matplotlib.pyplot as plt
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error)
# Benchmark Name
benchmark_name = "VQE Simulation"
# Selection of basis gate set for transpilation
# Note: selector 1 is a hardware agnostic gate set
basis_selector = 1
basis_gates_array = [
[],
['rx', 'ry', 'rz', 'cx'], # a common basis set, default
['cx', 'rz', 'sx', 'x'], # IBM default basis set
['rx', 'ry', 'rxx'], # IonQ default basis set
['h', 'p', 'cx'], # another common basis set
['u', 'cx'] # general unitaries basis gates
]
np.random.seed(0)
def get_QV(backend):
import json
# Assuming backend.conf_filename is the filename and backend.dirname is the directory path
conf_filename = backend.dirname + "/" + backend.conf_filename
# Open the JSON file
with open(conf_filename, 'r') as file:
# Load the JSON data
data = json.load(file)
# Extract the quantum_volume parameter
QV = data.get('quantum_volume', None)
return QV
def checkbackend(backend_name,Type_of_Simulator):
if Type_of_Simulator == "built_in":
available_backends = []
for i in Aer.backends():
available_backends.append(i.name)
if backend_name in available_backends:
platform = backend_name
return platform
else:
print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!")
print(f"available backends are : {available_backends}")
platform = "qasm_simulator"
return platform
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2":
import qiskit.providers.fake_provider as fake_backends
if hasattr(fake_backends,backend_name) is True:
print(f"Backend {backend_name} is available for type {Type_of_Simulator}.")
backend_class = getattr(fake_backends,backend_name)
backend_instance = backend_class()
return backend_instance
else:
print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!")
if Type_of_Simulator == "FAKEV2":
backend_class = getattr(fake_backends,"FakeSantiagoV2")
else:
backend_class = getattr(fake_backends,"FakeSantiago")
backend_instance = backend_class()
return backend_instance
if Type_of_Simulator == "built_in":
platform = checkbackend(backend_name,Type_of_Simulator)
#By default using "Qasm Simulator"
backend = Aer.get_backend(platform)
QV_=None
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"backend version is {backend.backend_version}")
elif Type_of_Simulator == "FAKE":
basis_selector = 0
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting.
max_qubits=backend.configuration().n_qubits
print(f"{platform} device is capable of running {backend.configuration().n_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
elif Type_of_Simulator == "FAKEV2":
basis_selector = 0
if "V2" not in backend_name:
backend_name = backend_name+"V2"
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.name +"-" +backend.backend_version
max_qubits=backend.num_qubits
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
else:
print("Enter valid Simulator.....")
# saved circuits for display
QC_ = None
Hf_ = None
CO_ = None
################### Circuit Definition #######################################
# Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz
# param: n_spin_orbs - The number of spin orbitals.
# return: return a Qiskit circuit for this VQE ansatz
def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1):
# number of alpha spin orbitals
norb_a = int(n_spin_orbs / 2)
# construct the Hamiltonian
qubit_op = ReadHamiltonian(n_spin_orbs)
# allocate qubits
num_qubits = n_spin_orbs
qr = QuantumRegister(num_qubits)
qc = QuantumCircuit(qr, name=f"vqe-ansatz({method})-{num_qubits}-{circuit_id}")
# initialize the HF state
Hf = HartreeFock(num_qubits, na, nb)
qc.append(Hf, qr)
# form the list of single and double excitations
excitationList = []
for occ_a in range(na):
for vir_a in range(na, norb_a):
excitationList.append((occ_a, vir_a))
for occ_b in range(norb_a, norb_a+nb):
for vir_b in range(norb_a+nb, n_spin_orbs):
excitationList.append((occ_b, vir_b))
for occ_a in range(na):
for vir_a in range(na, norb_a):
for occ_b in range(norb_a, norb_a+nb):
for vir_b in range(norb_a+nb, n_spin_orbs):
excitationList.append((occ_a, vir_a, occ_b, vir_b))
# get cluster operators in Paulis
pauli_list = readPauliExcitation(n_spin_orbs, circuit_id)
# loop over the Pauli operators
for index, PauliOp in enumerate(pauli_list):
# get circuit for exp(-iP)
cluster_qc = ClusterOperatorCircuit(PauliOp, excitationList[index])
# add to ansatz
qc.append(cluster_qc, [i for i in range(cluster_qc.num_qubits)])
# method 1, only compute the last term in the Hamiltonian
if method == 1:
# last term in Hamiltonian
qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits)
# return the circuit
return qc_with_mea
# now we need to add the measurement parts to the circuit
# circuit list
qc_list = []
diag = []
off_diag = []
global normalization
normalization = 0.0
# add the first non-identity term
identity_qc = qc.copy()
identity_qc.measure_all()
qc_list.append(identity_qc) # add to circuit list
diag.append(qubit_op[1])
normalization += abs(qubit_op[1].coeffs[0]) # add to normalization factor
diag_coeff = abs(qubit_op[1].coeffs[0]) # add to coefficients of diagonal terms
# loop over rest of terms
for index, p in enumerate(qubit_op[2:]):
# get the circuit with expectation measurements
qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits)
# accumulate normalization
normalization += abs(p.coeffs[0])
# add to circuit list if non-diagonal
if not is_diag:
qc_list.append(qc_with_mea)
else:
diag_coeff += abs(p.coeffs[0])
# diagonal term
if is_diag:
diag.append(p)
# off-diagonal term
else:
off_diag.append(p)
# modify the name of diagonal circuit
qc_list[0].name = qubit_op[1].primitive.to_list()[0][0] + " " + str(np.real(diag_coeff))
normalization /= len(qc_list)
return qc_list
# Function that constructs the circuit for a given cluster operator
def ClusterOperatorCircuit(pauli_op, excitationIndex):
# compute exp(-iP)
exp_ip = pauli_op.exp_i()
# Trotter approximation
qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip)
# convert to circuit
qc = qc_op.to_circuit(); qc.name = f'Cluster Op {excitationIndex}'
global CO_
if CO_ == None or qc.num_qubits <= 4:
if qc.num_qubits < 7: CO_ = qc
# return this circuit
return qc
# Function that adds expectation measurements to the raw circuits
def ExpectationCircuit(qc, pauli, nqubit, method=2):
# copy the unrotated circuit
raw_qc = qc.copy()
# whether this term is diagonal
is_diag = True
# primitive Pauli string
PauliString = pauli.primitive.to_list()[0][0]
# coefficient
coeff = pauli.coeffs[0]
# basis rotation
for i, p in enumerate(PauliString):
target_qubit = nqubit - i - 1
if (p == "X"):
is_diag = False
raw_qc.h(target_qubit)
elif (p == "Y"):
raw_qc.sdg(target_qubit)
raw_qc.h(target_qubit)
is_diag = False
# perform measurements
raw_qc.measure_all()
# name of this circuit
raw_qc.name = PauliString + " " + str(np.real(coeff))
# save circuit
global QC_
if QC_ == None or nqubit <= 4:
if nqubit < 7: QC_ = raw_qc
return raw_qc, is_diag
# Function that implements the Hartree-Fock state
def HartreeFock(norb, na, nb):
# initialize the quantum circuit
qc = QuantumCircuit(norb, name="Hf")
# alpha electrons
for ia in range(na):
qc.x(ia)
# beta electrons
for ib in range(nb):
qc.x(ib+int(norb/2))
# Save smaller circuit
global Hf_
if Hf_ == None or norb <= 4:
if norb < 7: Hf_ = qc
# return the circuit
return qc
################ Helper Functions
# Function that converts a list of single and double excitation operators to Pauli operators
def readPauliExcitation(norb, circuit_id=0):
# load pre-computed data
filename = os.path.join(f'ansatzes/{norb}_qubit_{circuit_id}.txt')
with open(filename) as f:
data = f.read()
ansatz_dict = json.loads(data)
# initialize Pauli list
pauli_list = []
# current coefficients
cur_coeff = 1e5
# current Pauli list
cur_list = []
# loop over excitations
for ext in ansatz_dict:
if cur_coeff > 1e4:
cur_coeff = ansatz_dict[ext]
cur_list = [(ext, ansatz_dict[ext])]
elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4:
pauli_list.append(PauliSumOp.from_list(cur_list))
cur_coeff = ansatz_dict[ext]
cur_list = [(ext, ansatz_dict[ext])]
else:
cur_list.append((ext, ansatz_dict[ext]))
# add the last term
pauli_list.append(PauliSumOp.from_list(cur_list))
# return Pauli list
return pauli_list
# Get the Hamiltonian by reading in pre-computed file
def ReadHamiltonian(nqubit):
# load pre-computed data
filename = os.path.join(f'Hamiltonians/{nqubit}_qubit.txt')
with open(filename) as f:
data = f.read()
ham_dict = json.loads(data)
# pauli list
pauli_list = []
for p in ham_dict:
pauli_list.append( (p, ham_dict[p]) )
# build Hamiltonian
ham = PauliSumOp.from_list(pauli_list)
# return Hamiltonian
return ham
# Create an empty noise model
noise_parameters = NoiseModel()
if Type_of_Simulator == "built_in":
# Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5%
depol_one_qb_error = 0.05
depol_two_qb_error = 0.005
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx'])
# Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0%
amp_damp_one_qb_error = 0.0
amp_damp_two_qb_error = 0.0
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx'])
# Add reset noise to all single qubit resets
reset_to_zero_error = 0.005
reset_to_one_error = 0.005
noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"])
# Add readout error
p0given1_error = 0.000
p1given0_error = 0.000
error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]])
noise_parameters.add_all_qubit_readout_error(error_meas)
#print(noise_parameters)
elif Type_of_Simulator == "FAKE"or"FAKEV2":
noise_parameters = NoiseModel.from_backend(backend)
#print(noise_parameters)
### Analysis methods to be expanded and eventually compiled into a separate analysis.py file
import math, functools
def hellinger_fidelity_with_expected(p, q):
""" p: result distribution, may be passed as a counts distribution
q: the expected distribution to be compared against
References:
`Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_
Qiskit Hellinger Fidelity Function
"""
p_sum = sum(p.values())
q_sum = sum(q.values())
if q_sum == 0:
print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0")
return 0
p_normed = {}
for key, val in p.items():
p_normed[key] = val/p_sum
# if p_sum != 0:
# p_normed[key] = val/p_sum
# else:
# p_normed[key] = 0
q_normed = {}
for key, val in q.items():
q_normed[key] = val/q_sum
total = 0
for key, val in p_normed.items():
if key in q_normed.keys():
total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2
del q_normed[key]
else:
total += val
total += sum(q_normed.values())
# in some situations (error mitigation) this can go negative, use abs value
if total < 0:
print(f"WARNING: using absolute value in fidelity calculation")
total = abs(total)
dist = np.sqrt(total)/np.sqrt(2)
fidelity = (1-dist**2)**2
return fidelity
def polarization_fidelity(counts, correct_dist, thermal_dist=None):
"""
Combines Hellinger fidelity and polarization rescaling into fidelity calculation
used in every benchmark
counts: the measurement outcomes after `num_shots` algorithm runs
correct_dist: the distribution we expect to get for the algorithm running perfectly
thermal_dist: optional distribution to pass in distribution from a uniform
superposition over all states. If `None`: generated as
`uniform_dist` with the same qubits as in `counts`
returns both polarization fidelity and the hellinger fidelity
Polarization from: `https://arxiv.org/abs/2008.11294v1`
"""
num_measured_qubits = len(list(correct_dist.keys())[0])
#print(num_measured_qubits)
counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()}
# calculate hellinger fidelity between measured expectation values and correct distribution
hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist)
# to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits
if num_measured_qubits > 16:
return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity }
# if not provided, generate thermal dist based on number of qubits
if thermal_dist == None:
thermal_dist = uniform_dist(num_measured_qubits)
# set our fidelity rescaling value as the hellinger fidelity for a depolarized state
floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist)
# rescale fidelity result so uniform superposition (random guessing) returns fidelity
# rescaled to 0 to provide a better measure of success of the algorithm (polarization)
new_floor_fidelity = 0
fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity)
return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity }
## Uniform distribution function commonly used
def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity):
"""
Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks
fidelity: raw fidelity to rescale
floor_fidelity: threshold fidelity which is equivalent to random guessing
new_floor_fidelity: what we rescale the floor_fidelity to
Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0:
1 -> 1;
0.25 -> 0;
0.5 -> 0.3333;
"""
rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1
# ensure fidelity is within bounds (0, 1)
if rescaled_fidelity < 0:
rescaled_fidelity = 0.0
if rescaled_fidelity > 1:
rescaled_fidelity = 1.0
return rescaled_fidelity
def uniform_dist(num_state_qubits):
dist = {}
for i in range(2**num_state_qubits):
key = bin(i)[2:].zfill(num_state_qubits)
dist[key] = 1/(2**num_state_qubits)
return dist
from matplotlib.patches import Rectangle
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize
from matplotlib.patches import Circle
############### Color Map functions
# Create a selection of colormaps from which to choose; default to custom_spectral
cmap_spectral = plt.get_cmap('Spectral')
cmap_greys = plt.get_cmap('Greys')
cmap_blues = plt.get_cmap('Blues')
cmap_custom_spectral = None
# the default colormap is the spectral map
cmap = cmap_spectral
cmap_orig = cmap_spectral
# current cmap normalization function (default None)
cmap_norm = None
default_fade_low_fidelity_level = 0.16
default_fade_rate = 0.7
# Specify a normalization function here (default None)
def set_custom_cmap_norm(vmin, vmax):
global cmap_norm
if vmin == vmax or (vmin == 0.0 and vmax == 1.0):
print("... setting cmap norm to None")
cmap_norm = None
else:
print(f"... setting cmap norm to [{vmin}, {vmax}]")
cmap_norm = Normalize(vmin=vmin, vmax=vmax)
# Remake the custom spectral colormap with user settings
def set_custom_cmap_style(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
#print("... set custom map style")
global cmap, cmap_custom_spectral, cmap_orig
cmap_custom_spectral = create_custom_spectral_cmap(
fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate)
cmap = cmap_custom_spectral
cmap_orig = cmap_custom_spectral
# Create the custom spectral colormap from the base spectral
def create_custom_spectral_cmap(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
# determine the breakpoint from the fade level
num_colors = 100
breakpoint = round(fade_low_fidelity_level * num_colors)
# get color list for spectral map
spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)]
#print(fade_rate)
# create a list of colors to replace those below the breakpoint
# and fill with "faded" color entries (in reverse)
low_colors = [0] * breakpoint
#for i in reversed(range(breakpoint)):
for i in range(breakpoint):
# x is index of low colors, normalized 0 -> 1
x = i / breakpoint
# get color at this index
bc = spectral_colors[i]
r0 = bc[0]
g0 = bc[1]
b0 = bc[2]
z0 = bc[3]
r_delta = 0.92 - r0
#print(f"{x} {bc} {r_delta}")
# compute saturation and greyness ratio
sat_ratio = 1 - x
#grey_ratio = 1 - x
''' attempt at a reflective gradient
if i >= breakpoint/2:
xf = 2*(x - 0.5)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (yf + 0.5)
else:
xf = 2*(0.5 - x)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (0.5 - yf)
'''
grey_ratio = 1 - math.pow(x, 1/fade_rate)
#print(f" {xf} {yf} ")
#print(f" {sat_ratio} {grey_ratio}")
r = r0 + r_delta * sat_ratio
g_delta = r - g0
b_delta = r - b0
g = g0 + g_delta * grey_ratio
b = b0 + b_delta * grey_ratio
#print(f"{r} {g} {b}\n")
low_colors[i] = (r,g,b,z0)
#print(low_colors)
# combine the faded low colors with the regular spectral cmap to make a custom version
cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:])
#spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)]
#for i in range(10): print(spectral_colors[i])
#print("")
return cmap_custom_spectral
# Make the custom spectral color map the default on module init
set_custom_cmap_style()
# Arrange the stored annotations optimally and add to plot
def anno_volumetric_data(ax, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True):
# sort all arrays by the x point of the text (anno_offs)
global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos
all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos))
x_anno_offs = [a for a,b,c,d,e in all_annos]
y_anno_offs = [b for a,b,c,d,e in all_annos]
anno_labels = [c for a,b,c,d,e in all_annos]
x_annos = [d for a,b,c,d,e in all_annos]
y_annos = [e for a,b,c,d,e in all_annos]
#print(f"{x_anno_offs}")
#print(f"{y_anno_offs}")
#print(f"{anno_labels}")
for i in range(len(anno_labels)):
x_anno = x_annos[i]
y_anno = y_annos[i]
x_anno_off = x_anno_offs[i]
y_anno_off = y_anno_offs[i]
label = anno_labels[i]
if i > 0:
x_delta = abs(x_anno_off - x_anno_offs[i - 1])
y_delta = abs(y_anno_off - y_anno_offs[i - 1])
if y_delta < 0.7 and x_delta < 2:
y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6
#x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1
ax.annotate(label,
xy=(x_anno+0.0, y_anno+0.1),
arrowprops=dict(facecolor='black', shrink=0.0,
width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)),
xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]),
rotation=labelrot,
horizontalalignment='left', verticalalignment='baseline',
color=(0.2,0.2,0.2),
clip_on=True)
if saveplots == True:
plt.savefig("VolumetricPlotSample.jpg")
# Plot one group of data for volumetric presentation
def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True,
x_size=1.0, y_size=1.0, zorder=1, offset_flag=False,
max_depth=0, suppress_low_fidelity=False):
# since data may come back out of order, save point at max y for annotation
i_anno = 0
x_anno = 0
y_anno = 0
# plot data rectangles
low_fidelity_count = True
last_y = -1
k = 0
# determine y-axis dimension for one pixel to use for offset of bars that start at 0
(_, dy) = get_pixel_dims(ax)
# do this loop in reverse to handle the case where earlier cells are overlapped by later cells
for i in reversed(range(len(d_data))):
x = depth_index(d_data[i], depth_base)
y = float(w_data[i])
f = f_data[i]
# each time we star a new row, reset the offset counter
# DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars
# that represent time starting from 0 secs. We offset by one pixel each and center the group
if y != last_y:
last_y = y;
k = 3 # hardcoded for 8 cells, offset by 3
#print(f"{i = } {x = } {y = }")
if max_depth > 0 and d_data[i] > max_depth:
#print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}")
break;
# reject cells with low fidelity
if suppress_low_fidelity and f < suppress_low_fidelity_level:
if low_fidelity_count: break
else: low_fidelity_count = True
# the only time this is False is when doing merged gradation plots
if do_border == True:
# this case is for an array of x_sizes, i.e. each box has different width
if isinstance(x_size, list):
# draw each of the cells, with no offset
if not offset_flag:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder))
# use an offset for y value, AND account for x and width to draw starting at 0
else:
ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder))
# this case is for only a single cell
else:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size))
# save the annotation point with the largest y value
if y >= y_anno:
x_anno = x
y_anno = y
i_anno = i
# move the next bar down (if using offset)
k -= 1
# if no data rectangles plotted, no need for a label
if x_anno == 0 or y_anno == 0:
return
x_annos.append(x_anno)
y_annos.append(y_anno)
anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 )
# adjust radius of annotation circle based on maximum width of apps
anno_max = 10
if w_max > 10:
anno_max = 14
if w_max > 14:
anno_max = 18
scale = anno_max / anno_dist
# offset of text from end of arrow
if scale > 1:
x_anno_off = scale * x_anno - x_anno - 0.5
y_anno_off = scale * y_anno - y_anno
else:
x_anno_off = 0.7
y_anno_off = 0.5
x_anno_off += x_anno
y_anno_off += y_anno
# print(f"... {xx} {yy} {anno_dist}")
x_anno_offs.append(x_anno_off)
y_anno_offs.append(y_anno_off)
anno_labels.append(label)
if do_label:
ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot,
horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2))
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# init arrays to hold annotation points for label spreading
def vplot_anno_init ():
global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# Number of ticks on volumetric depth axis
max_depth_log = 22
# average transpile factor between base QV depth and our depth based on results from QV notebook
QV_transpile_factor = 12.7
# format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1
# (sign handling may be incorrect)
def format_number(num, digits=0):
if isinstance(num, str): num = float(num)
num = float('{:.3g}'.format(abs(num)))
sign = ''
metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1}
for index in metric:
num_check = num / metric[index]
if num_check >= 1:
num = round(num_check, digits)
sign = index
break
numstr = f"{str(num)}"
if '.' in numstr:
numstr = numstr.rstrip('0').rstrip('.')
return f"{numstr}{sign}"
# Return the color associated with the spcific value, using color map norm
def get_color(value):
# if there is a normalize function installed, scale the data
if cmap_norm:
value = float(cmap_norm(value))
if cmap == cmap_spectral:
value = 0.05 + value*0.9
elif cmap == cmap_blues:
value = 0.00 + value*1.0
else:
value = 0.0 + value*0.95
return cmap(value)
# Return the x and y equivalent to a single pixel for the given plot axis
def get_pixel_dims(ax):
# transform 0 -> 1 to pixel dimensions
pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0))
xpix = pixdims[1][0]
ypix = pixdims[0][1]
#determine x- and y-axis dimension for one pixel
dx = (1 / xpix)
dy = (1 / ypix)
return (dx, dy)
############### Helper functions
# return the base index for a circuit depth value
# take the log in the depth base, and add 1
def depth_index(d, depth_base):
if depth_base <= 1:
return d
if d == 0:
return 0
return math.log(d, depth_base) + 1
# draw a box at x,y with various attributes
def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1):
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5*y_size,
zorder=zorder)
# draw a circle at x,y with various attributes
def circle_at(x, y, value, type=1, fill=True):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Circle((x, y), size/2,
alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5)
def box4_at(x, y, value, type=1, fill=True, alpha=1.0):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.3,0.3,0.3)
ec = fc
return Rectangle((x - size/8, y - size/2), size/4, size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.1)
# Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value
def qv_box_at(x, y, qv_width, qv_depth, value, depth_base):
#print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}")
return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width,
edgecolor = (value,value,value),
facecolor = (value,value,value),
fill=True,
lw=1)
def bkg_box_at(x, y, value=0.9):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (value,value,value),
fill=True,
lw=0.5)
def bkg_empty_box_at(x, y):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (1.0,1.0,1.0),
fill=True,
lw=0.5)
# Plot the background for the volumetric analysis
def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"):
if suptitle == None:
suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}"
QV0 = QV
qv_estimate = False
est_str = ""
if QV == 0: # QV = 0 indicates "do not draw QV background or label"
QV = 2048
elif QV < 0: # QV < 0 indicates "add est. to label"
QV = -QV
qv_estimate = True
est_str = " (est.)"
if avail_qubits > 0 and max_qubits > avail_qubits:
max_qubits = avail_qubits
max_width = 13
if max_qubits > 11: max_width = 18
if max_qubits > 14: max_width = 20
if max_qubits > 16: max_width = 24
if max_qubits > 24: max_width = 33
#print(f"... {avail_qubits} {max_qubits} {max_width}")
plot_width = 6.8
plot_height = 0.5 + plot_width * (max_width / max_depth_log)
#print(f"... {plot_width} {plot_height}")
# define matplotlib figure and axis; use constrained layout to fit colorbar to right
fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True)
plt.suptitle(suptitle)
plt.xlim(0, max_depth_log)
plt.ylim(0, max_width)
# circuit depth axis (x axis)
xbasis = [x for x in range(1,max_depth_log)]
xround = [depth_base**(x-1) for x in xbasis]
xlabels = [format_number(x) for x in xround]
ax.set_xlabel('Circuit Depth')
ax.set_xticks(xbasis)
plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor")
# other label options
#plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left')
#plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor")
# circuit width axis (y axis)
ybasis = [y for y in range(1,max_width)]
yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now
ylabels = [str(y) for y in yround] # not used now
#ax.set_ylabel('Circuit Width (Number of Qubits)')
ax.set_ylabel('Circuit Width')
ax.set_yticks(ybasis)
#create simple line plot (not used right now)
#ax.plot([0, 10],[0, 10])
log2QV = math.log2(QV)
QV_width = log2QV
QV_depth = log2QV * QV_transpile_factor
# show a quantum volume rectangle of QV = 64 e.g. (6 x 6)
if QV0 != 0:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base))
else:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base))
# the untranspiled version is commented out - we do not show this by default
# also show a quantum volume rectangle un-transpiled
# ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base))
# show 2D array of volumetric cells based on this QV_transpiled
# DEVNOTE: we use +1 only to make the visuals work; s/b without
# Also, the second arg of the min( below seems incorrect, needs correction
maxprod = (QV_width + 1) * (QV_depth + 1)
for w in range(1, min(max_width, round(QV) + 1)):
# don't show VB squares if width greater than known available qubits
if avail_qubits != 0 and w > avail_qubits:
continue
i_success = 0
for d in xround:
# polarization factor for low circuit widths
maxtest = maxprod / ( 1 - 1 / (2**w) )
# if circuit would fail here, don't draw box
if d > maxtest: continue
if w * d > maxtest: continue
# guess for how to capture how hardware decays with width, not entirely correct
# # reduce maxtext by a factor of number of qubits > QV_width
# # just an approximation to account for qubit distances
# if w > QV_width:
# over = w - QV_width
# maxtest = maxtest / (1 + (over/QV_width))
# draw a box at this width and depth
id = depth_index(d, depth_base)
# show vb rectangles; if not showing QV, make all hollow (or less dark)
if QV0 == 0:
#ax.add_patch(bkg_empty_box_at(id, w))
ax.add_patch(bkg_box_at(id, w, 0.95))
else:
ax.add_patch(bkg_box_at(id, w, 0.9))
# save index of last successful depth
i_success += 1
# plot empty rectangle after others
d = xround[i_success]
id = depth_index(d, depth_base)
ax.add_patch(bkg_empty_box_at(id, w))
# Add annotation showing quantum volume
if QV0 != 0:
t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12,
horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2),
bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1))
# add colorbar to right of plot
plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax,
shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7))
return ax
# Function to calculate circuit depth
def calculate_circuit_depth(qc):
# Calculate the depth of the circuit
depth = qc.depth()
return depth
def calculate_transpiled_depth(qc,basis_selector):
# use either the backend or one of the basis gate sets
if basis_selector == 0:
qc = transpile(qc, backend)
else:
basis_gates = basis_gates_array[basis_selector]
qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0)
transpiled_depth = qc.depth()
return transpiled_depth,qc
def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title):
avg_fidelity_means = []
avg_Hf_fidelity_means = []
avg_num_qubits_values = list(fidelity_data.keys())
# Calculate the average fidelity and Hamming fidelity for each unique number of qubits
for num_qubits in avg_num_qubits_values:
avg_fidelity = np.average(fidelity_data[num_qubits])
avg_fidelity_means.append(avg_fidelity)
avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits])
avg_Hf_fidelity_means.append(avg_Hf_fidelity)
return avg_fidelity_means,avg_Hf_fidelity_means
list_of_gates = []
def list_of_standardgates():
import qiskit.circuit.library as lib
from qiskit.circuit import Gate
import inspect
# List all the attributes of the library module
gate_list = dir(lib)
# Filter out non-gate classes (like functions, variables, etc.)
gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)]
# Get method names from QuantumCircuit
circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction)
method_names = [name for name, _ in circuit_methods]
# Map gate class names to method names
gate_to_method = {}
for gate in gates:
gate_class = getattr(lib, gate)
class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name
for method in method_names:
if method == class_name or method == class_name.replace('cr', 'c-r'):
gate_to_method[gate] = method
break
# Add common operations that are not strictly gates
additional_operations = {
'Measure': 'measure',
'Barrier': 'barrier',
}
gate_to_method.update(additional_operations)
for k,v in gate_to_method.items():
list_of_gates.append(v)
def update_counts(gates,custom_gates):
operations = {}
for key, value in gates.items():
operations[key] = value
for key, value in custom_gates.items():
if key in operations:
operations[key] += value
else:
operations[key] = value
return operations
def get_gate_counts(gates,custom_gate_defs):
result = gates.copy()
# Iterate over the gate counts in the quantum circuit
for gate, count in gates.items():
if gate in custom_gate_defs:
custom_gate_ops = custom_gate_defs[gate]
# Multiply custom gate operations by the count of the custom gate in the circuit
for _ in range(count):
result = update_counts(result, custom_gate_ops)
# Remove the custom gate entry as we have expanded it
del result[gate]
return result
dict_of_qc = dict()
custom_gates_defs = dict()
# Function to count operations recursively
def count_operations(qc):
dict_of_qc.clear()
circuit_traverser(qc)
operations = dict()
operations = dict_of_qc[qc.name]
del dict_of_qc[qc.name]
# print("operations :",operations)
# print("dict_of_qc :",dict_of_qc)
for keys in operations.keys():
if keys not in list_of_gates:
for k,v in dict_of_qc.items():
if k in operations.keys():
custom_gates_defs[k] = v
operations=get_gate_counts(operations,custom_gates_defs)
custom_gates_defs.clear()
return operations
def circuit_traverser(qc):
dict_of_qc[qc.name]=dict(qc.count_ops())
for i in qc.data:
if str(i.operation.name) not in list_of_gates:
qc_1 = i.operation.definition
circuit_traverser(qc_1)
def get_memory():
import resource
usage = resource.getrusage(resource.RUSAGE_SELF)
max_mem = usage.ru_maxrss/1024 #in MB
return max_mem
def analyzer(qc,references,num_qubits):
# total circuit name (pauli string + coefficient)
total_name = qc.name
# pauli string
pauli_string = total_name.split()[0]
# get the correct measurement
if (len(total_name.split()) == 2):
correct_dist = references[pauli_string]
else:
circuit_id = int(total_name.split()[2])
correct_dist = references[f"Qubits - {num_qubits} - {circuit_id}"]
return correct_dist,total_name
# Max qubits must be 12 since the referenced files only go to 12 qubits
MAX_QUBITS = 12
method = 1
def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=2,
max_circuits=max_circuits, num_shots=num_shots):
creation_times = []
elapsed_times = []
quantum_times = []
circuit_depths = []
transpiled_depths = []
fidelity_data = {}
Hf_fidelity_data = {}
numckts = []
mem_usage = []
algorithmic_1Q_gate_counts = []
algorithmic_2Q_gate_counts = []
transpiled_1Q_gate_counts = []
transpiled_2Q_gate_counts = []
print(f"{benchmark_name} Benchmark Program - {platform}")
#defining all the standard gates supported by qiskit in a list
if gate_counts_plots == True:
list_of_standardgates()
max_qubits = max(max_qubits, min_qubits) # max must be >= min
# validate parameters (smallest circuit is 4 qubits and largest is 10 qubits)
max_qubits = min(max_qubits, MAX_QUBITS)
min_qubits = min(max(4, min_qubits), max_qubits)
if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even
skip_qubits = max(1, skip_qubits)
if method == 2: max_circuits = 1
if max_qubits < 4:
print(f"Max number of qubits {max_qubits} is too low to run method {method} of VQE algorithm")
return
global max_ckts
max_ckts = max_circuits
global min_qbits,max_qbits,skp_qubits
min_qbits = min_qubits
max_qbits = max_qubits
skp_qubits = skip_qubits
print(f"min, max qubits = {min_qubits} {max_qubits}")
# Execute Benchmark Program N times for multiple circuit sizes
for input_size in range(min_qubits, max_qubits + 1, skip_qubits):
# reset random seed
np.random.seed(0)
# determine the number of circuits to execute for this group
num_circuits = min(3, max_circuits)
num_qubits = input_size
fidelity_data[num_qubits] = []
Hf_fidelity_data[num_qubits] = []
# decides number of electrons
na = int(num_qubits/4)
nb = int(num_qubits/4)
# random seed
np.random.seed(0)
numckts.append(num_circuits)
# create the circuit for given qubit size and simulation parameters, store time metric
ts = time.time()
# circuit list
qc_list = []
# Method 1 (default)
if method == 1:
# loop over circuits
for circuit_id in range(num_circuits):
# construct circuit
qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method)
qc_single.name = qc_single.name + " " + str(circuit_id)
# add to list
qc_list.append(qc_single)
# method 2
elif method == 2:
# construct all circuits
qc_list = VQEEnergy(num_qubits, na, nb, 0, method)
print(qc_list)
print(f"************\nExecuting [{len(qc_list)}] circuits with num_qubits = {num_qubits}")
for qc in qc_list:
print("*********************************************")
#print(f"qc of {qc} qubits for qc_list value: {qc_list}")
# get circuit id
if method == 1:
circuit_id = qc.name.split()[2]
else:
circuit_id = qc.name.split()[0]
#creation time
creation_time = time.time() - ts
creation_times.append(creation_time)
#print(qc)
print(f"creation time = {creation_time*1000} ms")
# Calculate gate count for the algorithmic circuit (excluding barriers and measurements)
if gate_counts_plots == True:
operations = count_operations(qc)
n1q = 0; n2q = 0
if operations != None:
for key, value in operations.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c") or key.startswith("mc"):
n2q += value
else:
n1q += value
print("operations: ",operations)
algorithmic_1Q_gate_counts.append(n1q)
algorithmic_2Q_gate_counts.append(n2q)
# collapse the sub-circuit levels used in this benchmark (for qiskit)
qc=qc.decompose()
#print(qc)
# Calculate circuit depth
depth = calculate_circuit_depth(qc)
circuit_depths.append(depth)
# Calculate transpiled circuit depth
transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector)
transpiled_depths.append(transpiled_depth)
#print(qc)
print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}")
if gate_counts_plots == True:
# Calculate gate count for the transpiled circuit (excluding barriers and measurements)
tr_ops = qc.count_ops()
#print("tr_ops = ",tr_ops)
tr_n1q = 0; tr_n2q = 0
if tr_ops != None:
for key, value in tr_ops.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c"): tr_n2q += value
else: tr_n1q += value
transpiled_1Q_gate_counts.append(tr_n1q)
transpiled_2Q_gate_counts.append(tr_n2q)
print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}")
print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}")
#execution
if Type_of_Simulator == "built_in":
#To check if Noise is required
if Noise_Inclusion == True:
noise_model = noise_parameters
else:
noise_model = None
ts = time.time()
job = execute(qc, backend, shots=num_shots, noise_model=noise_model)
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" :
ts = time.time()
job = backend.run(qc,shots=num_shots, noise_model=noise_parameters)
#retrieving the result
result = job.result()
#print(result)
#calculating elapsed time
elapsed_time = time.time() - ts
elapsed_times.append(elapsed_time)
# Calculate quantum processing time
quantum_time = result.time_taken
quantum_times.append(quantum_time)
print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms")
#counts in result object
counts = result.get_counts()
# load pre-computed data
if len(qc.name.split()) == 2:
filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit.json')
with open(filename) as f:
references = json.load(f)
else:
filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit_method2.json')
with open(filename) as f:
references = json.load(f)
#Correct distribution to compare with counts
correct_dist,total_name = analyzer(qc,references,num_qubits)
#fidelity calculation comparision of counts and correct_dist
fidelity_dict = polarization_fidelity(counts, correct_dist)
print(fidelity_dict)
# modify fidelity based on the coefficient
if (len(total_name.split()) == 2):
fidelity_dict *= ( abs(float(total_name.split()[1])) / normalization )
fidelity_data[num_qubits].append(fidelity_dict['fidelity'])
Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity'])
#maximum memory utilization (if required)
if Memory_utilization_plot == True:
max_mem = get_memory()
print(f"Maximum Memory Utilized: {max_mem} MB")
mem_usage.append(max_mem)
print("*********************************************")
##########
# print a sample circuit
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
print("\nHartree Fock Generator 'Hf' ="); print(Hf_ if Hf_ != None else " ... too large!")
print("\nCluster Operator Example 'Cluster Op' ="); print(CO_ if CO_ != None else " ... too large!")
return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths,
fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts,
transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage)
# Execute the benchmark program, accumulate metrics, and calculate circuit depths
(creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts,
algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run()
# Define the range of qubits for the x-axis
num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits)
print("num_qubits_range =",num_qubits_range)
# Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits
avg_creation_times = []
avg_elapsed_times = []
avg_quantum_times = []
avg_circuit_depths = []
avg_transpiled_depths = []
avg_1Q_algorithmic_gate_counts = []
avg_2Q_algorithmic_gate_counts = []
avg_1Q_Transpiled_gate_counts = []
avg_2Q_Transpiled_gate_counts = []
max_memory = []
start = 0
for num in numckts:
avg_creation_times.append(np.mean(creation_times[start:start+num]))
avg_elapsed_times.append(np.mean(elapsed_times[start:start+num]))
avg_quantum_times.append(np.mean(quantum_times[start:start+num]))
avg_circuit_depths.append(np.mean(circuit_depths[start:start+num]))
avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num]))
if gate_counts_plots == True:
avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num])))
avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num])))
avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num])))
avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num])))
if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num]))
start += num
# Calculate the fidelity data
avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison")
# Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits
# Add labels to the bars
def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"):
for rect in rects:
height = rect.get_height()
ax.annotate(str.format(height), # Formatting to two decimal places
xy=(rect.get_x() + rect.get_width() / 2, height / 2),
xytext=(0, 0),
textcoords="offset points",
ha='center', va=va,color=text_color,rotation=90)
bar_width = 0.3
# Determine the number of subplots and their arrangement
if Memory_utilization_plot and gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30))
# Plotting for both memory utilization and gate counts
# ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available
elif Memory_utilization_plot:
fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30))
# Plotting for memory utilization only
# ax1, ax2, ax3, ax6, ax7 are available
elif gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30))
# Plotting for gate counts only
# ax1, ax2, ax3, ax4, ax5, ax6 are available
else:
fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30))
# Default plotting
# ax1, ax2, ax3, ax6 are available
fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16)
for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000
avg_creation_times[i] *= 1000
ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue')
autolabel(ax1.patches, ax1)
ax1.set_xlabel('Number of Qubits')
ax1.set_ylabel('Average Creation Time (ms)')
ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14)
ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000
avg_elapsed_times[i] *= 1000
for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000
avg_quantum_times[i] *= 1000
Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time')
Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time')
autolabel(Elapsed,ax2,str='{:.1f}')
autolabel(Quantum,ax2,str='{:.1f}')
ax2.set_xlabel('Number of Qubits')
ax2.set_ylabel('Average Time (ms)')
ax2.set_title('Average Time vs Number of Qubits')
ax2.legend()
ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here
Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here
autolabel(Normalized,ax3,str='{:.2f}')
autolabel(Algorithmic,ax3,str='{:.2f}')
ax3.set_xlabel('Number of Qubits')
ax3.set_ylabel('Average Circuit Depth')
ax3.set_title('Average Circuit Depth vs Number of Qubits')
ax3.legend()
if gate_counts_plots == True:
ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_1Q_counts,ax4,str='{}')
autolabel(Algorithmic_1Q_counts,ax4,str='{}')
ax4.set_xlabel('Number of Qubits')
ax4.set_ylabel('Average 1-Qubit Gate Counts')
ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits')
ax4.legend()
ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_2Q_counts,ax5,str='{}')
autolabel(Algorithmic_2Q_counts,ax5,str='{}')
ax5.set_xlabel('Number of Qubits')
ax5.set_ylabel('Average 2-Qubit Gate Counts')
ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits')
ax5.legend()
ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here
Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here
autolabel(Hellinger,ax6,str='{:.2f}')
autolabel(Normalized,ax6,str='{:.2f}')
ax6.set_xlabel('Number of Qubits')
ax6.set_ylabel('Average Value')
ax6.set_title("Fidelity Comparison")
ax6.legend()
if Memory_utilization_plot == True:
ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations")
autolabel(ax7.patches, ax7)
ax7.set_xlabel('Number of Qubits')
ax7.set_ylabel('Maximum Memory Utilized (MB)')
ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14)
plt.tight_layout(rect=[0, 0, 1, 0.96])
if saveplots == True:
plt.savefig("ParameterPlotsSample.jpg")
plt.show()
# Quantum Volume Plot
Suptitle = f"Volumetric Positioning - {platform}"
appname=benchmark_name
if QV_ == None:
QV=2048
else:
QV=QV_
depth_base =2
ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity")
w_data = num_qubits_range
# determine width for circuit
w_max = 0
for i in range(len(w_data)):
y = float(w_data[i])
w_max = max(w_max, y)
d_tr_data = avg_transpiled_depths
f_data = avg_f
plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max)
anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
qc2.draw('mpl')
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""tests for circuit_to_cold_atom functions"""
from typing import Dict
from qiskit import QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.circuit import Parameter
from qiskit.providers import BackendV1 as Backend
from qiskit.providers.models import BackendConfiguration
from qiskit_cold_atom.exceptions import QiskitColdAtomError
from qiskit_cold_atom.circuit_tools import CircuitTools, WireOrder
# These imports are needed to decorate the quantum circuit
import qiskit_cold_atom.spins # pylint: disable=unused-import
import qiskit_cold_atom.fermions # pylint: disable=unused-import
class DummyBackend(Backend):
"""dummy backend class for test purposes only"""
def __init__(self, config_dict: Dict):
super().__init__(configuration=BackendConfiguration.from_dict(config_dict))
def run(self, run_input, **options):
pass
@classmethod
def _default_options(cls):
pass
class TestCircuitToColdAtom(QiskitTestCase):
"""circuit to cold atom tests."""
def setUp(self):
super().setUp()
# Set up a dummy backend from a configuration dictionary
test_config = {
"backend_name": "test_backend",
"backend_version": "0.0.1",
"simulator": True,
"local": True,
"coupling_map": None,
"description": "dummy backend for testing purposes only",
"basis_gates": ["hop, int"],
"memory": False,
"n_qubits": 5,
"conditional": False,
"max_shots": 100,
"max_experiments": 2,
"open_pulse": False,
"gates": [
{
"coupling_map": [[0], [1], [2], [3], [4]],
"name": "rlz",
"parameters": ["delta"],
"qasm_def": "gate rLz(delta) {}",
},
{
"coupling_map": [[0], [1], [2]],
"name": "rlz2",
"parameters": ["chi"],
"qasm_def": "gate rlz2(chi) {}",
},
{
"coupling_map": [[0], [1], [2], [3], [4]],
"name": "rlx",
"parameters": ["omega"],
"qasm_def": "gate rx(omega) {}",
},
],
"supported_instructions": [
"delay",
"rlx",
"rlz",
"rlz2",
"measure",
"barrier",
],
}
self.dummy_backend = DummyBackend(test_config)
def test_circuit_to_cold_atom(self):
"""test the circuit_to_cold_atom function"""
circ1 = QuantumCircuit(3)
circ1.rlx(0.5, [0, 1])
circ1.rlz(0.3, [1, 2])
circ1.measure_all()
circ2 = QuantumCircuit(2)
circ2.rlz2(0.5, 1)
circ2.measure_all()
shots = 10
target_output = {
"experiment_0": {
"instructions": [
["rlx", [0], [0.5]],
["rlx", [1], [0.5]],
["rlz", [1], [0.3]],
["rlz", [2], [0.3]],
["barrier", [0, 1, 2], []],
["measure", [0], []],
["measure", [1], []],
["measure", [2], []],
],
"num_wires": 3,
"shots": shots,
"wire_order": "sequential",
},
"experiment_1": {
"instructions": [
["rlz2", [1], [0.5]],
["barrier", [0, 1], []],
["measure", [0], []],
["measure", [1], []],
],
"num_wires": 2,
"shots": shots,
"wire_order": "sequential",
},
}
actual_output = CircuitTools.circuit_to_cold_atom(
[circ1, circ2], backend=self.dummy_backend, shots=shots
)
self.assertEqual(actual_output, target_output)
def test_validate_circuits(self):
"""test the validation of circuits against the backend configuration"""
with self.subTest("test size of circuit"):
circ = QuantumCircuit(6)
circ.rlx(0.4, 2)
with self.assertRaises(QiskitColdAtomError):
CircuitTools.validate_circuits(circ, backend=self.dummy_backend)
with self.subTest("test support of native instructions"):
circ = QuantumCircuit(4)
# add gate that is not supported by the backend
circ.fhop([0.5], [0, 1, 2, 3])
with self.assertRaises(QiskitColdAtomError):
CircuitTools.validate_circuits(circ, backend=self.dummy_backend)
with self.subTest("check gate coupling map"):
circ = QuantumCircuit(5)
circ.rlz2(0.5, 4)
with self.assertRaises(QiskitColdAtomError):
CircuitTools.validate_circuits(circ, backend=self.dummy_backend)
with self.subTest("test max. allowed circuits"):
circuits = [QuantumCircuit(2)] * 3
with self.assertRaises(QiskitColdAtomError):
CircuitTools.circuit_to_cold_atom(circuits=circuits, backend=self.dummy_backend)
with self.subTest("test max. allowed shots"):
circuits = QuantumCircuit(2)
with self.assertRaises(QiskitColdAtomError):
CircuitTools.circuit_to_cold_atom(
circuits=circuits, backend=self.dummy_backend, shots=1000
)
with self.subTest("test running with unbound parameters"):
theta = Parameter("θ")
circ = QuantumCircuit(1)
circ.rlx(theta, 0)
with self.assertRaises(QiskitColdAtomError):
CircuitTools.validate_circuits(circ, backend=self.dummy_backend)
def test_circuit_to_data(self):
"""test the circuit to data method"""
circ = QuantumCircuit(3)
circ.rlx(0.5, [0, 1])
circ.rlz(0.3, [1, 2])
circ.measure_all()
target_output = [
["rlx", [0], [0.5]],
["rlx", [1], [0.5]],
["rlz", [1], [0.3]],
["rlz", [2], [0.3]],
["barrier", [0, 1, 2], []],
["measure", [0], []],
["measure", [1], []],
["measure", [2], []],
]
actual_output = CircuitTools.circuit_to_data(circ, backend=self.dummy_backend)
self.assertEqual(actual_output, target_output)
def test_convert_wire_order(self):
"""test the convert_wire_order method"""
num_sites = 4
num_species = 3
# conversion rule: i -> (i % num_sites) * num_species + i // num_sites
wires_sequential = [0, 1, 4, 5, 8, 9]
wires_interleaved = [0, 3, 1, 4, 2, 5]
with self.subTest("test sequential to interleaved"):
wires_converted = CircuitTools.convert_wire_order(
wires=wires_sequential,
convention_from=WireOrder.SEQUENTIAL,
convention_to=WireOrder.INTERLEAVED,
num_sites=num_sites,
num_species=num_species,
)
self.assertEqual(wires_converted, wires_interleaved)
with self.subTest("test interleaved to sequential"):
wires_converted = CircuitTools.convert_wire_order(
wires=wires_interleaved,
convention_from=WireOrder.INTERLEAVED,
convention_to=WireOrder.SEQUENTIAL,
num_sites=num_sites,
num_species=num_species,
)
self.assertEqual(wires_converted, wires_sequential)
|
https://github.com/henrik-dreyer/MPS-in-Qiskit
|
henrik-dreyer
|
import prepare_MPS as mps
import numpy as np
from qiskit import BasicAer, execute
#Create Random MPS with size 4, bond dimension 4 and physical dimension 2 (qubits)
N=4
d=2
chi=4
phi_final=np.random.rand(chi)
phi_initial=np.random.rand(chi)
A=mps.create_random_tensors(N,chi,d)
#Create the circuit. The 'reg' register corresponds to the 'MPS' register in the picture above
qc, reg = mps.MPS_to_circuit(A, phi_initial, phi_final)
#Run the circuit on the statevector simulator
backend = BasicAer.get_backend("statevector_simulator")
job = execute(qc, backend)
result = job.result()
psi_out=result.get_statevector()
#Contract out the ancilla with the known state
psi_out=psi_out.reshape(d**N,chi)
exp=psi_out.dot(phi_final)
#Prepare the MPS classically
thr,_=mps.create_statevector(A,phi_initial,phi_final,qiskit_ordering=True)
#Compare the resulting vectors (fixing phase and normalization)
exp=mps.normalize(mps.extract_phase(exp))
thr=mps.normalize(mps.extract_phase(thr))
print("The MPS is \n {}".format(thr))
print("The statevector produced by the circuit is \n {}".format(exp))
from qiskit import ClassicalRegister
N=5
chi=2
#The following is the standard representation of a GHZ state in terms of MPS
phi_initial=np.array([1,1])
phi_final=np.array([1,1])
T=np.zeros((d,chi,chi))
T[0,0,0]=1
T[1,1,1]=1
A=[]
for _ in range(N):
A.append(T)
#Create the circuit, store the relevant wavefunction is register 'reg' and measure
qc, reg = mps.MPS_to_circuit(A, phi_initial, phi_final)
creg=ClassicalRegister(N)
qc.add_register(creg)
qc.measure(reg,creg)
#Run on a simulator
backend = BasicAer.get_backend("qasm_simulator")
job = execute(qc, backend)
result = job.result()
counts = result.get_counts(qc)
print("\nTotal counts are:",counts)
|
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/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Toffoli decomposition explained in Lemma 8 from
Quantum Circuits for Isometries.
https://arxiv.org/abs/1501.06911
'''
from numpy import pi
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
class Toffoli(Gate):
def __init__(self, cancel=None):
self.cancel = cancel
super().__init__('toffoli', 3, [], "Toffoli")
def _define(self):
self.definition = QuantumCircuit(3)
theta = pi / 4.
control_qubits = self.definition.qubits[:2]
target_qubit = self.definition.qubits[-1]
if self.cancel != 'left':
self.definition.u(theta=-theta, phi=0., lam=0., qubit=target_qubit)
self.definition.cx(control_qubits[0], target_qubit)
self.definition.u(theta=-theta, phi=0., lam=0., qubit=target_qubit)
self.definition.cx(control_qubits[1], target_qubit)
if self.cancel != 'right':
self.definition.u(theta=theta, phi=0., lam=0., qubit=target_qubit)
self.definition.cx(control_qubits[0], target_qubit)
self.definition.u(theta=theta, phi=0., lam=0., qubit=target_qubit)
@staticmethod
def ccx(circuit, controls=None, target=None, cancel=None):
if controls is None or target is None:
circuit.append(Toffoli(cancel), circuit.qubits[:3])
else:
circuit.append(Toffoli(cancel), [*controls, target])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
|
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
|
MonitSharma
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
import math
# importing Qiskit
from qiskit import transpile
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
# import basic plot tools and circuits
from qiskit.visualization import plot_histogram
from qiskit.circuit.library import QFT
from qiskit.primitives import Sampler, Estimator
qpe = QuantumCircuit(4, 3)
qpe.x(3)
qpe.draw('mpl')
for qubit in range(3):
qpe.h(qubit)
qpe.draw('mpl')
repetitions = 1
for counting_qubit in range(3):
for i in range(repetitions):
qpe.cp(math.pi/4, counting_qubit, 3); # controlled-T
repetitions *= 2
qpe.draw('mpl')
qpe.barrier()
# Apply inverse QFT
qpe = qpe.compose(QFT(3, inverse=True), [0,1,2])
# Measure
qpe.barrier()
for n in range(3):
qpe.measure(n,n)
qpe.draw('mpl')
sampler = Sampler()
result = sampler.run(qpe).result()
answer = result.quasi_dists[0]
plot_histogram(answer)
# Create and set up circuit
qpe2 = QuantumCircuit(4, 3)
# Apply H-Gates to counting qubits:
for qubit in range(3):
qpe2.h(qubit)
# Prepare our eigenstate |psi>:
qpe2.x(3)
# Do the controlled-U operations:
angle = 2*math.pi/3
repetitions = 1
for counting_qubit in range(3):
for i in range(repetitions):
qpe2.cp(angle, counting_qubit, 3);
repetitions *= 2
# Do the inverse QFT:
qpe2 = qpe2.compose(QFT(3, inverse=True), [0,1,2])
# Measure of course!
for n in range(3):
qpe2.measure(n,n)
qpe2.draw('mpl')
# Let's see the results!
result = sampler.run(qpe2).result()
answer = result.quasi_dists[0]
plot_histogram(answer)
# Create and set up circuit
qpe3 = QuantumCircuit(6, 5)
# Apply H-Gates to counting qubits:
for qubit in range(5):
qpe3.h(qubit)
# Prepare our eigenstate |psi>:
qpe3.x(5)
# Do the controlled-U operations:
angle = 2*math.pi/3
repetitions = 1
for counting_qubit in range(5):
for i in range(repetitions):
qpe3.cp(angle, counting_qubit, 5);
repetitions *= 2
# Do the inverse QFT:
qpe3 = qpe3.compose(QFT(5, inverse=True), range(5))
# Measure of course!
qpe3.barrier()
for n in range(5):
qpe3.measure(n,n)
qpe3.draw('mpl')
# Let's see the results!
result = sampler.run(qpe3).result()
answer = result.quasi_dists[0]
plot_histogram(answer)
qpe.draw('mpl')
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
service.backends()
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to nqubits
service = QiskitRuntimeService()
backend = service.least_busy(operational=True,min_num_qubits=5)
print(backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
pm = generate_preset_pass_manager(optimization_level=3, backend=backend,seed_transpiler=11)
qc = pm.run(qpe)
qpe.draw('mpl',idle_wires=False)
# get the results from the computation
from qiskit.primitives import BackendSampler
sampler = BackendSampler(backend)
result = sampler.run(qpe).result()
answer = result.quasi_dists[0]
plot_histogram(answer)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 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.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import enum
import math
import ddt
import qiskit.qasm2
from qiskit.circuit import Gate, library as lib
from qiskit.test import QiskitTestCase
from test import combine # pylint: disable=wrong-import-order
# We need to use this enum a _bunch_ of times, so let's not give it a long name.
# pylint: disable=invalid-name
class T(enum.Enum):
# This is a deliberately stripped-down list that doesn't include most of the expression-specific
# tokens, because we don't want to complicate matters with those in tests of the general parser
# errors. We test the expression subparser elsewhere.
OPENQASM = "OPENQASM"
BARRIER = "barrier"
CREG = "creg"
GATE = "gate"
IF = "if"
INCLUDE = "include"
MEASURE = "measure"
OPAQUE = "opaque"
QREG = "qreg"
RESET = "reset"
PI = "pi"
ARROW = "->"
EQUALS = "=="
SEMICOLON = ";"
COMMA = ","
LPAREN = "("
RPAREN = ")"
LBRACKET = "["
RBRACKET = "]"
LBRACE = "{"
RBRACE = "}"
ID = "q"
REAL = "1.5"
INTEGER = "1"
FILENAME = '"qelib1.inc"'
def bad_token_parametrisation():
"""Generate the test cases for the "bad token" tests; this makes a sequence of OpenQASM 2
statements, then puts various invalid tokens after them to verify that the parser correctly
throws an error on them."""
token_set = frozenset(T)
def without(*tokens):
return token_set - set(tokens)
# ddt isn't a particularly great parametriser - it'll only correctly unpack tuples and lists in
# the way we really want, but if we want to control the test id, we also have to set `__name__`
# which isn't settable on either of those. We can't use unpack, then, so we just need a class
# to pass.
class BadTokenCase:
def __init__(self, statement, disallowed, name=None):
self.statement = statement
self.disallowed = disallowed
self.__name__ = name
for statement, disallowed in [
# This should only include stopping points where the next token is somewhat fixed; in
# places where there's a real decision to be made (such as number of qubits in a gate,
# or the statement type in a gate body), there should be a better error message.
#
# There's a large subset of OQ2 that's reducible to a regular language, so we _could_
# define that, build a DFA for it, and use that to very quickly generate a complete set
# of tests. That would be more complex to read and verify for correctness, though.
(
"",
without(
T.OPENQASM,
T.ID,
T.INCLUDE,
T.OPAQUE,
T.GATE,
T.QREG,
T.CREG,
T.IF,
T.RESET,
T.BARRIER,
T.MEASURE,
T.SEMICOLON,
),
),
("OPENQASM", without(T.REAL, T.INTEGER)),
("OPENQASM 2.0", without(T.SEMICOLON)),
("include", without(T.FILENAME)),
('include "qelib1.inc"', without(T.SEMICOLON)),
("opaque", without(T.ID)),
("opaque bell", without(T.LPAREN, T.ID, T.SEMICOLON)),
("opaque bell (", without(T.ID, T.RPAREN)),
("opaque bell (a", without(T.COMMA, T.RPAREN)),
("opaque bell (a,", without(T.ID, T.RPAREN)),
("opaque bell (a, b", without(T.COMMA, T.RPAREN)),
("opaque bell (a, b)", without(T.ID, T.SEMICOLON)),
("opaque bell (a, b) q1", without(T.COMMA, T.SEMICOLON)),
("opaque bell (a, b) q1,", without(T.ID, T.SEMICOLON)),
("opaque bell (a, b) q1, q2", without(T.COMMA, T.SEMICOLON)),
("gate", without(T.ID)),
("gate bell (", without(T.ID, T.RPAREN)),
("gate bell (a", without(T.COMMA, T.RPAREN)),
("gate bell (a,", without(T.ID, T.RPAREN)),
("gate bell (a, b", without(T.COMMA, T.RPAREN)),
("gate bell (a, b) q1", without(T.COMMA, T.LBRACE)),
("gate bell (a, b) q1,", without(T.ID, T.LBRACE)),
("gate bell (a, b) q1, q2", without(T.COMMA, T.LBRACE)),
("qreg", without(T.ID)),
("qreg reg", without(T.LBRACKET)),
("qreg reg[", without(T.INTEGER)),
("qreg reg[5", without(T.RBRACKET)),
("qreg reg[5]", without(T.SEMICOLON)),
("creg", without(T.ID)),
("creg reg", without(T.LBRACKET)),
("creg reg[", without(T.INTEGER)),
("creg reg[5", without(T.RBRACKET)),
("creg reg[5]", without(T.SEMICOLON)),
("CX", without(T.LPAREN, T.ID, T.SEMICOLON)),
("CX(", without(T.PI, T.INTEGER, T.REAL, T.ID, T.LPAREN, T.RPAREN)),
("CX()", without(T.ID, T.SEMICOLON)),
("CX q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)),
("CX q[", without(T.INTEGER)),
("CX q[0", without(T.RBRACKET)),
("CX q[0]", without(T.COMMA, T.SEMICOLON)),
("CX q[0],", without(T.ID, T.SEMICOLON)),
("CX q[0], q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)),
# No need to repeatedly "every" possible number of arguments.
("measure", without(T.ID)),
("measure q", without(T.LBRACKET, T.ARROW)),
("measure q[", without(T.INTEGER)),
("measure q[0", without(T.RBRACKET)),
("measure q[0]", without(T.ARROW)),
("measure q[0] ->", without(T.ID)),
("measure q[0] -> c", without(T.LBRACKET, T.SEMICOLON)),
("measure q[0] -> c[", without(T.INTEGER)),
("measure q[0] -> c[0", without(T.RBRACKET)),
("measure q[0] -> c[0]", without(T.SEMICOLON)),
("reset", without(T.ID)),
("reset q", without(T.LBRACKET, T.SEMICOLON)),
("reset q[", without(T.INTEGER)),
("reset q[0", without(T.RBRACKET)),
("reset q[0]", without(T.SEMICOLON)),
("barrier", without(T.ID, T.SEMICOLON)),
("barrier q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)),
("barrier q[", without(T.INTEGER)),
("barrier q[0", without(T.RBRACKET)),
("barrier q[0]", without(T.COMMA, T.SEMICOLON)),
("if", without(T.LPAREN)),
("if (", without(T.ID)),
("if (cond", without(T.EQUALS)),
("if (cond ==", without(T.INTEGER)),
("if (cond == 0", without(T.RPAREN)),
("if (cond == 0)", without(T.ID, T.RESET, T.MEASURE)),
]:
for token in disallowed:
yield BadTokenCase(statement, token.value, name=f"'{statement}'-{token.name.lower()}")
def eof_parametrisation():
for tokens in [
("OPENQASM", "2.0", ";"),
("include", '"qelib1.inc"', ";"),
("opaque", "bell", "(", "a", ",", "b", ")", "q1", ",", "q2", ";"),
("gate", "bell", "(", "a", ",", "b", ")", "q1", ",", "q2", "{", "}"),
("qreg", "qr", "[", "5", "]", ";"),
("creg", "cr", "[", "5", "]", ";"),
("CX", "(", ")", "q", "[", "0", "]", ",", "q", "[", "1", "]", ";"),
("measure", "q", "[", "0", "]", "->", "c", "[", "0", "]", ";"),
("reset", "q", "[", "0", "]", ";"),
("barrier", "q", ";"),
# No need to test every combination of `if`, really.
("if", "(", "cond", "==", "0", ")", "CX q[0], q[1];"),
]:
prefix = ""
for token in tokens[:-1]:
prefix = f"{prefix} {token}".strip()
yield prefix
@ddt.ddt
class TestIncompleteStructure(QiskitTestCase):
PRELUDE = "OPENQASM 2.0; qreg q[5]; creg c[5]; creg cond[1];"
@ddt.idata(bad_token_parametrisation())
def test_bad_token(self, case):
"""Test that the parser raises an error when an incorrect token is given."""
statement = case.statement
disallowed = case.disallowed
prelude = "" if statement.startswith("OPENQASM") else self.PRELUDE
full = f"{prelude} {statement} {disallowed}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "needed .*, but instead"):
qiskit.qasm2.loads(full)
@ddt.idata(eof_parametrisation())
def test_eof(self, statement):
"""Test that the parser raises an error when the end-of-file is reached instead of a token
that is required."""
prelude = "" if statement.startswith("OPENQASM") else self.PRELUDE
full = f"{prelude} {statement}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "unexpected end-of-file"):
qiskit.qasm2.loads(full)
def test_loading_directory(self):
"""Test that the correct error is raised when a file fails to open."""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "failed to read"):
qiskit.qasm2.load(".")
class TestVersion(QiskitTestCase):
def test_invalid_version(self):
program = "OPENQASM 3.0;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only handle OpenQASM 2.0"):
qiskit.qasm2.loads(program)
program = "OPENQASM 2.1;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only handle OpenQASM 2.0"):
qiskit.qasm2.loads(program)
program = "OPENQASM 20.e-1;"
with self.assertRaises(qiskit.qasm2.QASM2ParseError):
qiskit.qasm2.loads(program)
def test_openqasm_must_be_first_statement(self):
program = "qreg q[0]; OPENQASM 2.0;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "only the first statement"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestScoping(QiskitTestCase):
def test_register_use_before_definition(self):
program = "CX after[0], after[1]; qreg after[2];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined in this scope"):
qiskit.qasm2.loads(program)
program = "qreg q[2]; measure q[0] -> c[0]; creg c[2];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined in this scope"):
qiskit.qasm2.loads(program)
@combine(
definer=["qreg reg[2];", "creg reg[2];", "gate reg a {}", "opaque reg a;"],
bad_definer=["qreg reg[2];", "creg reg[2];"],
)
def test_register_already_defined(self, definer, bad_definer):
program = f"{definer} {bad_definer}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_qelib1_not_implicit(self):
program = """
OPENQASM 2.0;
qreg q[2];
cx q[0], q[1];
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_gates_before_definition(self):
program = """
qreg q[2];
cx q[0], q[1];
gate cx a, b {
CX a, b;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_gate_recursively(self):
program = """
gate cx a, b {
cx a, b;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_qubits_from_previous_gate(self):
program = """
gate cx a, b {
CX a, b;
}
gate other c {
CX a, b;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'a' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_parameters_from_previous_gate(self):
program = """
gate first(a, b) q {
U(a, 0, b) q;
}
gate second q {
U(a, 0, b) q;
}
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "'a' is not a parameter.*defined"
):
qiskit.qasm2.loads(program)
def test_cannot_access_quantum_registers_within_gate(self):
program = """
qreg q[2];
gate my_gate a {
CX a, q;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a quantum register"):
qiskit.qasm2.loads(program)
def test_parameters_not_defined_outside_gate(self):
program = """
gate my_gate(a) q {}
qreg qr[2];
U(a, 0, 0) qr;
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "'a' is not a parameter.*defined"
):
qiskit.qasm2.loads(program)
def test_qubits_not_defined_outside_gate(self):
program = """
gate my_gate(a) q {}
U(0, 0, 0) q;
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is not defined"):
qiskit.qasm2.loads(program)
@ddt.data('include "qelib1.inc";', "gate h q { }")
def test_gates_cannot_redefine(self, definer):
program = f"{definer} gate h q {{ }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_cannot_use_undeclared_register_conditional(self):
program = "qreg q[1]; if (c == 0) U(0, 0, 0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestTyping(QiskitTestCase):
@ddt.data(
"CX q[0], U;",
"measure U -> c[0];",
"measure q[0] -> U;",
"reset U;",
"barrier U;",
"if (U == 0) CX q[0], q[1];",
"gate my_gate a { U(0, 0, 0) U; }",
)
def test_cannot_use_gates_incorrectly(self, usage):
program = f"qreg q[2]; creg c[2]; {usage}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'U' is a gate"):
qiskit.qasm2.loads(program)
@ddt.data(
"measure q[0] -> q[1];",
"if (q == 0) CX q[0], q[1];",
"q q[0], q[1];",
"gate my_gate a { U(0, 0, 0) q; }",
)
def test_cannot_use_qregs_incorrectly(self, usage):
program = f"qreg q[2]; creg c[2]; {usage}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a quantum register"):
qiskit.qasm2.loads(program)
@ddt.data(
"CX q[0], c[1];",
"measure c[0] -> c[1];",
"reset c[0];",
"barrier c[0];",
"c q[0], q[1];",
"gate my_gate a { U(0, 0, 0) c; }",
)
def test_cannot_use_cregs_incorrectly(self, usage):
program = f"qreg q[2]; creg c[2]; {usage}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'c' is a classical register"):
qiskit.qasm2.loads(program)
def test_cannot_use_parameters_incorrectly(self):
program = "gate my_gate(p) q { CX p, q; }"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'p' is a parameter"):
qiskit.qasm2.loads(program)
def test_cannot_use_qubits_incorrectly(self):
program = "gate my_gate(p) q { U(q, q, q) q; }"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a gate qubit"):
qiskit.qasm2.loads(program)
@ddt.data(("h", 0), ("h", 2), ("CX", 0), ("CX", 1), ("CX", 3), ("ccx", 2), ("ccx", 4))
@ddt.unpack
def test_gates_accept_only_valid_number_qubits(self, gate, bad_count):
arguments = ", ".join(f"q[{i}]" for i in range(bad_count))
program = f'include "qelib1.inc"; qreg q[5];\n{gate} {arguments};'
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "takes .* quantum arguments?"):
qiskit.qasm2.loads(program)
@ddt.data(("U", 2), ("U", 4), ("rx", 0), ("rx", 2), ("u3", 1))
@ddt.unpack
def test_gates_accept_only_valid_number_parameters(self, gate, bad_count):
arguments = ", ".join("0" for _ in [None] * bad_count)
program = f'include "qelib1.inc"; qreg q[5];\n{gate}({arguments}) q[0];'
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "takes .* parameters?"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestGateDefinition(QiskitTestCase):
def test_no_zero_qubit(self):
program = "gate zero {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
program = "gate zero(a) {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
def test_no_zero_qubit_opaque(self):
program = "opaque zero;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
program = "opaque zero(a);"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
def test_cannot_subscript_qubit(self):
program = """
gate my_gate a {
CX a[0], a[1];
}
"""
with self.assertRaises(qiskit.qasm2.QASM2ParseError):
qiskit.qasm2.loads(program)
def test_cannot_repeat_parameters(self):
program = "gate my_gate(a, a) q {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_cannot_repeat_qubits(self):
program = "gate my_gate a, a {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_qubit_cannot_shadow_parameter(self):
program = "gate my_gate(a) a {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
@ddt.data("measure q -> c;", "reset q", "if (c == 0) U(0, 0, 0) q;", "gate my_x q {}")
def test_definition_cannot_contain_nonunitary(self, statement):
program = f"OPENQASM 2.0; creg c[5]; gate my_gate q {{ {statement} }}"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "only gate applications are valid"
):
qiskit.qasm2.loads(program)
def test_cannot_redefine_u(self):
program = "gate U(a, b, c) q {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_cannot_redefine_cx(self):
program = "gate CX a, b {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestBitResolution(QiskitTestCase):
def test_disallow_out_of_range(self):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"):
qiskit.qasm2.loads("qreg q[2]; U(0, 0, 0) q[2];")
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"):
qiskit.qasm2.loads("qreg q[2]; creg c[2]; measure q[2] -> c[0];")
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"):
qiskit.qasm2.loads("qreg q[2]; creg c[2]; measure q[0] -> c[2];")
@combine(
conditional=[True, False],
call=[
"CX q1[0], q1[0];",
"CX q1, q1[0];",
"CX q1[0], q1;",
"CX q1, q1;",
"ccx q1[0], q1[1], q1[0];",
"ccx q2, q1, q2[0];",
],
)
def test_disallow_duplicate_qubits(self, call, conditional):
program = """
include "qelib1.inc";
qreg q1[3];
qreg q2[3];
qreg q3[3];
"""
if conditional:
program += "creg cond[1]; if (cond == 0) "
program += call
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "duplicate qubit"):
qiskit.qasm2.loads(program)
@ddt.data(
(("q1[1]", "q2[2]"), "CX q1, q2"),
(("q1[1]", "q2[2]"), "CX q2, q1"),
(("q1[3]", "q2[2]"), "CX q1, q2"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q1, q2, q3"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q2, q3, q1"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q3, q1, q2"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q1, q2[0], q3"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q2[0], q3, q1"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q3, q1, q2[0]"),
)
@ddt.unpack
def test_incorrect_gate_broadcast_lengths(self, registers, call):
setup = 'include "qelib1.inc";\n' + "\n".join(f"qreg {reg};" for reg in registers)
program = f"{setup}\n{call};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
cond = "creg cond[1];\nif (cond == 0)"
program = f"{setup}\n{cond} {call};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
@ddt.data(
("qreg q[2]; creg c[2];", "q[0] -> c"),
("qreg q[2]; creg c[2];", "q -> c[0]"),
("qreg q[1]; creg c[2];", "q -> c[0]"),
("qreg q[2]; creg c[1];", "q[0] -> c"),
("qreg q[2]; creg c[3];", "q -> c"),
)
@ddt.unpack
def test_incorrect_measure_broadcast_lengths(self, setup, operands):
program = f"{setup}\nmeasure {operands};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
program = f"{setup}\ncreg cond[1];\nif (cond == 0) measure {operands};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestCustomInstructions(QiskitTestCase):
def test_cannot_use_custom_before_definition(self):
program = "qreg q[2]; my_gate q[0], q[1];"
class MyGate(Gate):
def __init__(self):
super().__init__("my_gate", 2, [])
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "cannot use .* before definition"
):
qiskit.qasm2.loads(
program,
custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 0, 2, MyGate)],
)
def test_cannot_misdefine_u(self):
program = "qreg q[1]; U(0.5, 0.25) q[0]"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "custom instruction .* mismatched"
):
qiskit.qasm2.loads(
program, custom_instructions=[qiskit.qasm2.CustomInstruction("U", 2, 1, lib.U2Gate)]
)
def test_cannot_misdefine_cx(self):
program = "qreg q[1]; CX q[0]"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "custom instruction .* mismatched"
):
qiskit.qasm2.loads(
program, custom_instructions=[qiskit.qasm2.CustomInstruction("CX", 0, 1, lib.XGate)]
)
def test_builtin_is_typechecked(self):
program = "qreg q[1]; my(0.5) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' takes 2 quantum arguments"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate, builtin=True)
],
)
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' takes 2 parameters"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 2, 1, lib.U2Gate, builtin=True)
],
)
def test_cannot_define_builtin_twice(self):
program = "gate builtin q {}; gate builtin q {};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'builtin' is already defined"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("builtin", 0, 1, lambda: Gate("builtin", 1, []))
],
)
def test_cannot_redefine_custom_u(self):
program = "gate U(a, b, c) q {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("U", 3, 1, lib.UGate, builtin=True)
],
)
def test_cannot_redefine_custom_cx(self):
program = "gate CX a, b {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("CX", 0, 2, lib.CXGate, builtin=True)
],
)
@combine(
program=["gate my(a) q {}", "opaque my(a) q;"],
builtin=[True, False],
)
def test_custom_definition_must_match_gate(self, program, builtin):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' is mismatched"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate, builtin=builtin)
],
)
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' is mismatched"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 2, 1, lib.U2Gate, builtin=builtin)
],
)
def test_cannot_have_duplicate_customs(self):
customs = [
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate),
qiskit.qasm2.CustomInstruction("x", 0, 1, lib.XGate),
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RZZGate),
]
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "duplicate custom instruction"):
qiskit.qasm2.loads("", custom_instructions=customs)
def test_qiskit_delay_float_input_wraps_exception(self):
program = "opaque delay(t) q; qreg q[1]; delay(1.5) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only accept an integer"):
qiskit.qasm2.loads(program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS)
def test_u0_float_input_wraps_exception(self):
program = "opaque u0(n) q; qreg q[1]; u0(1.1) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "must be an integer"):
qiskit.qasm2.loads(program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS)
@ddt.ddt
class TestCustomClassical(QiskitTestCase):
@ddt.data("cos", "exp", "sin", "sqrt", "tan", "ln")
def test_cannot_override_builtin(self, builtin):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"cannot override builtin"):
qiskit.qasm2.loads(
"",
custom_classical=[qiskit.qasm2.CustomClassical(builtin, 1, math.exp)],
)
def test_duplicate_names_disallowed(self):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"duplicate custom classical"):
qiskit.qasm2.loads(
"",
custom_classical=[
qiskit.qasm2.CustomClassical("f", 1, math.exp),
qiskit.qasm2.CustomClassical("f", 1, math.exp),
],
)
def test_cannot_shadow_custom_instruction(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"custom classical.*naming clash"
):
qiskit.qasm2.loads(
"",
custom_instructions=[
qiskit.qasm2.CustomInstruction("f", 0, 1, lib.RXGate, builtin=True)
],
custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)],
)
def test_cannot_shadow_builtin_instruction(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"custom classical.*cannot shadow"
):
qiskit.qasm2.loads(
"",
custom_classical=[qiskit.qasm2.CustomClassical("U", 1, math.exp)],
)
def test_cannot_shadow_with_gate_definition(self):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"'f' is already defined"):
qiskit.qasm2.loads(
"gate f q {}",
custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)],
)
@ddt.data("qreg", "creg")
def test_cannot_shadow_with_register_definition(self, regtype):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"'f' is already defined"):
qiskit.qasm2.loads(
f"{regtype} f[2];",
custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)],
)
@ddt.data((0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1))
@ddt.unpack
def test_mismatched_argument_count(self, n_good, n_bad):
arg_string = ", ".join(["0" for _ in [None] * n_bad])
program = f"""
qreg q[1];
U(f({arg_string}), 0, 0) q[0];
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"custom function argument-count mismatch"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", n_good, lambda *_: 0)]
)
def test_output_type_error_is_caught(self):
program = """
qreg q[1];
U(f(), 0, 0) q[0];
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"user.*returned non-float"):
qiskit.qasm2.loads(
program,
custom_classical=[qiskit.qasm2.CustomClassical("f", 0, lambda: "not a float")],
)
def test_inner_exception_is_wrapped(self):
inner_exception = Exception("custom exception")
def raises():
raise inner_exception
program = """
qreg q[1];
U(raises(), 0, 0) q[0];
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "caught exception when constant folding"
) as excinfo:
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("raises", 0, raises)]
)
assert excinfo.exception.__cause__ is inner_exception
def test_cannot_be_used_as_gate(self):
program = """
qreg q[1];
f(0) q[0];
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)]
)
def test_cannot_be_used_as_qarg(self):
program = """
U(0, 0, 0) f;
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)]
)
def test_cannot_be_used_as_carg(self):
program = """
qreg q[1];
measure q[0] -> f;
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)]
)
@ddt.ddt
class TestStrict(QiskitTestCase):
@ddt.data(
"gate my_gate(p0, p1,) q0, q1 {}",
"gate my_gate(p0, p1) q0, q1, {}",
"opaque my_gate(p0, p1,) q0, q1;",
"opaque my_gate(p0, p1) q0, q1,;",
'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125,) q[0], q[1];',
'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125) q[0], q[1],;',
"qreg q[2]; barrier q[0], q[1],;",
'include "qelib1.inc"; qreg q[1]; rx(sin(pi,)) q[0];',
)
def test_trailing_comma(self, program):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*trailing comma"):
qiskit.qasm2.loads("OPENQASM 2.0;\n" + program, strict=True)
def test_trailing_semicolon_after_gate(self):
program = "OPENQASM 2.0; gate my_gate q {};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*extra semicolon"):
qiskit.qasm2.loads(program, strict=True)
def test_empty_statement(self):
program = "OPENQASM 2.0; ;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*empty statement"):
qiskit.qasm2.loads(program, strict=True)
def test_required_version_regular(self):
program = "qreg q[1];"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] the first statement"
):
qiskit.qasm2.loads(program, strict=True)
def test_required_version_empty(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] .*needed a version statement"
):
qiskit.qasm2.loads("", strict=True)
def test_barrier_requires_args(self):
program = "OPENQASM 2.0; qreg q[2]; barrier;"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] barrier statements must have at least one"
):
qiskit.qasm2.loads(program, strict=True)
|
https://github.com/qiskit-community/qiskit-dell-runtime
|
qiskit-community
|
import itertools
import json
import numpy as np
from numpy.random import RandomState
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.compiler import transpile
from cvxopt import matrix, solvers # pylint: disable=import-error
class QKA:
def __init__(self, feature_map, backend, initial_layout=None, user_messenger=None):
self.feature_map = feature_map
self.feature_map_circuit = self.feature_map.construct_circuit
self.backend = backend
self.initial_layout = initial_layout
self.num_parameters = self.feature_map._num_parameters
self._user_messenger = user_messenger
self.result = {}
self.kernel_matrix = KernelMatrix(
feature_map=self.feature_map, backend=self.backend, initial_layout=self.initial_layout
)
def spsa_parameters(self):
spsa_params = np.zeros((5))
spsa_params[0] = 0.05 # a
spsa_params[1] = 0.1 # c
spsa_params[2] = 0.602 # alpha
spsa_params[3] = 0.101 # gamma
spsa_params[4] = 0 # A
return spsa_params
def cvxopt_solver(self, K, y, C, max_iters=10000, show_progress=False):
if y.ndim == 1:
y = y[:, np.newaxis]
H = np.outer(y, y) * K
f = -np.ones(y.shape)
n = K.shape[1] # number of training points
y = y.astype("float")
P = matrix(H)
q = matrix(f)
G = matrix(np.vstack((-np.eye((n)), np.eye((n)))))
h = matrix(np.vstack((np.zeros((n, 1)), np.ones((n, 1)) * C)))
A = matrix(y, y.T.shape)
b = matrix(np.zeros(1), (1, 1))
solvers.options["maxiters"] = max_iters
solvers.options["show_progress"] = show_progress
ret = solvers.qp(P, q, G, h, A, b, kktsolver="ldl")
return ret
def spsa_step_one(self, lambdas, spsa_params, count):
prng = RandomState(count)
c_spsa = float(spsa_params[1]) / np.power(count + 1, spsa_params[3])
delta = 2 * prng.randint(0, 2, size=np.shape(lambdas)[0]) - 1
lambda_plus = lambdas + c_spsa * delta
lambda_minus = lambdas - c_spsa * delta
return lambda_plus, lambda_minus, delta
def spsa_step_two(self, cost_plus, cost_minus, lambdas, spsa_params, delta, count):
a_spsa = float(spsa_params[0]) / np.power(count + 1 + spsa_params[4], spsa_params[2])
c_spsa = float(spsa_params[1]) / np.power(count + 1, spsa_params[3])
g_spsa = (cost_plus - cost_minus) * delta / (2.0 * c_spsa)
lambdas_new = lambdas - a_spsa * g_spsa
lambdas_new = lambdas_new.flatten()
cost_final = (cost_plus + cost_minus) / 2
return cost_final, lambdas_new
def align_kernel(self, data, labels, initial_kernel_parameters=None, maxiters=1, C=1):
if initial_kernel_parameters is not None:
lambdas = initial_kernel_parameters
else:
lambdas = np.random.uniform(-1.0, 1.0, size=(self.num_parameters))
spsa_params = self.spsa_parameters()
lambda_save = []
cost_final_save = []
for count in range(maxiters):
lambda_plus, lambda_minus, delta = self.spsa_step_one(
lambdas=lambdas, spsa_params=spsa_params, count=count
)
kernel_plus = self.kernel_matrix.construct_kernel_matrix(
x1_vec=data, x2_vec=data, parameters=lambda_plus
)
kernel_minus = self.kernel_matrix.construct_kernel_matrix(
x1_vec=data, x2_vec=data, parameters=lambda_minus
)
ret_plus = self.cvxopt_solver(K=kernel_plus, y=labels, C=C)
cost_plus = -1 * ret_plus["primal objective"]
ret_minus = self.cvxopt_solver(K=kernel_minus, y=labels, C=C)
cost_minus = -1 * ret_minus["primal objective"]
cost_final, lambda_best = self.spsa_step_two(
cost_plus=cost_plus,
cost_minus=cost_minus,
lambdas=lambdas,
spsa_params=spsa_params,
delta=delta,
count=count,
)
lambdas = lambda_best
interim_result = {"cost": cost_final, "kernel_parameters": lambdas}
print(interim_result)
self._user_messenger.publish(interim_result)
lambda_save.append(lambdas)
cost_final_save.append(cost_final)
# Evaluate aligned kernel matrix with optimized set of
# parameters averaged over last 10% of SPSA steps:
num_last_lambdas = int(len(lambda_save) * 0.10)
if num_last_lambdas > 0:
last_lambdas = np.array(lambda_save)[-num_last_lambdas:, :]
lambdas = np.sum(last_lambdas, axis=0) / num_last_lambdas
else:
lambdas = np.array(lambda_save)[-1, :]
kernel_best = self.kernel_matrix.construct_kernel_matrix(
x1_vec=data, x2_vec=data, parameters=lambdas
)
self.result["aligned_kernel_parameters"] = lambdas
self.result["aligned_kernel_matrix"] = kernel_best
return self.result
class KernelMatrix:
def __init__(self, feature_map, backend, initial_layout=None):
self._feature_map = feature_map
self._feature_map_circuit = self._feature_map.construct_circuit
self._backend = backend
self._initial_layout = initial_layout
self.results = {}
def construct_kernel_matrix(self, x1_vec, x2_vec, parameters=None):
is_identical = False
if np.array_equal(x1_vec, x2_vec):
is_identical = True
experiments = []
measurement_basis = "0" * self._feature_map._num_qubits
if is_identical:
my_product_list = list(
itertools.combinations(range(len(x1_vec)), 2)
) # all pairwise combos of datapoint indices
for index_1, index_2 in my_product_list:
circuit_1 = self._feature_map_circuit(
x=x1_vec[index_1], parameters=parameters, name="{}_{}".format(index_1, index_2)
)
circuit_2 = self._feature_map_circuit(
x=x1_vec[index_2], parameters=parameters, inverse=True
)
circuit = circuit_1.compose(circuit_2)
circuit.measure_all()
experiments.append(circuit)
experiments = transpile(
experiments, backend=self._backend, initial_layout=self._initial_layout
)
program_data = self._backend.run(experiments, shots=8192).result()
self.results["program_data"] = program_data
mat = np.eye(
len(x1_vec), len(x1_vec)
) # kernel matrix element on the diagonal is always 1
for experiment, [index_1, index_2] in enumerate(my_product_list):
counts = program_data.get_counts(experiment=experiment)
shots = sum(counts.values())
mat[index_1][index_2] = (
counts.get(measurement_basis, 0) / shots
) # kernel matrix element is the probability of measuring all 0s
mat[index_2][index_1] = mat[index_1][index_2] # kernel matrix is symmetric
return mat
else:
for index_1, point_1 in enumerate(x1_vec):
for index_2, point_2 in enumerate(x2_vec):
circuit_1 = self._feature_map_circuit(
x=point_1, parameters=parameters, name="{}_{}".format(index_1, index_2)
)
circuit_2 = self._feature_map_circuit(
x=point_2, parameters=parameters, inverse=True
)
circuit = circuit_1.compose(circuit_2)
circuit.measure_all()
experiments.append(circuit)
experiments = transpile(
experiments, backend=self._backend, initial_layout=self._initial_layout
)
program_data = self._backend.run(experiments, shots=8192).result()
self.results["program_data"] = program_data
mat = np.zeros((len(x1_vec), len(x2_vec)))
i = 0
for index_1, _ in enumerate(x1_vec):
for index_2, _ in enumerate(x2_vec):
counts = program_data.get_counts(experiment=i)
shots = sum(counts.values())
mat[index_1][index_2] = counts.get(measurement_basis, 0) / shots
i += 1
return mat
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# upgrade/update pip library
!pip install --upgrade pip
# install the last official version of the grader from IBM's Qiskit Community
!pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git@main
# import the quantum circuit, Aer,
# and execute instruction
# from the IBM' Qiskit library
from qiskit import QuantumCircuit, Aer, execute
# import the numpy library
import numpy as np
# import the plot histogram function
# from the IBM's Qiskit Visualization module
from qiskit.visualization import plot_histogram
# import the plotting from
# the Matplotlib's Pyplot module
import matplotlib.pyplot as plt
# import the GCD (Greatest Common Divisor)
# from the built-in mathematics module
from math import gcd
# define the function to genera the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
def qft(n):
# creates a quantum circuit with n qubits,
# implementing the Quantum Fourier Transform (QFT)
circuit = QuantumCircuit(n)
# define the function to perform the Swap gates
# on the quantum registers of the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
def swap_registers( circuit, n ):
# for a number of iterations equal to half of
# the number of qubits used on the quantum circuit
# for the Quantum Fourier Transform (QFT)
for qubit in range( n // 2 ):
# apply the Swap gate between the kth qubit and
# the (n - k)th qubit on the quantum register defined before
circuit.swap( qubit, ( n - qubit - 1 ) )
# return the quantum circuit with the Swap gates
# applied on the n qubits of the quantum register,
# to implement the Quantum Fourier Transform (QFT)
return circuit
# define the function to perform the Controlled-Phase gates
# on the quantum registers of the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
# (it is applied to the first n qubits,
# and without the Swap gates performed)
def qft_rotations( circuit, n ):
# if it is the last opposite iteration
if n == 0:
# return with the Controlled-Phase gates
# on the quantum registers of the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
# (it is applied to the first n qubits,
# and without the Swap gates performed)
return circuit
# iterates on the opposite direction,
# setting a new nth iteration
n -= 1
# apply the Hadamard gate to the kth qubit,
# on the quantum register defined before,
# and iterating on the opposite direction
circuit.h(n)
# for the remaining qubits to consider
# i the kth opposite iteration
for qubit in range(n):
# apply the Controlled-Phase gate for
# the theta angle equal to (pi / 2)^(n - k),
# with control on the nth qubit and target on the kth qubit
circuit.cp( ( np.pi / 2 )**( n - qubit ), qubit, n )
# call this fuction recursively for
# the next opposite iteration
qft_rotations( circuit, n )
# perform the Controlled-Phase gates
# on the quantum registers of the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
# (it is applied to the first n qubits,
# and without the Swap gates performed)
qft_rotations( circuit, n )
# perform the Swap gates on the quantum registers of
# the quantum circuit for the Quantum Fourier Transform (QFT) on n qubits
swap_registers( circuit, n )
# return the quantum circuit with n qubits,
# implementing the Quantum Fourier Transform (QFT)
return circuit
# define the function to genera the quantum circuit
# for the Inverse Quantum Fourier Transform (IQFT) on n qubits
def qft_dagger( circuit, n ):
# note: do not forget to apply again the Swap gates
# to peform its inverse operation
# for a number of iterations equal to half of
# the number of qubits used on the quantum circuit
# for the Inverse Quantum Fourier Transform (IQFT)
for qubit in range( n // 2 ):
# apply the Swap gate between the kth qubit and
# the (n - k)th qubit on the quantum register defined before
circuit.swap( qubit, ( n - qubit - 1 ) )
# for each number of qubits of the quantum register defined before,
# to consider in the current jth iteration
for j in range(n):
# for each mth qubit of the quantum register defined before,
# to consider in the current iteration
for m in range(j):
# apply the Controlled-Phase gate for
# the theta angle equal to -pi / ( 2^( j - m ) ),
# with control on the mth qubit and target on the jth qubit
qc.cp( -np.pi / float( 2**( j - m ) ), m, j )
# apply the Hadamard gate to the jth qubit
# on the quantum register defined before
qc.h(j)
# define the size n of the quantum register to
# store the phase information
phase_register_size = 4
# create a quantum circuit with a quantum register
# with n qubits and a classical register with n bits,
# to implement the Quantum Phase Estimation (QPE) for n = 4 qubits
qpe4 = QuantumCircuit( ( phase_register_size + 1 ),
phase_register_size )
####################################################
#### insert your code here ####
# define the function to perform the Quantum Hadamard Transform on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
def apply_quantum_hadamard_transform( circuit, n ):
# for each qubit of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE) for n qubits
for qubit_idx in range(n):
# apply the Hadamard gate to the current ith qubit
circuit.h(qubit_idx)
# define the function to perform the Controlled-Phase gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
def apply_controlled_phases( theta, circuit, n ):
# for each ith step according to
# the number of n qubits used
for step in range(n):
# compute the iteration parameter t
# as a power of 2, according to the current step
t = 2**step
# for each iteration according to
# the iteration parameter t
for _ in range(t):
# apply the Controlled-Phase gate for the theta angle,
# with control on the ith qubit and target on the last qubit
circuit.cp( theta, step, n )
# define the function to perform the Swap gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
def apply_swaps( circuit, n ):
# for a number of iterations equal to half of
# the number of phase counting qubits used
# on the resepective quantum circuit
# for the Quantum Fourier Transform (QFT)
for qubit_idx in range( phase_register_size // 2 ):
# apply the Swap gate between the kth qubit and
# the (n - k)th qubit on the quantum register defined before
circuit.swap( qubit_idx, ( n - qubit_idx - 1 ) )
# define the function to perform
# the Inverse Quantum Fourier Transform (IQFT) on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
def apply_quantum_fourier_transform_inverse( circuit, n ):
# for each qubit on the quantum register
for j in range(n):
# for each additional mth qubit ranging to
# the current jth qubit being iterated before
for m in range(j):
# apply the Controlled-Phase gate for
# the theta angle equal to -pi / ( 2^( j - m ) ),
# with control on the mth qubit and target on the jth qubit
circuit.cp( -np.pi / float( 2**( j - m ) ), m, j )
# apply the Hadamard gate to the jth qubit (system's qubit)
circuit.h(j)
# define the function to perform a measurement of
# all the n qubits on the quantum register of a quantum circuit,
# and storing the classical outcomes on the n bits of
# the classical register of that same quantum circuit
def measure_all_qubits(circuit, n):
# for each pair of qubits and bits
for j in range(n):
# measure the current qubit on the quantum register,
# and stores the classical outcome obtained
# in the current bit on the classical register
circuit.measure(j, j)
# define the function to perform the Quantum Phase Estimation (QPE)
# according to a theta angle given, on a quantum circuit of n qubits
def quantum_phase_estimation( theta, circuit, n ):
# perform the Quantum Hadamard Transform on
# the n qubits of the quantum register of
# the quantum circuit implementing
# the Quantum Phase Estimation (QPE)
apply_quantum_hadamard_transform( circuit, n )
# apply the Pauli-X gate to the last qubit on
# the quantum register of the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.x(n)
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.barrier()
# perform the Controlled-Phase gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_controlled_phases( theta, circuit, n )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.barrier()
# perform the Swap gates on the n qubits of
# the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_swaps( circuit, n )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.barrier()
# perform the Inverse Quantum Fourier Transform (IQFT) on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
apply_quantum_fourier_transform_inverse( circuit, n )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.barrier()
# perform a measurement of all the n qubits on
# the quantum register of the quantum circuit of
# the Quantum Phase Estimation (QPE) and storing
# the classical outcomes on the n bits of
# the classical register of that same quantum circuit
measure_all_qubits( circuit, n )
####################################################
# define the theta angle to be equal to (2 * pi) / 3
theta = ( 2 * np.pi ) / 3
# perform the Quantum Phase Estimation (QPE)
# according to the theta angle defined,
# on the quantum circuit of n qubits defined before
quantum_phase_estimation( theta, qpe4, phase_register_size )
# draw the quantum circuit implementing
# the Quantum Phase Estimation (QPE) defined before
qpe4.draw("mpl")
# run this cell to simulate 'qpe4' and
# to plot the histogram of the result
# create the Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 20000
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation
count_qpe4 = execute( qpe4, sim, shots=shots ).result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n = 4 counting qubits
plot_histogram( count_qpe4, figsize=(9,5) )
# submit your answer
# import the grader for the exercise 1 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex1
# grade the exercise 1 of the lab 3
grade_lab3_ex1( count_qpe4 )
# process the result count data to determine accuracy of
# the estimated phase and grab the highest probability measurement
# define the maximum number of counts which will be obtained
max_binary_counts = 0
# define the maximum binary value which will be obtained
max_binary_val = ""
# for each count obtained from the quantum simulation of
# the Quantum Phase Estimation (QPE)
for key, item in count_qpe4.items():
# if the current number of counts is greater than
# the current maximum number of counts obtained
if item > max_binary_counts:
# update the maximum number of counts obtained
max_binary_counts = item
# update the maximum binary value obtained
max_binary_val = key
#########################################
#### your function to convert a binary ####
#### string to a decimal number goes here ####
# define the function to convert
# a binary string to a decimal number
def bin_to_decimal( binary_string ):
# return a binary string
# converted to a decimal number
return int( binary_string, 2 )
# calculate the estimated phase obtained
# from the quantum simulation of
# the Quantum Phase Estimation (QPE)
estimated_phase = ( bin_to_decimal(max_binary_val) / 2**phase_register_size )
# calculate the phase accuracy
# which can be obtained from
# the quantum simulation of
# the Quantum Phase Estimation (QPE)
# with the quantum circuit defined before,
# inverse of the highest power of 2
# (i.e. smallest decimal) this quantum circuit can estimate
phase_accuracy_window = 2**( -phase_register_size )
# submit your answer
# import the grader for the exercise 2 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex2
# grade the exercise 2 of the lab 3
grade_lab3_ex2( [ estimated_phase, phase_accuracy_window ] )
# import the IBM's Provider from
# the Qiskit's IBM Provider module
from qiskit_ibm_provider import IBMProvider
# import the transpile function from
# the IBM's Qikist Compiler module
from qiskit.compiler import transpile
# create an IBM's Provider object
provider = IBMProvider()
# define the hub for the IBM's Provider
hub = "summer-school-6"
# define the group for the IBM's Provider
group = "group-3"
# define the project for the IBM's Provider
project = "7048813929"
# define the backend's name for the IBM's Provider
backend_name = "ibmq_manila"
# retrieve the backend from the IBM's Provider
backend = provider.get_backend( backend_name, instance=f"{hub}/{group}/{project}" )
##########################################
#### your code goes here ####
# define the initial maximum quantum circuit depth obtained
max_depth = 1e-20
# define the initial minimum quantum circuit depth obtained
min_depth = 1e20
# define the number of trials to transpile/optimize
# the quantum circuit for the Quantum Phase Estimation (QPE)
num_trials = 10
# for each trial to transpile/optimize the quantum circuit
# for the Quantum Phase Estimation (QPE)
for _ in range(num_trials):
# transpile/optimize the quantum circuit
# for the Quantum Phase Estimation (QPE),
# for the current considering trial
transpiled_qpe4 = transpile( qpe4, backend, optimization_level=3 )
# retrieve the quantum circuit depth of
# the transpiled/optimized quantum circuit
# for the Quantum Phase Estimation (QPE)
transpiled_qpe4_depth = transpiled_qpe4.depth()
# if the quantum circuit depth of
# the transpiled/optimized quantum circuit
# for the Quantum Phase Estimation (QPE)
# is greater than the current maximum
# quantum circuit depth obtained
if transpiled_qpe4_depth > max_depth:
# update the maximum quantum circuit depth
# obtained with the current quantum circuit depth
max_depth = transpiled_qpe4_depth
# update the quantum circuit with the maximum depth
# with the current quantum circuit transpiled/optimized
max_depth_qpe = transpiled_qpe4
# if the quantum circuit depth of
# the transpiled/optimized quantum circuit
# for the Quantum Phase Estimation (QPE)
# is lower than the current minimum
# quantum circuit depth obtained
if transpiled_qpe4_depth < min_depth:
# update the minimum quantum circuit depth
# obtained with the current quantum circuit depth
min_depth = transpiled_qpe4_depth
# update the quantum circuit with the minimum depth
# with the current quantum circuit transpiled/optimized
min_depth_qpe = transpiled_qpe4
##########################################
# submit your answer
# import the grader for the exercise 3 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex3
# grade the exercise 3 of the lab 3
grade_lab3_ex3( [ max_depth_qpe, min_depth_qpe ] )
# define the number of shots
#shots = 2000
# OPTIONAL: run the minimum depth quantum circuit for
# the Quantum Phase Estimation (QPE)
# execute and retrieve the job for the simulation
# for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the minimum quantum circuit depth
#job_min_qpe4 = backend.run( min_depth_qpe, sim, shots=shots )
# print the id of the job of the simulation
# for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the minimum quantum circuit depth
#print( job_min_qpe4.job_id() )
# gather the result counts data
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the minimum quantum circuit depth
#count_min_qpe4 = job_min_qpe4.result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n = 4 counting qubits,
# and using the minimum quantum circuit depth
#plot_histogram( count_min_qpe4, figsize=(9,5) )
# OPTIONAL: run the maximum depth quantum circuit for
# the Quantum Phase Estimation (QPE)
# execute and retrieve the job for the simulation
# for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the maximum quantum circuit depth
#job_max_qpe4 = backend.run( max_depth_qpe, sim, shots=shots )
# print the id of the job of the simulation
# for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the maximum quantum circuit depth
#print( job_max_qpe4.job_id() )
# gather the result counts data
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the maximum quantum circuit depth
#count_max_qpe4 = job_max_qpe4.result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n = 4 counting qubits,
# and using the maximum quantum circuit depth
#plot_histogram( count_max_qpe4, figsize=(9,5) )
# define the function to perform the Quantum Hadamard Transform on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
def apply_quantum_hadamard_transform( circuit, n ):
# for each qubit of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE) for n qubits
for qubit_idx in range(n):
# apply the Hadamard gate to the current ith qubit
circuit.h(qubit_idx)
# define the function to perform the Controlled-Phase gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
def apply_controlled_phases( theta, circuit, n ):
# for each ith step according to
# the number of n qubits used
for step in range(n):
# compute the iteration parameter t
# as a power of 2, according to the current step
t = 2**step
# for each iteration according to
# the iteration parameter t
for _ in range(t):
# apply the Controlled-Phase gate for the theta angle,
# with control on the ith qubit and target on the last qubit
circuit.cp( theta, step, n )
# define the function to perform the Swap gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
def apply_swaps( circuit, n ):
# for a number of iterations equal to half of
# the number of phase counting qubits used
# on the resepective quantum circuit
# for the Quantum Fourier Transform (QFT)
for qubit_idx in range( phase_register_size // 2 ):
# apply the Swap gate between the kth qubit and
# the (n - k)th qubit on the quantum register defined before
circuit.swap( qubit_idx, ( n - qubit_idx - 1 ) )
# define the function to perform
# the Inverse Quantum Fourier Transform (IQFT) on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
def apply_quantum_fourier_transform_inverse( circuit, n ):
# for each jth qubit on the quantum register
for j in range(n):
# for each additional mth qubit ranging to
# the current jth qubit being iterated before
for m in range(j):
# apply the Controlled-Phase gate for
# the theta angle equal to -pi / ( 2^( j - m ) ),
# with control on the mth qubit and target on the jth qubit
circuit.cp( -np.pi / float( 2**( j - m ) ), m, j )
# apply the Hadamard gate to the jth qubit
circuit.h(j)
# define the function to perform a measurement of
# all the n qubits on the quantum register of a quantum circuit,
# and storing the classical outcomes on the n bits of
# the classical register of that same quantum circuit
def measure_all_qubits( circuit, n ):
# for each pair of qubits and bits
for j in range(n):
# measure the current qubit on the quantum register,
# and stores the classical outcome obtained
# in the current bit on the classical register
circuit.measure(j, j)
# define the function to create a quantum circuit,
# implementing the Quantum Phase Estimation (QPE) on (n + 1) qubits
def qpe_circuit(register_size):
#########################################
#### your code goes here ####
# define the theta phase angle to estimate
theta = 1/7
# create the quantum circuit with a quantum register with (n + 1) qubits
# and a classical register with n bits, intended to implement
# the Quantum Phase Estimation (QPE) on n qubits
qpe = QuantumCircuit( ( register_size + 1 ), register_size )
# perform the Quantum Hadamard Transform on
# the n qubits of the quantum register of
# the quantum circuit implementing
# the Quantum Phase Estimation (QPE)
apply_quantum_hadamard_transform( qpe, register_size )
# apply the Pauli-X gate to the last qubit on
# the quantum register of the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.x(register_size)
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.barrier()
# perform the Controlled-Phase gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_controlled_phases( theta, qpe, register_size )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.barrier()
# perform the Swap gates on the n qubits of
# the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_swaps( qpe, register_size )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.barrier()
# perform the Inverse Quantum Fourier Transform (IQFT) on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
apply_quantum_fourier_transform_inverse( qpe, register_size )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.barrier()
# perform a measurement of all the n qubits on
# the quantum register of the quantum circuit of
# the Quantum Phase Estimation (QPE) and storing
# the classical outcomes on the n bits of
# the classical register of that same quantum circuit
measure_all_qubits( qpe, register_size )
# return the quantum circuit, implementing
# the Quantum Phase Estimation (QPE) on n qubits
return qpe
#########################################
# run this cell to simulate 'qpe' and
# to plot the histogram of the result
# define several quantum register sizes
# equal to n, allowing to vary them
#reg_size = 4
reg_size = 5
#reg_size = 6
#reg_size = 7
#reg_size = 8
# create a quantum circuit for
# the Quantum Phase Estimation (QPE),
# given the quantum register defined before,
# with n counting qubits
qpe_check = qpe_circuit( reg_size )
# create the Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 10000
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n counting qubits, and retrieve its result counts
count_qpe = execute( qpe_check, sim, shots=shots ).result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits
plot_histogram( count_qpe, figsize=(9,5) )
# process the result count data to determine accuracy of
# the estimated phase and grab the highest probability measurement
# define the maximum number of counts which will be obtained
max_binary_counts = 0
# define the maximum binary value which will be obtained
max_binary_val = ""
# for each count obtained from the quantum simulation of
# the Quantum Phase Estimation (QPE)
for key, item in count_qpe.items():
# if the current number of counts is greater than
# the current maximum number of counts obtained
if item > max_binary_counts:
# update the maximum number of counts obtained
max_binary_counts = item
# update the maximum binary value obtained
max_binary_val = key
#########################################
#### your function to convert a binary ####
#### string to a decimal number goes here ####
# define the function to convert
# a binary string to a decimal number
def bin_to_decimal( binary_string ):
# return a binary string
# converted to a decimal number
return int( binary_string, 2 )
# calculate the estimated phase obtained
# from the quantum simulation of
# the Quantum Phase Estimation (QPE)
estimated_phase = ( bin_to_decimal(max_binary_val) / 2**reg_size )
# print the estimated phase obtained
# from the quantum simulation of
# the Quantum Phase Estimation (QPE)
print("Estimated Phase:", estimated_phase)
# calculate the phase accuracy
# which can be obtained from
# the quantum simulation of
# the Quantum Phase Estimation (QPE)
# with the quantum circuit defined before,
# inverse of the highest power of 2
# (i.e. smallest decimal) this quantum circuit can estimate
phase_accuracy_window = 2**( -reg_size )
# print the phase accuracy
# which can be obtained from
# the quantum simulation of
# the Quantum Phase Estimation (QPE)
# with the quantum circuit defined before,
# inverse of the highest power of 2
# (i.e. smallest decimal) this quantum circuit can estimate
print("Phase Accuracy Window:", phase_accuracy_window)
# define the theta phase angle,
# which was pretended to be estimated
theta = 1 / 7
# compute the accuracy of the estimated phase,
# as the distance between the estimated phase
# and the theta phase angle, which was pretended to be estimated
accuracy_estimated_phase = abs( theta - estimated_phase )
# print the accuracy of the estimated phase,
# as the distance between the estimated phase
# and the theta phase angle, which was pretended to be estimated
print("Accuracy of the Estimated Phase:", accuracy_estimated_phase)
### put your answer here ###
# to estimate accurately the phase information to be within 2^(-6)
# we need n + 1 = 6 (=) n = 5 qubits to store the phase information
required_register_size = 5
### submit your answer ###
# import the grader for the exercise 4 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex4
# grade the exercise 4 of the lab 3
grade_lab3_ex4( required_register_size )
# create 7 mod 15 unitary operator
# for a quantum circuit
N = 15
# define the number of m qubits required
# for the 7 mod 15 operator to be executed
m = int( np.ceil( np.log2( N ) ) )
# create the quantum circuit with
# a quantum register of m qubits
# to implement the 7 mod 15 unitary operator
U_qc = QuantumCircuit( m )
# apply the Pauli-X gate to all the m qubits of
# the quantum register of the quantum circuit
# implementing the 7 mod 15 unitary operator
U_qc.x( range(m) )
# apply the Swap gate between the 2nd qubit and
# the 3rd qubit on the quantum register of
# the quantum circuit implementing
# the 7 mod 15 unitary operator
U_qc.swap(1, 2)
# apply the Swap gate between the 3rd qubit and
# the 4th qubit on the quantum register of
# the quantum circuit implementing
# the 7 mod 15 unitary operator
U_qc.swap(2, 3)
# apply the Swap gate between the 1st qubit and
# the 4th qubit on the quantum register of
# the quantum circuit implementing
# the 7 mod 15 unitary operator
U_qc.swap(0, 3)
# convert the quantum circuit implementing
# the 7 mod 15 unitary operator to
# a quantum unitary gate
U = U_qc.to_gate()
# define the name of the 7 mod 15
# unitary operator created before
U.name ="{}Mod{}".format(7, N)
# your code goes here
# print the number of qubits
print("Num. qubits: m =", m);
# define the quantum circuits for the inputs
# |1> = |0001>, |2> = |0010>, and |5> = |0101>
#########################################
# create the a quantum circuit with m qubits,
# for the input state |1> = |0001>
qcirc_input_1 = QuantumCircuit(m)
# apply the Pauli-X gate to
# the 1st qubit of the quantum register of
# the quantum circuit defined before
qcirc_input_1.x(0)
# apply the U gate to all
# the m qubits of the quantum register of
# the quantum circuit defined before
qcirc_input_1.append( U, range(m) )
# measure all the m qubits of
# the quantum register of
# the quantum circuit defined before
qcirc_input_1.measure_all()
#########################################
# create the a quantum circuit with m qubits,
# for input state |2> = |0010>
qcirc_input_2 = QuantumCircuit(m)
# apply the Pauli-X gate to
# the 2nd qubit of the quantum register of
# the quantum circuit defined before
qcirc_input_2.x(1)
# apply the U gate to all
# the m qubits of the quantum register of
# the quantum circuit defined before
qcirc_input_2.append( U, range(m) )
# measure all the m qubits of
# the quantum register of
# the quantum circuit defined before
qcirc_input_2.measure_all()
#########################################
# create the a quantum circuit with m qubits,
# for input state |5> = |0101>
qcirc_input_5 = QuantumCircuit(m)
# apply the Pauli-X gate to
# the 1st qubit of the quantum register of
# the quantum circuit defined before
qcirc_input_5.x(0)
# apply the Pauli-X gate to
# the 3rd qubit of the quantum register of
# the quantum circuit defined before
qcirc_input_5.x(2)
# apply the U gate to all
# the m qubits of the quantum register of
# the quantum circuit defined before
qcirc_input_5.append( U, range(m) )
# measure all the m qubits of
# the quantum register of
# the quantum circuit defined before
qcirc_input_5.measure_all()
#########################################
# run this cell to simulate 'qcirc' and to plot the histogram of the result
# create the Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 20000
# save the count data for the input state |1> = |0001>
input_1 = execute(qcirc_input_1, sim, shots=shots).result().get_counts()
# save the count data for the input state |2> = |0010>
input_2 = execute(qcirc_input_2, sim, shots=shots).result().get_counts()
# save the count data for the input state |5> = |0101>
input_5 = execute(qcirc_input_5, sim, shots=shots).result().get_counts()
# submit your answer
# import the grader for the exercise 5 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex5
# grade the exercise 5 of the lab 3
grade_lab3_ex5( [ input_1, input_2, input_5 ] )
# create an unitary quantum circuit
# with a quantum register of m qubits
unitary_circ = QuantumCircuit(m)
#### your code goes here ####
# for each iteration in a range of 2^2 = 4
for _ in range( 2**2 ):
# apply the U gate on all
# the m qubits on the quantum register
unitary_circ.append( U, range(m) )
# create a Unitary Simulator object
sim = Aer.get_backend("unitary_simulator")
# execute the quantum simulation of
# an unitary quantum circuit with
# a quantum register of m qubits,
# defined before, retrieving its unitary operator
unitary = execute( unitary_circ, sim ).result().get_unitary()
# submit your answer
# import the grader for the exercise 6 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex6
# grade the exercise 6 of the lab 3
grade_lab3_ex6( unitary, unitary_circ )
# define the function to built a 2^k-Controlled-U gate object,
# which repeats the action of the operator U, 2^k times
def cU_multi(k):
# define the size n of the system's quantum register
sys_register_size = 4
# create the quantum circuit with n qubits on
# the system's quantum register, to build
# a 2^k-Controlled-U gate object
circ = QuantumCircuit( sys_register_size )
# for each iteration ranging until 2^k
for _ in range(2**k):
# apply the U gate to all the n qubits on
# the system's quantum register of
# the quantum circuit to represent
# the 2^k-Controlled-U gate
circ.append(U, range(sys_register_size))
# convert the operator resulting from the construction of
# the quantum circuit defined before, to a quantum gate
U_multi = circ.to_gate()
# define the name of the 2^k-Controlled-U gate,
# as being a "7 Mod 15 gate"
U_multi.name = "7Mod15_[2^{}]".format(k)
# set this 2^k-Controlled-U gate as multi-qubit gate,
# depending on a given control qubit
cU_multi = U_multi.control()
# return the 2^k-Controlled-U gate object,
# which repeats the action of the operator U, 2^k times
return cU_multi
# define the size m of the quantum register
# for the phase counting of the qubits
phase_register_size = 8
# define the size n of the quantum register
# for the successive applications of
# the 2^k-Controlled-U gate defined before
cu_register_size = 4
# create the Quantum Circuit needed to run
# with m = 8 qubits for the phase counting
# and with n = 4 qubits for the successive
# applications of the 2^k-Controlled-U gate
# defined before, to implement the Shor's Algorithm
# for Factoring, based on Quantum Phase Estimation (QPE)
shor_qpe = QuantumCircuit( ( phase_register_size + cu_register_size ),
phase_register_size )
# perform the Quantum Hadamard Transform on
# the m qubits for the phase counting of
# the quantum register of the quantum circuit
# implementing the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_quantum_hadamard_transform( shor_qpe, phase_register_size )
# apply the Pauli-X gate to the last qubit on
# the quantum register of the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.x( phase_register_size )
# apply a barrier to the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.barrier()
# for each kth qubit on the quantum register
# for the phase counting of the qubits
for k in range( phase_register_size ):
# retrieve the 2^k-Controlled-U gate object,
# which repeats the action of the operator U,
# 2^k times, defined before
cU = cU_multi(k)
# apply the 2^k-Controlled-U gate object,
# which repeats the action of the operator U,
# 2^k times, defined before, for the kth iteration,
# to the quantum circuit to implement
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.append( cU, [k] + list( range( phase_register_size,
( phase_register_size + cu_register_size ) ) ) )
# apply a barrier to the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.barrier()
# perform the Swap gates on the n qubits of
# the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT),
# required to build the quantum circuit to implement
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_swaps(shor_qpe, phase_register_size)
# apply a barrier to the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.barrier()
# perform the Inverse Quantum Fourier Transform (IQFT) on
# the m qubits for the phase counting of
# the quantum register of the quantum circuit
# implementing the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_quantum_fourier_transform_inverse( shor_qpe, phase_register_size )
# apply a barrier to the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.barrier()
# perform a measurement of all
# the m qubits for the phase counting of
# the quantum register of the quantum circuit
# implementing the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.measure( range( phase_register_size ),
range( phase_register_size ) )
# draw the quantum circuit implementing
# the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.draw("mpl")
# run this cell to simulate 'shor_qpe' and
# to plot the histogram of the results
# create an Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 20000
# execute the quantum simulation for
# the quantum circuit for the Shor's Algorithm,
# based on Quantum Phase Estimation (QPE),
# with n phase counting qubits, and retrieve
# the result counts of this quantum simulation
shor_qpe_counts = execute(shor_qpe, sim, shots=shots).result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the quantum circuit for the Shor's Algorithm, based on
# Quantum Phase Estimation (QPE), with n phase counting qubits
plot_histogram( shor_qpe_counts, figsize=(9,5) )
# submit your answer
# import the grader for the exercise 7 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex7
# grade the exercise 7 of the lab 3
grade_lab3_ex7( shor_qpe_counts )
# import the Fraction object
# from the built-in fractions module
from fractions import Fraction
# print the number '0.666',
# as an unlimited Fraction object
print( "Unlimited Fraction(0.666):",
Fraction(0.666), '\n')
# print the number '0.666',
# as a limited Fraction object
# with the denominator of 15
print( "Limited Fraction(0.666), with a max. denominator of 15:",
Fraction(0.666).limit_denominator(15) )
# create a list with the estimated phases of the result counts
# obtained from the execution of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits
estimated_phases = [ bin_to_decimal(binary_val) / 2**phase_register_size
for binary_val in shor_qpe_counts ]
# print the list with the estimated phases of the result counts
# obtained from the execution of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits
print( "Estimated Phases:", estimated_phases )
# create a list of with the estimated phases of the result counts
# obtained from the execution of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits,
# represented as Fraction objects with the format s/r
shor_qpe_fractions = [ Fraction(estimated_phase).limit_denominator(15)
for estimated_phase in estimated_phases ]
# print the list of with the estimated phases of the result counts
# obtained from the execution of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits,
# represented as Fraction objects with the format s/r
print( "Estimated Fractions:", shor_qpe_fractions )
# submit your answer
# import the grader for the exercise 8 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex8
# grade the exercise 8 of the lab 3
grade_lab3_ex8( shor_qpe_fractions )
# define the function to create and execute
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits
def shor_qpe(k):
# define the co-prime a
a = 7
# define the number N to factor
N = 15
# compute the number m of
# additional qubits required
m = int( np.ceil( np.log2(N) ) )
#################################################
# step 1. Begin a while loop until a nontrivial guess is found
#### your code goes here ####
# define the boolean flag to determine
# if a non trivial guess was found, initially as False
non_trivial_guess_found = False
# while no trivial factor guess was found,
# execute the while loop
while( not non_trivial_guess_found ):
#################################################
# step 2a. construct a QPE quantum circuit
# with m phase counting qubits to guess
# the phase phi = s/r, using the function
# cU_multi() defined before
#### your code goes here ####
# create a quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc = QuantumCircuit( ( k + m ), k)
# perform the Quantum Hadamard Transform on
# the k phase counting qubits of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_quantum_hadamard_transform( qc, k )
# apply a Pauli-X gate to the last
# phase counting qubit of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
qc.x(k)
# apply a barrier to the quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc.barrier()
# for each kth qubit on the quantum register
# for the phase counting of the qubits
for k_i in range(k):
# retrieve the 2^k-Controlled-U gate object,
# which repeats the action of the operator U,
# 2^k times, defined before
cU = cU_multi(k_i)
# apply the 2^k-Controlled-U gate object,
# which repeats the action of the operator U,
# 2^k times, defined before, for the kth iteration,
# to the quantum circuit for the Shor's Algorithm
# for Factoring, based on Quantum Phase Estimation (QPE),
# with k phase counting qubits, and additional m qubits
# for the successive applications of
# the 2^k-Controlled-U gate defined before
qc.append( cU, [k_i] + list( range( k, ( k + m ) ) ) )
# apply a barrier to the quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc.barrier()
# perform the Swap gates on the k
# phase counting qubits of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_swaps( qc, k )
# apply a barrier to the quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc.barrier()
# perform the Inverse Quantum Fourier Transform (IQFT) on
# the k phase counting qubits of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_quantum_fourier_transform_inverse( qc, k )
# apply a barrier to the quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc.barrier()
# perform a measurement of all
# the k phase counting qubits of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
qc.measure( range(k), range(k) )
#################################################
# step 2b. run the QPE quantum circuit with a single shot,
# record the results and convert the estimated phase
# bitstring to a decimal format
#### your code goes here ####
# create an Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 1
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n counting qubits, and retrieve the result counts
# obtained from this quantum simulation
shor_qpe_counts = execute( qc, sim, shots=shots ).result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits
plot_histogram( shor_qpe_counts, figsize=(9,5) )
# compute the estimated phases from the result counts
# obtained from the quantum simulation of the quantum circuit
# implementing the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
estimated_phases = [ bin_to_decimal( binary_val ) / 2**k
for binary_val in shor_qpe_counts ]
#################################################
# step 3. use the Fraction object to find the guess for r
#### your code goes here ####
# convert the estimated phase to a fraction s/r format
fraction_s_r = [ Fraction(estimated_phase).limit_denominator(N)
for estimated_phase in estimated_phases ][0]
# retrieve the numerator s and the denominator r
# from the estimated phase represented as a fraction
s, r = fraction_s_r.numerator, fraction_s_r.denominator
#################################################
# step 4. now that r has been found, use the built-in
# greatest common divisor function to determine
# the guesses for a factor of N
# build the list of guesses for possible non-trivial factors of N
guesses = [ gcd( a**( r // 2 ) - 1, N ),
gcd( a**( r // 2 ) + 1, N ) ]
#################################################
# step 5. for each guess in guesses, check if
# at least one is a non-trivial factor,
# i.e., ( ( guess != 1 ) or ( guess != N ) )
# and ( N % guess == 0 )
#### your code goes here ####
# for each of the guesses computed before
for guess in guesses:
# if the current guess is not a trivial factor
if ( ( ( guess != 1 ) or ( guess != N ) )
and ( N % guess == 0 ) ):
# update the boolean flag to determine
# if a non trivial guess was found, as True
non_trivial_guess_found = True
# break the current for loop
break
#################################################
# step 6. if a non-trivial factor is found return
# the list 'guesses', otherwise
# continue the while loop
# return the list of the guesses,
# containing a non-trivial factor of N
return guesses
#################################################
# submit your circuit
# import the grader for the exercise 9 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex9
# grade the exercise 9 of the lab 3
grade_lab3_ex9( shor_qpe )
# import the IBM's Qiskit Jupyter Tools
import qiskit.tools.jupyter
# show the table of the IBM's Qiskit version
%qiskit_version_table
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import Aer
from qiskit_chemistry import QiskitChemistry
import warnings
warnings.filterwarnings('ignore')
# setup qiskit_chemistry logging
import logging
from qiskit_chemistry import set_qiskit_chemistry_logging
set_qiskit_chemistry_logging(logging.ERROR) # choose among DEBUG, INFO, WARNING, ERROR, CRITICAL and NOTSET
# from qiskit import IBMQ
# IBMQ.load_accounts()
# First, we use classical eigendecomposition to get ground state energy (including nuclear repulsion energy) as reference.
qiskit_chemistry_dict = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': 'H2/H2_equilibrium_0.735_sto-3g.hdf5'},
'operator': {'name':'hamiltonian',
'qubit_mapping': 'parity',
'two_qubit_reduction': True},
'algorithm': {'name': 'ExactEigensolver'}
}
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict)
print('Ground state energy (classical): {:.12f}'.format(result['energy']))
# Second, we use variational quantum eigensolver (VQE)
qiskit_chemistry_dict['algorithm']['name'] = 'VQE'
qiskit_chemistry_dict['optimizer'] = {'name': 'SPSA', 'max_trials': 350}
qiskit_chemistry_dict['variational_form'] = {'name': 'RYRZ', 'depth': 3, 'entanglement':'full'}
backend = Aer.get_backend('statevector_simulator')
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict, backend=backend)
print('Ground state energy (quantum) : {:.12f}'.format(result['energy']))
print("====================================================")
# You can also print out other info in the field 'printable'
for line in result['printable']:
print(line)
# select H2 or LiH to experiment with
molecule='H2'
qiskit_chemistry_dict = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': ''},
'operator': {'name':'hamiltonian',
'qubit_mapping': 'parity',
'two_qubit_reduction': True},
'algorithm': {'name': ''},
'optimizer': {'name': 'SPSA', 'max_trials': 350},
'variational_form': {'name': 'RYRZ', 'depth': 3, 'entanglement':'full'}
}
# choose which backend want to use
# backend = Aer.get_backend('statevector_simulator')
backend = Aer.get_backend('qasm_simulator')
backend_cfg = {'shots': 1024}
algos = ['ExactEigensolver', 'VQE']
if molecule == 'LiH':
mol_distances = np.arange(0.6, 5.1, 0.1)
qiskit_chemistry_dict['operator']['freeze_core'] = True
qiskit_chemistry_dict['operator']['orbital_reduction'] = [-3, -2]
qiskit_chemistry_dict['optimizer']['max_trials'] = 2500
qiskit_chemistry_dict['variational_form']['depth'] = 5
else:
mol_distances = np.arange(0.2, 4.1, 0.1)
energy = np.zeros((len(algos), len(mol_distances)))
for j, algo in enumerate(algos):
qiskit_chemistry_dict['algorithm']['name'] = algo
if algo == 'ExactEigensolver':
qiskit_chemistry_dict.pop('backend', None)
elif algo == 'VQE':
qiskit_chemistry_dict['backend'] = backend_cfg
print("Using {}".format(algo))
for i, dis in enumerate(mol_distances):
print("Processing atomic distance: {:1.1f} Angstrom".format(dis), end='\r')
qiskit_chemistry_dict['HDF5']['hdf5_input'] = "{}/{:1.1f}_sto-3g.hdf5".format(molecule, dis)
result = solver.run(qiskit_chemistry_dict, backend=backend if algo == 'VQE' else None)
energy[j][i] = result['energy']
print("\n")
for i, algo in enumerate(algos):
plt.plot(mol_distances, energy[i], label=algo)
plt.xlabel('Atomic distance (Angstrom)')
plt.ylabel('Energy')
plt.legend()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw
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, backend=FakeBoeblingen())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import GroverOptimizer, MinimumEigenOptimizer
from qiskit_optimization.translators import from_docplex_mp
from docplex.mp.model import Model
model = Model()
x0 = model.binary_var(name="x0")
x1 = model.binary_var(name="x1")
x2 = model.binary_var(name="x2")
model.minimize(-x0 + 2 * x1 - 3 * x2 - 2 * x0 * x2 - 1 * x1 * x2)
qp = from_docplex_mp(model)
print(qp.prettyprint())
grover_optimizer = GroverOptimizer(6, num_iterations=10, sampler=Sampler())
results = grover_optimizer.solve(qp)
print(results.prettyprint())
exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
exact_result = exact_solver.solve(qp)
print(exact_result.prettyprint())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/henrik-dreyer/TASP-for-Qiskit
|
henrik-dreyer
|
import numpy as np
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit.chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit.aqua.components.variational_forms import TASP
from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock
from qiskit.aqua.components.optimizers import COBYLA
from qiskit import BasicAer
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry import FermionicOperator
from qiskit.aqua import QuantumInstance
#Classical part: set up molecular data, map to WeightedPauliOperator and find exact solution
dist=0.735
driver = PySCFDriver(atom="H .0 .0 .0; H .0 .0 " + str(dist), unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
molecule = driver.run()
repulsion_energy = molecule.nuclear_repulsion_energy
num_spin_orbitals=molecule.num_orbitals*2
map_type='jordan_wigner'
ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals)
qubitOp = ferOp.mapping(map_type=map_type, threshold=0.00000001)
exact_solution = ExactEigensolver(qubitOp).run()['energy']
exact_solution=exact_solution+repulsion_energy
#Set up initial state and UCCSD variational form with standard parameters
HF_state=HartreeFock(qubitOp.num_qubits, num_spin_orbitals, num_particles, map_type)
varform_UCCSD = UCCSD(qubitOp.num_qubits, depth=1, num_orbitals=num_spin_orbitals, num_particles=num_particles,
active_occupied=None, active_unoccupied=None, initial_state=HF_state,
qubit_mapping='jordan_wigner', two_qubit_reduction=False, num_time_slices=1,
shallow_circuit_concat=True, z2_symmetries=None)
#Run VQE using UCCSD variational form and compare with exact solution
print('Molecule H2 at bond length ' + str(dist))
print('Running VQE with UCCSD. This may take a few minutes. Some intermediary energies while you wait:')
opt_iter=15
optimizer = COBYLA(maxiter=opt_iter)
n_shots=1000
instance=QuantumInstance(backend=BasicAer.get_backend("qasm_simulator"), shots=n_shots)
vqe_instance = VQE(qubitOp, varform_UCCSD, optimizer=optimizer)
result=vqe_instance.run(instance)
energy=result['energy']+repulsion_energy
print('Optimal energy is ' + str(energy) +'. Exact result is ' + str(exact_solution))
#Split the Hamiltonian into the abovementioned pieces
diag_one_body=np.diag(np.diagonal(molecule.one_body_integrals))
offdiag_one_body=molecule.one_body_integrals-diag_one_body
diag_two_body=np.zeros((num_spin_orbitals,num_spin_orbitals,num_spin_orbitals,num_spin_orbitals))
hop_two_body=np.zeros((num_spin_orbitals,num_spin_orbitals,num_spin_orbitals,num_spin_orbitals))
ex_two_body=np.zeros((num_spin_orbitals,num_spin_orbitals,num_spin_orbitals,num_spin_orbitals))
for i1 in range(num_spin_orbitals):
for i2 in range(num_spin_orbitals):
for i3 in range(num_spin_orbitals):
for i4 in range(num_spin_orbitals):
if i2==i3:
if i1==i4:
diag_two_body[i1,i2,i3,i4]=molecule.two_body_integrals[i1,i2,i3,i4]
else:
hop_two_body[i1,i2,i3,i4]=molecule.two_body_integrals[i1,i2,i3,i4]
else:
ex_two_body[i1,i2,i3,i4]=molecule.two_body_integrals[i1,i2,i3,i4]
H_diag=FermionicOperator(h1=diag_one_body,h2=diag_two_body)
H_hop=FermionicOperator(h1=offdiag_one_body,h2=hop_two_body)
H_ex=FermionicOperator(h1=np.zeros((num_spin_orbitals,num_spin_orbitals)),h2=ex_two_body)
H_diag=H_diag.mapping(map_type=map_type, threshold=0.00000001)
H_hop=H_hop.mapping(map_type=map_type, threshold=0.00000001)
H_ex=H_ex.mapping(map_type=map_type, threshold=0.00000001)
h_list=[H_ex, H_hop, H_diag]
#Define TASP variational form (the TASP class file is attached to original comment)
S=1
varform_TASP=TASP(num_spin_orbitals, depth=S, h_list=h_list, initial_state=HF_state)
print('Running VQE with TASP. This may take a few minutes. Some intermediary energies while you wait:')
vqe_instance = VQE(qubitOp, varform_TASP, optimizer=optimizer)
result=vqe_instance.run(instance)
energy=result['energy']+repulsion_energy
print('Optimal energy is ' + str(energy) +'. Exact result is ' + str(exact_solution))
n_param_UCCSD=varform_UCCSD.num_parameters
qc_UCCSD=varform_UCCSD.construct_circuit(np.random.rand(n_param_UCCSD))
print('Number of parameters for UCCSD:', n_param_UCCSD)
print('Depth for UCCSD:', qc_UCCSD.depth())
print('Gate counts:', qc_UCCSD.count_ops())
n_param_TASP=varform_TASP.num_parameters
qc_TASP=varform_TASP.construct_circuit(np.random.rand(n_param_TASP))
print('Number of parameters for TASP:', n_param_TASP)
print('Depth for TASP:', qc_TASP.depth())
print('Gate counts:', qc_TASP.count_ops())
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
import json
import csv
# Array of JSON Objects
header = ['instance', 'iteration', 'distance']
length_instances = 40
with open('qaoa_multiple_distance.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
for instance in range(length_instances):
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution()
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
index = -1
for sample in UNIFORM_CONVERGENCE_SAMPLE:
mean = sample["mean"]
index += 1
distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"]))
UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state
iteration = 0
for sample in UNIFORM_CONVERGENCE_SAMPLE:
iteration += 1
mean = sample["mean"]
distance = sample["distance_pgs"]
writer.writerow([instance,iteration, distance])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
#General imports
import numpy as np
#Operator Imports
from qiskit.opflow import Z, X, I, StateFn, CircuitStateFn, SummedOp
from qiskit.opflow.gradients import Gradient, NaturalGradient, QFI, Hessian
#Circuit imports
from qiskit.circuit import QuantumCircuit, QuantumRegister, Parameter, ParameterVector, ParameterExpression
from qiskit.circuit.library import EfficientSU2
# Instantiate the quantum state
a = Parameter('a')
b = Parameter('b')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
# Instantiate the Hamiltonian observable
H = (2 * X) + Z
# Combine the Hamiltonian observable and the state
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
# Print the operator corresponding to the expectation value
print(op)
params = [a, b]
# Define the values to be assigned to the parameters
value_dict = {a: np.pi / 4, b: np.pi}
# Convert the operator and the gradient target params into the respective operator
grad = Gradient().convert(operator = op, params = params)
# Print the operator corresponding to the Gradient
print(grad)
# Assign the parameters and evaluate the gradient
grad_result = grad.assign_parameters(value_dict).eval()
print('Gradient', grad_result)
# Define the Hamiltonian with fixed coefficients
H = 0.5 * X - 1 * Z
# Define the parameters w.r.t. we want to compute the gradients
params = [a, b]
# Define the values to be assigned to the parameters
value_dict = { a: np.pi / 4, b: np.pi}
# Combine the Hamiltonian observable and the state into an expectation value operator
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
print(op)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameters using
# the parameter shift method.
state_grad = Gradient(grad_method='param_shift').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with parameter shift', state_grad_result)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using
# the linear combination of unitaries method.
state_grad = Gradient(grad_method='lin_comb').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with the linear combination method', state_grad_result)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using
# the finite difference method.
state_grad = Gradient(grad_method='fin_diff').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with finite difference', state_grad_result)
# Besides the method to compute the circuit gradients resp. QFI, a regularization method can be chosen:
# `ridge` or `lasso` with automatic parameter search or `perturb_diag_elements` or `perturb_diag`
# which perturb the diagonal elements of the QFI.
nat_grad = NaturalGradient(grad_method='lin_comb', qfi_method='lin_comb_full', regularization='ridge').convert(
operator=op, params=params)
# Assign the parameters and evaluate the gradient
nat_grad_result = nat_grad.assign_parameters(value_dict).eval()
print('Natural gradient computed with linear combination of unitaries', nat_grad_result)
# Instantiate the Hamiltonian observable
H = X
# Instantiate the quantum state with two parameters
a = Parameter('a')
b = Parameter('b')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
# Combine the Hamiltonian observable and the state
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
# Convert the operator and the hessian target coefficients into the respective operator
hessian = Hessian().convert(operator = op, params = [a, b])
# Define the values to be assigned to the parameters
value_dict = {a: np.pi / 4, b: np.pi/4}
# Assign the parameters and evaluate the Hessian w.r.t. the Hamiltonian coefficients
hessian_result = hessian.assign_parameters(value_dict).eval()
print('Hessian \n', np.real(np.array(hessian_result)))
# Define parameters
params = [a, b]
# Get the operator object representing the Hessian
state_hess = Hessian(hess_method='param_shift').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed using the parameter shift method\n', (np.array(hessian_result)))
# Get the operator object representing the Hessian
state_hess = Hessian(hess_method='lin_comb').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed using the linear combination of unitaries method\n', (np.array(hessian_result)))
# Get the operator object representing the Hessian using finite difference
state_hess = Hessian(hess_method='fin_diff').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed with finite difference\n', (np.array(hessian_result)))
# Wrap the quantum circuit into a CircuitStateFn
state = CircuitStateFn(primitive=qc, coeff=1.)
# Convert the state and the parameters into the operator object that represents the QFI
qfi = QFI(qfi_method='lin_comb_full').convert(operator=state, params=params)
# Define the values for which the QFI is to be computed
values_dict = {a: np.pi / 4, b: 0.1}
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('full QFI \n', np.real(np.array(qfi_result)))
# Convert the state and the parameters into the operator object that represents the QFI
# and set the approximation to 'block_diagonal'
qfi = QFI('overlap_block_diag').convert(operator=state, params=params)
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('Block-diagonal QFI \n', np.real(np.array(qfi_result)))
# Convert the state and the parameters into the operator object that represents the QFI
# and set the approximation to 'diagonal'
qfi = QFI('overlap_diag').convert(operator=state, params=params)
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('Diagonal QFI \n', np.real(np.array(qfi_result)))
# Execution Imports
from qiskit import Aer
from qiskit.utils import QuantumInstance
# Algorithm Imports
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import CG
from qiskit.opflow import I, X, Z
from qiskit.circuit import QuantumCircuit, ParameterVector
from scipy.optimize import minimize
# Instantiate the system Hamiltonian
h2_hamiltonian = -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X)
# This is the target energy
h2_energy = -1.85727503
# Define the Ansatz
wavefunction = QuantumCircuit(2)
params = ParameterVector('theta', length=8)
it = iter(params)
wavefunction.ry(next(it), 0)
wavefunction.ry(next(it), 1)
wavefunction.rz(next(it), 0)
wavefunction.rz(next(it), 1)
wavefunction.cx(0, 1)
wavefunction.ry(next(it), 0)
wavefunction.ry(next(it), 1)
wavefunction.rz(next(it), 0)
wavefunction.rz(next(it), 1)
# Define the expectation value corresponding to the energy
op = ~StateFn(h2_hamiltonian) @ StateFn(wavefunction)
grad = Gradient(grad_method='lin_comb')
qi_sv = QuantumInstance(Aer.get_backend('aer_simulator_statevector'),
shots=1,
seed_simulator=2,
seed_transpiler=2)
#Conjugate Gradient algorithm
optimizer = CG(maxiter=50)
# Gradient callable
vqe = VQE(wavefunction, optimizer=optimizer, gradient=grad, quantum_instance=qi_sv)
result = vqe.compute_minimum_eigenvalue(h2_hamiltonian)
print('Result:', result.optimal_value, 'Reference:', h2_energy)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Necessary imports
import numpy as np
import matplotlib.pyplot as plt
from torch import Tensor
from torch.nn import Linear, CrossEntropyLoss, MSELoss
from torch.optim import LBFGS
from qiskit import QuantumCircuit
from qiskit.utils import algorithm_globals
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN
from qiskit_machine_learning.connectors import TorchConnector
# Set seed for random generators
algorithm_globals.random_seed = 42
# Generate random dataset
# Select dataset dimension (num_inputs) and size (num_samples)
num_inputs = 2
num_samples = 20
# Generate random input coordinates (X) and binary labels (y)
X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1
y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1}, y01 will be used for SamplerQNN example
y = 2 * y01 - 1 # in {-1, +1}, y will be used for EstimatorQNN example
# Convert to torch Tensors
X_ = Tensor(X)
y01_ = Tensor(y01).reshape(len(y)).long()
y_ = Tensor(y).reshape(len(y), 1)
# Plot dataset
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()
# Set up a circuit
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs)
qc = QuantumCircuit(num_inputs)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
qc.draw("mpl")
# Setup QNN
qnn1 = EstimatorQNN(
circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters
)
# Set up PyTorch module
# Note: If we don't explicitly declare the initial weights
# they are chosen uniformly at random from [-1, 1].
initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn1.num_weights) - 1)
model1 = TorchConnector(qnn1, initial_weights=initial_weights)
print("Initial weights: ", initial_weights)
# Test with a single input
model1(X_[0, :])
# Define optimizer and loss
optimizer = LBFGS(model1.parameters())
f_loss = MSELoss(reduction="sum")
# Start training
model1.train() # set model to training mode
# Note from (https://pytorch.org/docs/stable/optim.html):
# Some optimization algorithms such as LBFGS need to
# reevaluate the function multiple times, so you have to
# pass in a closure that allows them to recompute your model.
# The closure should clear the gradients, compute the loss,
# and return it.
def closure():
optimizer.zero_grad() # Initialize/clear gradients
loss = f_loss(model1(X_), y_) # Evaluate loss function
loss.backward() # Backward pass
print(loss.item()) # Print loss
return loss
# Run optimizer step4
optimizer.step(closure)
# Evaluate model and compute accuracy
y_predict = []
for x, y_target in zip(X, y):
output = model1(Tensor(x))
y_predict += [np.sign(output.detach().numpy())[0]]
print("Accuracy:", sum(y_predict == y) / len(y))
# 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()
# Define feature map and ansatz
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs, entanglement="linear", reps=1)
# Define quantum circuit of num_qubits = input dim
# Append feature map and ansatz
qc = QuantumCircuit(num_inputs)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
# Define SamplerQNN and initial setup
parity = lambda x: "{:b}".format(x).count("1") % 2 # optional interpret function
output_shape = 2 # parity = 0, 1
qnn2 = SamplerQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=output_shape,
)
# Set up PyTorch module
# Reminder: If we don't explicitly declare the initial weights
# they are chosen uniformly at random from [-1, 1].
initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn2.num_weights) - 1)
print("Initial weights: ", initial_weights)
model2 = TorchConnector(qnn2, initial_weights)
# Define model, optimizer, and loss
optimizer = LBFGS(model2.parameters())
f_loss = CrossEntropyLoss() # Our output will be in the [0,1] range
# Start training
model2.train()
# Define LBFGS closure method (explained in previous section)
def closure():
optimizer.zero_grad(set_to_none=True) # Initialize gradient
loss = f_loss(model2(X_), y01_) # Calculate loss
loss.backward() # Backward pass
print(loss.item()) # Print loss
return loss
# Run optimizer (LBFGS requires closure)
optimizer.step(closure);
# Evaluate model and compute accuracy
y_predict = []
for x in X:
output = model2(Tensor(x))
y_predict += [np.argmax(output.detach().numpy())]
print("Accuracy:", sum(y_predict == y01) / len(y01))
# plot results
# red == wrongly classified
for x, y_target, y_ 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_:
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
# Generate random dataset
num_samples = 20
eps = 0.2
lb, ub = -np.pi, np.pi
f = lambda x: np.sin(x)
X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb
y = f(X) + eps * (2 * algorithm_globals.random.random([num_samples, 1]) - 1)
plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "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 feature map
param_y = Parameter("y")
ansatz = QuantumCircuit(1, name="vf")
ansatz.ry(param_y, 0)
qc = QuantumCircuit(1)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
# Construct QNN
qnn3 = EstimatorQNN(circuit=qc, input_params=[param_x], weight_params=[param_y])
# Set up PyTorch module
# Reminder: If we don't explicitly declare the initial weights
# they are chosen uniformly at random from [-1, 1].
initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn3.num_weights) - 1)
model3 = TorchConnector(qnn3, initial_weights)
# Define optimizer and loss function
optimizer = LBFGS(model3.parameters())
f_loss = MSELoss(reduction="sum")
# Start training
model3.train() # set model to training mode
# Define objective function
def closure():
optimizer.zero_grad(set_to_none=True) # Initialize gradient
loss = f_loss(model3(Tensor(X)), Tensor(y)) # Compute batch loss
loss.backward() # Backward pass
print(loss.item()) # Print loss
return loss
# Run optimizer
optimizer.step(closure)
# Plot target function
plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--")
# Plot data
plt.plot(X, y, "bo")
# Plot fitted line
y_ = []
for x in np.linspace(lb, ub):
output = model3(Tensor([x]))
y_ += [output.detach().numpy()[0]]
plt.plot(np.linspace(lb, ub), y_, "g-")
plt.show()
# Additional torch-related imports
import torch
from torch import cat, no_grad, manual_seed
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import torch.optim as optim
from torch.nn import (
Module,
Conv2d,
Linear,
Dropout2d,
NLLLoss,
MaxPool2d,
Flatten,
Sequential,
ReLU,
)
import torch.nn.functional as F
# Train Dataset
# -------------
# Set train shuffle seed (for reproducibility)
manual_seed(42)
batch_size = 1
n_samples = 100 # We will concentrate on the first 100 samples
# Use pre-defined torchvision function to load MNIST train data
X_train = datasets.MNIST(
root="./data", train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])
)
# Filter out labels (originally 0-9), leaving only labels 0 and 1
idx = np.append(
np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples]
)
X_train.data = X_train.data[idx]
X_train.targets = X_train.targets[idx]
# Define torch dataloader with filtered data
train_loader = DataLoader(X_train, batch_size=batch_size, shuffle=True)
n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[n_samples_show - 1].imshow(images[0, 0].numpy().squeeze(), cmap="gray")
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets[0].item()))
n_samples_show -= 1
# Test Dataset
# -------------
# Set test shuffle seed (for reproducibility)
# manual_seed(5)
n_samples = 50
# Use pre-defined torchvision function to load MNIST test data
X_test = datasets.MNIST(
root="./data", train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])
)
# Filter out labels (originally 0-9), leaving only labels 0 and 1
idx = np.append(
np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples]
)
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
# Define torch dataloader with filtered data
test_loader = DataLoader(X_test, batch_size=batch_size, shuffle=True)
# Define and create QNN
def create_qnn():
feature_map = ZZFeatureMap(2)
ansatz = RealAmplitudes(2, reps=1)
qc = QuantumCircuit(2)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
# REMEMBER TO SET input_gradients=True FOR ENABLING HYBRID GRADIENT BACKPROP
qnn = EstimatorQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
input_gradients=True,
)
return qnn
qnn4 = create_qnn()
# Define torch NN module
class Net(Module):
def __init__(self, qnn):
super().__init__()
self.conv1 = Conv2d(1, 2, kernel_size=5)
self.conv2 = Conv2d(2, 16, kernel_size=5)
self.dropout = Dropout2d()
self.fc1 = Linear(256, 64)
self.fc2 = Linear(64, 2) # 2-dimensional input to QNN
self.qnn = TorchConnector(qnn) # Apply torch connector, weights chosen
# uniformly at random from interval [-1,1].
self.fc3 = Linear(1, 1) # 1-dimensional output from QNN
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.qnn(x) # apply QNN
x = self.fc3(x)
return cat((x, 1 - x), -1)
model4 = Net(qnn4)
# Define model, optimizer, and loss function
optimizer = optim.Adam(model4.parameters(), lr=0.001)
loss_func = NLLLoss()
# Start training
epochs = 10 # Set number of epochs
loss_list = [] # Store loss history
model4.train() # Set model to training mode
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad(set_to_none=True) # Initialize gradient
output = model4(data) # Forward pass
loss = loss_func(output, target) # Calculate loss
loss.backward() # Backward pass
optimizer.step() # Optimize weights
total_loss.append(loss.item()) # Store loss
loss_list.append(sum(total_loss) / len(total_loss))
print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1]))
# Plot loss convergence
plt.plot(loss_list)
plt.title("Hybrid NN Training Convergence")
plt.xlabel("Training Iterations")
plt.ylabel("Neg. Log Likelihood Loss")
plt.show()
torch.save(model4.state_dict(), "model4.pt")
qnn5 = create_qnn()
model5 = Net(qnn5)
model5.load_state_dict(torch.load("model4.pt"))
model5.eval() # set model to evaluation mode
with no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model5(data)
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print(
"Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%".format(
sum(total_loss) / len(total_loss), correct / len(test_loader) / batch_size * 100
)
)
# Plot predicted labels
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
model5.eval()
with no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model5(data[0:1])
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(data[0].numpy().squeeze(), cmap="gray")
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title("Predicted {}".format(pred.item()))
count += 1
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit
from qiskit import Aer, transpile
from qiskit.tools.visualization import plot_histogram, plot_state_city
import qiskit.quantum_info as qi
Aer.backends()
simulator = Aer.get_backend('aer_simulator')
# Create circuit
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.measure_all()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get counts
result = simulator.run(circ).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
# Run and get memory
result = simulator.run(circ, shots=10, memory=True).result()
memory = result.get_memory(circ)
print(memory)
# Increase shots to reduce sampling variance
shots = 10000
# Stabilizer simulation method
sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer')
job_stabilizer = sim_stabilizer.run(circ, shots=shots)
counts_stabilizer = job_stabilizer.result().get_counts(0)
# Statevector simulation method
sim_statevector = Aer.get_backend('aer_simulator_statevector')
job_statevector = sim_statevector.run(circ, shots=shots)
counts_statevector = job_statevector.result().get_counts(0)
# Density Matrix simulation method
sim_density = Aer.get_backend('aer_simulator_density_matrix')
job_density = sim_density.run(circ, shots=shots)
counts_density = job_density.result().get_counts(0)
# Matrix Product State simulation method
sim_mps = Aer.get_backend('aer_simulator_matrix_product_state')
job_mps = sim_mps.run(circ, shots=shots)
counts_mps = job_mps.result().get_counts(0)
plot_histogram([counts_stabilizer, counts_statevector, counts_density, counts_mps],
title='Counts for different simulation methods',
legend=['stabilizer', 'statevector',
'density_matrix', 'matrix_product_state'])
from qiskit_aer import AerError
# Initialize a GPU backend
# Note that the cloud instance for tutorials does not have a GPU
# so this will raise an exception.
try:
simulator_gpu = Aer.get_backend('aer_simulator')
simulator_gpu.set_options(device='GPU')
except AerError as e:
print(e)
# Configure a single-precision statevector simulator backend
simulator = Aer.get_backend('aer_simulator_statevector')
simulator.set_options(precision='single')
# Run and get counts
result = simulator.run(circ).result()
counts = result.get_counts(circ)
print(counts)
# Construct quantum circuit without measure
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.save_statevector()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get statevector
result = simulator.run(circ).result()
statevector = result.get_statevector(circ)
plot_state_city(statevector, title='Bell state')
# Construct quantum circuit without measure
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.save_unitary()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get unitary
result = simulator.run(circ).result()
unitary = result.get_unitary(circ)
print("Circuit unitary:\n", np.asarray(unitary).round(5))
# Construct quantum circuit without measure
steps = 5
circ = QuantumCircuit(1)
for i in range(steps):
circ.save_statevector(label=f'psi_{i}')
circ.rx(i * np.pi / steps, 0)
circ.save_statevector(label=f'psi_{steps}')
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
data = result.data(0)
data
# Generate a random statevector
num_qubits = 2
psi = qi.random_statevector(2 ** num_qubits, seed=100)
# Set initial state to generated statevector
circ = QuantumCircuit(num_qubits)
circ.set_statevector(psi)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Use initilize instruction to set initial state
circ = QuantumCircuit(num_qubits)
circ.initialize(psi, range(num_qubits))
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get result data
result = simulator.run(circ).result()
result.data(0)
num_qubits = 2
rho = qi.random_density_matrix(2 ** num_qubits, seed=100)
circ = QuantumCircuit(num_qubits)
circ.set_density_matrix(rho)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Generate a random Clifford C
num_qubits = 2
stab = qi.random_clifford(num_qubits, seed=100)
# Set initial state to stabilizer state C|0>
circ = QuantumCircuit(num_qubits)
circ.set_stabilizer(stab)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Generate a random unitary
num_qubits = 2
unitary = qi.random_unitary(2 ** num_qubits, seed=100)
# Set initial state to unitary
circ = QuantumCircuit(num_qubits)
circ.set_unitary(unitary)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# 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 Operator construction, including OpPrimitives and singletons."""
import unittest
from test.python.opflow import QiskitOpflowTestCase
import numpy as np
from qiskit import QuantumCircuit, BasicAer, execute
from qiskit.circuit import ParameterVector
from qiskit.quantum_info import Statevector
from qiskit.opflow import (
StateFn,
Zero,
One,
Plus,
Minus,
PrimitiveOp,
CircuitOp,
SummedOp,
H,
I,
Z,
X,
Y,
CX,
CircuitStateFn,
DictToCircuitSum,
)
class TestStateConstruction(QiskitOpflowTestCase):
"""State Construction tests."""
def test_state_singletons(self):
"""state singletons test"""
self.assertEqual(Zero.primitive, {"0": 1})
self.assertEqual(One.primitive, {"1": 1})
self.assertEqual((Zero ^ 5).primitive, {"00000": 1})
self.assertEqual((One ^ 5).primitive, {"11111": 1})
self.assertEqual(((Zero ^ One) ^ 3).primitive, {"010101": 1})
def test_zero_broadcast(self):
"""zero broadcast test"""
np.testing.assert_array_almost_equal(((H ^ 5) @ Zero).to_matrix(), (Plus ^ 5).to_matrix())
def test_state_to_matrix(self):
"""state to matrix test"""
np.testing.assert_array_equal(Zero.to_matrix(), np.array([1, 0]))
np.testing.assert_array_equal(One.to_matrix(), np.array([0, 1]))
np.testing.assert_array_almost_equal(
Plus.to_matrix(), (Zero.to_matrix() + One.to_matrix()) / (np.sqrt(2))
)
np.testing.assert_array_almost_equal(
Minus.to_matrix(), (Zero.to_matrix() - One.to_matrix()) / (np.sqrt(2))
)
# TODO Not a great test because doesn't test against validated values
# or test internal representation. Fix this.
gnarly_state = (One ^ Plus ^ Zero ^ Minus * 0.3) @ StateFn(
Statevector.from_label("r0+l")
) + (StateFn(X ^ Z ^ Y ^ I) * 0.1j)
gnarly_mat = gnarly_state.to_matrix()
gnarly_mat_separate = (One ^ Plus ^ Zero ^ Minus * 0.3).to_matrix()
gnarly_mat_separate = np.dot(
gnarly_mat_separate, StateFn(Statevector.from_label("r0+l")).to_matrix()
)
gnarly_mat_separate = gnarly_mat_separate + (StateFn(X ^ Z ^ Y ^ I) * 0.1j).to_matrix()
np.testing.assert_array_almost_equal(gnarly_mat, gnarly_mat_separate)
def test_qiskit_result_instantiation(self):
"""qiskit result instantiation test"""
qc = QuantumCircuit(3)
# REMEMBER: This is Qubit 2 in Operator land.
qc.h(0)
sv_res = execute(qc, BasicAer.get_backend("statevector_simulator")).result()
sv_vector = sv_res.get_statevector()
qc_op = PrimitiveOp(qc) @ Zero
qasm_res = execute(
qc_op.to_circuit(meas=True), BasicAer.get_backend("qasm_simulator")
).result()
np.testing.assert_array_almost_equal(
StateFn(sv_res).to_matrix(), [0.5**0.5, 0.5**0.5, 0, 0, 0, 0, 0, 0]
)
np.testing.assert_array_almost_equal(
StateFn(sv_vector).to_matrix(), [0.5**0.5, 0.5**0.5, 0, 0, 0, 0, 0, 0]
)
np.testing.assert_array_almost_equal(
StateFn(qasm_res).to_matrix(), [0.5**0.5, 0.5**0.5, 0, 0, 0, 0, 0, 0], decimal=1
)
np.testing.assert_array_almost_equal(
((I ^ I ^ H) @ Zero).to_matrix(), [0.5**0.5, 0.5**0.5, 0, 0, 0, 0, 0, 0]
)
np.testing.assert_array_almost_equal(
qc_op.to_matrix(), [0.5**0.5, 0.5**0.5, 0, 0, 0, 0, 0, 0]
)
def test_state_meas_composition(self):
"""state meas composition test"""
pass
# print((~Zero^4).eval(Zero^4))
# print((~One^4).eval(Zero^4))
# print((~One ^ 4).eval(One ^ 4))
# print(StateFn(I^Z, is_measurement=True).eval(One^2))
def test_add_direct(self):
"""add direct test"""
wf = StateFn({"101010": 0.5, "111111": 0.3}) + (Zero ^ 6)
self.assertEqual(wf.primitive, {"101010": 0.5, "111111": 0.3, "000000": 1.0})
wf = (4 * StateFn({"101010": 0.5, "111111": 0.3})) + ((3 + 0.1j) * (Zero ^ 6))
self.assertEqual(
wf.primitive, {"000000": (3 + 0.1j), "101010": (2 + 0j), "111111": (1.2 + 0j)}
)
def test_circuit_state_fn_from_dict_as_sum(self):
"""state fn circuit from dict as sum test"""
statedict = {"1010101": 0.5, "1000000": 0.1, "0000000": 0.2j, "1111111": 0.5j}
sfc_sum = CircuitStateFn.from_dict(statedict)
self.assertIsInstance(sfc_sum, SummedOp)
for sfc_op in sfc_sum.oplist:
self.assertIsInstance(sfc_op, CircuitStateFn)
samples = sfc_op.sample()
self.assertIn(list(samples.keys())[0], statedict)
self.assertEqual(sfc_op.coeff, statedict[list(samples.keys())[0]])
np.testing.assert_array_almost_equal(StateFn(statedict).to_matrix(), sfc_sum.to_matrix())
def test_circuit_state_fn_from_dict_initialize(self):
"""state fn circuit from dict initialize test"""
statedict = {"101": 0.5, "100": 0.1, "000": 0.2, "111": 0.5}
sfc = CircuitStateFn.from_dict(statedict)
self.assertIsInstance(sfc, CircuitStateFn)
samples = sfc.sample()
np.testing.assert_array_almost_equal(
StateFn(statedict).to_matrix(), np.round(sfc.to_matrix(), decimals=1)
)
for k, v in samples.items():
self.assertIn(k, statedict)
# It's ok if these are far apart because the dict is sampled.
self.assertAlmostEqual(v, np.abs(statedict[k]) ** 0.5, delta=0.5)
# Follows same code path as above, but testing to be thorough
sfc_vector = CircuitStateFn.from_vector(StateFn(statedict).to_matrix())
np.testing.assert_array_almost_equal(StateFn(statedict).to_matrix(), sfc_vector.to_matrix())
# #1276
def test_circuit_state_fn_from_complex_vector_initialize(self):
"""state fn circuit from complex vector initialize test"""
sfc = CircuitStateFn.from_vector(np.array([1j / np.sqrt(2), 0, 1j / np.sqrt(2), 0]))
self.assertIsInstance(sfc, CircuitStateFn)
def test_sampling(self):
"""state fn circuit from dict initialize test"""
statedict = {"101": 0.5 + 1.0j, "100": 0.1 + 2.0j, "000": 0.2 + 0.0j, "111": 0.5 + 1.0j}
sfc = CircuitStateFn.from_dict(statedict)
circ_samples = sfc.sample()
dict_samples = StateFn(statedict).sample()
vec_samples = StateFn(statedict).to_matrix_op().sample()
for k, v in circ_samples.items():
self.assertIn(k, dict_samples)
self.assertIn(k, vec_samples)
# It's ok if these are far apart because the dict is sampled.
self.assertAlmostEqual(v, np.abs(dict_samples[k]) ** 0.5, delta=0.5)
self.assertAlmostEqual(v, np.abs(vec_samples[k]) ** 0.5, delta=0.5)
def test_dict_to_circuit_sum(self):
"""Test DictToCircuitSum converter."""
# Test qubits < entires, so dict is converted to Initialize CircuitStateFn
dict_state_3q = StateFn({"101": 0.5, "100": 0.1, "000": 0.2, "111": 0.5})
circuit_state_3q = DictToCircuitSum().convert(dict_state_3q)
self.assertIsInstance(circuit_state_3q, CircuitStateFn)
np.testing.assert_array_almost_equal(
dict_state_3q.to_matrix(), circuit_state_3q.to_matrix()
)
# Test qubits >= entires, so dict is converted to Initialize CircuitStateFn
dict_state_4q = dict_state_3q ^ Zero
circuit_state_4q = DictToCircuitSum().convert(dict_state_4q)
self.assertIsInstance(circuit_state_4q, SummedOp)
np.testing.assert_array_almost_equal(
dict_state_4q.to_matrix(), circuit_state_4q.to_matrix()
)
# Test VectorStateFn conversion
vect_state_3q = dict_state_3q.to_matrix_op()
circuit_state_3q_vect = DictToCircuitSum().convert(vect_state_3q)
self.assertIsInstance(circuit_state_3q_vect, CircuitStateFn)
np.testing.assert_array_almost_equal(
vect_state_3q.to_matrix(), circuit_state_3q_vect.to_matrix()
)
def test_circuit_permute(self):
r"""Test the CircuitStateFn's .permute method"""
perm = range(7)[::-1]
c_op = (
((CX ^ 3) ^ X)
@ (H ^ 7)
@ (X ^ Y ^ Z ^ I ^ X ^ X ^ X)
@ (Y ^ (CX ^ 3))
@ (X ^ Y ^ Z ^ I ^ X ^ X ^ X)
) @ Zero
c_op_perm = c_op.permute(perm)
self.assertNotEqual(c_op, c_op_perm)
c_op_id = c_op_perm.permute(perm)
self.assertEqual(c_op, c_op_id)
def test_primitive_param_binding(self):
"""Test that assign_parameters binds parameters of both the underlying primitive and coeffs."""
theta = ParameterVector("theta", 2)
# only OperatorStateFn can have a primitive with a parameterized coefficient
op = StateFn(theta[0] * X) * theta[1]
bound = op.assign_parameters(dict(zip(theta, [0.2, 0.3])))
self.assertEqual(bound.coeff, 0.3)
self.assertEqual(bound.primitive.coeff, 0.2)
# #6003
def test_flatten_statefn_composed_with_composed_op(self):
"""Test that composing a StateFn with a ComposedOp constructs a single ComposedOp"""
circuit = QuantumCircuit(1)
vector = [1, 0]
ex = ~StateFn(I) @ (CircuitOp(circuit) @ StateFn(vector))
self.assertEqual(len(ex), 3)
self.assertEqual(ex.eval(), 1)
def test_tensorstate_to_matrix(self):
"""Test tensored states to matrix works correctly with a global coefficient.
Regression test of Qiskit/qiskit-terra#9398.
"""
state = 0.5 * (Plus ^ Zero)
expected = 1 / (2 * np.sqrt(2)) * np.array([1, 0, 1, 0])
np.testing.assert_almost_equal(state.to_matrix(), expected)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
p = 0.2
import numpy as np
from qiskit.circuit import QuantumCircuit
class BernoulliA(QuantumCircuit):
"""A circuit representing the Bernoulli A operator."""
def __init__(self, probability):
super().__init__(1) # circuit on 1 qubit
theta_p = 2 * np.arcsin(np.sqrt(probability))
self.ry(theta_p, 0)
class BernoulliQ(QuantumCircuit):
"""A circuit representing the Bernoulli Q operator."""
def __init__(self, probability):
super().__init__(1) # circuit on 1 qubit
self._theta_p = 2 * np.arcsin(np.sqrt(probability))
self.ry(2 * self._theta_p, 0)
def power(self, k):
# implement the efficient power of Q
q_k = QuantumCircuit(1)
q_k.ry(2 * k * self._theta_p, 0)
return q_k
A = BernoulliA(p)
Q = BernoulliQ(p)
from qiskit.algorithms import EstimationProblem
problem = EstimationProblem(
state_preparation=A, # A operator
grover_operator=Q, # Q operator
objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0
)
from qiskit.primitives import Sampler
sampler = Sampler()
from qiskit.algorithms import AmplitudeEstimation
ae = AmplitudeEstimation(
num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy
sampler=sampler,
)
ae_result = ae.estimate(problem)
print(ae_result.estimation)
import matplotlib.pyplot as plt
# plot estimated values
gridpoints = list(ae_result.samples.keys())
probabilities = list(ae_result.samples.values())
plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities))
plt.axvline(p, color="r", ls="--")
plt.xticks(size=15)
plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.title("Estimated Values", size=15)
plt.ylabel("Probability", size=15)
plt.xlabel(r"Amplitude $a$", size=15)
plt.ylim((0, 1))
plt.grid()
plt.show()
print("Interpolated MLE estimator:", ae_result.mle)
ae_circuit = ae.construct_circuit(problem)
ae_circuit.decompose().draw(
"mpl", style="iqx"
) # decompose 1 level: exposes the Phase estimation circuit!
from qiskit import transpile
basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"]
transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx")
from qiskit.algorithms import IterativeAmplitudeEstimation
iae = IterativeAmplitudeEstimation(
epsilon_target=0.01, # target accuracy
alpha=0.05, # width of the confidence interval
sampler=sampler,
)
iae_result = iae.estimate(problem)
print("Estimate:", iae_result.estimation)
iae_circuit = iae.construct_circuit(problem, k=3)
iae_circuit.draw("mpl", style="iqx")
from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation
mlae = MaximumLikelihoodAmplitudeEstimation(
evaluation_schedule=3, # log2 of the maximal Grover power
sampler=sampler,
)
mlae_result = mlae.estimate(problem)
print("Estimate:", mlae_result.estimation)
from qiskit.algorithms import FasterAmplitudeEstimation
fae = FasterAmplitudeEstimation(
delta=0.01, # target accuracy
maxiter=3, # determines the maximal power of the Grover operator
sampler=sampler,
)
fae_result = fae.estimate(problem)
print("Estimate:", fae_result.estimation)
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/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import pandas as pd
import itertools
import cma
import os
import sys
import argparse
import pickle
import random
import re
from pprint import pprint
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute
from qiskit import Aer
from qiskit import IBMQ
from qiskit.compiler import transpile
from qiskit.providers.aer.noise.noise_model import NoiseModel
from qiskit.test.mock import *
from qiskit.providers.aer import AerSimulator, QasmSimulator
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
import mitiq
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)
real_device = provider.get_backend('ibmq_jakarta')
def qrem_encoder(num_qubits: int, initial_layout: list) -> list:
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
return transpile(meas_calibs, initial_layout=initial_layout, basis_gates=["sx", "rz", "cx"])
def execute_circuits(qcs: list, backend) -> (qiskit.providers.Job, str):
job = exec
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
def qrem_decoder():
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
import matplotlib.pyplot as plt
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
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
# Returns the matrix representation of the XXX Heisenberg model for 3 spin-1/2 particles in a line
def H_heis3():
# Interactions (I is the identity matrix; X, Y, and Z are Pauli matricies; ^ is a tensor product)
XXs = (I^X^X) + (X^X^I)
YYs = (I^Y^Y) + (Y^Y^I)
ZZs = (I^Z^Z) + (Z^Z^I)
# Sum interactions
H = XXs + YYs + ZZs
# Return Hamiltonian
return H
# Returns the matrix representation of U_heis3(t) for a given time t assuming an XXX Heisenberg Hamiltonian for 3 spins-1/2 particles in a line
def U_heis3(t):
# Compute XXX Hamiltonian for 3 spins in a line
H = H_heis3()
# Return the exponential of -i multipled by time t multipled by the 3 spin XXX Heisenberg Hamilonian
return (t * H).exp_i()
# Define array of time points
ts = np.linspace(0, np.pi, 100)
# Define initial state |110>
initial_state = One^One^Zero
# Compute probability of remaining in |110> state over the array of time points
# ~initial_state gives the bra of the initial state (<110|)
# @ is short hand for matrix multiplication
# U_heis3(t) is the unitary time evolution at time t
# t needs to be wrapped with float(t) to avoid a bug
# (...).eval() returns the inner product <110|U_heis3(t)|110>
# np.abs(...)**2 is the modulus squared of the innner product which is the expectation value, or probability, of remaining in |110>
probs_110 = [np.abs((~initial_state @ U_heis3(float(t)) @ initial_state).eval())**2 for t in ts]
# Plot evolution of |110>
plt.plot(ts, probs_110)
plt.xlabel('time')
plt.ylabel(r'probability of state $|110\rangle$')
plt.title(r'Evolution of state $|110\rangle$ under $H_{Heis3}$')
plt.grid()
plt.show()
# Importing standard Qiskit modules
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# 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')
# load IBMQ Account data
# IBMQ.save_account(TOKEN) # replace TOKEN with your API token string (https://quantum-computing.ibm.com/lab/docs/iql/manage/account/ibmq)
provider = IBMQ.load_account()
# Get backend for experiment
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
jakarta = provider.get_backend('ibmq_jakarta')
# properties = jakarta.properties()
# Simulated backend based on ibmq_jakarta's device noise profile
sim_noisy_jakarta = QasmSimulator.from_backend(provider.get_backend('ibmq_jakarta'))
# Noiseless simulated backend
sim = QasmSimulator()
# Parameterize variable t to be evaluated at t=pi later
t = Parameter('t')
# Build a subcircuit for XX(t) two-qubit gate
XX_qr = QuantumRegister(2)
XX_qc = QuantumCircuit(XX_qr, name='XX')
XX_qc.ry(np.pi/2,[0,1])
XX_qc.cnot(0,1)
XX_qc.rz(2 * t, 1)
XX_qc.cnot(0,1)
XX_qc.ry(-np.pi/2,[0,1])
# Convert custom quantum circuit into a gate
XX = XX_qc.to_instruction()
# Build a subcircuit for YY(t) two-qubit gate
YY_qr = QuantumRegister(2)
YY_qc = QuantumCircuit(YY_qr, name='YY')
YY_qc.rx(np.pi/2,[0,1])
YY_qc.cnot(0,1)
YY_qc.rz(2 * t, 1)
YY_qc.cnot(0,1)
YY_qc.rx(-np.pi/2,[0,1])
# Convert custom quantum circuit into a gate
YY = YY_qc.to_instruction()
# Build a subcircuit for ZZ(t) two-qubit gate
ZZ_qr = QuantumRegister(2)
ZZ_qc = QuantumCircuit(ZZ_qr, name='ZZ')
ZZ_qc.cnot(0,1)
ZZ_qc.rz(2 * t, 1)
ZZ_qc.cnot(0,1)
# Convert custom quantum circuit into a gate
ZZ = ZZ_qc.to_instruction()
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
Trot_qr = QuantumRegister(num_qubits)
Trot_qc = QuantumCircuit(Trot_qr, name='Trot')
for i in range(0, num_qubits - 1):
Trot_qc.append(ZZ, [Trot_qr[i], Trot_qr[i+1]])
Trot_qc.append(YY, [Trot_qr[i], Trot_qr[i+1]])
Trot_qc.append(XX, [Trot_qr[i], Trot_qr[i+1]])
# Convert custom quantum circuit into a gate
Trot_gate = Trot_qc.to_instruction()
# The final time of the state evolution
target_time = np.pi
# Number of trotter steps
trotter_steps = 4 ### CAN BE >= 4
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(7)
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([3,5]) # 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[3], qr[5]])
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({t: target_time/trotter_steps})
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [qr[1], qr[3], qr[5]])
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw() # only view trotter gates
shots = 8192
reps = 8
backend = sim_noisy_jakarta
# reps = 8
# backend = jakarta
jobs = []
for _ in range(reps):
# execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
for job in jobs:
job_monitor(job)
try:
if job.error_message() is not None:
print(job.error_message())
except:
pass
# 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 job in jobs:
fid = state_tomo(job.result(), st_qcs)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
# ******************************************************************************
# Copyright (c) 2023 University of Stuttgart
#
# See the NOTICE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ******************************************************************************
from qiskit import QiskitError
from qiskit.providers.jobstatus import JOB_FINAL_STATES
from qiskit_ionq import IonQProvider
def get_qpu(token, qpu_name):
provider = IonQProvider(token)
if "simulator" not in qpu_name:
qpu_name = qpu_name.replace(" ", "-").lower()
ionq_signature = "ionq_qpu."
qpu_name = ionq_signature + qpu_name
return provider.get_backend(qpu_name)
def execute_job(transpiled_circuit, shots, backend):
"""Generate qObject from transpiled circuit and execute it. Return result."""
try:
job = backend.run(transpiled_circuit, shots=shots)
job_status = job.status()
while job_status not in JOB_FINAL_STATES:
print("The job is still running")
job_status = job.status()
job_result = job.result()
print("\nJob result:")
print(job_result)
job_result_dict = job_result.to_dict()
print(job_result_dict)
try:
statevector = job_result.get_statevector()
print("\nState vector:")
print(statevector)
except QiskitError:
statevector = None
print("No statevector available!")
try:
counts = job_result.get_counts()
print("\nCounts:")
print(counts)
except QiskitError:
counts = None
print("No counts available!")
try:
unitary = job_result.get_unitary()
print("\nUnitary:")
print(unitary)
except QiskitError:
unitary = None
print("No unitary available!")
return {'job_result_raw': job_result_dict, 'statevector': statevector, 'counts': counts, 'unitary': unitary}
except Exception:
return None
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 8 18:22:28 2022
Created on Thu Oct 13 10:29:00 2022
@author: pej
"""
import numpy as np
import pandas as pd
from qiskit import QuantumCircuit
from MultiQubitGate.functions import multiqubit
from BasicFunctions.functions import getBinary, getState
from Phase.PhaseFunctions.computeAmplFromShots import computeAmplFromShots
####################################################################
####################################################################
####################################################################
####################################################################
################### When c0 == 0
def getRealPart(df_ampl, ### amplitude |c_j| computed from shots
circ_U,
circ_UQU,
Q,
significant_figure,
nspins,
shots,
j_ref,
machine_precision=10,
):
'''
for the scenario where j_ref=0 is NOT in df_ampl.index
or c_0 == 0
'''
# ################## FOR COMPARISON
# #### df_comp_exact, ### this is exact c_j for benchmark
# circ_state = getState(circ_UQU, machine_precision)
# vec=circ_state[df_ampl.index, : ]
# df_comp_exact = pd.DataFrame(vec, df_ampl.index)
# ##################
circ_adj = QuantumCircuit(nspins+1)
_gamma = -np.pi/4
circ_adj.ry(_gamma, qubit=-1) ### R_gamma
circ_adj.x(qubit=-1) ### X
### U
### attaches U to the q=1 ... q=n qubits, while q=0 is the ancillary
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U) )
### control-Q ; Ancillary - n target
for (q,o) in enumerate(Q):
if o==1:
circ_adj.cx(-1, q)
if o==2:
circ_adj.cy(-1, q)
if o==3:
circ_adj.cz(-1, q)
### U^
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U).inverse())
### control-P_{0 j_ref}
circ_adj.x(qubit=nspins)
J1 = list(getBinary(j_ref, nspins)) + [0]
for (q,o) in enumerate(J1):
if o==1:
circ_adj.cx(nspins, q)
circ_adj.x(nspins)
### S and H on ancillary
circ_adj.s(-1)
circ_adj.h(nspins)
#################### for each j2 The T_{j_ref -> j2} is different
indexs = df_ampl.index ### the observed bit strings from shots; j's
parts_real= [[ 0]] # ref
part_indexs=[j_ref]
for j2 in indexs:
#### T Gate
p_12_int = j2^j_ref
## operator
P_12 = getBinary(p_12_int, nspins).tolist()+[0] #bitstring array of p12
mult_gate, op_count = multiqubit(P_12, np.pi/4) # turned into T gate
circ_uhu_adj = circ_adj.compose( mult_gate ) #add to the circuit
##### from shots
m1, __ = computeAmplFromShots(circ_uhu_adj, shots, j_ref)
m1 = np.round(m1, significant_figure)
#### amplitude from shots
c2_2 = df_ampl[0][j2]**2 ### |c_j|^2
c2_2 = np.round(c2_2, significant_figure)
#### compute the cos of theta
real_part = (m1 - (1/4) * c2_2**2 * (np.cos(_gamma/2)**2) - (1/4)*(np.sin(_gamma/2))**2 )/ ((-1/2) * np.cos(_gamma/2) * np.sin(_gamma/2))
#### round to allowed prcision
real_part = np.round(real_part, significant_figure)
### collect results
parts_real.append([ real_part,
# df_comp_exact[0][j2].real
])
part_indexs.append(j2)
parts_real = pd.DataFrame(parts_real, index= part_indexs).round(significant_figure)
parts_real.columns=[ 'c_real_sim',
# 'c_real_exct'
]
return parts_real
if __name__=='__main__':
pass
from Amplitude.Amplitude import Amplitude
################################################################
################################################################
##################### FOR TEST #######################
################################################################
################################################################
################################################################
################################################################
################################################################
def getRandomU(nspins, num_layers=10):
circ = QuantumCircuit(nspins)
for l in range(num_layers):
for i in range(nspins):
##############
q=np.random.randint(nspins)
g=np.random.randint(1, 4)
p=np.random.uniform(-1,1)
if g==1:
circ.rx(p,q)
if g==2:
circ.ry(p,q)
if g==2:
circ.rz(p,q)
##############
q=np.random.randint(nspins-1)
circ.cnot(q, q+1)
return circ
################################################################
################################################################
def getRandomQ(nspins):
Q = np.random.randint(0,2, size=nspins)
return Q
################################################################
################################################################
def getCircUQU(circ, Q):
circ_uhu=QuantumCircuit.copy(circ)
for (q,o) in enumerate(Q):
if o==0:
pass
if o==1:
circ_uhu.x(q)
if o==2:
circ_uhu.y(q)
if o==3:
circ_uhu.z(q)
circ_uhu=circ_uhu.compose(QuantumCircuit.copy(circ).inverse())
return circ_uhu
################################################################
################################################################
seed = 1211
np.random.seed(seed)
################################################################
################################################################
nspins = 6 # >=2
num_layers =2
num_itr =1
machine_precision = 10
shots = 1000
eta = 100
significant_figures = 3#np.log10(np.sqrt(shots)).astype(int)
circ_U = getRandomU(nspins, num_layers)
Q = getRandomQ(nspins)
circ_UQU = getCircUQU(circ_U, Q)
print('Q=', Q)
## ### amplitude |c_j| computed from shots
localAmplitudeObj = Amplitude(circ_U, circ_UQU, shots, eta, significant_figures, machine_precision)
localAmplitudeObj()
df_ampl = localAmplitudeObj.df_ampl
######## EXCLUDE index 0
try:
df_ampl = df_ampl.drop(index=0)
except:
pass
print('df_ampl')
print(df_ampl)
print()
#### choose the ref
j_ref = np.random.randint(0, 2**nspins)
while j_ref in df_ampl.index:
j_ref = np.random.randint(0, 2**nspins)
print('j_ref = ' , j_ref)
print('number of js = ' , df_ampl.shape[0])
parts_real = getRealPart(df_ampl, ### amplitude |c_j| computed from shots
circ_U,
circ_UQU,
Q,
significant_figures,
nspins,
shots,
j_ref,
)
print(parts_real)
# print('\n\n##### sign errors')
# num_error = 0
# for jj in parts_real.index:
# if parts_real['c_real_exct'][jj]>=0 and parts_real['c_real_sim'][jj]>=0:
# num_error+= 0
# else:
# if parts_real['c_real_exct'][jj]<0 and parts_real['c_real_sim'][jj]<0:
# num_error+= 0
# else:
# print(parts_real['c_real_exct'][jj], ' ', parts_real['c_real_sim'][jj])
# num_error+= 1
# print('error %= ',
# np.round(num_error/parts_real.shape[0]*100, 2),
# 'num incorrect = ',
# num_error,
# 'total = ',
# parts_real.shape[0]
# )
# print('\n\n##### L2 norm')
# error_L2 = 0
# for jj in parts_real.index:
# diff = np.abs(parts_real['c_real_exct'][jj] - parts_real['c_real_sim'][jj])
# error = diff/( + 10**(-1*significant_figures) + np.abs(parts_real['c_real_exct'][jj] ) )
# print(error)
# error_L2+= error/parts_real.shape[0]
# print('---')
# print(error_L2)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from sklearn.datasets import make_blobs
# example dataset
features, labels = make_blobs(n_samples=20, n_features=2, centers=2, random_state=3, shuffle=True)
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
features = MinMaxScaler(feature_range=(0, np.pi)).fit_transform(features)
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=15, shuffle=False
)
# number of qubits is equal to the number of features
num_qubits = 2
# number of steps performed during the training procedure
tau = 100
# regularization parameter
C = 1000
from qiskit import BasicAer
from qiskit.circuit.library import ZFeatureMap
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.kernels import FidelityQuantumKernel
algorithm_globals.random_seed = 12345
feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1)
qkernel = FidelityQuantumKernel(feature_map=feature_map)
from qiskit_machine_learning.algorithms import PegasosQSVC
pegasos_qsvc = PegasosQSVC(quantum_kernel=qkernel, C=C, num_steps=tau)
# training
pegasos_qsvc.fit(train_features, train_labels)
# testing
pegasos_score = pegasos_qsvc.score(test_features, test_labels)
print(f"PegasosQSVC classification test score: {pegasos_score}")
grid_step = 0.2
margin = 0.2
grid_x, grid_y = np.meshgrid(
np.arange(-margin, np.pi + margin, grid_step), np.arange(-margin, np.pi + margin, grid_step)
)
meshgrid_features = np.column_stack((grid_x.ravel(), grid_y.ravel()))
meshgrid_colors = pegasos_qsvc.predict(meshgrid_features)
import matplotlib.pyplot as plt
plt.figure(figsize=(5, 5))
meshgrid_colors = meshgrid_colors.reshape(grid_x.shape)
plt.pcolormesh(grid_x, grid_y, meshgrid_colors, cmap="RdBu", shading="auto")
plt.scatter(
train_features[:, 0][train_labels == 0],
train_features[:, 1][train_labels == 0],
marker="s",
facecolors="w",
edgecolors="r",
label="A train",
)
plt.scatter(
train_features[:, 0][train_labels == 1],
train_features[:, 1][train_labels == 1],
marker="o",
facecolors="w",
edgecolors="b",
label="B train",
)
plt.scatter(
test_features[:, 0][test_labels == 0],
test_features[:, 1][test_labels == 0],
marker="s",
facecolors="r",
edgecolors="r",
label="A test",
)
plt.scatter(
test_features[:, 0][test_labels == 1],
test_features[:, 1][test_labels == 1],
marker="o",
facecolors="b",
edgecolors="b",
label="B test",
)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Pegasos Classification")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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.
"""Test QASM simulator."""
import os
import unittest
import io
from logging import StreamHandler, getLogger
import sys
import numpy as np
from qiskit import execute
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.compiler import transpile, assemble
from qiskit.providers.basicaer import QasmSimulatorPy
from qiskit.test import providers
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestBasicAerQasmSimulator(providers.BackendTestCase):
"""Test the Basic qasm_simulator."""
backend_cls = QasmSimulatorPy
def setUp(self):
super().setUp()
self.seed = 88
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
qasm_filename = os.path.join(qasm_dir, "example.qasm")
transpiled_circuit = QuantumCircuit.from_qasm_file(qasm_filename)
transpiled_circuit.name = "test"
transpiled_circuit = transpile(transpiled_circuit, backend=self.backend)
self.qobj = assemble(transpiled_circuit, shots=1000, seed_simulator=self.seed)
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel("DEBUG")
self.log_output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.log_output))
def assertExecuteLog(self, log_msg):
"""Runs execute and check for logs containing specified message"""
shots = 100
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(4, "cr")
circuit = QuantumCircuit(qr, cr)
execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed)
self.log_output.seek(0)
# Filter unrelated log lines
output_lines = self.log_output.readlines()
execute_log_lines = [x for x in output_lines if log_msg in x]
self.assertTrue(len(execute_log_lines) > 0)
def test_submission_log_time(self):
"""Check Total Job Submission Time is logged"""
self.assertExecuteLog("Total Job Submission Time")
def test_qasm_simulator_single_shot(self):
"""Test single shot run."""
shots = 1
self.qobj.config.shots = shots
result = self.backend.run(self.qobj).result()
self.assertEqual(result.success, True)
def test_measure_sampler_repeated_qubits(self):
"""Test measure sampler if qubits measured more than once."""
shots = 100
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(4, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
circuit.measure(qr[1], cr[2])
circuit.measure(qr[0], cr[3])
target = {"0110": shots}
job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target)
def test_measure_sampler_single_qubit(self):
"""Test measure sampler if single-qubit is measured."""
shots = 100
num_qubits = 5
qr = QuantumRegister(num_qubits, "qr")
cr = ClassicalRegister(1, "cr")
for qubit in range(num_qubits):
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[qubit])
circuit.measure(qr[qubit], cr[0])
target = {"1": shots}
job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target)
def test_measure_sampler_partial_qubit(self):
"""Test measure sampler if single-qubit is measured."""
shots = 100
num_qubits = 5
qr = QuantumRegister(num_qubits, "qr")
cr = ClassicalRegister(4, "cr")
# ░ ░ ░ ┌─┐ ░
# qr_0: ──────░─────░─────░─┤M├─░────
# ┌───┐ ░ ░ ┌─┐ ░ └╥┘ ░
# qr_1: ┤ X ├─░─────░─┤M├─░──╫──░────
# └───┘ ░ ░ └╥┘ ░ ║ ░
# qr_2: ──────░─────░──╫──░──╫──░────
# ┌───┐ ░ ┌─┐ ░ ║ ░ ║ ░ ┌─┐
# qr_3: ┤ X ├─░─┤M├─░──╫──░──╫──░─┤M├
# └───┘ ░ └╥┘ ░ ║ ░ ║ ░ └╥┘
# qr_4: ──────░──╫──░──╫──░──╫──░──╫─
# ░ ║ ░ ║ ░ ║ ░ ║
# cr: 4/═════════╩═════╩═════╩═════╩═
# 1 0 2 3
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[3])
circuit.x(qr[1])
circuit.barrier(qr)
circuit.measure(qr[3], cr[1])
circuit.barrier(qr)
circuit.measure(qr[1], cr[0])
circuit.barrier(qr)
circuit.measure(qr[0], cr[2])
circuit.barrier(qr)
circuit.measure(qr[3], cr[3])
target = {"1011": shots}
job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target)
def test_qasm_simulator(self):
"""Test data counts output for single circuit run against reference."""
result = self.backend.run(self.qobj).result()
shots = 1024
threshold = 0.04 * shots
counts = result.get_counts("test")
target = {
"100 100": shots / 8,
"011 011": shots / 8,
"101 101": shots / 8,
"111 111": shots / 8,
"000 000": shots / 8,
"010 010": shots / 8,
"110 110": shots / 8,
"001 001": shots / 8,
}
self.assertDictAlmostEqual(counts, target, threshold)
def test_if_statement(self):
"""Test if statements."""
shots = 100
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
# ┌───┐┌─┐ ┌─┐
# qr_0: ┤ X ├┤M├──────────┤M├──────
# ├───┤└╥┘┌─┐ └╥┘┌─┐
# qr_1: ┤ X ├─╫─┤M├────────╫─┤M├───
# └───┘ ║ └╥┘ ┌───┐ ║ └╥┘┌─┐
# qr_2: ──────╫──╫──┤ X ├──╫──╫─┤M├
# ║ ║ └─╥─┘ ║ ║ └╥┘
# ║ ║ ┌──╨──┐ ║ ║ ║
# cr: 3/══════╩══╩═╡ 0x3 ╞═╩══╩══╩═
# 0 1 └─────┘ 0 1 2
circuit_if_true = QuantumCircuit(qr, cr)
circuit_if_true.x(qr[0])
circuit_if_true.x(qr[1])
circuit_if_true.measure(qr[0], cr[0])
circuit_if_true.measure(qr[1], cr[1])
circuit_if_true.x(qr[2]).c_if(cr, 0x3)
circuit_if_true.measure(qr[0], cr[0])
circuit_if_true.measure(qr[1], cr[1])
circuit_if_true.measure(qr[2], cr[2])
# ┌───┐┌─┐ ┌─┐
# qr_0: ┤ X ├┤M├───────┤M├──────
# └┬─┬┘└╥┘ └╥┘┌─┐
# qr_1: ─┤M├──╫─────────╫─┤M├───
# └╥┘ ║ ┌───┐ ║ └╥┘┌─┐
# qr_2: ──╫───╫──┤ X ├──╫──╫─┤M├
# ║ ║ └─╥─┘ ║ ║ └╥┘
# ║ ║ ┌──╨──┐ ║ ║ ║
# cr: 3/══╩═══╩═╡ 0x3 ╞═╩══╩══╩═
# 1 0 └─────┘ 0 1 2
circuit_if_false = QuantumCircuit(qr, cr)
circuit_if_false.x(qr[0])
circuit_if_false.measure(qr[0], cr[0])
circuit_if_false.measure(qr[1], cr[1])
circuit_if_false.x(qr[2]).c_if(cr, 0x3)
circuit_if_false.measure(qr[0], cr[0])
circuit_if_false.measure(qr[1], cr[1])
circuit_if_false.measure(qr[2], cr[2])
job = execute(
[circuit_if_true, circuit_if_false],
backend=self.backend,
shots=shots,
seed_simulator=self.seed,
)
result = job.result()
counts_if_true = result.get_counts(circuit_if_true)
counts_if_false = result.get_counts(circuit_if_false)
self.assertEqual(counts_if_true, {"111": 100})
self.assertEqual(counts_if_false, {"001": 100})
def test_bit_cif_crossaffect(self):
"""Test if bits in a classical register other than
the single conditional bit affect the conditioned operation."""
# ┌───┐ ┌─┐
# q0_0: ────────┤ H ├──────────┤M├
# ┌───┐ └─╥─┘ ┌─┐ └╥┘
# q0_1: ┤ X ├─────╫──────┤M├────╫─
# ├───┤ ║ └╥┘┌─┐ ║
# q0_2: ┤ X ├─────╫───────╫─┤M├─╫─
# └───┘┌────╨─────┐ ║ └╥┘ ║
# c0: 3/═════╡ c0_0=0x1 ╞═╩══╩══╬═
# └──────────┘ 1 2 ║
# c1: 1/════════════════════════╩═
# 0
shots = 100
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
cr1 = ClassicalRegister(1)
circuit = QuantumCircuit(qr, cr, cr1)
circuit.x([qr[1], qr[2]])
circuit.measure(qr[1], cr[1])
circuit.measure(qr[2], cr[2])
circuit.h(qr[0]).c_if(cr[0], True)
circuit.measure(qr[0], cr1[0])
job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed)
result = job.result().get_counts()
target = {"0 110": 100}
self.assertEqual(result, target)
def test_teleport(self):
"""Test teleportation as in tutorials"""
# ┌─────────┐ ┌───┐ ░ ┌─┐
# qr_0: ┤ Ry(π/4) ├───────■──┤ H ├─░─┤M├────────────────────
# └──┬───┬──┘ ┌─┴─┐└───┘ ░ └╥┘┌─┐
# qr_1: ───┤ H ├─────■──┤ X ├──────░──╫─┤M├─────────────────
# └───┘ ┌─┴─┐└───┘ ░ ║ └╥┘ ┌───┐ ┌───┐ ┌─┐
# qr_2: ───────────┤ X ├───────────░──╫──╫──┤ Z ├──┤ X ├─┤M├
# └───┘ ░ ║ ║ └─╥─┘ └─╥─┘ └╥┘
# ║ ║ ┌──╨──┐ ║ ║
# cr0: 1/═════════════════════════════╩══╬═╡ 0x1 ╞═══╬════╬═
# 0 ║ └─────┘┌──╨──┐ ║
# cr1: 1/════════════════════════════════╩════════╡ 0x1 ╞═╬═
# 0 └─────┘ ║
# cr2: 1/═════════════════════════════════════════════════╩═
# 0
self.log.info("test_teleport")
pi = np.pi
shots = 2000
qr = QuantumRegister(3, "qr")
cr0 = ClassicalRegister(1, "cr0")
cr1 = ClassicalRegister(1, "cr1")
cr2 = ClassicalRegister(1, "cr2")
circuit = QuantumCircuit(qr, cr0, cr1, cr2, name="teleport")
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
circuit.ry(pi / 4, qr[0])
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.barrier(qr)
circuit.measure(qr[0], cr0[0])
circuit.measure(qr[1], cr1[0])
circuit.z(qr[2]).c_if(cr0, 1)
circuit.x(qr[2]).c_if(cr1, 1)
circuit.measure(qr[2], cr2[0])
job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed)
results = job.result()
data = results.get_counts("teleport")
alice = {
"00": data["0 0 0"] + data["1 0 0"],
"01": data["0 1 0"] + data["1 1 0"],
"10": data["0 0 1"] + data["1 0 1"],
"11": data["0 1 1"] + data["1 1 1"],
}
bob = {
"0": data["0 0 0"] + data["0 1 0"] + data["0 0 1"] + data["0 1 1"],
"1": data["1 0 0"] + data["1 1 0"] + data["1 0 1"] + data["1 1 1"],
}
self.log.info("test_teleport: circuit:")
self.log.info(circuit.qasm())
self.log.info("test_teleport: data %s", data)
self.log.info("test_teleport: alice %s", alice)
self.log.info("test_teleport: bob %s", bob)
alice_ratio = 1 / np.tan(pi / 8) ** 2
bob_ratio = bob["0"] / float(bob["1"])
error = abs(alice_ratio - bob_ratio) / alice_ratio
self.log.info("test_teleport: relative error = %s", error)
self.assertLess(error, 0.05)
def test_memory(self):
"""Test memory."""
# ┌───┐ ┌─┐
# qr_0: ┤ H ├──■─────┤M├───
# └───┘┌─┴─┐ └╥┘┌─┐
# qr_1: ─────┤ X ├────╫─┤M├
# └┬─┬┘ ║ └╥┘
# qr_2: ──────┤M├─────╫──╫─
# ┌───┐ └╥┘ ┌─┐ ║ ║
# qr_3: ┤ X ├──╫──┤M├─╫──╫─
# └───┘ ║ └╥┘ ║ ║
# cr0: 2/══════╬═══╬══╩══╩═
# ║ ║ 0 1
# ║ ║
# cr1: 2/══════╩═══╩═══════
# 0 1
qr = QuantumRegister(4, "qr")
cr0 = ClassicalRegister(2, "cr0")
cr1 = ClassicalRegister(2, "cr1")
circ = QuantumCircuit(qr, cr0, cr1)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.x(qr[3])
circ.measure(qr[0], cr0[0])
circ.measure(qr[1], cr0[1])
circ.measure(qr[2], cr1[0])
circ.measure(qr[3], cr1[1])
shots = 50
job = execute(circ, backend=self.backend, shots=shots, memory=True)
result = job.result()
memory = result.get_memory()
self.assertEqual(len(memory), shots)
for mem in memory:
self.assertIn(mem, ["10 00", "10 11"])
def test_unitary(self):
"""Test unitary gate instruction"""
max_qubits = 4
x_mat = np.array([[0, 1], [1, 0]])
# Test 1 to max_qubits for random n-qubit unitary gate
for i in range(max_qubits):
num_qubits = i + 1
# Apply X gate to all qubits
multi_x = x_mat
for _ in range(i):
multi_x = np.kron(multi_x, x_mat)
# Target counts
shots = 1024
target_counts = {num_qubits * "1": shots}
# Test circuit
qr = QuantumRegister(num_qubits, "qr")
cr = ClassicalRegister(num_qubits, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.unitary(multi_x, qr)
circuit.measure(qr, cr)
job = execute(circuit, self.backend, shots=shots)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target_counts)
if __name__ == "__main__":
unittest.main()
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%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/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
from transpile_benchy.metrics.gate_counts import (
DepthMetric,
TotalMetric,
TotalSwaps,
)
from qiskit.circuit.library import iSwapGate
from qiskit.transpiler import CouplingMap
from mirror_gates.pass_managers import Mirage, QiskitLevel3
from mirror_gates.utilities import SubsMetric
from mirror_gates.logging import transpile_benchy_logger
from clonk.backend_utils.coupling_map import Tree, Corral
tree = Tree()
corral = Corral(num_snails=18)
# N = 4
# coupling_map = CouplingMap.from_line(N)
# coupling_map = CouplingMap.from_heavy_hex(5)
square = CouplingMap.from_grid(6, 6)
from transpile_benchy.library import CircuitLibrary
library = CircuitLibrary.from_txt("../../circuits/medium_circuits.txt")
# library = CircuitLibrary.from_txt("../../circuits/debug.txt")
# XXX set consolidate to False
# this is allowed only because my pass manager will preserve consolidation
# see post_stage, I call fastconsolidate manually
# NOTE: use TotalSwaps to verify baselines have > 0 swaps
# otherwise, there is no room for improvement.
# we can include these if we want to show our methods will still work
# but somewhat trivial since we just append VF2Layout
metrics = [
DepthMetric(consolidate=False),
TotalMetric(consolidate=False),
TotalSwaps(consolidate=False),
SubsMetric(),
]
transpilers = [
QiskitLevel3(square, name="Qiskit-square"),
Mirage(square, name="Mirage-square"),
# QiskitLevel3(tree, name="Qiskit-tree"),
# Mirage(tree, name="Mirage-tree"),
QiskitLevel3(corral, name="Qiskit-corral"),
Mirage(corral, name="Mirage-corral"),
]
from transpile_benchy.benchmark import Benchmark
benchmark = Benchmark(
transpilers=transpilers,
circuit_library=library,
metrics=metrics,
logger=transpile_benchy_logger,
num_runs=1,
)
benchmark.run()
# print(benchmark)
# print(benchmark)
benchmark.summary_statistics(transpilers[2], transpilers[3])
from transpile_benchy.render import plot_benchmark
plot_benchmark(
benchmark,
save=0,
legend_show=1,
filename="grid",
color_override=[0, 3, 6, 7],
)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import ClassicalRegister
# Create a Classical Register with 2 bits.
c = ClassicalRegister(2)
from qiskit import QuantumRegister
# Create a Quantum Register with 2 qubits.
q = QuantumRegister(2)
from qiskit import QuantumCircuit
# Create a Quantum Circuit
qc = QuantumCircuit(q, c)
# perform a measurement of our qubits into our bits
qc.measure(q, c); # ; hides the output
# Jupyter command to activate matplotlib and allow the preview of our circuit
%matplotlib inline
from qiskit.tools.visualization import matplotlib_circuit_drawer as draw
draw(qc) # visualize quantum circuit
# Try both and use the one you like best
from qiskit.tools.visualization import circuit_drawer as draw2
draw2(qc) # visualize quantum circuit
# if you want to save it to a file
from qiskit.tools.visualization import circuit_drawer
diagram = circuit_drawer(qc, filename="my_first_quantum_circuit.png")
diagram.show() # or even open it on an external program (no need to save first)
# get the QASM representation of our circuit
print(qc.qasm())
|
https://github.com/andre-juan/quantum_nearest_neighbors
|
andre-juan
|
import numpy as np
from scipy.linalg import expm
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute
from qiskit.circuit import AncillaQubit
from qiskit.visualization import plot_histogram
from qiskit.circuit.library.standard_gates import XGate, ZGate, HGate
from qiskit.circuit.add_control import add_control
from qiskit.extensions import UnitaryGate
import matplotlib.pyplot as plt
def show_figure(fig):
'''
auxiliar function to display plot
even if it's not the last command of the cell
from: https://github.com/Qiskit/qiskit-terra/issues/1682
'''
new_fig = plt.figure()
new_mngr = new_fig.canvas.manager
new_mngr.canvas.figure = fig
fig.set_canvas(new_mngr.canvas)
plt.show(fig)
def test_circuit(qc):
'''
auxiliar function, to test intermediate steps, looking at measurement results
this function allows the inspection of the amplitudes of states,
at any point of the circuit (call it with the desired circuit)
'''
cr = ClassicalRegister(qc.num_qubits, "creg_test")
qc_cr = QuantumCircuit(cr)
qc_test = qc + qc_cr
for i in range(qc.num_qubits):
qc_test.measure(i, i)
#################################
backend = Aer.get_backend("qasm_simulator")
job = execute(qc_test, backend, shots=1e5, seed_simulator=42)
results = job.result()
counts = results.get_counts()
return plot_histogram(counts, title="Results", figsize=(12, 4))
def construct_input_state(X_test):
'''
construct quantum state from bit string X_test
'''
# number of features
n = len(X_test)
# build the circuit
qr_input = QuantumRegister(n, "features_input")
qc_input = QuantumCircuit(qr_input)
for i in range(n):
if X_test[i] == "1":
qc_input.x(i)
return qc_input
def construct_training_set_state(X, y):
'''
construct quantum superposition of training dataset from:
- X: feature matrix
- y: target array
returns the circuit as well as the number of features, n
'''
# number of examples
N = X.shape[0]
# number of features
n = X.shape[1]
# full dataset, of the form [[X], [y]]
dataset = np.append(X, y.reshape((-1, 1)), axis=1)
# n+1 because the last register will encode the class!
amplitudes = np.zeros(2**(n+1))
# integer representation of binary strings in training dataset
# notice the [::-1], which is necessary to adjust the endianness!
data_points_X = [int("".join(str(i) for i in X[j])[::-1], 2) for j in range(dataset.shape[0])]
# integer representation considering also the class
# IMPORTANT: sum 2**n for elements in class 1
# this is necessary to encode also the class, in n+1 registers!
data_points = [x + 2**n if y[i] == 1 else x for i, x in enumerate(data_points_X)]
# set amplitudesof existing datapoints
amplitudes[data_points] = 1
# normalize amplitudes
amplitudes = amplitudes/np.sqrt(amplitudes.sum())
###################################################
# build the circuit
qr_features = QuantumRegister(n, "features_train")
qr_target = QuantumRegister(1, "target_train")
qc_training = QuantumCircuit(qr_features, qr_target)
qc_training.initialize(amplitudes, [qr_features, qr_target])
return qc_training, n
def construct_ancilla_state():
'''
construct ancilla register
'''
# build the circuit
qr_anc = QuantumRegister(1, "anc")
qc_anc = QuantumCircuit(qr_anc)
qc_anc.draw("mpl")
return qc_anc
def construct_initial_state(X, y, X_test, draw=False):
'''
conjugate elements of the initial state (input, training dataset and ancilla) in a
single quantum circuit
returns the circuit as well as the number of features, n
'''
qc_input = construct_input_state(X_test)
qc_training, n = construct_training_set_state(X, y)
qc_anc = construct_ancilla_state()
qc = qc_input + qc_training + qc_anc
qc.barrier()
if draw:
print("\nInitial state:")
show_figure(qc.draw("mpl"))
return qc, n
def step1(qc, draw=False):
qc.h(-1)
qc.barrier()
if draw:
print("\nStep 1:")
show_figure(qc.draw("mpl"))
return qc
def step2(qc, n, draw=False):
for i in range(n):
qc.cnot(i, n+i)
qc.barrier()
if draw:
print("\nStep 2:")
show_figure(qc.draw("mpl"))
return qc
def step3(qc, n, draw):
# matrices of 1 and \sigma_z to be exponentiated below
# source of the matrix exponential methods below:
# https://quantumcomputing.stackexchange.com/questions/10317/quantum-circuit-to-implement-matrix-exponential
idtt = np.eye(2)
sz = np.array([[1,0],
[0,-1]])
###################################################
# define the exponentiated unitaries
U_1_minus = expm(-1j * (np.pi/(2*4)) * ((idtt-sz)/2))
U_1_plus = expm(1j * (np.pi/(2*4)) * ((idtt-sz)/2))
# defining controlled gates
u1m = add_control(operation=UnitaryGate(U_1_minus, label="$U_1^-$"),
num_ctrl_qubits=1, ctrl_state=0, label="$CU_1^-$")
u1p = add_control(operation=UnitaryGate(U_1_plus, label="$U_1^+$"),
num_ctrl_qubits=1, ctrl_state=1, label="$CU_1^+$")
# getting the registers
registers = qc.qregs
# register labels
registers_labels = [qr.name for qr in qc.qregs]
qr_features = registers[registers_labels.index("features_train")]
qr_anc = registers[registers_labels.index("anc")]
# build a circuit to apply the unitary above
# this will be combined with the main circuit later on (notice: same registers!!).
qc_u = QuantumCircuit(qr_features, qr_anc)
for i in range(n):
# apply the unitaries
qc_u.append(u1p, [qr_anc[0], qr_features[i]])
qc_u.append(u1m, [qr_anc[0], qr_features[i]])
###################################################
# combine the U circuit above to the main circuit
qc = qc.combine(qc_u)
qc.barrier()
###################################################
if draw:
print("\nStep 3:")
show_figure(qc.draw("mpl"))
return qc
def step4(qc, draw):
qc.h(-1)
qc.barrier()
if draw:
print("\nStep 4:")
show_figure(qc.draw("mpl"))
return qc
def measurement(qc, draw_final):
'''
implements the measurement of the circuit
'''
# getting the registers
registers = qc.qregs
registers_labels = [qr.name for qr in qc.qregs]
qr_anc = registers[registers_labels.index("anc")]
qr_target = registers[registers_labels.index("target_train")]
###########################3
cr_anc = ClassicalRegister(1, "c_anc")
qc_cr_anc = QuantumCircuit(cr_anc)
cr_class = ClassicalRegister(1, "c_class")
qc_cr_class = QuantumCircuit(cr_class)
qc = qc + qc_cr_anc + qc_cr_class
qc.measure(qr_anc, cr_anc)
qc.measure(qr_target, cr_class)
if draw_final:
print("\nStep 5 (measurement):")
show_figure(qc.draw("mpl"))
return qc
def run(qc):
'''
runs the circuit, display results and return both
predicted class and probability distribution of prediction
'''
backend = Aer.get_backend("qasm_simulator")
n_shots = 1e4
job = execute(qc, backend, shots=n_shots, seed_simulator=42)
results = job.result()
counts = results.get_counts()
# filtering out measurements of ancila = |1> (last register)
keys = list(counts.keys()).copy()
for key in keys:
if key[-1] == "1":
counts.pop(key)
show_figure(plot_histogram(counts, title="Results", figsize=(12, 4)))
####################################
# final prediction
# dictionary of counts sorted by value (sbv), decreasing order...
counts_sbv = dict(sorted(counts.items(), key=lambda item: item[1], reverse=True))
# ...will have its first key (first [0]) corresponding to the class with highest count (thus, probability!)
# the key is of the form "class ancilla", thus, to get the actual class, get the first character (second [0])
y_pred = list(counts_sbv.keys())[0][0]
# also display probabilities (predict_proba)
n_norm = sum(list(counts.values()))
y_proba = {"p(c={})".format(classe[0]): count/n_norm for classe, count in counts_sbv.items()}
print("\nProbability of belonging to each class:\n")
for k, v in y_proba.items():
print("{} = {:.3f}".format(k, v))
print("\n")
print("*"*30)
print("="*30)
print("*"*30)
print("\n")
print("Final prediction:\n")
print("y({}) = {}".format(X_test, y_pred))
return y_pred, y_proba
def quantum_nearest_neighbors(qc, n, X_test, draw=False, draw_final=False):
qc = step1(qc, draw)
qc = step2(qc, n, draw)
qc = step3(qc, n, draw)
qc = step4(qc, draw)
qc = measurement(qc, draw_final)
y_pred, y_proba = run(qc)
return y_pred, y_proba
X = np.array([[0, 0, 0, 0],
[0, 0, 0, 1],
[1, 1, 1, 0],
[1, 1, 1, 1]])
# balanced
y = np.array([0, 0, 1, 1])
#############################################
X_test = "0010"
#############################################
qc, n = construct_initial_state(X, y, X_test)
quantum_nearest_neighbors(qc, n, X_test)
X = np.array([[0, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 1, 1],
[1, 1, 1, 1, 0],
[1, 1, 1, 1, 1]])
# imbalanced
y = np.array([0, 0, 0, 1, 1])
#############################################
X_test = "10101"
#############################################
qc, n = construct_initial_state(X, y, X_test)
quantum_nearest_neighbors(qc, n, X_test)
X = np.array([[0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 1, 0],
[1, 1, 1, 1, 0, 1],
[1, 1, 1, 1, 1, 0]])
# imbalanced
y = np.array([0, 0, 0, 1, 1])
#############################################
X_test = "001111"
#############################################
qc, n = construct_initial_state(X, y, X_test)
quantum_nearest_neighbors(qc, n, X_test)
# modified dataset to cause ambiguity
# (notice how many examples have the central "11")
X = np.array([[0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 1],
[0, 0, 1, 1, 1, 0],
[1, 1, 1, 1, 0, 1],
[1, 1, 1, 1, 1, 0]])
# imbalanced
y = np.array([0, 0, 0, 1, 1])
#############################################
X_test = "001100"
#############################################
qc, n = construct_initial_state(X, y, X_test)
quantum_nearest_neighbors(qc, n, X_test)
# modified dataset to cause ambiguity
# (notice how many examples have the central "11")
X = np.array([[0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 1],
[0, 0, 1, 1, 1, 0],
[1, 1, 1, 1, 0, 1],
[1, 1, 1, 1, 1, 0],
[1, 1, 0, 0, 1, 1]])
# imbalanced
y = np.array([0, 0, 0, 1, 1, 1])
#############################################
X_test = "001100"
#############################################
qc, n = construct_initial_state(X, y, X_test)
quantum_nearest_neighbors(qc, n, X_test)
|
https://github.com/RigiResearch/qiskit-fall-fest-22-public
|
RigiResearch
|
# Imports from Qiskit Terra
from qiskit.circuit import QuantumCircuit
from qiskit.visualization import plot_bloch_vector, plot_bloch_multivector, plot_state_qsphere, plot_histogram, visualize_transition
from qiskit.quantum_info import Pauli, PauliList, Statevector
# Imports from Qiskit Aer
from qiskit import Aer, execute
# Creation of multi-qubit circuit
q_multi = QuantumCircuit() # Mention multi-quantum and classical bits in args
# Display circuit
q_multi.draw()
cx_circ = QuantumCircuit() # Mention number of quantum and classical bits in args
# Apply CX gate to the qubits [0 - Control qubit; 1 - Target qubit]
# Draw the circuit
cx_circ.draw()
# Bloch Sphere visualization
state = Statevector(cx_circ) # Statevector of the circuit
plot_bloch_multivector(state)
# Let's measaure the multi-qubit circuit
cx_circ.measure() # Add measurement gate with appropriate args
# Draw the circuit
cx_circ.draw()
# Import the backend
backend = Aer.get_backend('qasm_simulator')
# Creating a job and extracting results
job = execute(cx_circ, backend = backend, shots = 1024)
result = job.result()
counts = result.get_counts()
# Plotting the counts
plot_histogram(counts)
# Do you know some of the quantum gates are reversible?
# Can you verify what happens when you apply these gates twice?
reverse_gate_circ = QuantumCircuit(2, 2)
# Apply 2 CX gates on the same qubits
## APPLY GATE 1 HERE ##
## APPLY GATE 2 HERE ##
# Draw circuit
reverse_gate_circ.draw()
# Send the circuit to a simulator to check the results!
# Your blank canvas to apply the Toffoli gate!
# Let us contruct the circuit for the first Bell state |phi+>
entangled_circ = QuantumCircuit(2, 2)
# Apply H gate follwoed by a CX gate on the qubits [0 - Control qubit; 1 - Target qubit]
# Draw the circuit
entangled_circ.draw()
# Let's measaure the multi-qubit circuit
entangled_circ.measure([0, 1], [0, 1]) # Add measurement gate with appropriate args
# Draw the circuit
entangled_circ.draw()
# Import the backend
backend = Aer.get_backend('qasm_simulator')
# Creating a job and extracting results
job = execute(entangled_circ, backend = backend, shots = 1024)
result = job.result()
counts = result.get_counts()
# Plotting the counts
plot_histogram(counts) # Don't forget Qiskit uses a little-endian notation !
# Do you know there are 4 different Bell States? Can you build a circuit for the rest 3 Bell States?
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import time, warnings
import numpy as np
from qiskit import IBMQ
from qiskit.test.mock import FakeMumbai
from qiskit.providers.aer import AerSimulator
from qiskit.providers.aer.noise import NoiseModel
from qiskit_optimization.algorithms import CplexOptimizer
from utilities.helpers import create_qaoa_meo, create_quadratic_programs_from_paths
DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y")
DIR
def job_callback(job_id, job_status, queue_position, job):
# BUG ? This is not called and not set in quantum instance (see info logging)
print(job_id)
print(job_status)
print(queue_position)
print(job)
def qaoa_callback(eval_ct: int, opt_pars: np.ndarray, mean: float, stdev: float) -> None:
"""Print number of iteration in QAOA."""
print("Evaluation count:", eval_ct)
# select linear programs to solve
qps_dense = create_quadratic_programs_from_paths(DIR + "/DENSE/")
qp_dense = qps_dense['test_3']
qps_sparse = create_quadratic_programs_from_paths(DIR + "/SPARSE/")
qp_sparse = qps_sparse['test_3']
# init local backend simulator with noise model
device = FakeMumbai()
local = AerSimulator.from_backend(device)
noise_model = NoiseModel.from_backend(device)
conf = device.configuration()
# init IBM Q Experience Simulator
IBMQ.load_account()
ibmq = IBMQ.get_provider(hub='ibm-q').get_backend('simulator_statevector')
# init Optimizers
cplex = CplexOptimizer()
quantum_instance_kwargs = {"shots": 4096, "noise_model": noise_model,
"job_callback": job_callback, "optimization_level": 3}
qaoa_local_sim = create_qaoa_meo(backend=local, **quantum_instance_kwargs)
qaoa_ibmq_sim = create_qaoa_meo(backend=ibmq, coupling_map=conf.coupling_map, basis_gates=conf.basis_gates,
max_iter=5, qaoa_callback=qaoa_callback, **quantum_instance_kwargs)
# solve classically
cplex.solve(qp_sparse)
# solve by using noise model with local qasm sim
qaoa_local_sim.solve(qp_sparse)
cplex.solve(qp_dense)
qaoa_local_sim.solve(qp_dense)
# solve by using noise model with IBM Q Experience simulator
qp_sparse = qps_sparse['test_7']
warnings.filterwarnings("ignore", category=DeprecationWarning)
qaoa_ibmq_sim.solve(qp_sparse)
cplex.solve(qp_sparse)
# solve by using noise model with IBM Q Experience simulator
qp_dense = qps_dense['test_15']
warnings.filterwarnings("ignore", category=DeprecationWarning)
qaoa_ibmq_sim.solve(qp_dense)
cplex.solve(qp_dense)
|
https://github.com/epelaaez/QuantumLibrary
|
epelaaez
|
from qiskit import *
import numpy as np
n = 5
control_reg = QuantumRegister(n, 'c')
target_reg = QuantumRegister(1, 't')
ancilla_reg = QuantumRegister(1, 'a')
circuit = QuantumCircuit(control_reg, target_reg, ancilla_reg)
circuit.mct(control_reg[:int(np.ceil(n/2))], ancilla_reg[0])
circuit.mct(control_reg[int(np.ceil(n/2)):] + ancilla_reg[:], target_reg[0])
circuit.mct(control_reg[:int(np.ceil(n/2))], ancilla_reg[0])
circuit.mct(control_reg[int(np.ceil(n/2)):] + ancilla_reg[:], target_reg[0])
circuit.draw('mpl')
def n_m_2_ancilla(circuit, control_reg, target_reg, ancilla_reg):
n = len(control_reg)
# first mountain
circuit.ccx(ancilla_reg[-1], control_reg[-1], target_reg[0])
for i in range(n - 4, -1, -1):
circuit.ccx(ancilla_reg[i], control_reg[i + 2], ancilla_reg[i + 1])
circuit.ccx(control_reg[0], control_reg[1], ancilla_reg[0])
for i in range(0, n - 3):
circuit.ccx(ancilla_reg[i], control_reg[i + 2], ancilla_reg[i + 1])
circuit.ccx(ancilla_reg[-1], control_reg[-1], target_reg[0])
# second mountain, i.e., uncomputation
for i in range(n - 4, -1, -1):
circuit.ccx(ancilla_reg[i], control_reg[i + 2], ancilla_reg[i + 1])
circuit.ccx(control_reg[0], control_reg[1], ancilla_reg[0])
for i in range(0, n - 3):
circuit.ccx(ancilla_reg[i], control_reg[i + 2], ancilla_reg[i + 1])
n = 5
control_reg = QuantumRegister(n, 'c')
target_reg = QuantumRegister(1, 't')
ancilla_reg = QuantumRegister(n - 2, 'a')
circuit = QuantumCircuit(control_reg, target_reg, ancilla_reg)
n_m_2_ancilla(circuit, control_reg, target_reg, ancilla_reg)
circuit.draw('mpl')
n = 7
control_reg = QuantumRegister(n, 'c')
target_reg = QuantumRegister(1, 't')
ancilla_reg = QuantumRegister(1, 'a')
circuit = QuantumCircuit(control_reg, target_reg, ancilla_reg)
for _ in range(2):
# first gate
controls = [i for i in range(n) if i % 2 == 0]
target = [-1]
ancilla = [i for i in range(n) if i not in controls]
while len(ancilla) != len(controls) - 2:
ancilla.pop(0)
n_m_2_ancilla(circuit, controls, target, ancilla)
circuit.barrier()
# second gate
controls = [i for i in range(n) if i % 2 == 1] + [n + 1]
target = [-2]
ancilla = [i for i in range(n) if i not in controls]
while len(ancilla) != len(controls) - 2:
ancilla.pop(0)
n_m_2_ancilla(circuit, controls, target, ancilla)
circuit.barrier()
circuit.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice
from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel
line = LineLattice(2)
fermi = FermiHubbardModel.uniform_parameters(line, 2.0, 4.0, 3.0)
print(fermi.second_q_ops()) # Note: the trailing `s`
from qiskit_nature.second_q.hamiltonians.lattices import LineLattice
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
line = LineLattice(2)
fermi = FermiHubbardModel(line.uniform_parameters(2.0, 4.0), 3.0)
print(fermi.second_q_op()) # Note: NO trailing `s`
import numpy as np
from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
fermi = FermiHubbardModel.from_parameters(interaction, 3.0)
print(fermi.second_q_ops()) # Note: the trailing `s`
import numpy as np
from qiskit_nature.second_q.hamiltonians.lattices import Lattice
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
lattice = Lattice.from_adjacency_matrix(interaction)
fermi = FermiHubbardModel(lattice, 3.0)
print(fermi.second_q_op()) # Note: NO trailing `s`
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice
from qiskit_nature.problems.second_quantization.lattice.models import IsingModel
line = LineLattice(2)
ising = IsingModel.uniform_parameters(line, 2.0, 4.0)
print(ising.second_q_ops()) # Note: the trailing `s`
from qiskit_nature.second_q.hamiltonians.lattices import LineLattice
from qiskit_nature.second_q.hamiltonians import IsingModel
line = LineLattice(2)
ising = IsingModel(line.uniform_parameters(2.0, 4.0))
print(ising.second_q_op()) # Note: NO trailing `s`
import numpy as np
from qiskit_nature.problems.second_quantization.lattice.models import IsingModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
ising = IsingModel.from_parameters(interaction)
print(ising.second_q_ops()) # Note: the trailing `s`
import numpy as np
from qiskit_nature.second_q.hamiltonians.lattices import Lattice
from qiskit_nature.second_q.hamiltonians import IsingModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
lattice = Lattice.from_adjacency_matrix(interaction)
ising = IsingModel(lattice)
print(ising.second_q_op()) # Note: NO trailing `s`
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
import qiskit
from qiskit_aer.backends.aerbackend import AerBackend
from dc_qiskit_qml.encoding_maps import NormedAmplitudeEncoding
from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier
from dc_qiskit_qml.distance_based.hadamard.state import QmlGenericStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import QiskitNativeStatePreparation
initial_state_builder = QmlGenericStateCircuitBuilder(QiskitNativeStatePreparation())
execution_backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator')
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
classifier_circuit_factory=initial_state_builder,
encoding_map=NormedAmplitudeEncoding())
import numpy as np
from sklearn.preprocessing import StandardScaler, Normalizer
from sklearn.pipeline import Pipeline
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
X, y = load_wine(return_X_y=True)
X_train = X[[33, 88, 144]]
y_train = y[[33, 88, 144]]
X_test = X[[28, 140]]
y_test = y[[28, 140]]
pipeline = Pipeline([
('scaler', StandardScaler()),
('pca2', PCA(n_components=2)),
('l2norm', Normalizer(norm='l2', copy=True)),
('qml', qml)
])
import matplotlib.pyplot as plt
_X = pipeline.fit_transform(X, y)
_X_train = pipeline.transform(X_train)
_X_test = pipeline.transform(X_test)
colors = ['red', 'blue', 'green', 'orange']
plt.scatter(
_X[:,0], _X[:,1],
color=[colors[yy] for yy in y])
plt.scatter(
_X_train[:,0], _X_train[:,1],
color=[colors[yy] for yy in y_train],
marker='x', s=200)
plt.scatter(
_X_test[:,0], _X_test[:,1],
color=[colors[yy] for yy in y_test],
marker='o', s=200)
plt.show()
pipeline.fit(X_train, y_train)
pipeline.predict(X_test), y_test
qml._last_predict_circuits[0].draw(output='mpl', fold=-1)
|
https://github.com/jvscursulim/qamp_fall22_project
|
jvscursulim
|
import medmnist
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torchvision.transforms as transforms
from medmnist import INFO, Evaluator
from tqdm import tqdm
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.opflow import AerPauliExpectation
from qiskit_aer import Aer
from qiskit_machine_learning.neural_networks import CircuitQNN, TwoLayerQNN
from qiskit_machine_learning.connectors import TorchConnector
from qpie import QPIE
from neqr import NEQR
from skimage.transform import resize
import torch.nn.functional as F
flags = ["pathmnist",
"octmnist",
"pneumoniamnist",
"chestmnist",
"dermamnist",
"retinamnist",
"breastmnist",
"bloodmnist",
"tissuemnist",
"organcmnist",
"organsmnist",
"organmnist3d",
"nodulemnist3d",
"adrenalmnist3d",
"fracturemnist3d",
"vesselmnist3d",
"synapsemnist3d"]
NUM_EPOCHS = 3
BATCH_SIZE = 128
lr = 0.001
data_flag = flags[2]
info = INFO[data_flag]
task = info["task"]
n_channel = info["n_channels"]
n_classes = len(info["label"])
DataClass = getattr(medmnist, info["python_class"])
data_transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize(mean=[.5], std=[.5])])
train_dataset = DataClass(split='train', transform=data_transform)
test_dataset = DataClass(split='test', transform=data_transform)
len(train_dataset.imgs)
train_dataset.imgs.shape
train_dataset.imgs[0].shape
plt.imshow(train_dataset.imgs[0], cmap="gray")
plt.show()
train_loader = data.DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE, shuffle=True)
train_loader_at_eval = data.DataLoader(dataset=train_dataset, batch_size=2*BATCH_SIZE, shuffle=True)
test_loader = data.DataLoader(dataset=test_dataset, batch_size=2*BATCH_SIZE, shuffle=False)
class Net(nn.Module):
def __init__(self, in_channels, num_classes) -> None:
super(Net, self).__init__()
self.layer1 = nn.Sequential(nn.Conv2d(in_channels=in_channels, out_channels=16, kernel_size=3),
nn.BatchNorm2d(16),
nn.ReLU())
self.layer2 = nn.Sequential(nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.layer3 = nn.Sequential(nn.Conv2d(in_channels=16, out_channels=64, kernel_size=3),
nn.BatchNorm2d(64),
nn.ReLU())
self.layer4 = nn.Sequential(nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3),
nn.BatchNorm2d(64),
nn.ReLU())
self.layer5 = nn.Sequential(nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.fc = nn.Sequential(nn.Linear(64 * 4 * 4, 128),
nn.ReLU(),
nn.Linear(128, 128),
nn.ReLU(),
nn.Linear(128, num_classes))
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.layer5(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
model = Net(in_channels=n_channel, num_classes=n_classes)
if task == "multi-label, binary-class":
criterion = nn.BCEWithLogitsLoss()
else:
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=lr)
# optimizer = optim.LBFGS(model.parameters(), lr=lr)
for epoch in range(NUM_EPOCHS):
train_correct = 0
train_total = 0
test_correct = 0
test_total = 0
model.train()
for inputs, targets in tqdm(train_loader):
# forward + backward + optimize
optimizer.zero_grad()
outputs = model(inputs)
if task == 'multi-label, binary-class':
targets = targets.to(torch.float32)
loss = criterion(outputs, targets)
else:
targets = targets.squeeze().long()
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
def test(split):
model.eval()
y_true = torch.tensor([])
y_score = torch.tensor([])
data_loader = train_loader_at_eval if split == 'train' else test_loader
with torch.no_grad():
for inputs, targets in data_loader:
outputs = model(inputs)
if task == 'multi-label, binary-class':
targets = targets.to(torch.float32)
outputs = outputs.softmax(dim=-1)
else:
targets = targets.squeeze().long()
outputs = outputs.softmax(dim=-1)
targets = targets.float().resize_(len(targets), 1)
y_true = torch.cat((y_true, targets), 0)
y_score = torch.cat((y_score, outputs), 0)
y_true = y_true.numpy()
y_score = y_score.detach().numpy()
evaluator = Evaluator(data_flag, split)
metrics = evaluator.evaluate(y_score)
print('%s auc: %.3f acc:%.3f' % (split, *metrics))
print('==> Evaluating ...')
test('train')
test('test')
algorithm_globals.random_seed = 42
qi = QuantumInstance(backend=Aer.get_backend("statevector_simulator"))
# device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def create_qnn():
feature_map = ZZFeatureMap(2)
ansatz = RealAmplitudes(2, reps=1)
qnn = TwoLayerQNN(2,
feature_map=feature_map,
ansatz=ansatz,
input_gradients=True,
exp_val=AerPauliExpectation(),
quantum_instance=qi)
return qnn
from torch import cat
class HybridNet(nn.Module):
def __init__(self, qnn):
super().__init__()
self.conv1 = nn.Conv2d(1, 2, kernel_size=5)
self.conv2 = nn.Conv2d(2, 16, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(256, 64)
self.fc2 = nn.Linear(64, 2) # 2-dimensional input to QNN
self.qnn = TorchConnector(qnn) # Apply torch connector, weights chosen
# uniformly at random from interval [-1,1].
self.fc3 = nn.Linear(1, 1) # 1-dimensional output from QNN
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.qnn(x) # apply QNN
x = self.fc3(x)
return cat((x, 1 - x), -1)
qnn = create_qnn()
model4 = HybridNet(qnn)
data_transform = transforms.Compose([transforms.ToTensor()])
train_dataset = DataClass(split='train', transform=data_transform)
test_dataset = DataClass(split='test', transform=data_transform)
train_loader = data.DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE, shuffle=True)
train_loader_at_eval = data.DataLoader(dataset=train_dataset, batch_size=2*BATCH_SIZE, shuffle=True)
test_loader = data.DataLoader(dataset=test_dataset, batch_size=2*BATCH_SIZE, shuffle=False)
if task == "multi-label, binary-class":
criterion = nn.BCEWithLogitsLoss()
else:
criterion = nn.CrossEntropyLoss()
for epoch in range(NUM_EPOCHS):
train_correct = 0
train_total = 0
test_correct = 0
test_total = 0
model4.train()
for inputs, targets in tqdm(train_loader):
# forward + backward + optimize
optimizer.zero_grad()
outputs = model4(inputs)
if task == 'multi-label, binary-class':
targets = targets.to(torch.float32)
loss = criterion(outputs, targets)
else:
targets = targets.squeeze().long()
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
def test(split):
model4.eval()
y_true = torch.tensor([])
y_score = torch.tensor([])
data_loader = train_loader_at_eval if split == 'train' else test_loader
with torch.no_grad():
for inputs, targets in data_loader:
outputs = model4(inputs)
if task == 'multi-label, binary-class':
targets = targets.to(torch.float32)
outputs = outputs.softmax(dim=-1)
else:
targets = targets.squeeze().long()
outputs = outputs.softmax(dim=-1)
targets = targets.float().resize_(len(targets), 1)
y_true = torch.cat((y_true, targets), 0)
y_score = torch.cat((y_score, outputs), 0)
y_true = y_true.numpy()
y_score = y_score.detach().numpy()
evaluator = Evaluator(data_flag, split)
metrics = evaluator.evaluate(y_score)
print('%s auc: %.3f acc: %.3f' % (split, *metrics))
print('==> Evaluating ...')
test('train')
test('test')
|
https://github.com/tstopa/Qiskit_for_high_schools
|
tstopa
|
from qiskit.visualization import plot_bloch_vector
%matplotlib inline
plot_bloch_vector([0,0,1], title="Standard Qubit Value")
plot_bloch_vector([1,0,0], title="Qubit in the state |+⟩")
from qiskit import *
from math import pi
from qiskit.visualization import plot_bloch_multivector
qcA = QuantumCircuit(1)
qcA.x(0)
backend = Aer.get_backend('statevector_simulator')
out = execute(qcA,backend).result().get_statevector()
plot_bloch_multivector(out)
qcB = QuantumCircuit(1)
qcB.h(0)
backend = Aer.get_backend('statevector_simulator')
out = execute(qcB,backend).result().get_statevector()
plot_bloch_multivector(out)
|
https://github.com/helenup/Quantum-Euclidean-Distance
|
helenup
|
from qiskit import *
from qiskit import BasicAer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
qreg = QuantumRegister(3, 'qreg')
creg = ClassicalRegister(3, 'creg')
qc = QuantumCircuit (qreg, creg)
# Initial state |01>
qc.x(qreg[1])
#swap_test
qc.h(qreg[0]) #Apply superposition on the ancilla qubit
qc.cswap( qreg[0], qreg[1], qreg[2] )
qc.h(qreg[0])
qc.barrier()
qc.measure(qreg[0], creg[0])
display(qc.draw(output="mpl"))
#Result
shots = 1024
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=shots)
job_result = job.result()
counts = job_result.get_counts(qc)
print(counts)
# The results agree with the swap test function, where if the P|0> = 0.5 on the ancilla(control) qubit
#means the states are orthogonal, and if the P|0>=1 indicates the states are identical.
|
https://github.com/chunfuchen/qiskit-chemistry
|
chunfuchen
|
# -*- 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.
"""
This trial wavefunction is a Unitary Coupled-Cluster Single and Double excitations
variational form.
For more information, see https://arxiv.org/abs/1805.04340
"""
import logging
import sys
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.tools import parallel_map
from qiskit.tools.events import TextProgressBar
from qiskit.aqua import Operator, aqua_globals
from qiskit.aqua.components.variational_forms import VariationalForm
from qiskit.chemistry.fermionic_operator import FermionicOperator
from qiskit.chemistry import MP2Info
from qiskit.chemistry import QMolecule as qm
logger = logging.getLogger(__name__)
class UCCSD(VariationalForm):
"""
This trial wavefunction is a Unitary Coupled-Cluster Single and Double excitations
variational form.
For more information, see https://arxiv.org/abs/1805.04340
"""
CONFIGURATION = {
'name': 'UCCSD',
'description': 'UCCSD Variational Form',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'uccsd_schema',
'type': 'object',
'properties': {
'depth': {
'type': 'integer',
'default': 1,
'minimum': 1
},
'num_orbitals': {
'type': 'integer',
'default': 4,
'minimum': 1
},
'num_particles': {
'type': 'integer',
'default': 2,
'minimum': 1
},
'active_occupied': {
'type': ['array', 'null'],
'default': None
},
'active_unoccupied': {
'type': ['array', 'null'],
'default': None
},
'qubit_mapping': {
'type': 'string',
'default': 'parity',
'oneOf': [
{'enum': ['jordan_wigner', 'parity', 'bravyi_kitaev']}
]
},
'two_qubit_reduction': {
'type': 'boolean',
'default': False
},
'mp2_reduction': {
'type': 'boolean',
'default': False
},
'num_time_slices': {
'type': 'integer',
'default': 1,
'minimum': 1
},
},
'additionalProperties': False
},
'depends': [
{
'pluggable_type': 'initial_state',
'default': {
'name': 'HartreeFock',
}
},
],
}
def __init__(self, num_qubits, depth, num_orbitals, num_particles,
active_occupied=None, active_unoccupied=None, initial_state=None,
qubit_mapping='parity', two_qubit_reduction=False, mp2_reduction=False, num_time_slices=1,
cliffords=None, sq_list=None, tapering_values=None, symmetries=None,
shallow_circuit_concat=True):
"""Constructor.
Args:
num_orbitals (int): number of spin orbitals
depth (int): number of replica of basic module
num_particles (int): number of particles
active_occupied (list): list of occupied orbitals to consider as active space
active_unoccupied (list): list of unoccupied orbitals to consider as active space
initial_state (InitialState): An initial state object.
qubit_mapping (str): qubit mapping type.
two_qubit_reduction (bool): two qubit reduction is applied or not.
num_time_slices (int): parameters for dynamics.
cliffords ([Operator]): list of unitary Clifford transformation
sq_list ([int]): position of the single-qubit operators that anticommute
with the cliffords
tapering_values ([int]): array of +/- 1 used to select the subspace. Length
has to be equal to the length of cliffords and sq_list
symmetries ([Pauli]): represent the Z2 symmetries
shallow_circuit_concat (bool): indicate whether to use shallow (cheap) mode for circuit concatenation
"""
self.validate(locals())
super().__init__()
self._cliffords = cliffords
self._sq_list = sq_list
self._tapering_values = tapering_values
self._symmetries = symmetries
if self._cliffords is not None and self._sq_list is not None and \
self._tapering_values is not None and self._symmetries is not None:
self._qubit_tapering = True
else:
self._qubit_tapering = False
self._num_qubits = num_orbitals if not two_qubit_reduction else num_orbitals - 2
self._num_qubits = self._num_qubits if not self._qubit_tapering else self._num_qubits - len(sq_list)
if self._num_qubits != num_qubits:
raise ValueError('Computed num qubits {} does not match actual {}'
.format(self._num_qubits, num_qubits))
self._depth = depth
self._num_orbitals = num_orbitals
self._num_particles = num_particles
if self._num_particles > self._num_orbitals:
raise ValueError('# of particles must be less than or equal to # of orbitals.')
self._initial_state = initial_state
self._qubit_mapping = qubit_mapping
self._two_qubit_reduction = two_qubit_reduction
self._num_time_slices = num_time_slices
self._shallow_circuit_concat = shallow_circuit_concat
self._single_excitations, self._double_excitations = \
UCCSD.compute_excitation_lists(num_particles, num_orbitals,
active_occupied, active_unoccupied)
self._single_excitations = []
print('{} are the old doubles'.format(self._double_excitations))
print(mp2_reduction)
if mp2_reduction:
print('Getting new doubles')
self._double_excitations = get_mp2_doubles(self._single_excitations,self._double_excitations)
print('{} are the new doubles'.format(self._double_excitations))
self._hopping_ops, self._num_parameters = self._build_hopping_operators()
self._bounds = [(-np.pi, np.pi) for _ in range(self._num_parameters)]
self._logging_construct_circuit = True
def _build_hopping_operators(self):
from .uccsd import UCCSD
hopping_ops = []
if logger.isEnabledFor(logging.DEBUG):
TextProgressBar(sys.stderr)
results = parallel_map(UCCSD._build_hopping_operator, self._single_excitations + self._double_excitations,
task_args=(self._num_orbitals, self._num_particles,
self._qubit_mapping, self._two_qubit_reduction, self._qubit_tapering,
self._symmetries, self._cliffords, self._sq_list, self._tapering_values),
num_processes=aqua_globals.num_processes)
hopping_ops = [qubit_op for qubit_op in results if qubit_op is not None]
num_parameters = len(hopping_ops) * self._depth
return hopping_ops, num_parameters
@staticmethod
def _build_hopping_operator(index, num_orbitals, num_particles, qubit_mapping,
two_qubit_reduction, qubit_tapering, symmetries,
cliffords, sq_list, tapering_values):
def check_commutativity(op_1, op_2):
com = op_1 * op_2 - op_2 * op_1
com.zeros_coeff_elimination()
return True if com.is_empty() else False
h1 = np.zeros((num_orbitals, num_orbitals))
h2 = np.zeros((num_orbitals, num_orbitals, num_orbitals, num_orbitals))
if len(index) == 2:
i, j = index
h1[i, j] = 1.0
h1[j, i] = -1.0
elif len(index) == 4:
i, j, k, m = index
h2[i, j, k, m] = 1.0
h2[m, k, j, i] = -1.0
dummpy_fer_op = FermionicOperator(h1=h1, h2=h2)
qubit_op = dummpy_fer_op.mapping(qubit_mapping)
qubit_op = qubit_op.two_qubit_reduced_operator(num_particles) \
if two_qubit_reduction else qubit_op
if qubit_tapering:
for symmetry in symmetries:
symmetry_op = Operator(paulis=[[1.0, symmetry]])
symm_commuting = check_commutativity(symmetry_op, qubit_op)
if not symm_commuting:
break
if qubit_tapering:
if symm_commuting:
qubit_op = Operator.qubit_tapering(qubit_op, cliffords,
sq_list, tapering_values)
else:
qubit_op = None
if qubit_op is None:
logger.debug('Excitation ({}) is skipped since it is not commuted '
'with symmetries'.format(','.join([str(x) for x in index])))
return qubit_op
def construct_circuit(self, parameters, q=None):
"""
Construct the variational form, given its parameters.
Args:
parameters (numpy.ndarray): circuit parameters
q (QuantumRegister): Quantum Register for the circuit.
Returns:
QuantumCircuit: a quantum circuit with given `parameters`
Raises:
ValueError: the number of parameters is incorrect.
"""
from .uccsd import UCCSD
if len(parameters) != self._num_parameters:
raise ValueError('The number of parameters has to be {}'.format(self._num_parameters))
if q is None:
q = QuantumRegister(self._num_qubits, name='q')
if self._initial_state is not None:
circuit = self._initial_state.construct_circuit('circuit', q)
else:
circuit = QuantumCircuit(q)
if logger.isEnabledFor(logging.DEBUG) and self._logging_construct_circuit:
logger.debug("Evolving hopping operators:")
TextProgressBar(sys.stderr)
self._logging_construct_circuit = False
num_excitations = len(self._hopping_ops)
results = parallel_map(UCCSD._construct_circuit_for_one_excited_operator,
[(self._hopping_ops[index % num_excitations], parameters[index])
for index in range(self._depth * num_excitations)],
task_args=(q, self._num_time_slices),
num_processes=aqua_globals.num_processes)
for qc in results:
if self._shallow_circuit_concat:
circuit.data += qc.data
else:
circuit += qc
return circuit
@staticmethod
def _construct_circuit_for_one_excited_operator(qubit_op_and_param, qr, num_time_slices):
qubit_op, param = qubit_op_and_param
qc = qubit_op.evolve(None, param * -1j, 'circuit', num_time_slices, qr)
return qc
@property
def preferred_init_points(self):
"""Getter of preferred initial points based on the given initial state."""
if self._initial_state is None:
return None
else:
bitstr = self._initial_state.bitstr
if bitstr is not None:
return np.zeros(self._num_parameters, dtype=np.float)
else:
return None
@staticmethod
def compute_excitation_lists(num_particles, num_orbitals, active_occ_list=None,
active_unocc_list=None, same_spin_doubles=True):
"""
Computes single and double excitation lists
Args:
num_particles: Total number of particles
num_orbitals: Total number of spin orbitals
active_occ_list: List of occupied orbitals to include, indices are
0 to n where n is num particles // 2
active_unocc_list: List of unoccupied orbitals to include, indices are
0 to m where m is (num_orbitals - num particles) // 2
same_spin_doubles: True to include alpha,alpha and beta,beta double excitations
as well as alpha,beta pairings. False includes only alpha,beta
Returns:
Single and double excitation lists
"""
if num_particles < 2 or num_particles % 2 != 0:
raise ValueError('Invalid number of particles {}'.format(num_particles))
if num_orbitals < 4 or num_orbitals % 2 != 0:
raise ValueError('Invalid number of orbitals {}'.format(num_orbitals))
if num_orbitals <= num_particles:
raise ValueError('No unoccupied orbitals')
if active_occ_list is not None:
active_occ_list = [i if i >= 0 else i + num_particles // 2 for i in active_occ_list]
for i in active_occ_list:
if i >= num_particles // 2:
raise ValueError('Invalid index {} in active active_occ_list {}'
.format(i, active_occ_list))
if active_unocc_list is not None:
active_unocc_list = [i + num_particles // 2 if i >=
0 else i + num_orbitals // 2 for i in active_unocc_list]
for i in active_unocc_list:
if i < 0 or i >= num_orbitals // 2:
raise ValueError('Invalid index {} in active active_unocc_list {}'
.format(i, active_unocc_list))
if active_occ_list is None or len(active_occ_list) <= 0:
active_occ_list = [i for i in range(0, num_particles // 2)]
if active_unocc_list is None or len(active_unocc_list) <= 0:
active_unocc_list = [i for i in range(num_particles // 2, num_orbitals // 2)]
single_excitations = []
double_excitations = []
logger.debug('active_occ_list {}'.format(active_occ_list))
logger.debug('active_unocc_list {}'.format(active_unocc_list))
beta_idx = num_orbitals // 2
for occ_alpha in active_occ_list:
for unocc_alpha in active_unocc_list:
single_excitations.append([occ_alpha, unocc_alpha])
for occ_beta in [i + beta_idx for i in active_occ_list]:
for unocc_beta in [i + beta_idx for i in active_unocc_list]:
single_excitations.append([occ_beta, unocc_beta])
for occ_alpha in active_occ_list:
for unocc_alpha in active_unocc_list:
for occ_beta in [i + beta_idx for i in active_occ_list]:
for unocc_beta in [i + beta_idx for i in active_unocc_list]:
double_excitations.append([occ_alpha, unocc_alpha, occ_beta, unocc_beta])
if same_spin_doubles and len(active_occ_list) > 1 and len(active_unocc_list) > 1:
for i, occ_alpha in enumerate(active_occ_list[:-1]):
for j, unocc_alpha in enumerate(active_unocc_list[:-1]):
for occ_alpha_1 in active_occ_list[i + 1:]:
for unocc_alpha_1 in active_unocc_list[j + 1:]:
double_excitations.append([occ_alpha, unocc_alpha,
occ_alpha_1, unocc_alpha_1])
up_active_occ_list = [i + beta_idx for i in active_occ_list]
up_active_unocc_list = [i + beta_idx for i in active_unocc_list]
for i, occ_beta in enumerate(up_active_occ_list[:-1]):
for j, unocc_beta in enumerate(up_active_unocc_list[:-1]):
for occ_beta_1 in up_active_occ_list[i + 1:]:
for unocc_beta_1 in up_active_unocc_list[j + 1:]:
double_excitations.append([occ_beta, unocc_beta,
occ_beta_1, unocc_beta_1])
logger.debug('single_excitations ({}) {}'.format(len(single_excitations), single_excitations))
logger.debug('double_excitations ({}) {}'.format(len(double_excitations), double_excitations))
return single_excitations, double_excitations
def get_mp2_doubles(single_excitations, double_excitations):
print('Is the class still populated with the correct info: ', qm.nuclear_repulsion_energy)
mp2 = MP2Info(qm, single_excitations, double_excitations, threshold=1e-3)
mp2_doubles = mp2._mp2_doubles
return mp2_doubles
|
https://github.com/jwalaQ/my-qiskit-textbook-solutions
|
jwalaQ
|
from qiskit import Aer, execute, QuantumCircuit, QuantumRegister
from qiskit.visualization import plot_bloch_multivector,plot_histogram
input_bit = QuantumRegister(1,'input')
output_bit = QuantumRegister(1,'output')
garbage_bit = QuantumRegister(1,'garbage')
Uf = QuantumCircuit(input_bit,output_bit,garbage_bit)
Uf.cx(input_bit,output_bit)
# Uf.draw('mpl',justify=None)
Vf = QuantumCircuit(input_bit,output_bit,garbage_bit)
Vf.cx(input_bit,garbage_bit)
Vf.cx(input_bit,output_bit)
# Vf.draw('mpl',justify=None)
qc = Uf + Vf.inverse()
# qc.draw('mpl')
final_output_bit = QuantumRegister(1,'final_output')
copy = QuantumCircuit(output_bit,final_output_bit)
copy.cx(output_bit,final_output_bit)
# copy.draw('mpl',justify='None')
(Vf.inverse() + copy + Vf).draw(output='mpl',justify='None')
qc0 = QuantumCircuit(input_bit,output_bit,garbage_bit,final_output_bit)
qc0 = qc0 + Vf.inverse() + copy + Vf
qc0.draw('mpl',justify='none')
qasm_sim = Aer.get_backend('qasm_simulator')
qc0.measure_all()
result = execute(qc0,backend=qasm_sim).result()
counts = result.get_counts()
plot_histogram(counts)
qc1 = QuantumCircuit(input_bit,output_bit,garbage_bit,final_output_bit)
qc1.x(0)
qc1 = qc1 + Vf.inverse() + copy + Vf
qc1.draw('mpl',justify='none')
qc1.measure_all()
result = execute(qc1,backend=qasm_sim).result()
counts = result.get_counts()
plot_histogram(counts)
qc = QuantumCircuit(input_bit,output_bit,garbage_bit,final_output_bit)
qc.x(1)
qc = qc + Vf.inverse() + copy + Vf
qc = qc.reverse_bits()
qc.draw('mpl',justify='none')
qc.measure_all()
result = execute(qc,backend=qasm_sim).result()
counts = result.get_counts()
plot_histogram(counts)
qc = QuantumCircuit(input_bit,output_bit,garbage_bit,final_output_bit)
qc.x([0,1])
qc = qc + Vf.inverse() + copy + Vf
qc = qc.reverse_bits()
qc.draw('mpl',justify='none')
qc.measure_all()
result = execute(qc,backend=qasm_sim).result()
counts = result.get_counts()
plot_histogram(counts)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
with pulse.build() as hahn_echo:
with pulse.align_equispaced(duration=100):
pulse.play(x90, d0)
pulse.play(x180, d0)
pulse.play(x90, d0)
hahn_echo.draw()
|
https://github.com/FerjaniMY/Quantum_Steganography
|
FerjaniMY
|
from qiskit import *
import numpy as np
import matplotlib.pyplot as plt
from qiskit.visualization import plot_histogram
# Creating registers with n qubits
n =7 # for a local backend n can go as up as 23, after that it raises a Memory Error
qr = QuantumRegister(n, name='qr')
cr = ClassicalRegister(n, name='cr')
qc = QuantumCircuit(qr, cr, name='QC')
"""
qr2 = QuantumRegister(n, name='qr')
cr2= ClassicalRegister(n, name='cr')
qc2 = QuantumCircuit(qr2, cr2, name='QC')
for i in range(n):
qc2.h(i)
qc2.measure(qr2,cr2)
qc2.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
execute(qc2, backend = simulator)
result = execute(qc2, backend = simulator).result()
k=list(result.get_counts(qc2))[0]
print(k)
"""
# Generate a random number in the range of available qubits [0,65536))
alice_key = np.random.randint(0,2**n)# we can remplace it by a key from a quantum key generator
alice_key = np.binary_repr(alice_key,n)
print(alice_key)
for i in range(len(alice_key)):
if alice_key[i]=='1':
qc.x(qr[i])
B=[]
for i in range(len(alice_key)):
if 0.5 < np.random.random():
qc.h(qr[i])
B.append("H")
else:
B.append("S")
pass
qc.barrier()
print("Alice Basis",B)
%config InlineBackend.figure_format = 'svg'
qc.draw(output='mpl')
C=[]
for i in range(len(alice_key)):
if 0.5 < np.random.random():
qc.h(qr[i])
C.append("H")
else:
C.append("S")
qc.barrier()
for i in range(len(alice_key)):
qc.measure(qr[i],cr[i])
print("Bob Basis",C)
qc.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
execute(qc, backend = simulator)
result = execute(qc, backend = simulator).result()
print("Bob key :",list(result.get_counts(qc))[0])
print("Bob Basis",C)
print("Alice key :",alice_key)
print("Alice Basis :",B)
def sifted_key(A_basis,B_basis,key):
correct_basis=[]
sifted_key=''
for i in range(len(A_basis)):
if A_basis[i]==B_basis[i]:
correct_basis.append(i)
sifted_key+=key[i]
else:
pass
return sifted_key,correct_basis
a=sifted_key(B,C,alice_key)
print("sifted key",a[0])
print("Basis",a[1])
BB84_key=a[0]
def wordToBV(s) :
#convert text to binar
a_byte_array = bytearray(s, "utf8")
byte_list = []
for byte in a_byte_array:
binary_representation = bin(byte)
byte_list.append(binary_representation[9-n:])
#chop off the "0b" at the beginning. can also truncate the binary to fit on a device with N qubits
#binary has 2 extra digits for "0b", so it starts at 9 for our 7 bit operation.
print(byte_list)
circuit_array = []
length = len(byte_list)
for i in range(length):
s = byte_list[i]
#do all this stuff for every letter
# We need a circuit with n qubits, plus one ancilla qubit
# Also need n classical bits to write the output to
bv_circuit = QuantumCircuit(n+1, n)
# put ancilla in state |->
bv_circuit.h(n)
bv_circuit.z(n)
# Apply Hadamard gates before querying the oracle
for i in range(n):
bv_circuit.h(i)
# Apply barrier
bv_circuit.barrier()
# Apply the inner-product oracle
s = s[::-1] # reverse s to fit qiskit's qubit ordering
for q in range(n):
if s[q] == '0':
bv_circuit.i(q)
else:
bv_circuit.cx(q, n)
# Apply barrier
bv_circuit.barrier()
#Apply Hadamard gates after querying the oracle
for i in range(n):
bv_circuit.h(i)
# Measurement
for i in range(n):
bv_circuit.measure(i, i)
circuit_array.append(bv_circuit)
return circuit_array
circuit_to_run = wordToBV('Qiskit')#Secret Msg
circuit_to_run[0].draw(output='mpl')
backend = BasicAer.get_backend('qasm_simulator')
shots = 4096
results = execute(circuit_to_run[::-1], backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
def encrypt(BB84_key, letter):
"""Calculates XOR"""
b = int(BB84_key, 2)
x = ord(letter)
return format(b ^ x, "b")
def stega_encoder(LM, carrier_msg):
"""Encodes LM bits message into carrier_msg"""
message = ""
size = len(LM[0])
i = 0
for j, bitstring in enumerate(LM):
for k, digit in enumerate(bitstring):
while (not carrier_msg[i].isalpha()):
message += carrier_msg[i]
i += 1
if digit == "1":
letter = carrier_msg[i].upper()
message += letter
else:
message += carrier_msg[i]
i += 1
if i < len(carrier_msg):
message += carrier_msg[i:]
return message
def stega_decoder(new_carrier_msg, BB84_key):
"""Decodes secret message from new_carrier_msg"""
b = int(BB84_key, 2)
message = ""
bitstring = ""
for char in new_carrier_msg:
if char.isalpha():
if char.isupper():
bitstring += "1"
else:
bitstring += "0"
if len(bitstring) == 7:
x = int(bitstring, 2)
message += chr(b ^ x)
bitstring = ""
return message
a = chr(1110100)
str(a)
encrypt(BB84_key,'q')
secret_msg='qiskit'
L=[]
for c in secret_msg:
L.append(encrypt(BB84_key,c))
carrier_msg='aaaa aaa aaa aaaa aaaaaaa aaaaaaa aaaaaaa aaabaaa'
new_carrier_msg=stega_encoder(L, carrier_msg)
new_carrier_msg
stega_decoder(new_carrier_msg, BB84_key)
|
https://github.com/Aurelien-Pelissier/IBMQ-Quantum-Programming
|
Aurelien-Pelissier
|
import sys
import numpy as np
from matplotlib import pyplot as plt
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, visualization
from random import randint
def to_binary(N,n_bit):
Nbin = np.zeros(n_bit, dtype=bool)
for i in range(1,n_bit+1):
bit_state = (N % (2**i) != 0)
if bit_state:
N -= 2**(i-1)
Nbin[n_bit-i] = bit_state
return Nbin
def modular_multiplication(qc,a,N):
"""
applies the unitary operator that implements
modular multiplication function x -> a*x(modN)
Only works for the particular case x -> 7*x(mod15)!
"""
for i in range(0,3):
qc.x(i)
qc.cx(2,1)
qc.cx(1,2)
qc.cx(2,1)
qc.cx(1,0)
qc.cx(0,1)
qc.cx(1,0)
qc.cx(3,0)
qc.cx(0,1)
qc.cx(1,0)
def quantum_period(a, N, n_bit):
# Quantum part
print(" Searching the period for N =", N, "and a =", a)
qr = QuantumRegister(n_bit)
cr = ClassicalRegister(n_bit)
qc = QuantumCircuit(qr,cr)
simulator = Aer.get_backend('qasm_simulator')
s0 = randint(1, N-1) # Chooses random int
sbin = to_binary(s0,n_bit) # Turns to binary
print("\n Starting at \n s =", s0, "=", "{0:b}".format(s0), "(bin)")
# Quantum register is initialized with s (in binary)
for i in range(0,n_bit):
if sbin[n_bit-i-1]:
qc.x(i)
s = s0
r=-1 # makes while loop run at least 2 times
# Applies modular multiplication transformation until we come back to initial number s
while s != s0 or r <= 0:
r+=1
# sets up circuit structure
qc.measure(qr, cr)
modular_multiplication(qc,a,N)
qc.draw('mpl')
# runs circuit and processes data
job = execute(qc,simulator, shots=10)
result_counts = job.result().get_counts(qc)
result_histogram_key = list(result_counts)[0] # https://qiskit.org/documentation/stubs/qiskit.result.Result.get_counts.html#qiskit.result.Result.get_counts
s = int(result_histogram_key, 2)
print(" ", result_counts)
plt.show()
print("\n Found period r =", r)
return r
if __name__ == '__main__':
a = 7
N = 15
n_bit=5
r = quantum_period(a, N, n_bit)
|
https://github.com/dhanton/quantum-chess
|
dhanton
|
import math
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info.operators import Operator
from qiskit import Aer
from qiskit import execute
from qiskit.tools.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
MAX_QUBIT_MEMORY = backend.MAX_QUBIT_MEMORY
b = math.sqrt(2)
iSwap = Operator([
[1, 0, 0, 0],
[0, 0, 1j, 0],
[0, 1j, 0, 0],
[0, 0, 0, 1],
])
#when the controlled qubit holds if a path is clear
#then this gate can be understood as the slide gate
iSwap_controlled = Operator([
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1j, 0, 0, 0, 0, 0],
[0, 1j, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
])
iSwap_sqrt = Operator([
[1, 0, 0, 0],
[0, 1/b, 1j/b, 0],
[0, 1j/b, 1/b, 0],
[0, 0, 0, 1],
])
#in base s, t, control
iSwap_sqrt_controlled = Operator([
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1/b, 1j/b, 0, 0, 0, 0, 0],
[0, 1j/b, 1/b, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
])
def perform_standard_jump(engine, source, target):
qsource = engine.get_qubit(source.x, source.y)
qtarget = engine.get_qubit(target.x, target.y)
engine.qcircuit.unitary(iSwap, [qsource, qtarget], label='iSwap')
def perform_capture_jump(engine, source, target):
qsource = engine.get_qubit(source.x, source.y)
qtarget = engine.get_qubit(target.x, target.y)
#this ancilla qubit is going to hold the captured piece
captured_piece = engine.aregister[0]
engine.qcircuit.reset(captured_piece)
engine.qcircuit.unitary(iSwap, [qtarget, captured_piece], label='iSwap')
engine.qcircuit.unitary(iSwap, [qsource, qtarget], label='iSwap')
def perform_split_jump(engine, source, target1, target2):
qsource = engine.get_qubit(source.x, source.y)
qtarget1 = engine.get_qubit(target1.x, target1.y)
qtarget2 = engine.get_qubit(target2.x, target2.y)
engine.qcircuit.unitary(iSwap_sqrt, [qtarget1, qsource], label='iSwap_sqrt')
engine.qcircuit.unitary(iSwap, [qsource, qtarget2], label='iSwap')
def perform_merge_jump(engine, source1, source2, target):
qsource1 = engine.get_qubit(source1.x, source1.y)
qsource2 = engine.get_qubit(source2.x, source2.y)
qtarget = engine.get_qubit(target.x, target.y)
engine.qcircuit.unitary(iSwap, [qtarget, qsource2], label='iSwap')
engine.qcircuit.unitary(iSwap_sqrt, [qsource1, qtarget], label='iSwap_sqrt')
def perform_standard_slide(engine, source, target):
control_qubits = []
for point in engine.qchess.get_path_points(source, target):
control_qubits.append(engine.get_qubit(point.x, point.y))
engine.qcircuit.x(engine.get_qubit(point.x, point.y))
qsource = engine.get_qubit(source.x, source.y)
qtarget = engine.get_qubit(target.x, target.y)
path_ancilla = engine.aregister[0]
engine.qcircuit.reset(path_ancilla)
engine.qcircuit.x(path_ancilla)
engine.qcircuit.mct(control_qubits, path_ancilla, engine.mct_register, mode='advanced')
engine.qcircuit.unitary(iSwap_controlled, [qsource, qtarget, path_ancilla])
for point in engine.qchess.get_path_points(source, target):
engine.qcircuit.x(engine.get_qubit(point.x, point.y))
"""
*The source piece has already been collapsed before this is called*
So the basic idea behind this circuit is that if:
-The path is clear (doesn't matter if target is empty or not)
OR
-The path is not clear but the target is empty
Then there's no double occupancy and the piece can capture.
"""
def perform_capture_slide(engine, source, target):
control_qubits = []
for point in engine.qchess.get_path_points(source, target):
control_qubits.append(engine.get_qubit(point.x, point.y))
engine.qcircuit.x(engine.get_qubit(point.x, point.y))
qsource = engine.get_qubit(source.x, source.y)
qtarget = engine.get_qubit(target.x, target.y)
#holds if the path is clear or not
path_ancilla = engine.aregister[0]
engine.qcircuit.reset(path_ancilla)
engine.qcircuit.x(path_ancilla)
engine.qcircuit.mct(control_qubits, path_ancilla, engine.mct_register, mode='advanced')
#holds the final condition that's going to be measured
cond_ancilla = engine.aregister[1]
engine.qcircuit.reset(cond_ancilla)
#holds the captured piece
captured_piece = engine.aregister[2]
engine.qcircuit.reset(captured_piece)
#path is not blocked
engine.qcircuit.x(path_ancilla)
engine.qcircuit.cx(path_ancilla, cond_ancilla)
engine.qcircuit.x(path_ancilla)
#blocked but target empty
engine.qcircuit.x(qtarget)
engine.qcircuit.ccx(qtarget, path_ancilla, cond_ancilla)
engine.qcircuit.x(qtarget)
engine.qcircuit.measure(cond_ancilla, engine.cbit_misc[0])
engine.qcircuit.unitary(iSwap_controlled, [qtarget, captured_piece, path_ancilla]).c_if(engine.cbit_misc, 1)
engine.qcircuit.unitary(iSwap_controlled, [qsource, qtarget, path_ancilla]).c_if(engine.cbit_misc, 1)
for qubit in control_qubits:
engine.qcircuit.x(qubit)
result = execute(engine.qcircuit, backend=backend, shots=1).result()
#since get_counts() gives '1 00000001'
#a bit hacky but I don't know any other way to get this result
cbit_value = int(list(result.get_counts().keys())[0].split(' ')[0])
return (cbit_value == 1)
"""
Since the differences between both operations are only two gates,
it's useful to implement them together.
The args (single, double1, double2) are
split: (source, target1, target2)
merge: (target, source1, source2)
"""
def _slide_split_merge(engine, single, double1, double2, is_split):
qsingle = engine.get_qubit(single.x, single.y)
qdouble1 = engine.get_qubit(double1.x, double1.y)
qdouble2 = engine.get_qubit(double2.x, double2.y)
#get all qubits in first path
control_qubits1 = []
for point in engine.qchess.get_path_points(single, double1):
control_qubits1.append(engine.get_qubit(point.x, point.y))
engine.qcircuit.x(engine.get_qubit(point.x, point.y))
#holds if the first path is clear or not
path_ancilla1 = engine.aregister[0]
engine.qcircuit.reset(path_ancilla1)
engine.qcircuit.x(path_ancilla1)
#perform their combined CNOT
engine.qcircuit.mct(control_qubits1, path_ancilla1, engine.mct_register, mode='advanced')
#undo the X
for qubit in control_qubits1:
engine.qcircuit.x(qubit)
#get all qubits in second path
control_qubits2 = []
for point in engine.qchess.get_path_points(single, double2):
control_qubits2.append(engine.get_qubit(point.x, point.y))
engine.qcircuit.x(engine.get_qubit(point.x, point.y))
#holds if the second path is clear or not
path_ancilla2 = engine.aregister[1]
engine.qcircuit.reset(path_ancilla2)
engine.qcircuit.x(path_ancilla2)
#perform their combined CNOT
engine.qcircuit.mct(control_qubits2, path_ancilla2, engine.mct_register, mode='advanced')
for qubit in control_qubits2:
engine.qcircuit.x(qubit)
#holds the control for jump and slide
control_ancilla = engine.aregister[2]
engine.qcircuit.reset(control_ancilla)
engine.qcircuit.x(control_ancilla)
#perform the split/merge
engine.qcircuit.x(path_ancilla1)
engine.qcircuit.x(path_ancilla2)
engine.qcircuit.ccx(path_ancilla1, path_ancilla2, control_ancilla)
if is_split:
engine.qcircuit.unitary(iSwap_sqrt_controlled, [qdouble1, qsingle, control_ancilla])
engine.qcircuit.unitary(iSwap_controlled, [qsingle, qdouble2, control_ancilla])
else:
engine.qcircuit.unitary(iSwap_controlled, [qsingle, qdouble2, control_ancilla])
engine.qcircuit.unitary(iSwap_sqrt_controlled, [qdouble1, qsingle, control_ancilla])
engine.qcircuit.x(path_ancilla1)
engine.qcircuit.x(path_ancilla2)
#reset the control
engine.qcircuit.reset(control_ancilla)
engine.qcircuit.x(control_ancilla)
#perform one jump
engine.qcircuit.x(path_ancilla1)
engine.qcircuit.ccx(path_ancilla1, path_ancilla2, control_ancilla)
engine.qcircuit.unitary(iSwap_controlled, [qdouble1, qsingle, control_ancilla])
engine.qcircuit.x(path_ancilla1)
#reset the control
engine.qcircuit.reset(control_ancilla)
engine.qcircuit.x(control_ancilla)
#perform the other jump
engine.qcircuit.x(path_ancilla2)
engine.qcircuit.ccx(path_ancilla1, path_ancilla2, control_ancilla)
engine.qcircuit.unitary(iSwap_controlled, [qsingle, qdouble2, control_ancilla])
engine.qcircuit.x(path_ancilla2)
def perform_split_slide(engine, source, target1, target2):
_slide_split_merge(engine, source, target1, target2, is_split=True)
def perform_merge_slide(engine, source1, source2, target):
_slide_split_merge(engine, target, source1, source2, is_split=False)
def perform_standard_en_passant(engine, source, target, ep_target):
qsource = engine.get_qubit(source.x, source.y)
qtarget = engine.get_qubit(target.x, target.y)
qep_target = engine.get_qubit(ep_target.x, ep_target.y)
captured_ancilla = engine.aregister[0]
engine.qcircuit.reset(captured_ancilla)
#holds if both source and ep_target are empty or not at the same time
both_pieces_ancilla = engine.aregister[1]
engine.qcircuit.reset(both_pieces_ancilla)
engine.qcircuit.ccx(qsource, qep_target, both_pieces_ancilla)
engine.qcircuit.x(both_pieces_ancilla)
engine.qcircuit.unitary(iSwap_controlled, [qep_target, captured_ancilla, both_pieces_ancilla])
engine.qcircuit.unitary(iSwap_controlled, [qsource, qtarget, both_pieces_ancilla])
def perform_capture_en_passant(engine, source, target, ep_target):
qsource = engine.get_qubit(source.x, source.y)
qtarget = engine.get_qubit(target.x, target.y)
qep_target = engine.get_qubit(ep_target.x, ep_target.y)
#since this move can capture two pieces at the same time,
#we need two ancillas to hold them
captured_ancilla1 = engine.aregister[0]
engine.qcircuit.reset(captured_ancilla1)
captured_ancilla2 = engine.aregister[1]
engine.qcircuit.reset(captured_ancilla2)
#holds if any of target, ep_target exist
#Note: It's impossible for them to exist at the same time (during this function's call),
# since if they did that would mean that target piece has reached its position
# after the pawn moved and thus EP would not be not a valid move.
any_piece_ancilla = engine.aregister[2]
engine.qcircuit.reset(any_piece_ancilla)
engine.qcircuit.cx(qep_target, any_piece_ancilla)
engine.qcircuit.cx(qtarget, any_piece_ancilla)
engine.qcircuit.x(any_piece_ancilla)
engine.qcircuit.unitary(iSwap_controlled, [qep_target, captured_ancilla1, any_piece_ancilla])
engine.qcircuit.unitary(iSwap_controlled, [qtarget, captured_ancilla2, any_piece_ancilla])
engine.qcircuit.unitary(iSwap_controlled, [qsource, qtarget, any_piece_ancilla])
#path holds all points that must be empty for the move to be valid (excluding targets)
def perform_castle(engine, king_source, rook_source, king_target, rook_target, path=None):
qking_source = engine.get_qubit(king_source.x, king_source.y)
qrook_source = engine.get_qubit(rook_source.x, rook_source.y)
qking_target = engine.get_qubit(king_target.x, king_target.y)
qrook_target = engine.get_qubit(rook_target.x, rook_target.y)
if path:
#holds all the qubits of the path
control_qubits = []
for point in path:
control_qubits.append(engine.get_qubit(point.x, point.y))
engine.qcircuit.x(engine.get_qubit(point.x, point.y))
#holds if the path is empty or not
path_ancilla = engine.aregister[0]
engine.qcircuit.reset(path_ancilla)
engine.qcircuit.x(path_ancilla)
engine.qcircuit.mct(control_qubits, path_ancilla, engine.mct_register, mode='advanced')
#undo the x
for qubit in control_qubits:
engine.qcircuit.x(qubit)
#perform the movement
engine.qcircuit.unitary(iSwap_controlled, [qking_source, qking_target, path_ancilla])
engine.qcircuit.unitary(iSwap_controlled, [qrook_source, qrook_target, path_ancilla])
else:
#perform the movement
engine.qcircuit.unitary(iSwap, [qking_source, qking_target])
engine.qcircuit.unitary(iSwap, [qrook_source, qrook_target])
|
https://github.com/PayalSolanki2906/Quantum_algorithms_using_Qiskit
|
PayalSolanki2906
|
from qiskit import QuantumCircuit, assemble, Aer
from math import pi, sqrt, exp
from qiskit.visualization import plot_bloch_multivector, plot_histogram
sim = Aer.get_backend('aer_simulator')
qc = QuantumCircuit(1)
qc.x(0)
qc.draw()
qc.save_statevector()
qobj = assemble(qc)
state = sim.run(qobj).result().get_statevector()
plot_bloch_multivector(state)
qc = QuantumCircuit(1)
qc.y(0)
qc.draw()
qc.save_statevector()
qobj = assemble(qc)
state = sim.run(qobj).result().get_statevector()
plot_bloch_multivector(state)
qc = QuantumCircuit(1)
qc.z(0)
qc.draw()
qc.save_statevector()
qobj = assemble(qc)
state = sim.run(qobj).result().get_statevector()
plot_bloch_multivector(state)
qc = QuantumCircuit(1)
qc.h(0)
qc.draw()
qc.save_statevector()
qobj = assemble(qc)
state = sim.run(qobj).result().get_statevector()
plot_bloch_multivector(state)
qc = QuantumCircuit(1)
qc.p(pi/4, 0)
qc.draw()
qc = QuantumCircuit(1)
qc.s(0) # Apply S-gate to qubit 0
qc.sdg(0) # Apply Sdg-gate to qubit 0
qc.draw()
qc = QuantumCircuit(1)
qc.t(0) # Apply T-gate to qubit 0
qc.tdg(0) # Apply Tdg-gate to qubit 0
qc.draw()
qc = QuantumCircuit(1)
qc.u(pi/2, 0, pi, 0)
qc.draw()
qc.save_statevector()
qobj = assemble(qc)
state = sim.run(qobj).result().get_statevector()
plot_bloch_multivector(state)
initial_state =[1/sqrt(2), -1/sqrt(2)] # Define state |q_0>
qc = QuantumCircuit(1) # Must redefine qc
qc.initialize(initial_state, 0) # Initialize the 0th qubit in the state `initial_state`
qc.save_statevector() # Save statevector
qobj = assemble(qc)
state = sim.run(qobj).result().get_statevector() # Execute the circuit
print(state) # Print the result
qobj = assemble(qc)
results = sim.run(qobj).result().get_counts()
plot_histogram(results)
initial_state =[1/sqrt(2), 1/sqrt(2)] # Define state |q_0>
qc = QuantumCircuit(1) # Must redefine qc
qc.initialize(initial_state, 0) # Initialize the 0th qubit in the state `initial_state`
qc.save_statevector() # Save statevector
qobj = assemble(qc)
state = sim.run(qobj).result().get_statevector() # Execute the circuit
print(state) # Print the result
qobj = assemble(qc)
results = sim.run(qobj).result().get_counts()
plot_histogram(results)
# Create the Y-measurement function:
def x_measurement(qc, qubit, cbit):
"""Measure 'qubit' in the X-basis, and store the result in 'cbit'"""
qc.s(qubit)
qc.h(qubit)
qc.measure(qubit, cbit)
return qc
initial_state = [1/sqrt(2), -complex(0,1)/sqrt(2)]
# Initialize our qubit and measure it
qc = QuantumCircuit(1,1)
qc.initialize(initial_state, 0)
x_measurement(qc, 0, 0) # measure qubit 0 to classical bit 0
qc.draw()
qobj = assemble(qc) # Assemble circuit into a Qobj that can be run
counts = sim.run(qobj).result().get_counts() # Do the simulation, returning the state vector
plot_histogram(counts) # Display the output on measurement of state vector
|
https://github.com/tigerjack/qiskit_grover
|
tigerjack
|
circuit = None
oracle_simple = None
execute = None
Aer = None
IBMQ = None
least_busy = None
def _import_modules():
print("Importing modules")
global circuit, oracle_simple, execute, least_busy
import circuit
import oracle_simple
from qiskit import execute
from qiskit.backends.ibmq import least_busy
# To be used from REPL
def build_and_infos(n, x_stars, real=False, online=False, backend_name=None):
_import_modules()
oracles = []
for i in range(len(x_stars)):
oracles.append(oracle_simple.OracleSimple(n, x_stars[i]))
gc, n_qubits = circuit.get_circuit(n, oracles)
if real:
online = True
backend, max_credits, shots = get_appropriate_backend(
n_qubits, real, online, backend_name)
res = get_compiled_circuit_infos(gc, backend, max_credits, shots)
return res
# To be used from REPL
def build_and_run(n, x_stars, real=False, online=False, backend_name=None):
"""
This just build the grover circuit for the specific n and x_star
and run them on the selected backend.
It may be convenient to use in an interactive shell for quick testing.
"""
_import_modules()
oracles = []
for i in range(len(x_stars)):
oracles.append(oracle_simple.OracleSimple(n, x_stars[i]))
gc, n_qubits = circuit.get_circuit(n, oracles)
if real:
online = True
backend, max_credits, shots = get_appropriate_backend(
n_qubits, real, online, backend_name)
return run_grover_algorithm(gc, backend, max_credits, shots)
def get_appropriate_backend(n, real, online, backend_name):
# Online, real or simuator?
if (not online):
global Aer
from qiskit import Aer
max_credits = 10
shots = 4098
print("Local simulator backend")
backend = Aer.get_backend('qasm_simulator')
# list of online devices: ibmq_qasm_simulator, ibmqx2, ibmqx4, ibmqx5, ibmq_16_melbourne
else:
global IBMQ
from qiskit import IBMQ
print("Online {0} backend".format("real" if real else "simulator"))
max_credits = 3
shots = 4098
import Qconfig
IBMQ.load_accounts()
if (backend_name is not None):
backend = IBMQ.get_backend(backend_name)
else:
large_enough_devices = IBMQ.backends(
filters=lambda x: x.configuration()['n_qubits'] >= n and x.configuration()[
'simulator'] == (not real)
)
backend = least_busy(large_enough_devices)
print("Backend name is {0}; max_credits = {1}, shots = {2}".format(
backend, max_credits, shots))
return backend, max_credits, shots
def get_compiled_circuit_infos(qc, backend, max_credits, shots):
result = {}
print("Getting infos ... ")
backend_coupling = backend.configuration()['coupling_map']
from qiskit import compile
grover_compiled = compile(
qc, backend=backend, coupling_map=backend_coupling, shots=shots)
grover_compiled_qasm = grover_compiled.experiments[
0].header.compiled_circuit_qasm
result['n_gates'] = len(grover_compiled_qasm.split("\n")) - 4
return result
def run_grover_algorithm(qc, backend, max_credits, shots):
"""
Run the grover algorithm, i.e. the quantum circuit qc.
:param qc: The (qiskit) quantum circuit
:param real: False (default) to run the circuit on a simulator backend, True to run on a real backend
:param backend_name: None (default) to run the circuit on the default backend (local qasm for simulation, least busy IBMQ device for a real backend); otherwise, it should contain the name of the backend you want to use.
:returns: Result of the computations, i.e. the dictionary of result counts for an execution.
:rtype: dict
"""
_import_modules()
pending_jobs = backend.status()['pending_jobs']
print("Backend has {0} pending jobs".format(pending_jobs))
print("Compiling ... ")
job = execute(qc, backend, shots=shots, max_credits=max_credits)
print("Job id is {0}".format(job.job_id()))
print(
"At this point, if any error occurs, you can always retrieve the job results using the backend name and the job id using the utils/retrieve_job_results.py script"
)
if pending_jobs > 1:
s = input(
"Do you want to wait for the job to go up in the queue list or exit the program(q)? If you exit now you can still retrieve the job results later on using the backend name and the job id w/ the utils/retrieve_job_results.py script"
)
if (s == "q"):
print(
"WARNING: Take note of backend name and job id to retrieve the job"
)
from sys import exit
exit()
result = job.result()
return result.get_counts(qc)
def get_max_key_value(counts):
mx = max(counts.keys(), key=(lambda key: counts[key]))
total = sum(counts.values())
confidence = counts[mx] / total
return mx, confidence
def main():
import argparse
parser = argparse.ArgumentParser(description="Grover algorithm")
parser.add_argument(
'n',
metavar='n',
type=int,
help='the number of bits used to store the oracle data.')
parser.add_argument(
'x_stars',
metavar='x_star',
type=int,
nargs='+',
help='the number(s) for which the oracle returns 1, in the range [0..2**n-1].'
)
parser.add_argument(
'-r',
'--real',
action='store_true',
help='Invoke the real device (implies -o). Default is simulator.')
parser.add_argument(
'-o',
'--online',
action='store_true',
help='Use the online IBMQ devices. Default is local (simulator). This option is automatically set when we want to use a real device (see -r).'
)
parser.add_argument(
'-i',
'--infos',
action='store_true',
help='Print only infos on the circuit built for the specific backend (such as the number of gates) without executing it.'
)
parser.add_argument(
'-b',
'--backend_name',
help="The name of the backend. It makes sense only for online ibmq devices and it's useless otherwise. If not specified, the program automatically choose the least busy ibmq backend."
)
parser.add_argument(
'--img_dir',
help='If you want to store the image of the circuit, you need to specify the directory.'
)
parser.add_argument(
'--plot',
action='store_true',
help='Plot the histogram of the results. Default is false')
args = parser.parse_args()
n = args.n
x_stars = args.x_stars
print("n: {0}, x_stars: {1}".format(n, x_stars))
real = args.real
online = True if real else args.online
infos = args.infos
backend_name = args.backend_name
img_dir = args.img_dir
plot = args.plot
print("real: {0}, online: {1}, infos: {2}, backend_name: {3}".format(
real, online, infos, backend_name))
_import_modules()
oracles = []
for i in range(len(x_stars)):
oracles.append(oracle_simple.OracleSimple(n, x_stars[i]))
gc, n_qubits = circuit.get_circuit(n, oracles)
if (img_dir is not None):
from qiskit.tools.visualization import circuit_drawer
circuit_drawer(
gc, filename=img_dir + "grover_{0}_{1}.png".format(n, x_stars[0]))
backend, max_credits, shots = get_appropriate_backend(
n_qubits, real, online, backend_name)
if (infos):
res = get_compiled_circuit_infos(gc, backend, max_credits, shots)
for k, v in res.items():
print("{0} --> {1}".format(k, v))
else: # execute
counts = run_grover_algorithm(gc, backend, max_credits, shots)
print(counts)
max, confidence = get_max_key_value(counts)
print("Max value: {0}, confidence {1}".format(max, confidence))
if (plot):
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
print("END")
# Assumption: if run from console we're inside src/.. dir
if __name__ == "__main__":
main()
|
https://github.com/ctuning/ck-qiskit
|
ctuning
|
import numpy as np
import IPython
import ipywidgets as widgets
import colorsys
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister
from qiskit import execute, Aer, BasicAer
from qiskit.visualization import plot_bloch_multivector
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import os
import glob
import moviepy.editor as mpy
import seaborn as sns
sns.set()
'''========State Vector======='''
def getStateVector(qc):
'''get state vector in row matrix form'''
backend = BasicAer.get_backend('statevector_simulator')
job = execute(qc,backend).result()
vec = job.get_statevector(qc)
return vec
def vec_in_braket(vec: np.ndarray) -> str:
'''get bra-ket notation of vector'''
nqubits = int(np.log2(len(vec)))
state = ''
for i in range(len(vec)):
rounded = round(vec[i], 3)
if rounded != 0:
basis = format(i, 'b').zfill(nqubits)
state += np.str(rounded).replace('-0j', '+0j')
state += '|' + basis + '\\rangle + '
state = state.replace("j", "i")
return state[0:-2].strip()
def vec_in_text_braket(vec):
return '$$\\text{{State:\n $|\\Psi\\rangle = $}}{}$$'\
.format(vec_in_braket(vec))
def writeStateVector(vec):
return widgets.HTMLMath(vec_in_text_braket(vec))
'''==========Bloch Sphere ========='''
def getBlochSphere(qc):
'''plot multi qubit bloch sphere'''
vec = getStateVector(qc)
return plot_bloch_multivector(vec)
def getBlochSequence(path,figs):
'''plot block sphere sequence and save it
to a folder for gif movie creation'''
try:
os.mkdir(path)
except:
print('Directory already exist')
for i,fig in enumerate(figs):
fig.savefig(path+"/rot_"+str(i)+".png")
return
def getBlochGif(figs,path,fname,fps,remove = True):
'''create gif movie from provided images'''
file_list = glob.glob(path + "/*.png")
list.sort(file_list, key=lambda x: int(x.split('_')[1].split('.png')[0]))
clip = mpy.ImageSequenceClip(file_list, fps=fps)
clip.write_gif('{}.gif'.format(fname), fps=fps)
'''remove all image files after gif creation'''
if remove:
for file in file_list:
os.remove(file)
return
'''=========Matrix================='''
def getMatrix(qc):
'''get numpy matrix representing a circuit'''
backend = BasicAer.get_backend('unitary_simulator')
job = execute(qc, backend)
ndArray = job.result().get_unitary(qc, decimals=3)
Matrix = np.matrix(ndArray)
return Matrix
def plotMatrix(M):
'''visualize a matrix using seaborn heatmap'''
MD = [["0" for i in range(M.shape[0])] for j in range(M.shape[1])]
for i in range(M.shape[0]):
for j in range(M.shape[1]):
r = M[i,j].real
im = M[i,j].imag
MD[i][j] = str(r)[0:4]+ " , " +str(im)[0:4]
plt.figure(figsize = [2*M.shape[1],M.shape[0]])
sns.heatmap(np.abs(M),\
annot = np.array(MD),\
fmt = '',linewidths=.5,\
cmap='Blues')
return
'''=========Measurement========'''
def getCount(qc):
backend= Aer.get_backend('qasm_simulator')
result = execute(qc,backend).result()
counts = result.get_counts(qc)
return counts
def plotCount(counts,figsize):
plot_histogram(counts)
'''========Phase============'''
def getPhaseCircle(vec):
'''get phase color, angle and radious of phase circir'''
Phase = []
for i in range(len(vec)):
angles = (np.angle(vec[i]) + (np.pi * 4)) % (np.pi * 2)
rgb = colorsys.hls_to_rgb(angles / (np.pi * 2), 0.5, 0.5)
mag = np.abs(vec[i])
Phase.append({"rgb":rgb,"mag": mag,"ang":angles})
return Phase
def getPhaseDict(QCs):
'''get a dictionary of state vector phase circles for
each quantum circuit and populate phaseDict list'''
phaseDict = []
for qc in QCs:
vec = getStateVector(qc)
Phase = getPhaseCircle(vec)
phaseDict.append(Phase)
return phaseDict
def plotiPhaseCircle(phaseDict,depth,path,show=False,save=False):
'''plot any quantum circuit phase circle diagram
from provided phase Dictionary'''
r = 0.30
dx = 1.0
nqubit = len(phaseDict[0])
fig = plt.figure(figsize = [depth,nqubit])
for i in range(depth):
x0 = i
for j in range(nqubit):
y0 = j+1
try:
mag = phaseDict[i][j]['mag']
ang = phaseDict[i][j]['ang']
rgb = phaseDict[i][j]['rgb']
ax=plt.gca()
circle1= plt.Circle((dx+x0,y0), radius = r, color = 'white')
ax.add_patch(circle1)
circle2= plt.Circle((dx+x0,y0), radius= r*mag, color = rgb)
ax.add_patch(circle2)
line = plt.plot((dx+x0,dx+x0+(r*mag*np.cos(ang))),\
(y0,y0+(r*mag*np.sin(ang))),color = "black")
except:
ax=plt.gca()
circle1= plt.Circle((dx+x0,y0), radius = r, color = 'white')
ax.add_patch(circle1)
plt.ylim(nqubit+1,0)
plt.yticks([y+1 for y in range(nqubit)])
plt.xticks([x for x in range(depth+2)])
plt.xlabel("Circuit Depth")
plt.ylabel("Basis States")
if show:
plt.show()
plt.savefig(path+".png")
plt.close(fig)
if save:
plt.savefig(path +".png")
plt.close(fig)
return
def plotiPhaseCircle_rotated(phaseDict,depth,path,show=False,save=False):
'''plot any quantum circuit phase circle diagram
from provided phase Dictionary'''
r = 0.30
dy = 1.0
nqubit = len(phaseDict[0])
fig = plt.figure(figsize = [nqubit,depth])
for i in range(depth):
y0 = i
for j in range(nqubit):
x0 = j+1
try:
mag = phaseDict[i][j]['mag']
ang = phaseDict[i][j]['ang']
rgb = phaseDict[i][j]['rgb']
ax=plt.gca()
circle1= plt.Circle((x0,dy+y0), radius = r, color = 'white')
ax.add_patch(circle1)
circle2= plt.Circle((x0,dy+y0), radius= r*mag, color = rgb)
ax.add_patch(circle2)
line = plt.plot((x0,x0+(r*mag*np.cos(ang))),\
(dy+y0,dy+y0+(r*mag*np.sin(ang))),color = "black")
except:
ax=plt.gca()
circle1= plt.Circle((x0,dy+y0), radius = r, color = 'white')
ax.add_patch(circle1)
plt.ylim(0,depth+1)
plt.yticks([x+1 for x in range(depth)])
plt.xticks([y for y in range(nqubit+2)])
plt.ylabel("Circuit Depth")
plt.xlabel("Basis States")
if show:
plt.show()
plt.savefig(path+".png")
plt.close(fig)
if save:
plt.savefig(path +".png")
plt.close(fig)
return
def getPhaseSequence(QCs,path,rotated=False):
'''plot a sequence of phase circle diagram for a given
sequence of quantum circuits'''
try:
os.mkdir(path)
except:
print("Directory already exist")
depth = len(QCs)
phaseDict =[]
for i,qc in enumerate(QCs):
vec = getStateVector(qc)
Phase = getPhaseCircle(vec)
phaseDict.append(Phase)
ipath = path + "phase_" + str(i)
if rotated:
plotiPhaseCircle_rotated(phaseDict,depth,ipath,save=True,show=False)
else:
plotiPhaseCircle(phaseDict,depth,ipath,save=True,show=False)
return
def getPhaseGif(path,fname,fps,remove = True):
'''create a gif movie file from phase circle figures'''
file_list = glob.glob(path+ "/*.png")
list.sort(file_list, key=lambda x: int(x.split('_')[1].split('.png')[0]))
clip = mpy.ImageSequenceClip(file_list, fps=fps)
clip.write_gif('{}.gif'.format(fname), fps=fps)
'''remove all image files after gif creation'''
if remove:
for file in file_list:
os.remove(file)
return
|
https://github.com/qiskit-community/prototype-quantum-kernel-training
|
qiskit-community
|
from typing import List, Callable, Union
from qiskit import QuantumCircuit
from qiskit.circuit import ParameterVector
# To visualize circuit creation process
from qiskit.visualization import circuit_drawer
# For a dataset with 12 features; and 2 features per qubit
FEATURE_DIMENSION = 12
NUM_QUBITS = int(FEATURE_DIMENSION / 2)
# Qiskit feature maps should generally be QuantumCircuits or extensions of QuantumCircuit
feature_map = QuantumCircuit(NUM_QUBITS)
user_params = ParameterVector("θ", NUM_QUBITS)
# Create circuit layer with trainable parameters
for i in range(NUM_QUBITS):
feature_map.ry(user_params[i], feature_map.qubits[i])
print(circuit_drawer(feature_map))
# Linear entanglement
entanglement = [[i, i + 1] for i in range(NUM_QUBITS - 1)]
for source, target in entanglement:
feature_map.cz(feature_map.qubits[source], feature_map.qubits[target])
feature_map.barrier()
print(circuit_drawer(feature_map))
input_params = ParameterVector("x", FEATURE_DIMENSION)
for i in range(NUM_QUBITS):
feature_map.rz(input_params[2 * i + 1], feature_map.qubits[i])
feature_map.rx(input_params[2 * i], feature_map.qubits[i])
print(circuit_drawer(feature_map))
class ExampleFeatureMap(QuantumCircuit):
"""The Example Feature Map circuit"""
def __init__(
self,
feature_dimension: int,
entanglement: Union[str, List[List[int]], Callable[[int], List[int]]] = None,
name: str = "ExampleFeatureMap",
) -> None:
"""Create a new Example Feature Map circuit.
Args:
feature_dimension: The number of features
entanglement: Entanglement scheme to be used in second layer
name: Name of QuantumCircuit object
Raises:
ValueError: ExampleFeatureMap requires an even number of input features
"""
if (feature_dimension % 2) != 0:
raise ValueError(
"""
Example feature map requires an even number of input features.
"""
)
self.feature_dimension = feature_dimension
self.entanglement = entanglement
self.training_parameters = None
# Call the QuantumCircuit initialization
num_qubits = feature_dimension / 2
super().__init__(
num_qubits,
name=name,
)
# Build the feature map circuit
self._generate_feature_map()
def _generate_feature_map(self):
# If no entanglement scheme specified, use linear entanglement
if self.entanglement is None:
self.entanglement = [[i, i + 1] for i in range(self.num_qubits - 1)]
# Vector of data parameters
input_params = ParameterVector("x", self.feature_dimension)
training_params = ParameterVector("θ", self.num_qubits)
# Create an initial rotation layer of trainable parameters
for i in range(self.num_qubits):
self.ry(training_params[i], self.qubits[i])
self.training_parameters = training_params
# Create the entanglement layer
for source, target in self.entanglement:
self.cz(self.qubits[source], self.qubits[target])
self.barrier()
# Create a circuit representation of the data group
for i in range(self.num_qubits):
self.rz(input_params[2 * i + 1], self.qubits[i])
self.rx(input_params[2 * i], self.qubits[i])
feature_map = ExampleFeatureMap(feature_dimension=10)
circuit_drawer(feature_map)
#import qiskit.tools.jupyter
#
#%qiskit_version_table
#%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
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__
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 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.
"""An algorithm to implement a Trotterization real time-evolution."""
from __future__ import annotations
from qiskit import QuantumCircuit
from qiskit_algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem
from qiskit_algorithms.time_evolvers.time_evolution_result import TimeEvolutionResult
from qiskit_algorithms.time_evolvers.real_time_evolver import RealTimeEvolver
from qiskit_algorithms.observables_evaluator import estimate_observables
from qiskit.opflow import PauliSumOp
from qiskit.circuit.library import PauliEvolutionGate
from qiskit.circuit.parametertable import ParameterView
from qiskit.primitives import BaseEstimator
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit.synthesis import ProductFormula, LieTrotter
class TrotterQRTE(RealTimeEvolver):
"""Quantum Real Time Evolution using Trotterization.
Type of Trotterization is defined by a ``ProductFormula`` provided.
Examples:
.. code-block:: python
from qiskit.opflow import PauliSumOp
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit import QuantumCircuit
from qiskit_algorithms import TimeEvolutionProblem
from qiskit_algorithms.time_evolvers import TrotterQRTE
from qiskit.primitives import Estimator
operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")]))
initial_state = QuantumCircuit(1)
time = 1
evolution_problem = TimeEvolutionProblem(operator, time, initial_state)
# LieTrotter with 1 rep
estimator = Estimator()
trotter_qrte = TrotterQRTE(estimator=estimator)
evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state
"""
def __init__(
self,
product_formula: ProductFormula | None = None,
estimator: BaseEstimator | None = None,
num_timesteps: int = 1,
) -> None:
"""
Args:
product_formula: A Lie-Trotter-Suzuki product formula. If ``None`` provided, the
Lie-Trotter first order product formula with a single repetition is used. ``reps``
should be 1 to obtain a number of time-steps equal to ``num_timesteps`` and an
evaluation of :attr:`.TimeEvolutionProblem.aux_operators` at every time-step. If ``reps``
is larger than 1, the true number of time-steps will be ``num_timesteps * reps``.
num_timesteps: The number of time-steps the full evolution time is devided into
(repetitions of ``product_formula``)
estimator: An estimator primitive used for calculating expectation values of
``TimeEvolutionProblem.aux_operators``.
"""
self.product_formula = product_formula
self.num_timesteps = num_timesteps
self.estimator = estimator
@property
def product_formula(self) -> ProductFormula:
"""Returns a product formula."""
return self._product_formula
@product_formula.setter
def product_formula(self, product_formula: ProductFormula | None):
"""Sets a product formula. If ``None`` provided, sets the Lie-Trotter first order product
formula with a single repetition."""
if product_formula is None:
product_formula = LieTrotter()
self._product_formula = product_formula
@property
def estimator(self) -> BaseEstimator | None:
"""
Returns an estimator.
"""
return self._estimator
@estimator.setter
def estimator(self, estimator: BaseEstimator) -> None:
"""
Sets an estimator.
"""
self._estimator = estimator
@property
def num_timesteps(self) -> int:
"""Returns the number of timesteps."""
return self._num_timesteps
@num_timesteps.setter
def num_timesteps(self, num_timesteps: int) -> None:
"""
Sets the number of time-steps.
Raises:
ValueError: If num_timesteps is not positive.
"""
if num_timesteps <= 0:
raise ValueError(
f"Number of time steps must be positive integer, {num_timesteps} provided"
)
self._num_timesteps = num_timesteps
@classmethod
def supports_aux_operators(cls) -> bool:
"""
Whether computing the expectation value of auxiliary operators is supported.
Returns:
``True`` if ``aux_operators`` expectations in the ``TimeEvolutionProblem`` can be
evaluated, ``False`` otherwise.
"""
return True
def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult:
"""
Evolves a quantum state for a given time using the Trotterization method
based on a product formula provided. The result is provided in the form of a quantum
circuit. If auxiliary operators are included in the ``evolution_problem``, they are
evaluated on the ``init_state`` and on the evolved state at every step (``num_timesteps``
times) using an estimator primitive provided.
Args:
evolution_problem: Instance defining evolution problem. For the included Hamiltonian,
``Pauli`` or ``PauliSumOp`` are supported by TrotterQRTE.
Returns:
Evolution result that includes an evolved state as a quantum circuit and, optionally,
auxiliary operators evaluated for a resulting state on an estimator primitive.
Raises:
ValueError: If ``t_param`` is not set to ``None`` in the ``TimeEvolutionProblem``
(feature not currently supported).
ValueError: If ``aux_operators`` provided in the time evolution problem but no estimator
provided to the algorithm.
ValueError: If the ``initial_state`` is not provided in the ``TimeEvolutionProblem``.
ValueError: If an unsupported Hamiltonian type is provided.
"""
evolution_problem.validate_params()
if evolution_problem.aux_operators is not None and self.estimator is None:
raise ValueError(
"The time evolution problem contained ``aux_operators`` but no estimator was "
"provided. The algorithm continues without calculating these quantities. "
)
# ensure the hamiltonian is a sparse pauli op
hamiltonian = evolution_problem.hamiltonian
if not isinstance(hamiltonian, (Pauli, PauliSumOp, SparsePauliOp)):
raise ValueError(
f"TrotterQRTE only accepts Pauli | PauliSumOp | SparsePauliOp, {type(hamiltonian)} "
"provided."
)
if isinstance(hamiltonian, PauliSumOp):
hamiltonian = hamiltonian.primitive * hamiltonian.coeff
elif isinstance(hamiltonian, Pauli):
hamiltonian = SparsePauliOp(hamiltonian)
t_param = evolution_problem.t_param
free_parameters = hamiltonian.parameters
if t_param is not None and free_parameters != ParameterView([t_param]):
raise ValueError(
f"Hamiltonian time parameters ({free_parameters}) do not match "
f"evolution_problem.t_param ({t_param})."
)
# make sure PauliEvolutionGate does not implement more than one Trotter step
dt = evolution_problem.time / self.num_timesteps
if evolution_problem.initial_state is not None:
initial_state = evolution_problem.initial_state
else:
raise ValueError("``initial_state`` must be provided in the ``TimeEvolutionProblem``.")
evolved_state = QuantumCircuit(initial_state.num_qubits)
evolved_state.append(initial_state, evolved_state.qubits)
if evolution_problem.aux_operators is not None:
observables = []
observables.append(
estimate_observables(
self.estimator,
evolved_state,
evolution_problem.aux_operators,
None,
evolution_problem.truncation_threshold,
)
)
else:
observables = None
if t_param is None:
# the evolution gate
single_step_evolution_gate = PauliEvolutionGate(
hamiltonian, dt, synthesis=self.product_formula
)
for n in range(self.num_timesteps):
# if hamiltonian is time-dependent, bind new time-value at every step to construct
# evolution for next step
if t_param is not None:
time_value = (n + 1) * dt
bound_hamiltonian = hamiltonian.assign_parameters([time_value])
single_step_evolution_gate = PauliEvolutionGate(
bound_hamiltonian,
dt,
synthesis=self.product_formula,
)
evolved_state.append(single_step_evolution_gate, evolved_state.qubits)
if evolution_problem.aux_operators is not None:
observables.append(
estimate_observables(
self.estimator,
evolved_state,
evolution_problem.aux_operators,
None,
evolution_problem.truncation_threshold,
)
)
evaluated_aux_ops = None
if evolution_problem.aux_operators is not None:
evaluated_aux_ops = observables[-1]
return TimeEvolutionResult(evolved_state, evaluated_aux_ops, observables)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
gate_counts = []
non_local_gate_counts = []
levels = [str(x) for x in range(4)]
for level in range(4):
circ = transpile(ghz, backend, optimization_level=level)
depths.append(circ.depth())
gate_counts.append(sum(circ.count_ops().values()))
non_local_gate_counts.append(circ.num_nonlocal_gates())
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.bar(levels, depths, label='Depth')
ax1.set_xlabel("Optimization Level")
ax1.set_ylabel("Depth")
ax1.set_title("Output Circuit Depth")
ax2.bar(levels, gate_counts, label='Number of Circuit Operations')
ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates')
ax2.set_xlabel("Optimization Level")
ax2.set_ylabel("Number of gates")
ax2.legend()
ax2.set_title("Number of output circuit gates")
fig.tight_layout()
plt.show()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# 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 StateVectorSimulatorPy."""
import unittest
import numpy as np
from qiskit.providers.basicaer import StatevectorSimulatorPy
from qiskit.test import ReferenceCircuits
from qiskit.test import providers
from qiskit import QuantumRegister, QuantumCircuit, execute
from qiskit.quantum_info.random import random_unitary
from qiskit.quantum_info import state_fidelity
class StatevectorSimulatorTest(providers.BackendTestCase):
"""Test BasicAer statevector simulator."""
backend_cls = StatevectorSimulatorPy
circuit = None
def test_run_circuit(self):
"""Test final state vector for single circuit run."""
# Set test circuit
self.circuit = ReferenceCircuits.bell_no_measure()
# Execute
result = super().test_run_circuit()
actual = result.get_statevector(self.circuit)
# state is 1/sqrt(2)|00> + 1/sqrt(2)|11>, up to a global phase
self.assertAlmostEqual((abs(actual[0])) ** 2, 1 / 2)
self.assertEqual(actual[1], 0)
self.assertEqual(actual[2], 0)
self.assertAlmostEqual((abs(actual[3])) ** 2, 1 / 2)
def test_measure_collapse(self):
"""Test final measurement collapses statevector"""
# Set test circuit
self.circuit = ReferenceCircuits.bell()
# Execute
result = super().test_run_circuit()
actual = result.get_statevector(self.circuit)
# The final state should be EITHER |00> OR |11>
diff_00 = np.linalg.norm(np.array([1, 0, 0, 0]) - actual) ** 2
diff_11 = np.linalg.norm(np.array([0, 0, 0, 1]) - actual) ** 2
success = np.allclose([diff_00, diff_11], [0, 2]) or np.allclose([diff_00, diff_11], [2, 0])
# state is 1/sqrt(2)|00> + 1/sqrt(2)|11>, up to a global phase
self.assertTrue(success)
def test_unitary(self):
"""Test unitary gate instruction"""
num_trials = 10
max_qubits = 3
# Test 1 to max_qubits for random n-qubit unitary gate
for i in range(max_qubits):
num_qubits = i + 1
psi_init = np.zeros(2**num_qubits)
psi_init[0] = 1.0
qr = QuantumRegister(num_qubits, "qr")
for _ in range(num_trials):
# Create random unitary
unitary = random_unitary(2**num_qubits)
# Compute expected output state
psi_target = unitary.data.dot(psi_init)
# Simulate output on circuit
circuit = QuantumCircuit(qr)
circuit.unitary(unitary, qr)
job = execute(circuit, self.backend)
result = job.result()
psi_out = result.get_statevector(0)
fidelity = state_fidelity(psi_target, psi_out)
self.assertGreater(fidelity, 0.999)
def test_global_phase(self):
"""Test global_phase"""
n_qubits = 4
qr = QuantumRegister(n_qubits)
circ = QuantumCircuit(qr)
circ.x(qr)
circ.global_phase = 0.5
self.circuit = circ
result = super().test_run_circuit()
actual = result.get_statevector(self.circuit)
expected = np.exp(1j * circ.global_phase) * np.repeat([[0], [1]], [n_qubits**2 - 1, 1])
self.assertTrue(np.allclose(actual, expected))
def test_global_phase_composite(self):
"""Test global_phase"""
n_qubits = 4
qr = QuantumRegister(n_qubits)
circ = QuantumCircuit(qr)
circ.x(qr)
circ.global_phase = 0.5
gate = circ.to_gate()
comp = QuantumCircuit(qr)
comp.append(gate, qr)
comp.global_phase = 0.1
self.circuit = comp
result = super().test_run_circuit()
actual = result.get_statevector(self.circuit)
expected = np.exp(1j * 0.6) * np.repeat([[0], [1]], [n_qubits**2 - 1, 1])
self.assertTrue(np.allclose(actual, expected))
if __name__ == "__main__":
unittest.main()
|
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
|
JessicaJohnBritto
|
## Importing Packages
import cirq
import numpy as np
from cirq.contrib.svg import SVGCircuit
import matplotlib.pyplot as plt
## Defining QFT and Inverse QFT
def qft_rotations(n_qubits):
"""A circuit performs the QFT rotations on the specified qubits.
Args:
n_qubits (list): List of qubits.
"""
n = len(n_qubits)
for i in range(n):
k = 0
yield cirq.H(n_qubits[i])
for jj in range(i+1,n,1):
k = k+1
yield (cirq.CZ ** (1/(2**(k))))(n_qubits[jj], n_qubits[i])
pass
def inverse_qft(n_qubits):
"""A circuit performs the inverse of QFT rotations on the specified qubits.
Args:
n_qubits (list): List of qubits.
"""
n = len(n_qubits)
n_qubits1 = np.flip(n_qubits)
for i in range(n):
k = 0
yield cirq.H(n_qubits1[i])
for jj in range(i+1,n,1):
k = k+1
yield (cirq.CZ ** (-1/(2**(k))))(n_qubits1[jj], n_qubits1[i])
# """Visually check the inverse QFT circuit."""
# qubits = cirq.LineQubit.range(4)
# qft = cirq.Circuit(inverse_qft(qubits))
# SVGCircuit(qft)
"""Visually check the QFT circuit."""
qubits = cirq.LineQubit.range(2)
qft = cirq.Circuit(qft_rotations(qubits))
SVGCircuit(qft)
cirq.unitary(qft)
#Defining Quantum Adder
def quantum_adder(n_qubits):
''' A circuit performs addition of two numbers
Args:
n_qubits (list): list of qubits representing the binary representation of ('binary(a)'+'binary(b)').
'''
n = len(n_qubits)
# Appending the first half of the qubits to list - kk
kk =[n_qubits[i] for i in range(0, int(len(n_qubits)/2),1)]
# Perfoms QFT on the first half of the qubits, i.e, on the first number
yield qft_rotations(kk)
for i in range(0,int(n/2),1):
k=0
for j in range(i+int(n/2),(n),1):
yield (cirq.CZ ** (1/(2**(k))))(n_qubits[j], n_qubits[i])
k+=1
yield inverse_qft(kk)
circuit = cirq.Circuit()
# Inputting the two integers in a and b
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
c = max(len(np.binary_repr(a)), len(np.binary_repr(b))) + 1
a_bit = np.binary_repr(a, width = c)
b_bit = np.binary_repr(b, width = c)
# Combined form of binary(a) and binary(b)
c1 = a_bit+b_bit
qubits = cirq.LineQubit.range(len(c1))
# Preparing Basis State for c1 by applying X-gate on the qubit corresponding to the index of c1 being 1
circuit.append(cirq.X(qubits[i]) for i in range(len(c1)) if c1[i]=='1')
circuit.append(quantum_adder(qubits))
# Measuring the first half of the qubits
k = [qubits[i] for i in range(0, int(len(qubits)/2),1)]
circuit.append(cirq.measure(k, key = 'ab'))
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=1)
# print(result.data)
c = result.histogram(key="ab")
# Retrieving the result from Counter
print(list(c)[0])
# print(cirq.ResultDict('ab'))
# cirq.plot_state_histogram(result)
# SVGCircuit(circuit)
def quantum_multiplier(n_qubits):
''' A circuit performs multiplication of two numbers
Args:
n_qubits (list): list of qubits representing the binary representation of ('binary(a)'+'binary(b)').
'''
n = len(n_qubits)
# Appending the first half of the qubits to list - kk
kk =[n_qubits[i] for i in range(0, int(len(n_qubits)/2),1)]
# Perfoms QFT on the first half of the qubits, i.e, on the first number
yield qft_rotations(kk)
for i in range(int(3*n/4), n,1):
for j in range(int(n/2), int(3*n/4),1):
for m in range(int(n/2)):
yield (cirq.CCZ ** (1/(2**(-(5*n/4)-m+j+i+1))))(n_qubits[j], n_qubits[i], n_qubits[m])
yield inverse_qft(kk)
pass
circuit = cirq.Circuit()
# Inputting the two integers in a and b
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
c = max(len(np.binary_repr(a)), len(np.binary_repr(b))) + 1
a1 = np.binary_repr(0, width = 2*c)
a_bit = np.binary_repr(a, width = c)
b_bit = np.binary_repr(b, width = c)
# Combined form of binary(0), binary(a) and binary(b)
c1 = a1 + a_bit+b_bit
qubits = cirq.LineQubit.range(len(c1))
# Preparing Basis State for c1 by applying X-gate on the qubit corresponding to the index of c1 being 1
circuit.append(cirq.X(qubits[i]) for i in range(len(c1)) if c1[i]=='1')
circuit.append(quantum_multiplier(qubits))
k = [qubits[i] for i in range(0, int(len(qubits)/2),1)]
# Measuring the first half of the qubits
circuit.append(cirq.measure(k, key = 'ab'))
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=1)
# print(result.data)
c = result.histogram(key="ab")
# Retrieving the result from Counter
print(list(c)[0])
# SVGCircuit(circuit)
# a = 3
# b = 2
# a_bit = np.binary_repr(a)
# # print(a_bit)
# b_bit = np.binary_repr(b)
# # print(a_bit+ b_bit)
# c = a_bit+b_bit
# print(c)
# qubits = cirq.LineQubit.range(len(c))
# # print(k,f,g,h)
# circuit = cirq.Circuit(quantum_adder(qubits))
# SVGCircuit(circuit)
# state2 = cirq.Simulator().simulate(circuit, initial_state=1110).state_vector()
# print(state2)
# print(cirq.dirac_notation(state2))
# circuit.append(cirq.measure(qubits))
# simulator = cirq.Simulator()
# result = simulator.run(circuit, repetitions=2)
# print(result)
# SVGCircuit(circuit)
# k = cirq.big_endian_int_to_bits(3, bit_count = 4)
# print(k)
# for i in range(len(qubits)):
# qubits[i] = np.pad(np.array([k[i]]), (2*len(qubits)-1,0))
class MyGate(cirq.Gate):
def _init_(self):
super(MyGate, self)
def _num_qubits_(self):
return 1
def _circuit_diagram_info_(self, args):
return "MyGate"
class MyGate(cirq.Gate):
def _init_(self):
super(MyGate, self)
def _num_qubits_(self):
return 1
def _unitary_(self):
return np.array([[1,0], [0,1]])
def _circuit_diagram_info_(self, args):
return "MyGate"
mygate = MyGate()
qubits = cirq.LineQubit(0)
circuit = cirq.Circuit([cirq.H(qubits), mygate(qubits)])
SVGCircuit(circuit)
class MG(cirq.Gate):
def __init__(self, k):
super(MG, self)
self.k = k
def _num_qubits_(self):
return 2
def _unitary_(self):
return np.array([[1,0,0,0],
[0,1,0,0],
[0,0,1,0],
[0,0,0, np.sin(self.k)]])
def _circuit_diagram_info_(self, args):
return "ctrl", f"R({self.k})"
mg = MG(k=np.pi)
qubits = cirq.LineQubit.range(2)
circuit = cirq.Circuit(mg(*qubits))
SVGCircuit(circuit)
cirq.unitary(circuit)
## QFT gate
class QFT(cirq.Gate):
def __init__(self, n_qubits):
super(QFT, self)
self.n_qubits = n_qubits
def _num_qubits_(self):
return self.n_qubits
def _decompose_(self, n_qubits):
n = len(n_qubits)
for i in range(n):
k = 0
yield cirq.H(n_qubits[i])
for jj in range(i+1,n,1):
k = k+1
yield (cirq.CZ ** (1/(2**(k))))(n_qubits[jj], n_qubits[i])
def _circuit_diagram_info_(self, args):
return ["QFT"] * self.num_qubits()
# qubits = cirq.LineQubit.range(2)
# circuit = cirq.Circuit(QFT(n_qubits = 2).on(*qubits))
# SVGCircuit(circuit)
# cirq.unitary(circuit)
## Quantum Multiplier gate
class qmulti(cirq.Gate):
def __init__(self, n_qubits):
super(qmulti, self)
self.n_qubits = n_qubits
def _num_qubits_(self):
return self.n_qubits
def _decompose_(self, n_qubits):
n = len(n_qubits)
kk =[n_qubits[i] for i in range(0, int(len(n_qubits)/2),1)]
yield QFT(n_qubits = int(n/2)).on(*kk)
for i in range(int(3*n/4), n, 1):
for j in range(int(n/2), int(3*n/4),1):
for m in range(int(n/2)):
yield (cirq.CCZ ** (1/(2**(-(5*n/4)-m+j+i+1))))(n_qubits[j], n_qubits[i], n_qubits[m])
yield cirq.inverse(QFT(n_qubits = int(n/2)).on(*kk))
def _circuit_diagram_info_(self, args):
return ["QMultiplier"] * self.num_qubits()
circuit = cirq.Circuit()
# Inputting the two integers in a and b
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
c = max(len(np.binary_repr(a)), len(np.binary_repr(b))) + 1
a1 = np.binary_repr(0, width = 2*c)
a_bit = np.binary_repr(a, width = c)
b_bit = np.binary_repr(b, width = c)
# Combined form of binary(0), binary(a) and binary(b)
c1 = a1 + a_bit+b_bit
qubits = cirq.LineQubit.range(len(c1))
# Preparing Basis State for c1 by applying X-gate on the qubit corresponding to the index of c1 being 1
circuit.append(cirq.X(qubits[i]) for i in range(len(c1)) if c1[i]=='1')
circuit.append(qmulti(n_qubits = len(qubits)).on(*qubits))
k = [qubits[i] for i in range(0, int(len(qubits)/2),1)]
# Measuring the first half of the qubits
circuit.append(cirq.measure(k, key = 'ab'))
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=1)
c = result.histogram(key="ab")
# Retrieving the result from Counter
print(list(c)[0])
|
https://github.com/hritiksauw199/Qiskit-textbook-solutions
|
hritiksauw199
|
import numpy as np
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, assemble, transpile
from qiskit.visualization import plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle = dj_problem_oracle(1)
dj_circuit = dj_algorithm(oracle, n)
dj_circuit.draw()
sim = Aer.get_backend('aer_simulator')
transpiled_dj_circuit = transpile(dj_circuit, sim)
qobj = assemble(transpiled_dj_circuit)
results = sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
oracle = dj_problem_oracle(2)
dj_circuit = dj_algorithm(oracle, n)
dj_circuit.draw()
sim = Aer.get_backend('aer_simulator')
transpiled_dj_circuit = transpile(dj_circuit, sim)
qobj = assemble(transpiled_dj_circuit)
results = sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
oracle = dj_problem_oracle(3)
dj_circuit = dj_algorithm(oracle, n)
dj_circuit.draw()
sim = Aer.get_backend('aer_simulator')
transpiled_dj_circuit = transpile(dj_circuit, sim)
qobj = assemble(transpiled_dj_circuit)
results = sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
oracle = dj_problem_oracle(4)
dj_circuit = dj_algorithm(oracle, n)
dj_circuit.draw()
sim = Aer.get_backend('aer_simulator')
transpiled_dj_circuit = transpile(dj_circuit, sim)
qobj = assemble(transpiled_dj_circuit)
results = sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
oracle = dj_problem_oracle(5)
dj_circuit = dj_algorithm(oracle, n)
dj_circuit.draw()
sim = Aer.get_backend('aer_simulator')
transpiled_dj_circuit = transpile(dj_circuit, sim)
qobj = assemble(transpiled_dj_circuit)
results = sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
%run init.ipynb
p = symbols('p')
Ubf = Matrix([[sqrt(1-p),-sqrt(p),0,0],[0,0,sqrt(p),sqrt(1-p)],[0,0,sqrt(1-p),-sqrt(p)],[sqrt(p),sqrt(1-p),0,0]])
Ubf
Ubf*Ubf.T, Ubf.T*Ubf
g = symbols('gamma')
Uad = Matrix([[sqrt(1-g),0,0,sqrt(g)],[0,1,0,0],[0,0,1,0],[-sqrt(g),0,0,sqrt(1-g)]])
Uad, Uad*Uad.T, Uad.T*Uad
|
https://github.com/chunfuchen/qiskit-chemistry
|
chunfuchen
|
# -*- 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 unittest
from parameterized import parameterized
import qiskit
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms.adaptive import VQE
from qiskit.aqua.components.variational_forms import RYRZ
from qiskit.aqua.components.optimizers import COBYLA, SPSA
from test.common import QiskitChemistryTestCase
from qiskit.chemistry.drivers import HDF5Driver
from qiskit.chemistry.core import Hamiltonian, TransformationType, QubitMappingType
class TestEnd2End(QiskitChemistryTestCase):
"""End2End tests."""
def setUp(self):
super().setUp()
driver = HDF5Driver(hdf5_input=self._get_resource_path('test_driver_hdf5.hdf5'))
self.qmolecule = driver.run()
core = Hamiltonian(transformation=TransformationType.FULL,
qubit_mapping=QubitMappingType.PARITY,
two_qubit_reduction=True,
freeze_core=False,
orbital_reduction=[])
self.qubit_op, self.aux_ops = core.run(self.qmolecule)
self.reference_energy = -1.857275027031588
@parameterized.expand([
['COBYLA_M', 'COBYLA', qiskit.BasicAer.get_backend('statevector_simulator'), 'matrix', 1],
['COBYLA_P', 'COBYLA', qiskit.BasicAer.get_backend('statevector_simulator'), 'paulis', 1],
# ['SPSA_P', 'SPSA', qiskit.BasicAer.get_backend('qasm_simulator'), 'paulis', 1024],
# ['SPSA_GP', 'SPSA', qiskit.BasicAer.get_backend('qasm_simulator'), 'grouped_paulis', 1024]
])
def test_end2end_h2(self, name, optimizer, backend, mode, shots):
if optimizer == 'COBYLA':
optimizer = COBYLA()
optimizer.set_options(maxiter=1000)
elif optimizer == 'SPSA':
optimizer = SPSA(max_trials=2000)
ryrz = RYRZ(self.qubit_op.num_qubits, depth=3, entanglement='full')
vqe = VQE(self.qubit_op, ryrz, optimizer, mode, aux_operators=self.aux_ops)
quantum_instance = QuantumInstance(backend, shots=shots)
results = vqe.run(quantum_instance)
self.assertAlmostEqual(results['energy'], self.reference_energy, places=4)
if __name__ == '__main__':
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.