repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
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/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022 Qiskit on IQM developers
#
# 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.
"""Conversion tools from Qiskit to IQM representation.
"""
from __future__ import annotations
from dataclasses import dataclass
import re
from qiskit import QuantumCircuit as QiskitQuantumCircuit
from qiskit.circuit import Clbit
class InstructionNotSupportedError(RuntimeError):
"""Raised when a given instruction is not supported by the IQM server."""
@dataclass(frozen=True)
class MeasurementKey:
"""Unique key associated with a measurement instruction.
Qiskit stores the results of quantum measurements in classical registers consisting of bits.
The circuit execution results are presented as bitstrings of a certain structure so that the classical
register and the index within that register for each bit is implied from its position in the bitstring.
For example, if you have two classical registers in the circuit with lengths 3 and 2, then the
measurement results will look like '01 101' if the classical register of length 3 was added to
the circuit first, and '101 01' otherwise. If a bit in a classical register is not used in any
measurement operation it will still show up in the results with the default value of '0'.
To be able to handle measurement results in a Qiskit-friendly way, we need to keep around some
information about how the circuit was constructed. This can, for example, be achieved by keeping
around the original Qiskit quantum circuit and using it when constructing the results in
:class:`.IQMJob`. This should be done so that the circuit is saved on the server side and not in
``IQMJob``, since otherwise users will not be able to retrieve results from a detached Python
environment solely based on the job id. Another option is to use measurement key strings to
store the required info. Qiskit does not use measurement keys, so we are free to use them
internally in the communication with the IQM server, and can encode the necessary information in
them.
This class encapsulates the necessary info, and provides methods to transform between this
representation and the measurement key string representation.
Args:
creg_name: name of the classical register
creg_len: number of bits in the classical register
creg_idx: Index of the classical register in the circuit. Determines the order in which this register was added
to the circuit relative to the others.
clbit_idx: index of the classical bit within the classical register
"""
creg_name: str
creg_len: int
creg_idx: int
clbit_idx: int
def __str__(self):
return f'{self.creg_name}_{self.creg_len}_{self.creg_idx}_{self.clbit_idx}'
@classmethod
def from_string(cls, string: str) -> MeasurementKey:
"""Create a MeasurementKey from its string representation."""
match = re.match(r'^(.*)_(\d+)_(\d+)_(\d+)$', string)
if match is None:
raise ValueError('Invalid measurement key string representation.')
return cls(match.group(1), int(match.group(2)), int(match.group(3)), int(match.group(4)))
@classmethod
def from_clbit(cls, clbit: Clbit, circuit: QiskitQuantumCircuit) -> MeasurementKey:
"""Create a MeasurementKey for a classical bit in a quantum circuit."""
bitloc = circuit.find_bit(clbit)
creg = bitloc.registers[0][0]
creg_idx = circuit.cregs.index(creg)
clbit_idx = bitloc.registers[0][1]
return cls(creg.name, len(creg), creg_idx, clbit_idx)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_aer.utils import approximate_quantum_error, approximate_noise_model
import numpy as np
# Import Aer QuantumError functions that will be used
from qiskit_aer.noise import amplitude_damping_error, reset_error, pauli_error
from qiskit.quantum_info import Kraus
gamma = 0.23
error = amplitude_damping_error(gamma)
results = approximate_quantum_error(error, operator_string="reset")
print(results)
p = (1 + gamma - np.sqrt(1 - gamma)) / 2
q = 0
print("")
print("Expected results:")
print("P(0) = {}".format(1-(p+q)))
print("P(1) = {}".format(p))
print("P(2) = {}".format(q))
gamma = 0.23
K0 = np.array([[1,0],[0,np.sqrt(1-gamma)]])
K1 = np.array([[0,np.sqrt(gamma)],[0,0]])
results = approximate_quantum_error(Kraus([K0, K1]), operator_string="reset")
print(results)
reset_to_0 = Kraus([np.array([[1,0],[0,0]]), np.array([[0,1],[0,0]])])
reset_to_1 = Kraus([np.array([[0,0],[1,0]]), np.array([[0,0],[0,1]])])
reset_kraus = [reset_to_0, reset_to_1]
gamma = 0.23
error = amplitude_damping_error(gamma)
results = approximate_quantum_error(error, operator_list=reset_kraus)
print(results)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/pedroripper/qiskit_tutoriais
|
pedroripper
|
from qiskit import *
%matplotlib inline
# Podemos transformar o nosso circuito em apenas uma porta
circuito = QuantumCircuit(2)
circuito.x(0)
circuito.h(1)
circuito.draw(output='mpl')
# Para conseguir uma porta que represente essas operações fazemos
# Podemos ainda adicionar um titulo para a nossa porta ou apenas deixar em branco
minha_porta = circuito.to_gate(label='Minha porta')
# Agora vamos adicionar ela em outro circuito
c2 = QuantumCircuit(2)
# Para adicionar uma porta dessa forma usamos o comando append()
c2.append(minha_porta,[0,1])
c2.draw(output='mpl')
# Para conferir se essa porta realmente representa a original fazemos
c2.decompose().draw(output='mpl')
|
https://github.com/divyanshchoubisa/Quantum-Computing-Dynamic-Circuits
|
divyanshchoubisa
|
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def step_1_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
########## your code goes here #######
##1 Initialization
q0, q1 = qr
# apply Hadamard on the auxiliary qubit
qc.h(q0)
# put the system qubit into the |1> state
qc.x(q1)
##2 Apply control-U operator as many times as needed to get the least significant phase bit
# controlled-S is equivalent to CPhase with angle pi / 2
s_angle = np.pi / 2
# we want to apply controlled-S 2^k times
k = 1
# calculate the angle of CPhase corresponding to 2^k applications of controlled-S
cphase_angle = s_angle * 2**k
# apply the controlled phase gate
qc.cp(cphase_angle, q0, q1)
##3 Measure the auxiliary qubit in x-basis into the first classical bit
# apply Hadamard to change to the X basis
qc.h(q0)
# measure the auxiliary qubit into the first classical bit
c0, _ = cr
qc.measure(q0, c0)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_1_circuit(qr, cr)
qc.draw("mpl")
# Submit your circuit
from qc_grader.challenges.spring_2023 import grade_ex3a
grade_ex3a(qc)
def step_2_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
# begin with the circuit from Step 1
qc = step_1_circuit(qr, cr)
########## your code goes here #######
##1 Reset and re-initialize the auxiliary qubit
q0, q1 = qr
# reset the auxiliary qubit
qc.reset(q0)
# apply Hadamard on the auxiiliary qubit
qc.h(q0)
##2 Apply phase correction conditioned on the first classical bit
c0, c1 = cr
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
##3 Apply control-U operator as many times as needed to get the next phase bit
# controlled-S is equivalent to CPhase with angle pi / 2
s_angle = np.pi / 2
# we want to apply controlled-S 2^k times
k = 0
# calculate the angle of CPhase corresponding to 2^k applications of controlled-S
cphase_angle = s_angle * 2**k
# apply the controlled phase gate
qc.cp(cphase_angle, q0, q1)
##4 Measure the auxiliary qubit in x-basis into the second classical bit
# apply Hadamard to change to the X basis
qc.h(q0)
# measure the auxiliary qubit into the first classical bit
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_2_circuit(qr, cr)
qc.draw("mpl")
# Submit your circuit
from qc_grader.challenges.spring_2023 import grade_ex3b
grade_ex3b(qc)
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def t_gate_ipe_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 3 bits
qc = QuantumCircuit(qr, cr)
########## your code goes here #######
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
t_angle = np.pi / 4
k = 2
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the first classical bit
qc.h(q0)
c0, c1, c2 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 1
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first and second classical bits
with qc.if_test((c0, 1)):
qc.p(-np.pi / 4, q0)
with qc.if_test((c1, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 0
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the third classical bit
qc.h(q0)
qc.measure(q0, c2)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(3, "c")
qc = QuantumCircuit(qr, cr)
qc = t_gate_ipe_circuit(qr, cr)
qc.draw("mpl")
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
# Submit your circuit
from qc_grader.challenges.spring_2023 import grade_ex3c
grade_ex3c(qc)
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
u_angle = 2 * np.pi / 3
k = 1
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the first classical bit
qc.h(q0)
c0, c1 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 0
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
print(counts)
success_probability = counts["01"] / counts.shots()
print(f"Success probability: {success_probability}")
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 1 bits
qc = QuantumCircuit(qr, cr)
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
u_angle = 2 * np.pi / 3
k = 1
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis
qc.h(q0)
(c0,) = cr
qc.measure(q0, c0)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
job = sim.run(qc, shots=15)
result = job.result()
counts = result.get_counts()
print(counts)
step1_bit = 1
####### your code goes here #######
print(step1_bit)
# Submit your result
from qc_grader.challenges.spring_2023 import grade_ex3d
grade_ex3d(step1_bit)
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
########## your code goes here #######
# Initialization
q0, q1 = qr
if step1_bit:
qc.x(q0)
qc.x(q1)
# Measure the auxiliary qubit
c0, c1 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
u_angle = 2 * np.pi / 3
k = 0
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
# Submit your result
from qc_grader.challenges.spring_2023 import grade_ex3e
grade_ex3e(qc)
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
print(counts)
success_probability = counts["01"] / counts.shots()
print(f"Success probability: {success_probability}")
from qiskit_ibm_provider import IBMProvider
provider = IBMProvider()
hub = "qc-spring-23-1"
group = "group-1"
project = "recIvcxUcc27LvvSh"
backend_name = "ibm_peekskill"
backend = provider.get_backend(backend_name, instance=f"{hub}/{group}/{project}")
from qiskit import transpile
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_2_circuit(qr, cr)
qc_transpiled = transpile(qc, backend)
job = backend.run(qc_transpiled, shots=1000, dynamic=True)
job_id = job.job_id()
print(job_id)
retrieve_job = provider.retrieve_job(job_id)
retrieve_job.status()
from qiskit.tools.visualization import plot_histogram
counts = retrieve_job.result().get_counts()
plot_histogram(counts)
|
https://github.com/arnavdas88/QuGlassyIsing
|
arnavdas88
|
!pip install qiskit
J = 4.0
B_x = 2.0
B_z = 1.0
import numpy as np
from qiskit.providers.aer import AerSimulator, QasmSimulator
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.aqua.operators import *
from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance
from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, NumPyEigensolver
from qiskit.circuit import QuantumCircuit, ParameterVector
from qiskit.visualization import plot_histogram
Hamiltonian = J * (Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)
- B_z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z )
) - B_x * ( ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ))
ansatz = TwoLocal(num_qubits=36, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)
print(ansatz)
backend = AerSimulator(method='matrix_product_state')
quantum_instance = QuantumInstance(backend,
shots = 8192,
initial_layout = None,
optimization_level = 3)
optimizer = COBYLA(maxiter=10000, tol=0.000000001)
vqe = VQE(Hamiltonian, ansatz, optimizer, include_custom = False)
print('We are using:', quantum_instance.backend)
vqe_result = vqe.run(quantum_instance)
print(vqe['result'])
plot_histogram(vqe_result['eigenstate'])
import pickle
filename = "2D_Ising_Model_CountsDIS2.pkl"
a = {'vqe_result': vqe_result}
#This saves the data
with open(filename, 'wb') as handle:
pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL)
# This loads the data
with open(filename, 'rb') as handle:
b = pickle.load(handle)
|
https://github.com/hephaex/Quantum-Computing-Awesome-List
|
hephaex
|
pip install cirq
import cirq
circuit = cirq.Circuit()
(q0,q1) = cirq.LineQubit.range(2)
circuit.append([cirq.H(q0), cirq.CNOT(q0, q1)])
circuit.append([cirq.measure(q0), cirq.measure(q1)])
print(circuit)
sim = cirq.Simulator()
results = sim.run(circuit, repetitions=10)
print(results)
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
from matplotlib import pyplot
from qiskit import *
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua
from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector
from qiskit.quantum_info import Statevector
from qiskit.extensions import *
provider = IBMQ.load_account()
from qiskit.quantum_info import random_unitary
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
from math import pi, sqrt
from scipy.special import rel_entr
from random import seed
from random import random
import cmath
import sys
sys.path.append('../Pyfiles')
from circuits import *
#Possible Bin
bins_list=[];
for i in range(76):
bins_list.append((i)/75)
#Center of the Bean
bins_x=[]
for i in range(75):
bins_x.append(bins_list[1]+bins_list[i])
def P_harr(l,u,N):
return (1-l)**(N-1)-(1-u)**(N-1)
#Harr historgram
P_harr_hist=[]
for i in range(75):
P_harr_hist.append(P_harr(bins_list[i],bins_list[i+1],2))
#Imaginary
j=(-1)**(1/2)
backend = Aer.get_backend('qasm_simulator')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
print(nshot,'shots per simulation',nparam,'distribution size')
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_qasm.txt",qasm)
qasm
backend = QasmSimulator(method='density_matrix')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
print(nshot,'shots per simulation',nparam,'distribution size KL=',sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
density_mat=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_density_mat.txt",density_mat)
density_mat
backend = QasmSimulator(method='statevector')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
print(nshot,'shots per simulation',nparam,'distribution size KL=',sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
statevector1=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_statevector.txt",statevector1)
statevector1
backend = QasmSimulator(method='matrix_product_state')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
print(nshot,'shots per simulation',nparam,'distribution size KL=',sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
matrix_product1=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_matrix_product1.txt",matrix_product1)
matrix_product1
def plotdata(i,data):
klll=np.transpose(data)
x=[];
y=[];
for nsh in range(0,9,1):
x.append(int(round(1000*(nsh)**1.5,0)))
y.append(klll[nsh][i])
return [x,y]
#loading dataset
fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(20, 5))
datalist=[density_mat,statevector1,matrix_product1,qasm]
datalistn=['density_mat','statevector','matrix_product','qasm']
indx=0;
for indx in range(4):
data=datalist[indx];
axes[indx].plot(plotdata(0,data)[0],plotdata(0,data)[1], color='red', label='npram=1000');
axes[indx].plot(plotdata(1,data)[0],plotdata(1,data)[1], color='blue', label='npram=2000');
axes[indx].plot(plotdata(2,data)[0],plotdata(2,data)[1], color='black', label='npram=3000');
axes[indx].plot(plotdata(3,data)[0],plotdata(3,data)[1], color='green', label='npram=4000');
axes[indx].plot(plotdata(4,data)[0],plotdata(4,data)[1], color='purple', label='npram=5000');
axes[indx].plot(plotdata(5,data)[0],plotdata(5,data)[1], color='gray', label='npram=6000');
axes[indx].plot(plotdata(6,data)[0],plotdata(6,data)[1], color='black', label='npram=7000');
axes[indx].plot(plotdata(7,data)[0],plotdata(7,data)[1], color='yellow', label='npram=8000');
axes[indx].plot(plotdata(8,data)[0],plotdata(8,data)[1], color='pink', label='npram=9000');
axes[indx].set_ylim([0.003, 0.05])
axes[indx].legend(loc='upper right')
axes[indx].set_title(datalistn[indx])
axes[indx].set_yscale('log',base=10)
axes[indx].set_ylabel('Expressibility')
from matplotlib import pyplot as plt
fig.savefig('ExpressibilitybySimulator.png')
fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(20, 5))
indx=0
for indx in range(4):
data=density_mat;
axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='red', label='density_mat');
data=statevector1;
axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='blue', label='statevector');
data=matrix_product1;
axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='green', label='matrix_product1');
data=qasm;
axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='pink', label='qasm');
axes[indx].set_title('nparam='+str((indx+1)*1000))
axes[indx].set_yscale('log',base=10)
axes[indx].set_ylim([0.003, 0.05])
axes[indx].set_ylabel('Expressibility')
axes[indx].legend(['density_mat','statevector','matrix_product1','qasm'])
axes[indx].set_xlabel('iteration')
fig.savefig('ExpressibilitybySimulatornparam1.png')
fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(20, 5))
indx=0
for indx1 in range(4,8,1):
indx=indx1-4
data=density_mat;
axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='red', label='density_mat');
data=statevector1;
axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='blue', label='statevector');
data=matrix_product1;
axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='green', label='matrix_product1');
data=qasm;
axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='pink', label='qasm');
axes[indx].set_title('nparam='+str((indx1+1)*1000))
axes[indx].set_yscale('log',base=10)
axes[indx].set_ylabel('Expressibility')
axes[indx].set_ylim([0.003, 0.05])
axes[indx].legend(['density_mat','statevector','matrix_product1','qasm'])
axes[indx].set_xlabel('iteration')
fig.savefig('ExpressibilitybySimulatornparam2.png')
|
https://github.com/bagmk/qiskit-quantum-state-classifier
|
bagmk
|
import numpy as np
import json as json
from o_plot import opl # a small local package dedicated to this project
import sys
print(sys.executable)
# loading the data
file_name = 'QAD_data_new.json'
f = open(file_name)
All_data = json.load(f)
# this for Jensen-Shannon metric
s_metric = 'jensenshannon'
sm = np.array([96])
SAD=0
# ! will be unselected by running the next cell
# main option for metric: squared euclidean distance
# skip this cell if you don't want this option
s_metric = 'sqeuclidean'
sm = np.array([97])
SAD=2
# this for measurement mitigation
mit = 'yes'
MIT=0
# ! will be unselected by running the next cell
# main option: no mitigation
# skip this cell if you don't want this option
mit = 'no'
MIT=-4
ADD=-3
opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]),
"Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - no delay",
["model","mitigation"], ["device","metric"], right_xlimit = 90)
ADD=1
opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]),
"Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - no delay",
["model","mitigation"], ["device","metric"], right_xlimit = 90)
ADD=45
opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]),
"Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - with delay",
["model","mitigation"], ["device","metric"], right_xlimit = 90)
ADD=49
opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]),
"Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - with delay",
["model","mitigation"], ["device","metric"], right_xlimit = 90)
ADD=-4
opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]),
"Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - no delay",
["model","mitigation"], ["device","metric"], right_xlimit = 90)
ADD=0
opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]),
"Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - no delay",
["model","mitigation"], ["device","metric"], right_xlimit = 90)
ADD=44
opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]),
"Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - with delay",
["model","mitigation"], ["device","metric"], right_xlimit = 90)
ADD=48
opl.plot_curves(All_data,ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]),
"Jensen-Shannon vs squared eucliden distance - $\epsilon=0.001$ - with delay",
["model","mitigation"], ["device","metric"], right_xlimit = 90)
ADD=1+SAD
opl.plot_curves(All_data, np.append(sm,ADD+np.array([0,4,8,12,16,20,24,28,32,36,40,44])),
"Effect of mitigation - $\epsilon=0.001$ - no delay",
["model","metric"], ["device","mitigation"], right_xlimit = 90)
ADD=49+SAD
opl.plot_curves(All_data, np.append(sm,ADD+np.array([0,4,8,12,16,20,24,28,32,36,40,44])),
"Effect of mitigation - $\epsilon=0.001$ - with delay",
["model","metric"], ["device","mitigation"], right_xlimit = 90)
ADD=0+SAD
opl.plot_curves(All_data,np.append(sm,ADD+np.array([0,4,8,12,16,20,24,28,32,36,40,44])),
"Effect of mitigation - $\epsilon=0.001$ - no delay",
["model","metric"], ["device","mitigation"], right_xlimit = 90)
ADD=48+SAD
opl.plot_curves(All_data,np.append(sm,ADD+np.array([0,4,8,12,16,20,24,28,32,36,40,44])),
"Effect of mitigation - $\epsilon=0.001$ - with delay",
["model","metric"], ["device","mitigation"], right_xlimit =90)
ADD=-3+SAD
opl.plot_curves(All_data,np.append(sm,ADD+np.array([4,52,12,60,20,68,28,76,36,84,44,92])),
"Effect of Delay - $\epsilon=0.001$",
["model","metric","mitigation"],
["device","model","id_gates"], right_xlimit = 90)
ADD=1+SAD
opl.plot_curves(All_data,np.append(sm,ADD+np.array([4,52,12,60,20,68,28,76,36,84,44,92])),
"Effect of Delay - $\epsilon=0.001$",
["model","metric","mitigation"],
["device","model","id_gates"], right_xlimit = 90)
ADD=-4+SAD
opl.plot_curves(All_data,np.append(sm,ADD+np.array([4,52,12,60,20,68,28,76,36,84,44,92])),
"Effect of Delay - $\epsilon=0.001$",
["model","metric","mitigation"],
["device","model","id_gates"], right_xlimit = 90)
ADD=0+SAD
opl.plot_curves(All_data,np.append(sm,ADD+np.array([4,52,12,60,20,68,28,76,36,84,44,92])),
"Effect of Delay - $\epsilon=0.001$",
["model","metric","mitigation"],
["device","model","id_gates"], right_xlimit = 90)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import IBMQ, transpile
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.fake_provider import FakeVigo
device_backend = FakeVigo()
# Construct quantum circuit
circ = QuantumCircuit(3, 3)
circ.h(0)
circ.cx(0, 1)
circ.cx(1, 2)
circ.measure([0, 1, 2], [0, 1, 2])
sim_ideal = AerSimulator()
# Execute and get counts
result = sim_ideal.run(transpile(circ, sim_ideal)).result()
counts = result.get_counts(0)
plot_histogram(counts, title='Ideal counts for 3-qubit GHZ state')
sim_vigo = AerSimulator.from_backend(device_backend)
# Transpile the circuit for the noisy basis gates
tcirc = transpile(circ, sim_vigo)
# Execute noisy simulation and get counts
result_noise = sim_vigo.run(tcirc).result()
counts_noise = result_noise.get_counts(0)
plot_histogram(counts_noise,
title="Counts for 3-qubit GHZ state with device noise model")
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/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# let's randomly pick a number between 0 and 9, and print its value if it is greater than 5
from random import randrange
r = randrange(10)
if r > 5: print(r) # when the condition (r > 5) is valid/true, the code (print(r)) will be executed
# you may need to execute your code more than once to observe an outcome
# repeat the same task four times, and also print the value of iteration variable (i)
for i in range(4):
r = randrange(10) # this code belongs to for-loop, and so it is indented
if r > 5: # this code also belongs to for-loop, and so it is indented as well
print("i=",i,"r=",r) # this code belongs to if-statement, and so it is indented with respect to if-statement
# if you are unlucky (with probabability less than 13/100), you may still do not see any outcome in a single run
# do the same task 100 times, and find the percentage of successful iteration (attempt)
# an iteration (attempt) is successful if the randomly picked number is greater than 5
# the expected percentage is 40, because, out of 10 numbers, there are 4 numbers greater than 5
# but the experimental results differ
success = 0
for i in range(100):
r = randrange(10)
if r > 5:
success = success + 1
print(success,"%")
# each run most probabily will give different percentage value
# let's randomly pick a number between 0 and 9, and says whether it less than 6 or not
# we use two conditionals here
r = randrange(10)
print("the picked number is ",r)
if r < 6:
print("it is less than 6")
if r >= 6:
print("it is greater than or equal to 6")
# let's write the same code by using if-else
r = randrange(10)
print("the picked number is ",r)
if r < 6:
print("it is less than 6")
else: # if the above condition (r<6) is False
print("it is greater than or equal to 6")
#
# your solution is here
#
#
# when there are many conditionals, we can use if-elif-else
#
# let's randomly pick an even number between 1 and 99
# then determine whether it is less than 25, between 25 and 50, between 51 and 75, or greater than 75.
r = randrange(2,100,2) # randonmly pick a number in range {2,4,6,...,98}, which satisfies our condition
# let's print this range to verify our claim
print(list(range(2,100,2)))
print() # print an empty line
print("the picked number is",r)
if r < 25:
print("it is less than 25")
elif r<=50: # if the above condition is False and my condition is True
print("it is between 25 and 50")
elif r<=75: # if both conditions above are False and my condition is True
print("it is between 51 and 75")
else: # if all conditions above are False
print("it is greater than 75")
#
# your solution is here
#
# let's determine whether a randomly picked number between -10 and 100 is prime or not.
# this is a good example for using more than one conditionals in different parts of the program
# this is also an example for "break" command, which terminates any loop immediately
r = randrange(-10,101) # pick a number between -10 and 100
print(r) # print is value
if r < 2: print("it is NOT a prime number") # this is by definition
elif r == 2: print("it is a PRIME number") # we already know this
else:
prime=True # we assume that r is prime, and try to falsify this assumption by looking for a divisor in the following loop
for i in range(2,r): # check all integers between 2 and r-1
if r % i ==0: # if i divides r without any reminder (or reminder is zero), then r is not be a prime number
print("it is NOT a prime number")
prime=False # our assumption is falsifed
break # TERMINATE the iteration immediately
# we are out of if-scope
# we are out of for-loop-scope
if prime == True: # if our assumption is still True (if it was not falsied inside for-loop)
print("it is a PRIME number")
# this is an example to write a function
# our function will return a Boolean value True or False
def prime(number): # our function has one parameter
if number < 2: return False # once return command is executed, we exit the function
if number == 2: return True # because of return command, we can use "if" instead of "elif"
if number % 2 == 0: return False # any even number greater than 2 is not prime, because it is divisible by 2
for i in range(3,number,2): # we can skip even integers
if number % i == 0: return False # once we find a divisor of the number, we return False and exit the function
return True # the number has passed all checks until now
# because of return command, the program can be shorten
# remark that this might not be a good choice everytime for readibility of codes
# let's test our program by printing all prime numbers between -10 and 30
for i in range(-10,30):
# we pass i to the function prime
if prime(i): # the function prime(i) returns True or False
print(i) # this code will be executed if i is prime, i.e., prime(i) returns True
|
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.
r"""
.. image:: ../images/qiskit_cold_atom_logo_with_text.svg
:alt: Missing Logo
==================================================
Qiskit Cold Atom module (:mod:`qiskit_cold_atom`)
==================================================
.. currentmodule:: qiskit_cold_atom
The Qiskit Cold Atom module provides functionality to describe quantum systems of trapped cold atoms
in a gate- and circuit-based framework.
Traditionally, each wire in a quantum circuit represents one qubit as the fundamental unit of information
processing. Here, we extend this concept and allow wires to represent individual internal states of
trapped cold atoms. This currently covers two settings, one for fermionic modes and one for spin
modes.
In a fermionic setting, each wire of a quantum circuit represents an abstract fermionic mode in second
quantization which can either be occupied (1) or empty (0). Such systems are realized experimentally by
individual fermionic atoms trapped in arrays of optical tweezers. Circuit instructions and backends
to interact with and simulate such circuits are given by the :mod:`qiskit_cold_atom.fermions` module.
In a spin setting, each wire of a quantum circuit represents a quantum mechanical spin of a given length
:math:`S`. Upon measurement, each spin is measured in one of its :math:`2S+1` internal basis states
labelled :math:`0` to :math:`2S`, thus it can be thought of as a qudit with dimension :math:`d = 2S+1`.
This setting describes the collective spin of bosonic atoms trapped in a Bose-Einstein-condensate.
Circuit instructions and backends to interact with and simulate such circuits are provided by the
:mod:`qiskit_cold_atom.spins` module.
The quantum circuits that these systems can implement thus utilize a fundamentally different form of
quantum information processing compared to qubits. Therefore, the typical qubit gates can not be applied
to these circuits. Instead, the fermions and spin modules define their own gate sets which are defined
by their second-quantized Hamiltonians that generate the unitary gate. Note that loading the
:mod:`qiskit_cold_atom.fermions` or :mod:`qiskit_cold_atom.spins` module will decorate the
:class:`QuantumCircuit` class in Qiskit by adding methods to call pre-defined fermionic and spin gates,
respectively.
To enable the control of real quantum hardware, the :mod:`qiskit_cold_atom.providers`
module contains a provider which enables access to cold atomic device backends.
The top-level classes and submodules of qiskit_cold_atom are:
.. autosummary::
:toctree: ../stubs/
:nosignatures:
QiskitColdAtomError
Submodules
==========
.. autosummary::
:toctree:
applications
fermions
providers
spins
"""
from functools import wraps
from qiskit import QuantumCircuit
from qiskit_cold_atom.exceptions import QiskitColdAtomError
def add_gate(func):
"""Decorator to add a gate method to the QuantumCircuit class"""
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
setattr(QuantumCircuit, func.__name__, wrapper)
return func
__version__ = "0.1.0"
__all__ = ["__version__", "QiskitColdAtomError", "add_gate"]
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
import numpy as np
import hhl_components as cmp
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
from qiskit import Aer, execute
from qiskit.visualization import plot_histogram
# Initialize parameters
t0 = 2 * np.pi
r = 6
A = [[3.75, 2.25, 1.25, -0.75],
[2.25, 3.75, 0.75, -1.25],
[1.25, 0.75, 3.75, -2.25],
[-0.75, -1.25, -2.25, 3.75]]
b = [0.5, 0.5, 0.5, 0.5]
x = [-0.0312, 0.2188, 0.3437, 0.4062]
p = [i ** 2 for i in x]
basis = ['00', '01', '10', '11']
# Build circuit
circ = QuantumCircuit(7, 3)
circ.initialize(b, range(2))
circ.append(cmp.ad_hoc_hhl(A, t0, r), range(7))
circ.measure(6, 2)
circ.measure([0, 1], [0, 1])
# Get simulators
qasm = Aer.get_backend('qasm_simulator')
svsm = Aer.get_backend('statevector_simulator')
# QASM simulation
job = execute(circ, qasm, shots=1024)
counts = job.result().get_counts()
measured_data = {}
expected_data = {basis[i]: np.floor(p[i] * 1024) for i in range(4)}
for key in counts.keys():
if key[0] == '1':
measured_data[key[1::]] = counts[key]
plot_histogram([expected_data, measured_data], title='HHL QASM Simulation', legend=['expected', 'measured'])
plt.subplots_adjust(left=0.15, right=0.72, top=0.9, bottom=0.15)
plt.show()
|
https://github.com/Sentdex/QuantumComputing
|
Sentdex
|
import qiskit as q
%matplotlib inline
circuit = q.QuantumCircuit(2,2) # 2 qubits, 2 classical bits
circuit.x(0) # not gate, flips qubit 0.
circuit.cx(0, 1) #cnot, controlled not, Flips 2nd qubit's value if first qubit is 1
circuit.measure([0,1], [0,1]) # ([qbitregister], [classicalbitregister]) Measure qubit 0 and 1 to classical bits 0 and 1
circuit.draw() # text-based visualization. (pretty cool ...actually! Nice job whoever did this.)
circuit.draw(output="mpl") # matplotlib-based visualization.
from qiskit import IBMQ
IBMQ.save_account(open("token.txt","r").read())
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider("ibm-q")
for backend in provider.backends():
try:
qubit_count = len(backend.properties().qubits)
except:
qubit_count = "simulated"
print(f"{backend.name()} has {backend.status().pending_jobs} queued and {qubit_count} qubits")
from qiskit.tools.monitor import job_monitor
backend = provider.get_backend("ibmq_london")
job = q.execute(circuit, backend=backend, shots=500)
job_monitor(job)
from qiskit.visualization import plot_histogram
from matplotlib import style
style.use("dark_background") # I am using dark mode notebook, so I use this to see the chart.
result = job.result()
counts = result.get_counts(circuit)
plot_histogram([counts], legend=['Device'])
circuit = q.QuantumCircuit(2,2) # 2 qbits, 2 classical bits.
circuit.h(0) # Hadamard gate, puts qubit 0 into superposition
circuit.cx(0, 1) #cnot, controlled not, Flips 2nd qubit's value if first qubit is 1
circuit.measure([0,1], [0,1]) # ([qbitregister], [classicalbitregister]) Measure qubit 0 and 1 to classical bits 0 and 1
circuit.draw(output="mpl")
backend = provider.get_backend("ibmq_london")
job = q.execute(circuit, backend=backend, shots=500)
job_monitor(job)
result = job.result()
counts = result.get_counts(circuit)
plot_histogram([counts], legend=['Device'])
from qiskit import Aer # simulator framework from qiskit
# will create a statevector of possibilities.
sim_backend = Aer.get_backend('qasm_simulator')
for backend in Aer.backends():
print(backend)
job = q.execute(circuit, backend=sim_backend, shots=500)
job_monitor(job)
result = job.result()
counts = result.get_counts(circuit)
plot_histogram([counts], legend=['Device'])
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
#!/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.
"""Test cases to verify qpy backwards compatibility."""
import argparse
import itertools
import random
import re
import sys
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.classicalregister import Clbit
from qiskit.circuit.quantumregister import Qubit
from qiskit.circuit.parameter import Parameter
from qiskit.circuit.parametervector import ParameterVector
from qiskit.quantum_info.random import random_unitary
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, QFT, DCXGate, PauliGate
from qiskit.circuit.gate import Gate
try:
from qiskit.qpy import dump, load
except ModuleNotFoundError:
from qiskit.circuit.qpy_serialization import dump, load
# This version pattern is taken from the pypa packaging project:
# https://github.com/pypa/packaging/blob/21.3/packaging/version.py#L223-L254
# which is dual licensed Apache 2.0 and BSD see the source for the original
# authors and other details
VERSION_PATTERN = (
"^"
+ r"""
v?
(?:
(?:(?P<epoch>[0-9]+)!)? # epoch
(?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
(?P<pre> # pre-release
[-_\.]?
(?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
[-_\.]?
(?P<pre_n>[0-9]+)?
)?
(?P<post> # post release
(?:-(?P<post_n1>[0-9]+))
|
(?:
[-_\.]?
(?P<post_l>post|rev|r)
[-_\.]?
(?P<post_n2>[0-9]+)?
)
)?
(?P<dev> # dev release
[-_\.]?
(?P<dev_l>dev)
[-_\.]?
(?P<dev_n>[0-9]+)?
)?
)
(?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
"""
+ "$"
)
def generate_full_circuit():
"""Generate a multiregister circuit with name, metadata, phase."""
qr_a = QuantumRegister(4, "a")
qr_b = QuantumRegister(4, "b")
cr_c = ClassicalRegister(4, "c")
cr_d = ClassicalRegister(4, "d")
full_circuit = QuantumCircuit(
qr_a,
qr_b,
cr_c,
cr_d,
name="MyCircuit",
metadata={"test": 1, "a": 2},
global_phase=3.14159,
)
full_circuit.h(qr_a)
full_circuit.cx(qr_a, qr_b)
full_circuit.barrier(qr_a)
full_circuit.barrier(qr_b)
full_circuit.measure(qr_a, cr_c)
full_circuit.measure(qr_b, cr_d)
return full_circuit
def generate_unitary_gate_circuit():
"""Generate a circuit with a unitary gate."""
unitary_circuit = QuantumCircuit(5, name="unitary_circuit")
unitary_circuit.unitary(random_unitary(32, seed=100), [0, 1, 2, 3, 4])
unitary_circuit.measure_all()
return unitary_circuit
def generate_random_circuits():
"""Generate multiple random circuits."""
random_circuits = []
for i in range(1, 15):
qc = QuantumCircuit(i, name=f"random_circuit-{i}")
qc.h(0)
if i > 1:
for j in range(i - 1):
qc.cx(0, j + 1)
qc.measure_all()
for j in range(i):
qc.reset(j)
qc.x(0).c_if(qc.cregs[0], i)
for j in range(i):
qc.measure(j, j)
random_circuits.append(qc)
return random_circuits
def generate_string_parameters():
"""Generate a circuit for the XYZ pauli string."""
op_circuit = QuantumCircuit(3, name="X^Y^Z")
op_circuit.append(PauliGate("XYZ"), op_circuit.qubits, [])
return op_circuit
def generate_register_edge_cases():
"""Generate register edge case circuits."""
register_edge_cases = []
# Circuit with shared bits in a register
qubits = [Qubit() for _ in range(5)]
shared_qc = QuantumCircuit(name="shared_bits")
shared_qc.add_bits(qubits)
shared_qr = QuantumRegister(bits=qubits)
shared_qc.add_register(shared_qr)
shared_qc.h(shared_qr)
shared_qc.cx(0, 1)
shared_qc.cx(0, 2)
shared_qc.cx(0, 3)
shared_qc.cx(0, 4)
shared_qc.measure_all()
register_edge_cases.append(shared_qc)
# Circuit with registers that have a mix of standalone and shared register
# bits
qr = QuantumRegister(5, "foo")
qr = QuantumRegister(name="bar", bits=qr[:3] + [Qubit(), Qubit()])
cr = ClassicalRegister(5, "foo")
cr = ClassicalRegister(name="classical_bar", bits=cr[:3] + [Clbit(), Clbit()])
hybrid_qc = QuantumCircuit(qr, cr, name="mix_standalone_bits_registers")
hybrid_qc.h(0)
hybrid_qc.cx(0, 1)
hybrid_qc.cx(0, 2)
hybrid_qc.cx(0, 3)
hybrid_qc.cx(0, 4)
hybrid_qc.measure(qr, cr)
register_edge_cases.append(hybrid_qc)
# Circuit with mixed standalone and shared registers
qubits = [Qubit() for _ in range(5)]
clbits = [Clbit() for _ in range(5)]
mixed_qc = QuantumCircuit(name="mix_standalone_bits_with_registers")
mixed_qc.add_bits(qubits)
mixed_qc.add_bits(clbits)
qr = QuantumRegister(bits=qubits)
cr = ClassicalRegister(bits=clbits)
mixed_qc.add_register(qr)
mixed_qc.add_register(cr)
qr_standalone = QuantumRegister(2, "standalone")
mixed_qc.add_register(qr_standalone)
cr_standalone = ClassicalRegister(2, "classical_standalone")
mixed_qc.add_register(cr_standalone)
mixed_qc.unitary(random_unitary(32, seed=42), qr)
mixed_qc.unitary(random_unitary(4, seed=100), qr_standalone)
mixed_qc.measure(qr, cr)
mixed_qc.measure(qr_standalone, cr_standalone)
register_edge_cases.append(mixed_qc)
# Circuit with out of order register bits
qr_standalone = QuantumRegister(2, "standalone")
qubits = [Qubit() for _ in range(5)]
clbits = [Clbit() for _ in range(5)]
ooo_qc = QuantumCircuit(name="out_of_order_bits")
ooo_qc.add_bits(qubits)
ooo_qc.add_bits(clbits)
random.seed(42)
random.shuffle(qubits)
random.shuffle(clbits)
qr = QuantumRegister(bits=qubits)
cr = ClassicalRegister(bits=clbits)
ooo_qc.add_register(qr)
ooo_qc.add_register(cr)
qr_standalone = QuantumRegister(2, "standalone")
cr_standalone = ClassicalRegister(2, "classical_standalone")
ooo_qc.add_bits([qr_standalone[1], qr_standalone[0]])
ooo_qc.add_bits([cr_standalone[1], cr_standalone[0]])
ooo_qc.add_register(qr_standalone)
ooo_qc.add_register(cr_standalone)
ooo_qc.unitary(random_unitary(32, seed=42), qr)
ooo_qc.unitary(random_unitary(4, seed=100), qr_standalone)
ooo_qc.measure(qr, cr)
ooo_qc.measure(qr_standalone, cr_standalone)
register_edge_cases.append(ooo_qc)
return register_edge_cases
def generate_parameterized_circuit():
"""Generate a circuit with parameters and parameter expressions."""
param_circuit = QuantumCircuit(1, name="parameterized")
theta = Parameter("theta")
lam = Parameter("λ")
theta_pi = 3.14159 * theta
pe = theta_pi / lam
param_circuit.append(U3Gate(theta, theta_pi, lam), [0])
param_circuit.append(U1Gate(pe), [0])
param_circuit.append(U2Gate(theta_pi, lam), [0])
return param_circuit
def generate_qft_circuit():
"""Generate a QFT circuit with initialization."""
k = 5
state = (1 / np.sqrt(8)) * np.array(
[
np.exp(-1j * 2 * np.pi * k * (0) / 8),
np.exp(-1j * 2 * np.pi * k * (1) / 8),
np.exp(-1j * 2 * np.pi * k * (2) / 8),
np.exp(-1j * 2 * np.pi * k * 3 / 8),
np.exp(-1j * 2 * np.pi * k * 4 / 8),
np.exp(-1j * 2 * np.pi * k * 5 / 8),
np.exp(-1j * 2 * np.pi * k * 6 / 8),
np.exp(-1j * 2 * np.pi * k * 7 / 8),
]
)
qubits = 3
qft_circ = QuantumCircuit(qubits, qubits, name="QFT")
qft_circ.initialize(state)
qft_circ.append(QFT(qubits), range(qubits))
qft_circ.measure(range(qubits), range(qubits))
return qft_circ
def generate_param_phase():
"""Generate circuits with parameterize global phase."""
output_circuits = []
# Generate circuit with ParameterExpression global phase
theta = Parameter("theta")
phi = Parameter("phi")
sum_param = theta + phi
qc = QuantumCircuit(5, 1, global_phase=sum_param, name="parameter_phase")
qc.h(0)
for i in range(4):
qc.cx(i, i + 1)
qc.barrier()
qc.rz(sum_param, range(3))
qc.rz(phi, 3)
qc.rz(theta, 4)
qc.barrier()
for i in reversed(range(4)):
qc.cx(i, i + 1)
qc.h(0)
qc.measure(0, 0)
output_circuits.append(qc)
# Generate circuit with Parameter global phase
theta = Parameter("theta")
bell_qc = QuantumCircuit(2, global_phase=theta, name="bell_param_global_phase")
bell_qc.h(0)
bell_qc.cx(0, 1)
bell_qc.measure_all()
output_circuits.append(bell_qc)
return output_circuits
def generate_single_clbit_condition_teleportation(): # pylint: disable=invalid-name
"""Generate single clbit condition teleportation circuit."""
qr = QuantumRegister(1)
cr = ClassicalRegister(2, name="name")
teleport_qc = QuantumCircuit(qr, cr, name="Reset Test")
teleport_qc.x(0)
teleport_qc.measure(0, cr[0])
teleport_qc.x(0).c_if(cr[0], 1)
teleport_qc.measure(0, cr[1])
return teleport_qc
def generate_parameter_vector():
"""Generate tests for parameter vector element ordering."""
qc = QuantumCircuit(11, name="parameter_vector")
input_params = ParameterVector("x_par", 11)
user_params = ParameterVector("θ_par", 11)
for i, param in enumerate(user_params):
qc.ry(param, i)
for i, param in enumerate(input_params):
qc.rz(param, i)
return qc
def generate_parameter_vector_expression(): # pylint: disable=invalid-name
"""Generate tests for parameter vector element ordering."""
qc = QuantumCircuit(7, name="vector_expansion")
entanglement = [[i, i + 1] for i in range(7 - 1)]
input_params = ParameterVector("x_par", 14)
user_params = ParameterVector("\u03B8_par", 1)
for i in range(qc.num_qubits):
qc.ry(user_params[0], qc.qubits[i])
for source, target in entanglement:
qc.cz(qc.qubits[source], qc.qubits[target])
for i in range(qc.num_qubits):
qc.rz(-2 * input_params[2 * i + 1], qc.qubits[i])
qc.rx(-2 * input_params[2 * i], qc.qubits[i])
return qc
def generate_evolution_gate():
"""Generate a circuit with a pauli evolution gate."""
# Runtime import since this only exists in terra 0.19.0
from qiskit.circuit.library import PauliEvolutionGate
from qiskit.synthesis import SuzukiTrotter
from qiskit.quantum_info import SparsePauliOp
synthesis = SuzukiTrotter()
op = SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)])
evo = PauliEvolutionGate([op] * 5, time=2.0, synthesis=synthesis)
qc = QuantumCircuit(2, name="pauli_evolution_circuit")
qc.append(evo, range(2))
return qc
def generate_control_flow_circuits():
"""Test qpy serialization with control flow instructions."""
from qiskit.circuit.controlflow import WhileLoopOp, IfElseOp, ForLoopOp
# If instruction
circuits = []
qc = QuantumCircuit(2, 2, name="control_flow")
qc.h(0)
qc.measure(0, 0)
true_body = QuantumCircuit(1)
true_body.x(0)
if_op = IfElseOp((qc.clbits[0], True), true_body=true_body)
qc.append(if_op, [1])
qc.measure(1, 1)
circuits.append(qc)
# If else instruction
qc = QuantumCircuit(2, 2, name="if_else")
qc.h(0)
qc.measure(0, 0)
false_body = QuantumCircuit(1)
false_body.y(0)
if_else_op = IfElseOp((qc.clbits[0], True), true_body, false_body)
qc.append(if_else_op, [1])
qc.measure(1, 1)
circuits.append(qc)
# While loop
qc = QuantumCircuit(2, 1, name="while_loop")
block = QuantumCircuit(2, 1)
block.h(0)
block.cx(0, 1)
block.measure(0, 0)
while_loop = WhileLoopOp((qc.clbits[0], 0), block)
qc.append(while_loop, [0, 1], [0])
circuits.append(qc)
# for loop range
qc = QuantumCircuit(2, 1, name="for_loop")
body = QuantumCircuit(2, 1)
body.h(0)
body.cx(0, 1)
body.measure(0, 0)
body.break_loop().c_if(0, True)
for_loop_op = ForLoopOp(range(5), None, body=body)
qc.append(for_loop_op, [0, 1], [0])
circuits.append(qc)
# For loop iterator
qc = QuantumCircuit(2, 1, name="for_loop_iterator")
for_loop_op = ForLoopOp(iter(range(5)), None, body=body)
qc.append(for_loop_op, [0, 1], [0])
circuits.append(qc)
return circuits
def generate_control_flow_switch_circuits():
"""Generate circuits with switch-statement instructions."""
from qiskit.circuit.controlflow import CASE_DEFAULT
circuits = []
qc = QuantumCircuit(2, 1, name="switch_clbit")
case_t = qc.copy_empty_like()
case_t.x(0)
case_f = qc.copy_empty_like()
case_f.z(1)
qc.switch(qc.clbits[0], [(True, case_t), (False, case_f)], qc.qubits, qc.clbits)
circuits.append(qc)
qreg = QuantumRegister(2, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg, name="switch_creg")
case_0 = QuantumCircuit(qreg, creg)
case_0.x(0)
case_1 = QuantumCircuit(qreg, creg)
case_1.z(1)
case_2 = QuantumCircuit(qreg, creg)
case_2.x(1)
qc.switch(
creg, [(0, case_0), ((1, 2), case_1), ((3, 4, CASE_DEFAULT), case_2)], qc.qubits, qc.clbits
)
circuits.append(qc)
return circuits
def generate_schedule_blocks():
"""Standard QPY testcase for schedule blocks."""
from qiskit.pulse import builder, channels, library
from qiskit.utils import optionals
# Parameterized schedule test is avoided.
# Generated reference and loaded QPY object may induce parameter uuid mismatch.
# As workaround, we need test with bounded parameters, however, schedule.parameters
# are returned as Set and thus its order is random.
# Since schedule parameters are validated, we cannot assign random numbers.
# We need to upgrade testing framework.
schedule_blocks = []
# Instructions without parameters
with builder.build() as block:
with builder.align_sequential():
builder.set_frequency(5e9, channels.DriveChannel(0))
builder.shift_frequency(10e6, channels.DriveChannel(1))
builder.set_phase(1.57, channels.DriveChannel(0))
builder.shift_phase(0.1, channels.DriveChannel(1))
builder.barrier(channels.DriveChannel(0), channels.DriveChannel(1))
builder.play(library.Gaussian(160, 0.1j, 40), channels.DriveChannel(0))
builder.play(library.GaussianSquare(800, 0.1, 64, 544), channels.ControlChannel(0))
builder.play(library.Drag(160, 0.1, 40, 1.5), channels.DriveChannel(1))
builder.play(library.Constant(800, 0.1), channels.MeasureChannel(0))
builder.acquire(1000, channels.AcquireChannel(0), channels.MemorySlot(0))
schedule_blocks.append(block)
# Raw symbolic pulse
if optionals.HAS_SYMENGINE:
import symengine as sym
else:
import sympy as sym
duration, amp, t = sym.symbols("duration amp t") # pylint: disable=invalid-name
expr = amp * sym.sin(2 * sym.pi * t / duration)
my_pulse = library.SymbolicPulse(
pulse_type="Sinusoidal",
duration=100,
parameters={"amp": 0.1},
envelope=expr,
valid_amp_conditions=sym.Abs(amp) <= 1.0,
)
with builder.build() as block:
builder.play(my_pulse, channels.DriveChannel(0))
schedule_blocks.append(block)
# Raw waveform
my_waveform = 0.1 * np.sin(2 * np.pi * np.linspace(0, 1, 100))
with builder.build() as block:
builder.play(my_waveform, channels.DriveChannel(0))
schedule_blocks.append(block)
return schedule_blocks
def generate_referenced_schedule():
"""Test for QPY serialization of unassigned reference schedules."""
from qiskit.pulse import builder, channels, library
schedule_blocks = []
# Completely unassigned schedule
with builder.build() as block:
builder.reference("cr45p", "q0", "q1")
builder.reference("x", "q0")
builder.reference("cr45m", "q0", "q1")
schedule_blocks.append(block)
# Partly assigned schedule
with builder.build() as x_q0:
builder.play(library.Constant(100, 0.1), channels.DriveChannel(0))
with builder.build() as block:
builder.reference("cr45p", "q0", "q1")
builder.call(x_q0)
builder.reference("cr45m", "q0", "q1")
schedule_blocks.append(block)
return schedule_blocks
def generate_calibrated_circuits():
"""Test for QPY serialization with calibrations."""
from qiskit.pulse import builder, Constant, DriveChannel
circuits = []
# custom gate
mygate = Gate("mygate", 1, [])
qc = QuantumCircuit(1, name="calibrated_circuit_1")
qc.append(mygate, [0])
with builder.build() as caldef:
builder.play(Constant(100, 0.1), DriveChannel(0))
qc.add_calibration(mygate, (0,), caldef)
circuits.append(qc)
# override instruction
qc = QuantumCircuit(1, name="calibrated_circuit_2")
qc.x(0)
with builder.build() as caldef:
builder.play(Constant(100, 0.1), DriveChannel(0))
qc.add_calibration("x", (0,), caldef)
circuits.append(qc)
return circuits
def generate_controlled_gates():
"""Test QPY serialization with custom ControlledGates."""
circuits = []
qc = QuantumCircuit(3, name="custom_controlled_gates")
controlled_gate = DCXGate().control(1)
qc.append(controlled_gate, [0, 1, 2])
circuits.append(qc)
custom_gate = Gate("black_box", 1, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
nested_qc = QuantumCircuit(3, name="nested_qc")
qc.append(custom_gate, [0])
controlled_gate = custom_gate.control(2)
nested_qc.append(controlled_gate, [0, 1, 2])
nested_qc.measure_all()
circuits.append(nested_qc)
qc_open = QuantumCircuit(2, name="open_cx")
qc_open.cx(0, 1, ctrl_state=0)
circuits.append(qc_open)
return circuits
def generate_open_controlled_gates():
"""Test QPY serialization with custom ControlledGates with open controls."""
circuits = []
qc = QuantumCircuit(3, name="open_controls_simple")
controlled_gate = DCXGate().control(1, ctrl_state=0)
qc.append(controlled_gate, [0, 1, 2])
circuits.append(qc)
custom_gate = Gate("black_box", 1, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
nested_qc = QuantumCircuit(3, name="open_controls_nested")
nested_qc.append(custom_gate, [0])
controlled_gate = custom_gate.control(2, ctrl_state=1)
nested_qc.append(controlled_gate, [0, 1, 2])
nested_qc.measure_all()
circuits.append(nested_qc)
return circuits
def generate_acquire_instruction_with_kernel_and_discriminator():
"""Test QPY serialization with Acquire instruction with kernel and discriminator."""
from qiskit.pulse import builder, AcquireChannel, MemorySlot, Discriminator, Kernel
schedule_blocks = []
with builder.build() as block:
builder.acquire(
100,
AcquireChannel(0),
MemorySlot(0),
kernel=Kernel(
name="my_kernel", my_params_1={"param1": 0.1, "param2": 0.2}, my_params_2=[0, 1]
),
)
schedule_blocks.append(block)
with builder.build() as block:
builder.acquire(
100,
AcquireChannel(0),
MemorySlot(0),
discriminator=Discriminator(
name="my_disc", my_params_1={"param1": 0.1, "param2": 0.2}, my_params_2=[0, 1]
),
)
schedule_blocks.append(block)
return schedule_blocks
def generate_layout_circuits():
"""Test qpy circuits with layout set."""
from qiskit.transpiler.layout import TranspileLayout, Layout
qr = QuantumRegister(3, "foo")
qc = QuantumCircuit(qr, name="GHZ with layout")
qc.h(0)
qc.cx(0, 1)
qc.swap(0, 1)
qc.cx(0, 2)
input_layout = {qr[index]: index for index in range(len(qc.qubits))}
qc._layout = TranspileLayout(
Layout(input_layout),
input_qubit_mapping=input_layout,
final_layout=Layout.from_qubit_list([qc.qubits[1], qc.qubits[0], qc.qubits[2]]),
)
return [qc]
def generate_control_flow_expr():
"""`IfElseOp`, `WhileLoopOp` and `SwitchCaseOp` with `Expr` nodes in their discriminators."""
from qiskit.circuit.classical import expr, types
body1 = QuantumCircuit(1)
body1.x(0)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
qc1 = QuantumCircuit(qr1, cr1)
qc1.if_test(expr.equal(cr1, 3), body1.copy(), [0], [])
qc1.while_loop(expr.logic_not(cr1[1]), body1.copy(), [0], [])
inner2 = QuantumCircuit(1)
inner2.x(0)
outer2 = QuantumCircuit(1, 1)
outer2.if_test(expr.logic_not(outer2.clbits[0]), inner2, [0], [])
qr2 = QuantumRegister(2, "q2")
cr1_2 = ClassicalRegister(3, "c1")
cr2_2 = ClassicalRegister(3, "c2")
qc2 = QuantumCircuit(qr2, cr1_2, cr2_2)
qc2.if_test(expr.logic_or(expr.less(cr1_2, cr2_2), cr1_2[1]), outer2, [1], [1])
inner3 = QuantumCircuit(1)
inner3.x(0)
outer3 = QuantumCircuit(1, 1)
outer3.switch(expr.logic_not(outer2.clbits[0]), [(False, inner2)], [0], [])
qr3 = QuantumRegister(2, "q2")
cr1_3 = ClassicalRegister(3, "c1")
cr2_3 = ClassicalRegister(3, "c2")
qc3 = QuantumCircuit(qr3, cr1_3, cr2_3)
qc3.switch(expr.bit_xor(cr1_3, cr2_3), [(0, outer2)], [1], [1])
cr1_4 = ClassicalRegister(256, "c1")
cr2_4 = ClassicalRegister(4, "c2")
cr3_4 = ClassicalRegister(4, "c3")
inner4 = QuantumCircuit(1)
inner4.x(0)
outer_loose = Clbit()
outer4 = QuantumCircuit(QuantumRegister(2, "q_outer"), cr2_4, [outer_loose], cr1_4)
outer4.if_test(
expr.logic_and(
expr.logic_or(
expr.greater(expr.bit_or(cr2_4, 7), 10),
expr.equal(expr.bit_and(cr1_4, cr1_4), expr.bit_not(cr1_4)),
),
expr.logic_or(
outer_loose,
expr.cast(cr1_4, types.Bool()),
),
),
inner4,
[0],
[],
)
qc4_loose = Clbit()
qc4 = QuantumCircuit(QuantumRegister(2, "qr4"), cr1_4, cr2_4, cr3_4, [qc4_loose])
qc4.rz(np.pi, 0)
qc4.switch(
expr.logic_and(
expr.logic_or(
expr.logic_or(
expr.less(cr2_4, cr3_4),
expr.logic_not(expr.greater_equal(cr3_4, cr2_4)),
),
expr.logic_or(
expr.logic_not(expr.less_equal(cr3_4, cr2_4)),
expr.greater(cr2_4, cr3_4),
),
),
expr.logic_and(
expr.equal(cr3_4, 2),
expr.not_equal(expr.bit_xor(cr1_4, 0x0F), 0x0F),
),
),
[(False, outer4)],
[1, 0],
list(cr2_4) + [qc4_loose] + list(cr1_4),
)
qc4.rz(np.pi, 0)
return [qc1, qc2, qc3, qc4]
def generate_circuits(version_parts):
"""Generate reference circuits."""
output_circuits = {
"full.qpy": [generate_full_circuit()],
"unitary.qpy": [generate_unitary_gate_circuit()],
"multiple.qpy": generate_random_circuits(),
"string_parameters.qpy": [generate_string_parameters()],
"register_edge_cases.qpy": generate_register_edge_cases(),
"parameterized.qpy": [generate_parameterized_circuit()],
}
if version_parts is None:
return output_circuits
if version_parts >= (0, 18, 1):
output_circuits["qft_circuit.qpy"] = [generate_qft_circuit()]
output_circuits["teleport.qpy"] = [generate_single_clbit_condition_teleportation()]
if version_parts >= (0, 19, 0):
output_circuits["param_phase.qpy"] = generate_param_phase()
if version_parts >= (0, 19, 1):
output_circuits["parameter_vector.qpy"] = [generate_parameter_vector()]
output_circuits["pauli_evo.qpy"] = [generate_evolution_gate()]
output_circuits["parameter_vector_expression.qpy"] = [
generate_parameter_vector_expression()
]
if version_parts >= (0, 19, 2):
output_circuits["control_flow.qpy"] = generate_control_flow_circuits()
if version_parts >= (0, 21, 0):
output_circuits["schedule_blocks.qpy"] = generate_schedule_blocks()
output_circuits["pulse_gates.qpy"] = generate_calibrated_circuits()
if version_parts >= (0, 24, 0):
output_circuits["referenced_schedule_blocks.qpy"] = generate_referenced_schedule()
output_circuits["control_flow_switch.qpy"] = generate_control_flow_switch_circuits()
if version_parts >= (0, 24, 1):
output_circuits["open_controlled_gates.qpy"] = generate_open_controlled_gates()
output_circuits["controlled_gates.qpy"] = generate_controlled_gates()
if version_parts >= (0, 24, 2):
output_circuits["layout.qpy"] = generate_layout_circuits()
if version_parts >= (0, 25, 0):
output_circuits[
"acquire_inst_with_kernel_and_disc.qpy"
] = generate_acquire_instruction_with_kernel_and_discriminator()
output_circuits["control_flow_expr.qpy"] = generate_control_flow_expr()
return output_circuits
def assert_equal(reference, qpy, count, version_parts, bind=None):
"""Compare two circuits."""
if bind is not None:
reference_parameter_names = [x.name for x in reference.parameters]
qpy_parameter_names = [x.name for x in qpy.parameters]
if reference_parameter_names != qpy_parameter_names:
msg = (
f"Circuit {count} parameter mismatch:"
f" {reference_parameter_names} != {qpy_parameter_names}"
)
sys.stderr.write(msg)
sys.exit(4)
reference = reference.bind_parameters(bind)
qpy = qpy.bind_parameters(bind)
if reference != qpy:
msg = (
f"Reference Circuit {count}:\n{reference}\nis not equivalent to "
f"qpy loaded circuit {count}:\n{qpy}\n"
)
sys.stderr.write(msg)
sys.exit(1)
# Check deprecated bit properties, if set. The QPY dumping code before Terra 0.23.2 didn't
# include enough information for us to fully reconstruct this, so we only test if newer.
if version_parts >= (0, 23, 2) and isinstance(reference, QuantumCircuit):
for ref_bit, qpy_bit in itertools.chain(
zip(reference.qubits, qpy.qubits), zip(reference.clbits, qpy.clbits)
):
if ref_bit._register is not None and ref_bit != qpy_bit:
msg = (
f"Reference Circuit {count}:\n"
"deprecated bit-level register information mismatch\n"
f"reference bit: {ref_bit}\n"
f"loaded bit: {qpy_bit}\n"
)
sys.stderr.write(msg)
sys.exit(1)
if (
version_parts >= (0, 24, 2)
and isinstance(reference, QuantumCircuit)
and reference.layout != qpy.layout
):
msg = f"Circuit {count} layout mismatch {reference.layout} != {qpy.layout}\n"
sys.stderr.write(msg)
sys.exit(4)
# Don't compare name on bound circuits
if bind is None and reference.name != qpy.name:
msg = f"Circuit {count} name mismatch {reference.name} != {qpy.name}\n{reference}\n{qpy}"
sys.stderr.write(msg)
sys.exit(2)
if reference.metadata != qpy.metadata:
msg = f"Circuit {count} metadata mismatch: {reference.metadata} != {qpy.metadata}"
sys.stderr.write(msg)
sys.exit(3)
def generate_qpy(qpy_files):
"""Generate qpy files from reference circuits."""
for path, circuits in qpy_files.items():
with open(path, "wb") as fd:
dump(circuits, fd)
def load_qpy(qpy_files, version_parts):
"""Load qpy circuits from files and compare to reference circuits."""
for path, circuits in qpy_files.items():
print(f"Loading qpy file: {path}")
with open(path, "rb") as fd:
qpy_circuits = load(fd)
for i, circuit in enumerate(circuits):
bind = None
if path == "parameterized.qpy":
bind = [1, 2]
elif path == "param_phase.qpy":
if i == 0:
bind = [1, 2]
else:
bind = [1]
elif path == "parameter_vector.qpy":
bind = np.linspace(1.0, 2.0, 22)
elif path == "parameter_vector_expression.qpy":
bind = np.linspace(1.0, 2.0, 15)
assert_equal(circuit, qpy_circuits[i], i, version_parts, bind=bind)
def _main():
parser = argparse.ArgumentParser(description="Test QPY backwards compatibilty")
parser.add_argument("command", choices=["generate", "load"])
parser.add_argument(
"--version",
"-v",
help=(
"Optionally specify the version being tested. "
"This will enable additional circuit features "
"to test generating and loading QPY."
),
)
args = parser.parse_args()
# Terra 0.18.0 was the first release with QPY, so that's the default.
version_parts = (0, 18, 0)
if args.version:
version_match = re.search(VERSION_PATTERN, args.version, re.VERBOSE | re.IGNORECASE)
version_parts = tuple(int(x) for x in version_match.group("release").split("."))
qpy_files = generate_circuits(version_parts)
if args.command == "generate":
generate_qpy(qpy_files)
else:
load_qpy(qpy_files, version_parts)
if __name__ == "__main__":
_main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure(0, 0)
circ.measure(1, 1)
circ.draw('mpl')
from qiskit import pulse
from qiskit.pulse.library import Gaussian
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration('h', [0], h_q0)
from qiskit import transpile
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
circ = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ.draw('mpl', idle_wires=False)
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
circ = QuantumCircuit(1, 1)
custom_gate = Gate('my_custom_gate', 1, [3.14, 1])
# 3.14 is an arbitrary parameter for demonstration
circ.append(custom_gate, [0])
circ.measure(0, 0)
circ.draw('mpl')
with pulse.build(backend, name='custom') as my_schedule:
pulse.play(Gaussian(duration=64, amp=0.2, sigma=8), pulse.drive_channel(0))
circ.add_calibration('my_custom_gate', [0], my_schedule, [3.14, 1])
# Alternatively: circ.add_calibration(custom_gate, [0], my_schedule)
circ = transpile(circ, backend)
circ.draw('mpl', idle_wires=False)
circ = QuantumCircuit(2, 2)
circ.append(custom_gate, [1])
from qiskit import QiskitError
try:
circ = transpile(circ, backend)
except QiskitError as e:
print(e)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/C2QA/bosonic-qiskit
|
C2QA
|
from pathlib import Path
import c2qa
import numpy
import qiskit
def test_plot_zero(capsys):
with capsys.disabled():
qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=4)
qr = qiskit.QuantumRegister(size=1)
circuit = c2qa.CVCircuit(qmr, qr)
# dist = numpy.sqrt(numpy.pi) / numpy.sqrt(2)
dist = 1.0
# qr[0] will init to zero
circuit.cv_initialize(0, qmr[0])
circuit.h(qr[0])
circuit.cv_c_d(dist, qmr[0], qr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
trace = c2qa.util.trace_out_qubits(circuit, state)
c2qa.wigner.plot_wigner(circuit, trace, file="tests/zero.png", trace=False)
def test_plot_one(capsys):
with capsys.disabled():
qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=2)
qr = qiskit.QuantumRegister(size=1)
cr = qiskit.ClassicalRegister(size=1)
circuit = c2qa.CVCircuit(qmr, qr, cr)
# qr[0] and cr[0] will init to zero
circuit.cv_initialize(1, qmr[0])
state, result, fock_counts = c2qa.util.simulate(circuit)
# print("Qumode initialized to one:")
# print(state)
c2qa.wigner.plot_wigner(circuit, state, file="tests/one.png")
def test_plot_wigner_projection(capsys):
with capsys.disabled():
qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=4)
qr = qiskit.QuantumRegister(size=1)
circuit = c2qa.CVCircuit(qmr, qr)
# dist = numpy.sqrt(numpy.pi) / numpy.sqrt(2)
dist = 1.0
# qr[0] will init to zero
circuit.cv_initialize(0, qmr[0])
circuit.h(qr[0])
circuit.cv_c_d(dist, qmr[0], qr[0])
# circuit.cv_d(dist, qmr[0])
c2qa.wigner.plot_wigner_projection(circuit, qr[0], file="tests/interference.png")
def test_cat_state_wigner_plot(capsys):
with capsys.disabled():
num_qubits_per_qumode = 4
dist = 2
qmr = c2qa.QumodeRegister(
num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode
)
qr = qiskit.QuantumRegister(size=1)
cr = qiskit.ClassicalRegister(size=1)
circuit = c2qa.CVCircuit(qmr, qr, cr)
circuit.initialize([1, 0], qr[0])
circuit.cv_initialize(0, qmr[0])
circuit.h(qr[0])
circuit.cv_c_d(dist, qmr[0], qr[0])
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
# conditional_state_vector=True will return two state vectors, one for 0 and 1 classical register value
state, result, fock_counts = c2qa.util.simulate(circuit, conditional_state_vector=True)
even_state = state["0x0"]
odd_state = state["0x1"]
wigner_filename = "tests/cat_wigner_even.png"
c2qa.wigner.plot_wigner(
circuit,
even_state,
file=wigner_filename,
trace=True,
axes_min=-6,
axes_max=6,
)
assert Path(wigner_filename).is_file()
wigner_filename = "tests/cat_wigner_odd.png"
c2qa.wigner.plot_wigner(
circuit,
odd_state,
file=wigner_filename,
trace=True,
axes_min=-6,
axes_max=6,
)
assert Path(wigner_filename).is_file()
# # Need to recreate circuit state prior to measure collapsing qubit state for projections
# qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode)
# qr = qiskit.QuantumRegister(size=1)
# cr = qiskit.ClassicalRegister(size=1)
# circuit = c2qa.CVCircuit(qmr, qr, cr)
# circuit.initialize(state)
# wigner_filename = "tests/repeat_projection_wigner.png"
# c2qa.wigner.plot_wigner_projection(circuit, qr[0], file=wigner_filename)
# assert Path(wigner_filename).is_file()
def test_wigner_mle(capsys):
with capsys.disabled():
num_qubits_per_qumode = 4
dist = 2
qmr = c2qa.QumodeRegister(
num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode
)
qr = qiskit.QuantumRegister(size=1)
cr = qiskit.ClassicalRegister(size=1)
circuit = c2qa.CVCircuit(qmr, qr, cr)
circuit.initialize([1, 0], qr[0])
circuit.cv_initialize(0, qmr[0])
circuit.h(qr[0])
circuit.cv_c_d(dist, qmr[0], qr[0])
circuit.h(qr[0])
state, result, fock_counts = c2qa.util.simulate(circuit, per_shot_state_vector=True)
wigner = c2qa.wigner.wigner_mle(state)
assert wigner is not None
print(wigner)
def test_plot_wigner_snapshot(capsys):
with capsys.disabled():
num_qubits_per_qumode = 4
dist = 2
qmr = c2qa.QumodeRegister(
num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode
)
qr = qiskit.QuantumRegister(size=1)
cr = qiskit.ClassicalRegister(size=1)
circuit = c2qa.CVCircuit(qmr, qr, cr)
circuit.initialize([1, 0], qr[0])
circuit.cv_initialize(0, qmr[0])
circuit.cv_snapshot()
circuit.h(qr[0])
circuit.cv_snapshot()
circuit.cv_c_d(dist, qmr[0], qr[0])
circuit.cv_snapshot()
circuit.h(qr[0])
circuit.cv_snapshot()
state, result, fock_counts = c2qa.util.simulate(circuit)
c2qa.wigner.plot_wigner_snapshot(circuit, result, "tests")
def test_plot_zero_contour(capsys):
with capsys.disabled():
data = numpy.zeros((200, 200)).tolist()
filename = "tests/test_plot_zero_contour.png"
c2qa.wigner.plot(data, file=filename)
assert Path(filename).is_file()
|
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 itertools
import math
import sys
import ddt
import qiskit.qasm2
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestSimple(QiskitTestCase):
def test_unary_constants(self):
program = "qreg q[1]; U(-(0.5 + 0.5), +(+1 - 2), -+-+2) q[0];"
parsed = qiskit.qasm2.loads(program)
expected = [-1.0, -1.0, 2.0]
self.assertEqual(list(parsed.data[0].operation.params), expected)
def test_unary_symbolic(self):
program = """
gate u(a, b, c) q {
U(-(a + a), +(+b - c), -+-+c) q;
}
qreg q[1];
u(0.5, 1.0, 2.0) q[0];
"""
parsed = qiskit.qasm2.loads(program)
expected = [-1.0, -1.0, 2.0]
actual = [float(x) for x in parsed.data[0].operation.definition.data[0].operation.params]
self.assertEqual(list(actual), expected)
@ddt.data(
("+", lambda a, b: a + b),
("-", lambda a, b: a - b),
("*", lambda a, b: a * b),
("/", lambda a, b: a / b),
("^", lambda a, b: a**b),
)
@ddt.unpack
def test_binary_constants(self, str_op, py_op):
program = f"qreg q[1]; U(0.25{str_op}0.5, 1.0{str_op}0.5, 3.2{str_op}-0.8) q[0];"
parsed = qiskit.qasm2.loads(program)
expected = [py_op(0.25, 0.5), py_op(1.0, 0.5), py_op(3.2, -0.8)]
# These should be bit-for-bit exact.
self.assertEqual(list(parsed.data[0].operation.params), expected)
@ddt.data(
("+", lambda a, b: a + b),
("-", lambda a, b: a - b),
("*", lambda a, b: a * b),
("/", lambda a, b: a / b),
("^", lambda a, b: a**b),
)
@ddt.unpack
def test_binary_symbolic(self, str_op, py_op):
program = f"""
gate u(a, b, c) q {{
U(a {str_op} b, a {str_op} (b {str_op} c), 0.0) q;
}}
qreg q[1];
u(1.0, 2.0, 3.0) q[0];
"""
parsed = qiskit.qasm2.loads(program)
outer = [1.0, 2.0, 3.0]
abstract_op = parsed.data[0].operation
self.assertEqual(list(abstract_op.params), outer)
expected = [py_op(1.0, 2.0), py_op(1.0, py_op(2.0, 3.0)), 0.0]
actual = [float(x) for x in abstract_op.definition.data[0].operation.params]
self.assertEqual(list(actual), expected)
@ddt.data(
("cos", math.cos),
("exp", math.exp),
("ln", math.log),
("sin", math.sin),
("sqrt", math.sqrt),
("tan", math.tan),
)
@ddt.unpack
def test_function_constants(self, function_str, function_py):
program = f"qreg q[1]; U({function_str}(0.5),{function_str}(1.0),{function_str}(pi)) q[0];"
parsed = qiskit.qasm2.loads(program)
expected = [function_py(0.5), function_py(1.0), function_py(math.pi)]
# These should be bit-for-bit exact.
self.assertEqual(list(parsed.data[0].operation.params), expected)
@ddt.data(
("cos", math.cos),
("exp", math.exp),
("ln", math.log),
("sin", math.sin),
("sqrt", math.sqrt),
("tan", math.tan),
)
@ddt.unpack
def test_function_symbolic(self, function_str, function_py):
program = f"""
gate u(a, b, c) q {{
U({function_str}(a), {function_str}(b), {function_str}(c)) q;
}}
qreg q[1];
u(0.5, 1.0, pi) q[0];
"""
parsed = qiskit.qasm2.loads(program)
outer = [0.5, 1.0, math.pi]
abstract_op = parsed.data[0].operation
self.assertEqual(list(abstract_op.params), outer)
expected = [function_py(x) for x in outer]
actual = [float(x) for x in abstract_op.definition.data[0].operation.params]
self.assertEqual(list(actual), expected)
class TestPrecedenceAssociativity(QiskitTestCase):
def test_precedence(self):
# OQ3's precedence rules are the same as Python's, so we can effectively just eval.
expr = " 1.0 + 2.0 * -3.0 ^ 1.5 - 0.5 / +0.25"
expected = 1.0 + 2.0 * -(3.0**1.5) - 0.5 / +0.25
program = f"qreg q[1]; U({expr}, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(parsed.data[0].operation.params[0], expected)
def test_addition_left(self):
# `eps` is the smallest floating-point value such that `1 + eps != 1`. That means that if
# addition is correctly parsed and resolved as left-associative, then the first parameter
# should first calculate `1 + (eps / 2)`, which will be 1, and then the same again, whereas
# the second will do `(eps / 2) + (eps / 2) = eps`, then `eps + 1` will be different.
eps = sys.float_info.epsilon
program = f"qreg q[1]; U(1 + {eps / 2} + {eps / 2}, {eps / 2} + {eps / 2} + 1, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertNotEqual(1.0 + eps, 1.0) # Sanity check for the test.
self.assertEqual(list(parsed.data[0].operation.params), [1.0, 1.0 + eps, 0.0])
def test_multiplication_left(self):
# A similar principle to the epsilon test for addition; if multiplication associates right,
# then `(0.5 * 2.0 * fmax)` is `inf`, otherwise it's `fmax`.
fmax = sys.float_info.max
program = f"qreg q[1]; U({fmax} * 0.5 * 2.0, 2.0 * 0.5 * {fmax}, 2.0 * {fmax} * 0.5) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [fmax, fmax, math.inf])
def test_subtraction_left(self):
# If subtraction associated right, we'd accidentally get 2.
program = "qreg q[1]; U(2.0 - 1.0 - 1.0, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [0.0, 0.0, 0.0])
def test_division_left(self):
# If division associated right, we'd accidentally get 4.
program = "qreg q[1]; U(4.0 / 2.0 / 2.0, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [1.0, 0.0, 0.0])
def test_power_right(self):
# If the power operator associated left, we'd accidentally get 64 instead.
program = "qreg q[1]; U(2.0 ^ 3.0 ^ 2.0, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [512.0, 0.0, 0.0])
class TestCustomClassical(QiskitTestCase):
def test_evaluation_order(self):
"""We should be evaluating all functions, including custom user ones the exact number of
times we expect, and left-to-right in parameter lists."""
# pylint: disable=invalid-name
order = itertools.count()
def f():
return next(order)
program = """
qreg q[1];
U(f(), 2 * f() + f(), atan2(f(), f()) - f()) q[0];
"""
parsed = qiskit.qasm2.loads(
program,
custom_classical=[
qiskit.qasm2.CustomClassical("f", 0, f),
qiskit.qasm2.CustomClassical("atan2", 2, math.atan2),
],
)
self.assertEqual(
list(parsed.data[0].operation.params), [0, 2 * 1 + 2, math.atan2(3, 4) - 5]
)
self.assertEqual(next(order), 6)
@ddt.ddt
class TestErrors(QiskitTestCase):
@ddt.data("0.0", "(1.0 - 1.0)")
def test_refuses_to_divide_by_zero(self, denom):
program = f"qreg q[1]; U(2.0 / {denom}, 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "divide by zero"):
qiskit.qasm2.loads(program)
program = f"gate rx(a) q {{ U(a / {denom}, 0.0, 0.0) q; }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "divide by zero"):
qiskit.qasm2.loads(program)
@ddt.data("0.0", "1.0 - 1.0", "-2.0", "2.0 - 3.0")
def test_refuses_to_ln_non_positive(self, operand):
program = f"qreg q[1]; U(ln({operand}), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "ln of non-positive"):
qiskit.qasm2.loads(program)
program = f"gate rx(a) q {{ U(a + ln({operand}), 0.0, 0.0) q; }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "ln of non-positive"):
qiskit.qasm2.loads(program)
@ddt.data("-2.0", "2.0 - 3.0")
def test_refuses_to_sqrt_negative(self, operand):
program = f"qreg q[1]; U(sqrt({operand}), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "sqrt of negative"):
qiskit.qasm2.loads(program)
program = f"gate rx(a) q {{ U(a + sqrt({operand}), 0.0, 0.0) q; }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "sqrt of negative"):
qiskit.qasm2.loads(program)
@ddt.data("*", "/", "^")
def test_cannot_use_nonunary_operators_in_unary_position(self, operator):
program = f"qreg q[1]; U({operator}1.0, 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not a valid unary operator"):
qiskit.qasm2.loads(program)
@ddt.data("+", "-", "*", "/", "^")
def test_missing_binary_operand_errors(self, operator):
program = f"qreg q[1]; U(1.0 {operator}, 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "missing operand"):
qiskit.qasm2.loads(program)
program = f"qreg q[1]; U((1.0 {operator}), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "missing operand"):
qiskit.qasm2.loads(program)
def test_parenthesis_must_be_closed(self):
program = "qreg q[1]; U((1 + 1 2), 3, 2) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "needed a closing parenthesis"):
qiskit.qasm2.loads(program)
def test_premature_right_parenthesis(self):
program = "qreg q[1]; U(sin(), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "did not find an .* expression"):
qiskit.qasm2.loads(program)
|
https://github.com/Innanov/Qiskit-Global-Summer-School-2022
|
Innanov
|
# General Imports
import numpy as np
# Visualisation Imports
import matplotlib.pyplot as plt
# Scikit Imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Qiskit Imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# Load digits dataset
digits = datasets.load_digits(n_class=2)
# Plot example '0' and '1'
fig, axs = plt.subplots(1, 2, figsize=(6,3))
axs[0].set_axis_off()
axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest')
axs[1].set_axis_off()
axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
# Split dataset
sample_train, sample_test, label_train, label_test = train_test_split(
digits.data, digits.target, test_size=0.2, random_state=22)
# Reduce dimensions
n_dim = 4
pca = PCA(n_components=n_dim).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Normalise
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Scale
samples = np.append(sample_train, sample_test, axis=0)
minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
sample_train = minmax_scale.transform(sample_train)
sample_test = minmax_scale.transform(sample_test)
# Select
train_size = 100
sample_train = sample_train[:train_size]
label_train = label_train[:train_size]
test_size = 20
sample_test = sample_test[:test_size]
label_test = label_test[:test_size]
print(sample_train[0], label_train[0])
print(sample_test[0], label_test[0])
# 3 features, depth 2
map_z = ZFeatureMap(feature_dimension=3, reps=2)
map_z.draw('mpl')
# 3 features, depth 1
map_zz = ZZFeatureMap(feature_dimension=3, reps=1)
map_zz.draw('mpl')
# 3 features, depth 1, linear entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear')
map_zz.draw('mpl')
# 3 features, depth 1, circular entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular')
map_zz.draw('mpl')
# 3 features, depth 1
map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ'])
map_pauli.draw('mpl')
def custom_data_map_func(x):
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x))
return coeff
map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'],
data_map_func=custom_data_map_func)
#map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map
twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'],
entanglement_blocks='cx', entanglement='circular', insert_barriers=True)
twolocal.draw('mpl')
twolocaln = NLocal(num_qubits=3, reps=2,
rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))],
entanglement_blocks=CXGate(),
entanglement='circular', insert_barriers=True)
twolocaln.draw('mpl')
# rotation block:
rot = QuantumCircuit(2)
params = ParameterVector('r', 2)
rot.ry(params[0], 0)
rot.rz(params[1], 1)
# entanglement block:
ent = QuantumCircuit(4)
params = ParameterVector('e', 3)
ent.crx(params[0], 0, 1)
ent.crx(params[1], 1, 2)
ent.crx(params[2], 2, 3)
nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent,
entanglement='linear', insert_barriers=True)
nlocal.draw('mpl')
qubits = 3
repeats = 2
x = ParameterVector('x', length=qubits)
var_custom = QuantumCircuit(qubits)
for _ in range(repeats):
for i in range(qubits):
var_custom.rx(x[i], i)
for i in range(qubits):
for j in range(i + 1, qubits):
var_custom.cx(i, j)
var_custom.p(x[i] * x[j], j)
var_custom.cx(i, j)
var_custom.barrier()
var_custom.draw('mpl')
print(sample_train[0])
encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
encode_circuit = encode_map.bind_parameters(sample_train[0])
encode_circuit.draw(output='mpl')
x = [-0.1,0.2]
# YOUR CODE HERE
encode_map_x =ZZFeatureMap(feature_dimension=2, reps=4)
ex1_circuit =encode_map_x.bind_parameters(x)
ex1_circuit.draw(output='mpl')
from qc_grader import grade_lab3_ex1
# Note that the grading function is expecting a quantum circuit
grade_lab3_ex1(ex1_circuit)
zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator'))
print(sample_train[0])
print(sample_train[1])
zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1])
zz_circuit.decompose().decompose().draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(zz_circuit, backend, shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts = job.result().get_counts(zz_circuit)
counts['0000']/sum(counts.values())
matrix_train = zz_kernel.evaluate(x_vec=sample_train)
matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(np.asmatrix(matrix_train),
interpolation='nearest', origin='upper', cmap='Blues')
axs[0].set_title("training kernel matrix")
axs[1].imshow(np.asmatrix(matrix_test),
interpolation='nearest', origin='upper', cmap='Reds')
axs[1].set_title("testing kernel matrix")
plt.show()
x = [-0.1,0.2]
y = [0.4,-0.6]
# YOUR CODE HERE
encode_map_x2 = ZZFeatureMap(feature_dimension=2, reps=4)
zz_kernel_x2 =QuantumKernel(feature_map=encode_map_x2,quantum_instance=Aer.get_backend('statevector_simulator'))
zz_circuit_x2 =zz_kernel_x2.construct_circuit(x,y)
backend =Aer.get_backend('qasm_simulator')
job = execute(zz_circuit_x2,backend,shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts_x2 = job.result().get_counts(zz_circuit_x2)
amplitude= counts_x2['00']/sum(counts_x2.values())
from qc_grader import grade_lab3_ex2
# Note that the grading function is expecting a floating point number
grade_lab3_ex2(amplitude)
zzpc_svc = SVC(kernel='precomputed')
zzpc_svc.fit(matrix_train, label_train)
zzpc_score = zzpc_svc.score(matrix_test, label_test)
print(f'Precomputed kernel classification test score: {zzpc_score}')
zzcb_svc = SVC(kernel=zz_kernel.evaluate)
zzcb_svc.fit(sample_train, label_train)
zzcb_score = zzcb_svc.score(sample_test, label_test)
print(f'Callable kernel classification test score: {zzcb_score}')
classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid']
for kernel in classical_kernels:
classical_svc = SVC(kernel=kernel)
classical_svc.fit(sample_train, label_train)
classical_score = classical_svc.score(sample_test, label_test)
print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
|
https://github.com/LuukCoopmans/Qiskit-Hackathon-QIP
|
LuukCoopmans
|
import numpy as np
from matplotlib import pyplot as plt
import os
import cv2
from qiskit import *
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])
def get_Coeff(Image, watermark=None):
""" Function that takes in an Greyscale Image matrix of any size and and optional
watermark image and shape and returns qubit coefficients in the computational
basis.
TO DO: build in a check that ensures the sizes of the Image and watermark are the same
"""
Flatten_Image = np.reshape(Image, np.shape(Image)[0]*np.shape(Image)[1])
# Get the theta angles of the Image and watermark from the greyscale values
Theta_I = 2*np.arccos(np.sqrt(Flatten_Image/255))
if watermark is None:
Theta_W = np.zeros(len(Theta_I))
else:
Flatten_watermark = np.reshape(watermark, np.shape(watermark)[0]*np.shape(watermark)[1])
Theta_W = 2*np.arccos(np.sqrt(Flatten_watermark/255))
# Compute the qubit Coeff and return them in a normalized qubit state vector.
Coeff = np.stack((np.cos(Theta_I/2)*np.cos(Theta_W/2),
np.cos(Theta_I/2)*np.sin(Theta_W/2),
np.sin(Theta_I/2)*np.cos(Theta_W/2),
np.sin(Theta_I/2)*np.sin(Theta_W/2)))
Coeff = np.ndarray.flatten(np.transpose(Coeff))
return Coeff/np.linalg.norm(Coeff)
def initialise_state(desired_initial_state):
""" Returns an initialized quantum circuit for a given input state"""
n = int(round(np.log2(desired_initial_state.size))) #number of qubits
qc_init = QuantumCircuit(n)
qc_init.initialize(desired_initial_state, range(n))
return qc_init
def get_Images(probability_vector):
""" Takes in an probability vector obtained from measuring all the qubits in the quantum circuit and returns
the corresponding matrices of the greyscale values of the measured images.
TO DO: vectorize this function
"""
n = int(np.round(len(probability_vector)/4)) # get sizes back of classical images
c_Image = np.zeros(n)
w_Image = np.zeros(n)
# Sum and normalize the probabilities to get the greyscale pixel value out
for i in range(n):
c_Image[i] = (probability_vector[4*i]+probability_vector[4*i+1])*255/np.sum(probability_vector[4*i:(4*i)+4])
w_Image[i] = (probability_vector[4*i]+probability_vector[4*i+2])*255/np.sum(probability_vector[4*i:(4*i)+4])
c_Image = np.reshape(c_Image,[np.int(np.round(np.sqrt(n))),np.int(np.round(np.sqrt(n)))])
w_Image = np.reshape(w_Image,[np.int(np.round(np.sqrt(n))),np.int(np.round(np.sqrt(n)))])
return c_Image, w_Image
N = 16 #size in pixels
# Carrier Image
img_file = os.path.expanduser("cat.png")
img = cv2.imread(img_file)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
res = cv2.resize(img, dsize=(N, N), interpolation=cv2.INTER_CUBIC)
C_Image = rgb2gray(res)
# Watermark
img_file2 = os.path.expanduser("IBM-logo.png")
img2 = cv2.imread(img_file2)
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)
res2 = cv2.resize(img2, dsize=(N, N), interpolation=cv2.INTER_CUBIC)
W_Image = rgb2gray(res2)
plt.rcParams['figure.figsize'] = [9, 7]
plt.rcParams['figure.dpi'] = 100
fig, axs = plt.subplots(1,2)
axs[0].imshow(C_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
axs[0].title.set_text('Carrier Image')
axs[1].imshow(W_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
axs[1].title.set_text('Watermark Image')
State_vector = get_Coeff(C_Image, W_Image)
qc_init = initialise_state(State_vector)
#qc_init.draw('mpl')
n = int(round(np.log2(State_vector.size))) # number of qubits
shots0 = 100000
# Create a Quantum Circuit
meas = QuantumCircuit(n, n)
meas.barrier(range(n))
# map the quantum measurement to the classical bits
meas.measure(range(n), range(n))
# The Qiskit circuit object supports composition using
# the addition operator.
qc = qc_init + meas
#drawing the circuit
#qc.draw('mpl')
# Use Aer's qasm_simulator
backend_sim = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
job_sim = execute(qc, backend_sim, shots=shots0)
# Grab the results from the job.
result_sim = job_sim.result()
#from qiskit import IBMQ
#IBMQ.load_account()
#provider = IBMQ.get_provider("ibm-q")
#backend = provider.get_backend("ibmq_essex")
#job = q.execute(qc, backend=backend, shots=shots0)
#job_monitor(job)
counts = result_sim.get_counts(qc)
probability_vector = np.zeros(2**n)
int_counts = counts.int_outcomes()
for k in range(2**n):
probability_vector[k] = int_counts.get(k, 0)/shots0
RC_Image, RW_Image = get_Images(probability_vector)
fig, axs = plt.subplots(2,2)
axs[0,0].imshow(RC_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
axs[0,0].title.set_text('Retrieved Carrier Image')
axs[0,1].imshow(C_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
axs[0,1].title.set_text('Original Carrier Image')
axs[1,0].imshow(RW_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
axs[1,0].title.set_text('Retrieved Watermark Image')
axs[1,1].imshow(W_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
axs[1,1].title.set_text('Original Watermark Image')
plt.show()
n = int(round(np.log2(State_vector.size)))
shots0 = 100000
# Create the Quantum Scramble Circuit with controlled U3 rotations
meas = QuantumCircuit(n, n)
meas.barrier(range(n))
meas.cu3(np.pi/4, 0, 0, 3, 0)
meas.cu3(-np.pi/4, 0, 0, 4, 0)
meas.cu3(-np.pi/2, 0, 0, 5, 0)
meas.cu3(-np.pi/3, 0, 0, 6, 0)
meas.cu3(np.pi/2, 0, 0, 7, 0)
# map the quantum measurement to the classical bits
meas.measure(range(n), range(n))
# The Qiskit circuit object supports composition using
# the addition operator.
qc = qc_init + meas
# Optional uncomment to draw the circuit
#qc.draw('mpl')
# Use Aer's qasm_simulator
backend_sim = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = execute(qc, backend_sim, shots=shots0)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
probability_vector = np.zeros(2**n)
int_counts = counts.int_outcomes()
for k in range(2**n):
probability_vector[k] = int_counts.get(k, 0)/shots0
RRC_Image, SCrW_Image = get_Images(probability_vector)
fig, axs = plt.subplots(2,2)
axs[0,0].imshow(RRC_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
axs[0,0].title.set_text('Retrieved Carrier Image')
axs[0,1].imshow(C_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
axs[0,1].title.set_text('Original Carrier Image')
axs[1,0].imshow(SCrW_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
axs[1,0].title.set_text('Scrambled Watermark Image')
axs[1,1].imshow(W_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
axs[1,1].title.set_text('Original Watermark Image')
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.problems import ElectronicBasis
driver = PySCFDriver()
driver.run_pyscf()
ao_problem = driver.to_problem(basis=ElectronicBasis.AO)
print(ao_problem.basis)
ao_hamil = ao_problem.hamiltonian
print(ao_hamil.electronic_integrals.alpha)
from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema
qcschema = driver.to_qcschema()
basis_transformer = get_ao_to_mo_from_qcschema(qcschema)
print(basis_transformer.initial_basis)
print(basis_transformer.final_basis)
mo_problem = basis_transformer.transform(ao_problem)
print(mo_problem.basis)
mo_hamil = mo_problem.hamiltonian
print(mo_hamil.electronic_integrals.alpha)
import numpy as np
from qiskit_nature.second_q.operators import ElectronicIntegrals
from qiskit_nature.second_q.problems import ElectronicBasis
from qiskit_nature.second_q.transformers import BasisTransformer
ao2mo_alpha = np.random.random((2, 2))
ao2mo_beta = np.random.random((2, 2))
basis_transformer = BasisTransformer(
ElectronicBasis.AO,
ElectronicBasis.MO,
ElectronicIntegrals.from_raw_integrals(ao2mo_alpha, h1_b=ao2mo_beta),
)
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5")
full_problem = driver.run()
print(full_problem.molecule)
print(full_problem.num_particles)
print(full_problem.num_spatial_orbitals)
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
fc_transformer = FreezeCoreTransformer()
fc_problem = fc_transformer.transform(full_problem)
print(fc_problem.num_particles)
print(fc_problem.num_spatial_orbitals)
print(fc_problem.hamiltonian.constants)
fc_transformer = FreezeCoreTransformer(remove_orbitals=[4, 5])
fc_problem = fc_transformer.transform(full_problem)
print(fc_problem.num_particles)
print(fc_problem.num_spatial_orbitals)
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5")
full_problem = driver.run()
print(full_problem.num_particles)
print(full_problem.num_spatial_orbitals)
from qiskit_nature.second_q.transformers import ActiveSpaceTransformer
as_transformer = ActiveSpaceTransformer(2, 2)
as_problem = as_transformer.transform(full_problem)
print(as_problem.num_particles)
print(as_problem.num_spatial_orbitals)
print(as_problem.hamiltonian.electronic_integrals.alpha)
as_transformer = ActiveSpaceTransformer(2, 2, active_orbitals=[0, 4])
as_problem = as_transformer.transform(full_problem)
print(as_problem.num_particles)
print(as_problem.num_spatial_orbitals)
print(as_problem.hamiltonian.electronic_integrals.alpha)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from math import pi
import numpy as np
import rustworkx as rx
from qiskit_nature.second_q.hamiltonians.lattices import (
BoundaryCondition,
HyperCubicLattice,
Lattice,
LatticeDrawStyle,
LineLattice,
SquareLattice,
TriangularLattice,
)
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
num_nodes = 11
boundary_condition = BoundaryCondition.OPEN
line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition)
line_lattice.draw()
num_nodes = 11
boundary_condition = BoundaryCondition.PERIODIC
line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition)
line_lattice.draw()
line_lattice.draw_without_boundary()
num_nodes = 11
boundary_condition = BoundaryCondition.PERIODIC
edge_parameter = 1.0 + 1.0j
onsite_parameter = 1.0
line_lattice = LineLattice(
num_nodes=num_nodes,
edge_parameter=edge_parameter,
onsite_parameter=onsite_parameter,
boundary_condition=boundary_condition,
)
set(line_lattice.graph.weighted_edge_list())
line_lattice.to_adjacency_matrix()
line_lattice.to_adjacency_matrix(weighted=True)
rows = 5
cols = 4
boundary_condition = BoundaryCondition.OPEN
square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition)
square_lattice.draw()
rows = 5
cols = 4
boundary_condition = (
BoundaryCondition.OPEN,
BoundaryCondition.PERIODIC,
) # open in the x-direction, periodic in the y-direction
square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition)
square_lattice.draw()
rows = 5
cols = 4
edge_parameter = (1.0, 1.0 + 1.0j)
boundary_condition = (
BoundaryCondition.OPEN,
BoundaryCondition.PERIODIC,
) # open in the x-direction, periodic in the y-direction
onsite_parameter = 1.0
square_lattice = SquareLattice(
rows=rows,
cols=cols,
edge_parameter=edge_parameter,
onsite_parameter=onsite_parameter,
boundary_condition=boundary_condition,
)
set(square_lattice.graph.weighted_edge_list())
size = (3, 4, 5)
boundary_condition = (
BoundaryCondition.OPEN,
BoundaryCondition.OPEN,
BoundaryCondition.OPEN,
)
cubic_lattice = HyperCubicLattice(size=size, boundary_condition=boundary_condition)
# function for setting the positions
def indextocoord_3d(index: int, size: tuple, angle) -> list:
z = index // (size[0] * size[1])
a = index % (size[0] * size[1])
y = a // size[0]
x = a % size[0]
vec_x = np.array([1, 0])
vec_y = np.array([np.cos(angle), np.sin(angle)])
vec_z = np.array([0, 1])
return_coord = x * vec_x + y * vec_y + z * vec_z
return return_coord.tolist()
pos = dict([(index, indextocoord_3d(index, size, angle=pi / 4)) for index in range(np.prod(size))])
cubic_lattice.draw(style=LatticeDrawStyle(pos=pos))
rows = 4
cols = 3
boundary_condition = BoundaryCondition.OPEN
triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition)
triangular_lattice.draw()
rows = 4
cols = 3
boundary_condition = BoundaryCondition.PERIODIC
triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition)
triangular_lattice.draw()
graph = rx.PyGraph(multigraph=False) # multigraph shoud be False
graph.add_nodes_from(range(6))
weighted_edge_list = [
(0, 1, 1.0 + 1.0j),
(0, 2, -1.0),
(2, 3, 2.0),
(4, 2, -1.0 + 2.0j),
(4, 4, 3.0),
(2, 5, -1.0),
]
graph.add_edges_from(weighted_edge_list)
# make a lattice
general_lattice = Lattice(graph)
set(general_lattice.graph.weighted_edge_list())
general_lattice.draw()
general_lattice.draw(self_loop=True)
general_lattice.draw(self_loop=True, style=LatticeDrawStyle(with_labels=True))
square_lattice = SquareLattice(rows=5, cols=4, boundary_condition=BoundaryCondition.PERIODIC)
t = -1.0 # the interaction parameter
v = 0.0 # the onsite potential
u = 5.0 # the interaction parameter U
fhm = FermiHubbardModel(
square_lattice.uniform_parameters(
uniform_interaction=t,
uniform_onsite_potential=v,
),
onsite_interaction=u,
)
ham = fhm.second_q_op().simplify()
print(ham)
graph = rx.PyGraph(multigraph=False) # multiigraph shoud be False
graph.add_nodes_from(range(6))
weighted_edge_list = [
(0, 1, 1.0 + 1.0j),
(0, 2, -1.0),
(2, 3, 2.0),
(4, 2, -1.0 + 2.0j),
(4, 4, 3.0),
(2, 5, -1.0),
]
graph.add_edges_from(weighted_edge_list)
general_lattice = Lattice(graph) # the lattice whose weights are seen as the interaction matrix.
u = 5.0 # the interaction parameter U
fhm = FermiHubbardModel(lattice=general_lattice, onsite_interaction=u)
ham = fhm.second_q_op().simplify()
print(ham)
from qiskit_nature.second_q.problems import LatticeModelProblem
num_nodes = 4
boundary_condition = BoundaryCondition.OPEN
line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition)
fhm = FermiHubbardModel(
line_lattice.uniform_parameters(
uniform_interaction=t,
uniform_onsite_potential=v,
),
onsite_interaction=u,
)
lmp = LatticeModelProblem(fhm)
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import JordanWignerMapper
numpy_solver = NumPyMinimumEigensolver()
qubit_mapper = JordanWignerMapper()
calc = GroundStateEigensolver(qubit_mapper, numpy_solver)
res = calc.solve(lmp)
print(res)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
"""Expression-tree nodes."""
# Given the nature of the tree representation and that there are helper functions associated with
# many of the classes whose arguments naturally share names with themselves, it's inconvenient to
# use synonyms everywhere. This goes for the builtin 'type' as well.
# pylint: disable=redefined-builtin,redefined-outer-name
from __future__ import annotations
__all__ = [
"Expr",
"Var",
"Value",
"Cast",
"Unary",
"Binary",
]
import abc
import enum
import typing
from .. import types
if typing.TYPE_CHECKING:
import qiskit
_T_co = typing.TypeVar("_T_co", covariant=True)
# If adding nodes, remember to update `visitors.ExprVisitor` as well.
class Expr(abc.ABC):
"""Root base class of all nodes in the expression tree. The base case should never be
instantiated directly.
This must not be subclassed by users; subclasses form the internal data of the representation of
expressions, and it does not make sense to add more outside of Qiskit library code.
All subclasses are responsible for setting their ``type`` attribute in their ``__init__``, and
should not call the parent initialiser."""
__slots__ = ("type",)
type: types.Type
# Sentinel to prevent instantiation of the base class.
@abc.abstractmethod
def __init__(self): # pragma: no cover
pass
def accept(
self, visitor: qiskit.circuit.classical.expr.ExprVisitor[_T_co], /
) -> _T_co: # pragma: no cover
"""Call the relevant ``visit_*`` method on the given :class:`ExprVisitor`. The usual entry
point for a simple visitor is to construct it, and then call :meth:`accept` on the root
object to be visited. For example::
expr = ...
visitor = MyVisitor()
visitor.accept(expr)
Subclasses of :class:`Expr` should override this to call the correct virtual method on the
visitor. This implements double dispatch with the visitor."""
return visitor.visit_generic(self)
@typing.final
class Cast(Expr):
"""A cast from one type to another, implied by the use of an expression in a different
context."""
__slots__ = ("operand", "implicit")
def __init__(self, operand: Expr, type: types.Type, implicit: bool = False):
self.type = type
self.operand = operand
self.implicit = implicit
def accept(self, visitor, /):
return visitor.visit_cast(self)
def __eq__(self, other):
return (
isinstance(other, Cast)
and self.type == other.type
and self.operand == other.operand
and self.implicit == other.implicit
)
def __repr__(self):
return f"Cast({self.operand}, {self.type}, implicit={self.implicit})"
@typing.final
class Var(Expr):
"""A classical variable."""
__slots__ = ("var",)
def __init__(
self, var: qiskit.circuit.Clbit | qiskit.circuit.ClassicalRegister, type: types.Type
):
self.type = type
self.var = var
def accept(self, visitor, /):
return visitor.visit_var(self)
def __eq__(self, other):
return isinstance(other, Var) and self.type == other.type and self.var == other.var
def __repr__(self):
return f"Var({self.var}, {self.type})"
@typing.final
class Value(Expr):
"""A single scalar value."""
__slots__ = ("value",)
def __init__(self, value: typing.Any, type: types.Type):
self.type = type
self.value = value
def accept(self, visitor, /):
return visitor.visit_value(self)
def __eq__(self, other):
return isinstance(other, Value) and self.type == other.type and self.value == other.value
def __repr__(self):
return f"Value({self.value}, {self.type})"
@typing.final
class Unary(Expr):
"""A unary expression.
Args:
op: The opcode describing which operation is being done.
operand: The operand of the operation.
type: The resolved type of the result.
"""
__slots__ = ("op", "operand")
class Op(enum.Enum):
"""Enumeration of the opcodes for unary operations.
The bitwise negation :data:`BIT_NOT` takes a single bit or an unsigned integer of known
width, and returns a value of the same type.
The logical negation :data:`LOGIC_NOT` takes an input that is implicitly coerced to a
Boolean, and returns a Boolean.
"""
# If adding opcodes, remember to add helper constructor functions in `constructors.py`.
# The opcode integers should be considered a public interface; they are used by
# serialisation formats that may transfer data between different versions of Qiskit.
BIT_NOT = 1
"""Bitwise negation. ``~operand``."""
LOGIC_NOT = 2
"""Logical negation. ``!operand``."""
def __str__(self):
return f"Unary.{super().__str__()}"
def __repr__(self):
return f"Unary.{super().__repr__()}"
def __init__(self, op: Unary.Op, operand: Expr, type: types.Type):
self.op = op
self.operand = operand
self.type = type
def accept(self, visitor, /):
return visitor.visit_unary(self)
def __eq__(self, other):
return (
isinstance(other, Unary)
and self.type == other.type
and self.op is other.op
and self.operand == other.operand
)
def __repr__(self):
return f"Unary({self.op}, {self.operand}, {self.type})"
@typing.final
class Binary(Expr):
"""A binary expression.
Args:
op: The opcode describing which operation is being done.
left: The left-hand operand.
right: The right-hand operand.
type: The resolved type of the result.
"""
__slots__ = ("op", "left", "right")
class Op(enum.Enum):
"""Enumeration of the opcodes for binary operations.
The bitwise operations :data:`BIT_AND`, :data:`BIT_OR` and :data:`BIT_XOR` apply to two
operands of the same type, which must be a single bit or an unsigned integer of fixed width.
The resultant type is the same as the two input types.
The logical operations :data:`LOGIC_AND` and :data:`LOGIC_OR` first implicitly coerce their
arguments to Booleans, and then apply the logical operation. The resultant type is always
Boolean.
The binary mathematical relations :data:`EQUAL`, :data:`NOT_EQUAL`, :data:`LESS`,
:data:`LESS_EQUAL`, :data:`GREATER` and :data:`GREATER_EQUAL` take unsigned integers
(with an implicit cast to make them the same width), and return a Boolean.
"""
# If adding opcodes, remember to add helper constructor functions in `constructors.py`
# The opcode integers should be considered a public interface; they are used by
# serialisation formats that may transfer data between different versions of Qiskit.
BIT_AND = 1
"""Bitwise "and". ``lhs & rhs``."""
BIT_OR = 2
"""Bitwise "or". ``lhs | rhs``."""
BIT_XOR = 3
"""Bitwise "exclusive or". ``lhs ^ rhs``."""
LOGIC_AND = 4
"""Logical "and". ``lhs && rhs``."""
LOGIC_OR = 5
"""Logical "or". ``lhs || rhs``."""
EQUAL = 6
"""Numeric equality. ``lhs == rhs``."""
NOT_EQUAL = 7
"""Numeric inequality. ``lhs != rhs``."""
LESS = 8
"""Numeric less than. ``lhs < rhs``."""
LESS_EQUAL = 9
"""Numeric less than or equal to. ``lhs <= rhs``"""
GREATER = 10
"""Numeric greater than. ``lhs > rhs``."""
GREATER_EQUAL = 11
"""Numeric greater than or equal to. ``lhs >= rhs``."""
def __str__(self):
return f"Binary.{super().__str__()}"
def __repr__(self):
return f"Binary.{super().__repr__()}"
def __init__(self, op: Binary.Op, left: Expr, right: Expr, type: types.Type):
self.op = op
self.left = left
self.right = right
self.type = type
def accept(self, visitor, /):
return visitor.visit_binary(self)
def __eq__(self, other):
return (
isinstance(other, Binary)
and self.type == other.type
and self.op is other.op
and self.left == other.left
and self.right == other.right
)
def __repr__(self):
return f"Binary({self.op}, {self.left}, {self.right}, {self.type})"
|
https://github.com/VicentePerezSoloviev/QAOA_BNSL_IBM
|
VicentePerezSoloviev
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
We use n(n-1) qubits for the adj matrix and n(n-1)/2 qubits for the transition matrix
"""
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from itertools import combinations
m = 2
def mapping_mat_vec(n, row, col):
index = 0
for i in range(n):
for j in range(n):
if i != j:
if i == row and j == col:
return index
else:
index = index + 1
def mapping_vec_mat(n, index):
index_new = 0
for i in range(n):
for j in range(n):
if i != j:
if index == index_new:
return i, j
else:
index_new = index_new + 1
def state_2_str(state):
return str(state)[1:len(str(state)) - 1]
class QAOA:
layers = 0
def __init__(self, n, alpha1, alpha2, weights):
assert isinstance(weights, dict), 'Length of weights matrix is different than expected'
self.n = n
self.alpha1 = alpha1
self.alpha2 = alpha2
self.q_adj = n * (n - 1) # number of qubits for the adj matrix
self.q_r = (n * (n - 1)) / 2 # number of qubits for the transition matrix
# weights is a matrix of elements whose keys are tuples of first element the target and following the parents
self.weights = weights
# Create quantum circuit
nqubits = int(self.q_adj + self.q_r)
self.qreg = QuantumRegister(nqubits)
self.creg = ClassicalRegister(nqubits)
self.circuit = QuantumCircuit(self.qreg, self.creg)
self.adders = []
self.gen_adders()
def index_adj_adder(self, i, j):
assert i != j, "Diagonal adjacency indexes must not be taken into account"
if j > i:
return (i * self.n) + j - (i + 1)
else:
return (i * self.n) + j - i
def index_r_adder(self, i, j):
assert i < j, "Diagonal r indexes must not be taken into account"
aux = self.n * (self.n - 1)
return aux + (i * self.n) + j - int(((i + 2) * (i + 1)) / 2)
def gen_adders(self):
# Transcription of the general formulas of hamiltonian to general indexes of qubits
for i in range(self.n):
for j in range(i + 1, self.n):
for k in range(j + 1, self.n):
self.adders.append([self.alpha1, self.index_r_adder(i, k)])
self.adders.append([self.alpha1, self.index_r_adder(i, j), self.index_r_adder(j, k)])
self.adders.append([-self.alpha1, self.index_r_adder(i, j), self.index_r_adder(i, k)])
self.adders.append([-self.alpha1, self.index_r_adder(j, k), self.index_r_adder(i, k)])
for i in range(self.n):
for j in range(i + 1, self.n):
self.adders.append([self.alpha2, self.index_adj_adder(j, i), self.index_r_adder(i, j)])
self.adders.append([self.alpha2, self.index_adj_adder(i, j)])
self.adders.append([-self.alpha2, self.index_adj_adder(i, j), self.index_r_adder(i, j)])
def evaluate_solution(self, string):
to_bin = []
for i in range(len(string)):
to_bin.append(int(string[i]))
cost = 0
# multiplication of combination of 2-nodes and weight(node|2parents)
for i in range(self.n):
# array = to_bin[i * (self.n - 1): i * (self.n - 1) + (self.n - 1)] # separate each row of adj matrix
array = [[to_bin[mapping_mat_vec(self.n, k, i)], mapping_mat_vec(self.n, k, i)]
for k in range(self.n) if k != i] # separate each col adj m
sum_col = sum([k[0] for k in array])
if sum_col > m:
# cases with more than m parents
cost = cost + 99999999 # penalize
else:
# cases of 0, 1 or 2 parents
# find index of each 1
# indexes = [j * (self.n-1) for j, x in enumerate(array) if x == 1] # index general array(no diagonal)
indexes = [k[1] for k in array if k[0] == 1] # index general array(no diagonal)
if len(indexes) == 1:
# weight (i | index)
row, col = mapping_vec_mat(self.n, indexes[0])
value = self.weights[i, row]
cost = cost + value
elif len(indexes) == 2:
# weight (i | index, index)
row1, col1 = mapping_vec_mat(self.n, indexes[0])
row2, col2 = mapping_vec_mat(self.n, indexes[1])
value = self.weights[i, row1, row2]
cost = cost + value
else:
# 0
cost = cost + self.weights[i]
pass
# restrictions
for i in self.adders:
if len(i) == 2:
cost = cost + i[0] * to_bin[i[1]]
if len(i) == 3:
cost = cost + i[0] * (to_bin[i[1]] * to_bin[i[2]])
return cost
def add_superposition_layer(self):
# Superposition
for i in range(len(self.qreg)):
self.circuit.h(self.qreg[i])
def spin_mult(self, spins, gamma):
if len(spins) == 0 or len(spins) > 4:
raise Exception('number of spins does not match the function requirements')
if not isinstance(spins, list):
raise Exception('A list is required as argument "spins"')
for i in range(len(spins) - 1):
self.circuit.cnot(spins[i], spins[len(spins) - 1])
self.circuit.rz(gamma, spins[len(spins) - 1])
for i in range(len(spins) - 2, -1, -1):
self.circuit.cnot(spins[i], spins[len(spins) - 1])
def adj_mult(self, adjs, gamma, coef):
if not isinstance(adjs, list):
raise Exception('A list is required as argument "adjs"')
if len(adjs) == 0 or len(adjs) > 4:
raise Exception('number of adj indexes does not match the function requirements')
angle = coef * (gamma * 2) / (2 ** (len(adjs)))
for adj in adjs:
self.circuit.rz(-angle, self.qreg[adj])
for tam in range(2, len(adjs) + 1):
for comb in combinations(adjs, tam):
self.spin_mult([self.qreg[i] for i in list(comb)], angle)
def add_layer(self, nlayers, beta, gamma):
for lay in range(nlayers):
# Phase Operator
# multiplication of each isolated and weight(node|1parent)
for i in range(self.n):
for j in range(self.n):
if i != j:
# in qubit i, j is the weight of j->i
value = (-1) * (self.weights[i, j] - self.weights[i]) # subtract w_i({null})
self.circuit.rz(gamma[lay] * value, self.qreg[self.index_adj_adder(j, i)])
# multiplication of combination of 2-nodes and weight(node|2parents) in same adj col
for i in range(self.n):
array = [k for k in range(self.n) if k != i]
perm = combinations(array, m)
for per in perm:
# i | perm, perm
value = self.weights[i, per[0], per[1]] + self.weights[i] - \
self.weights[i, per[0]] - self.weights[i, per[1]]
self.adj_mult([self.index_adj_adder(per[0], i), self.index_adj_adder(per[1], i)],
gamma[lay], value) # coef = 1 -> not in the restrictions
# multiplication of each of the couple restrictions
for i in self.adders:
self.adj_mult(i[1:], gamma[lay], i[0])
# Mixing Operator
for i in range(len(self.qreg)):
self.circuit.rx(2*beta[lay], self.qreg[i])
def measure(self):
self.circuit.measure(range(len(self.qreg)), range(len(self.qreg)-1, -1, -1))
|
https://github.com/nahumsa/volta
|
nahumsa
|
# 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
import qiskit
from qiskit.circuit.library import TwoLocal
from qiskit import BasicAer
from qiskit.utils import QuantumInstance
from qiskit.opflow import Z, I
from volta.vqd import VQD
from volta.utils import classical_solver
class TestVQDSWAP(unittest.TestCase):
def setUp(self):
optimizer = qiskit.algorithms.optimizers.COBYLA()
backend = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"),
shots=50000,
seed_simulator=42,
seed_transpiler=42,
)
hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z)
ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2)
self.Algo = VQD(
hamiltonian=hamiltonian,
ansatz=ansatz,
n_excited_states=1,
beta=1.0,
optimizer=optimizer,
backend=backend,
overlap_method="swap",
)
self.Algo.run(verbose=0)
self.eigenvalues, _ = classical_solver(hamiltonian)
def test_energies_0(self):
decimal_place = 1
want = self.eigenvalues[0]
got = self.Algo.energies[0]
message = (
"VQD with SWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))"
)
self.assertAlmostEqual(want, got, decimal_place, message)
def test_energies_1(self):
decimal_place = 1
want = self.eigenvalues[1]
got = self.Algo.energies[1]
message = "VQD with SWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))"
self.assertAlmostEqual(want, got, decimal_place, message)
class TestVQDDSWAP(unittest.TestCase):
def setUp(self):
optimizer = qiskit.algorithms.optimizers.COBYLA()
# backend = BasicAer.get_backend("qasm_simulator")
backend = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"),
shots=50000,
seed_simulator=42,
seed_transpiler=42,
)
hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z)
ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1)
self.Algo = VQD(
hamiltonian=hamiltonian,
ansatz=ansatz,
n_excited_states=1,
beta=1.0,
optimizer=optimizer,
backend=backend,
overlap_method="dswap",
)
self.Algo.run(verbose=0)
self.eigenvalues, _ = classical_solver(hamiltonian)
def test_energies_0(self):
decimal_place = 1
want = self.eigenvalues[0]
got = self.Algo.energies[0]
self.assertAlmostEqual(
want,
got,
decimal_place,
"VQD with DSWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))",
)
def test_energies_1(self):
decimal_place = 1
want = self.eigenvalues[1]
got = self.Algo.energies[1]
self.assertAlmostEqual(
want,
got,
decimal_place,
"VQD with DSWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))",
)
class TestVQDAmplitude(unittest.TestCase):
def setUp(self):
optimizer = qiskit.algorithms.optimizers.COBYLA()
backend = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"),
shots=50000,
seed_simulator=42,
seed_transpiler=42,
)
hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z)
ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1)
self.Algo = VQD(
hamiltonian=hamiltonian,
ansatz=ansatz,
n_excited_states=1,
beta=1.0,
optimizer=optimizer,
backend=backend,
overlap_method="amplitude",
)
self.Algo.run(verbose=0)
self.eigenvalues, _ = classical_solver(hamiltonian)
def test_energies_0(self):
decimal_place = 1
want = self.eigenvalues[0]
got = self.Algo.energies[0]
self.assertAlmostEqual(
want,
got,
decimal_place,
"VQD with Excitation Amplitude not working for the ground state of 1/2*((Z^I) + (Z^Z))",
)
def test_energies_1(self):
decimal_place = 1
want = self.eigenvalues[1]
got = self.Algo.energies[1]
self.assertAlmostEqual(
want,
got,
decimal_place,
"VQD with Excitation Amplitude not working for the first excited state of 1/2*((Z^I) + (Z^Z))",
)
class VQDRaiseError(unittest.TestCase):
def test_not_implemented_overlapping_method(self):
optimizer = qiskit.algorithms.optimizers.COBYLA()
backend = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"), shots=50000
)
hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z)
ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2)
with self.assertRaises(NotImplementedError):
VQD(
hamiltonian=hamiltonian,
ansatz=ansatz,
n_excited_states=1,
beta=1.0,
optimizer=optimizer,
backend=backend,
overlap_method="test",
),
if __name__ == "__main__":
unittest.main(argv=[""], verbosity=2, exit=False)
|
https://github.com/lmarza/QuantumDeskCalculator
|
lmarza
|
# -*- coding: utf-8 -*-
# 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.
"""Utils for using with Qiskit unit tests."""
import logging
import os
import unittest
from enum import Enum
from qiskit import __path__ as qiskit_path
class Path(Enum):
"""Helper with paths commonly used during the tests."""
# Main SDK path: qiskit/
SDK = qiskit_path[0]
# test.python path: qiskit/test/python/
TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python'))
# Examples path: examples/
EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples'))
# Schemas path: qiskit/schemas
SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas'))
# VCR cassettes path: qiskit/test/cassettes/
CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes'))
# Sample QASMs path: qiskit/test/python/qasm
QASMS = os.path.normpath(os.path.join(TEST, 'qasm'))
def setup_test_logging(logger, log_level, filename):
"""Set logging to file and stdout for a logger.
Args:
logger (Logger): logger object to be updated.
log_level (str): logging level.
filename (str): name of the output file.
"""
# Set up formatter.
log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
' %(message)s'.format(logger.name))
formatter = logging.Formatter(log_fmt)
# Set up the file handler.
file_handler = logging.FileHandler(filename)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Set the logging level from the environment variable, defaulting
# to INFO if it is not a valid level.
level = logging._nameToLevel.get(log_level, logging.INFO)
logger.setLevel(level)
class _AssertNoLogsContext(unittest.case._AssertLogsContext):
"""A context manager used to implement TestCase.assertNoLogs()."""
# pylint: disable=inconsistent-return-statements
def __exit__(self, exc_type, exc_value, tb):
"""
This is a modified version of TestCase._AssertLogsContext.__exit__(...)
"""
self.logger.handlers = self.old_handlers
self.logger.propagate = self.old_propagate
self.logger.setLevel(self.old_level)
if exc_type is not None:
# let unexpected exceptions pass through
return False
if self.watcher.records:
msg = 'logs of level {} or higher triggered on {}:\n'.format(
logging.getLevelName(self.level), self.logger.name)
for record in self.watcher.records:
msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname,
record.lineno,
record.getMessage())
self._raiseFailure(msg)
|
https://github.com/Quantum-Ducks/QuBayes
|
Quantum-Ducks
|
import pandas as pd
import numpy as np
march = pd.read_csv('march.csv', names = ['region', 'day', 'rec', 'work'])
april = pd.read_csv('april.csv', names = ['region', 'day', 'rec', 'work'])
may = pd.read_csv('may.csv', names = ['region', 'day', 'rec', 'work'])
june = pd.read_csv('june.csv', names = ['region', 'day', 'rec', 'work'])
print(np.shape(march))
print(np.shape(april))
print(np.shape(may))
print(np.shape(june))
print(np.shape(march.region))
print(357./7.)
i=0
marrecavgs = []
marworkavgs = []
aprrecavgs = []
aprworkavgs = []
mayworkavgs = []
mayrecavgs = []
junrecavgs = []
junworkavgs = []
marrecstate = []
marworkstate = []
aprrecstate = []
aprworkstate = []
mayrecstate = []
mayworkstate = []
junrecstate = []
junworkstate = []
zerolow = 0.
onelow = -26.
twolow = -53.
while i < np.shape(march)[0]:
marwk = march.iloc[i:i+7]
marrecavg = np.mean(marwk.rec)
marworkavg = np.mean(marwk.work)
marrecavgs.append(marrecavg)
marworkavgs.append(marworkavg)
if marrecavg > zerolow:
marrecstate.append(3)
elif (marrecavg < zerolow) & (marrecavg > onelow):
marrecstate.append(2)
elif (marrecavg < onelow) & (marrecavg > twolow):
marrecstate.append(1)
elif marrecavg < twolow:
marrecstate.append(0)
if marworkavg > zerolow:
marworkstate.append(3)
elif (marworkavg < zerolow) & (marworkavg > onelow):
marworkstate.append(2)
elif (marworkavg < onelow) & (marworkavg > twolow):
marworkstate.append(1)
elif marworkavg < twolow:
marworkstate.append(0)
aprwk = april.iloc[i:i+7]
aprrecavg = np.mean(aprwk.rec)
aprworkavg = np.mean(aprwk.work)
aprrecavgs.append(aprrecavg)
aprworkavgs.append(aprworkavg)
if aprrecavg >= zerolow:
aprrecstates.append(3)
elif (aprrecavg < zerolow) & (aprrecavg >= onelow):
aprrecstate.append(2)
elif (aprrecavg < onelow) & (aprrecavg >= twolow):
aprrecstate.append(1)
elif aprrecavg < twolow:
aprrecstate.append(0)
if aprworkavg >= zerolow:
aprworkstate.append(3)
elif (aprworkavg < zerolow) & (aprworkavg >= onelow):
aprworkstate.append(2)
elif (aprworkavg < onelow) & (aprworkavg >= twolow):
aprworkstate.append(1)
elif aprworkavg < twolow:
aprworkstate.append(0)
maywk = may.iloc[i:i+7]
mayrecavg = np.mean(maywk.rec)
mayworkavg = np.mean(maywk.work)
mayrecavgs.append(mayrecavg)
mayworkavgs.append(mayworkavg)
if mayrecavg > zerolow:
mayrecstate.append(3)
elif (mayrecavg < zerolow) & (mayrecavg > onelow):
mayrecstate.append(2)
elif (mayrecavg < onelow) & (mayrecavg > twolow):
mayrecstate.append(1)
elif mayrecavg < twolow:
mayrecstate.append(0)
if mayworkavg > zerolow:
mayworkstate.append(3)
elif (mayworkavg < zerolow) & (mayworkavg > onelow):
mayworkstate.append(2)
elif (mayworkavg < onelow) & (mayworkavg > twolow):
mayworkstate.append(1)
elif mayworkavg < twolow:
mayworkstate.append(0)
junwk = june.iloc[i:i+7]
junrecavg = np.mean(junwk.rec)
junworkavg = np.mean(junwk.work)
junrecavgs.append(junrecavg)
junworkavgs.append(junworkavg)
if junrecavg > zerolow:
junrecstate.append(3)
elif (junrecavg < zerolow) & (junrecavg > onelow):
junrecstate.append(2)
elif (junrecavg < onelow) & (junrecavg > twolow):
junrecstate.append(1)
elif junrecavg < twolow:
junrecstate.append(0)
if junworkavg > zerolow:
junworkstate.append(3)
elif (junworkavg < zerolow) & (junworkavg > onelow):
junworkstate.append(2)
elif (junworkavg < onelow) & (junworkavg > twolow):
junworkstate.append(1)
elif junworkavg < twolow:
junworkstate.append(0)
i += 7
print(len(marrecavgs))
print(len(aprrecavgs))
print(len(mayrecavgs))
print(len(junrecavgs))
print(len(marworkavgs))
print(len(aprworkavgs))
print(len(mayworkavgs))
print(len(junworkavgs))
print(len(marrecstate))
print(len(aprrecstate))
print(len(mayrecstate))
print(len(junrecstate))
print(len(marworkstate))
print(len(aprworkstate))
print(len(mayworkstate))
print(len(junworkstate))
mobility_data_andstates = pd.DataFrame(data={'marrec': marrecavgs, 'aprrec' : aprrecavgs, 'mayrec':mayrecavgs, 'junrec':junrecavgs
,'marwork':marworkavgs, 'aprwork':aprworkavgs, 'maywork':mayworkavgs, 'junwork':junworkavgs
,'marrecstates':marrecstate, 'aprrecstates':aprrecstate, 'mayrecstates':mayrecstate, 'junrecstates':junrecstate
,'marworkstates':marworkstate, 'aprworkstates':aprworkstate, 'mayworkstates':mayworkstate, 'junworkstates':junworkstate})
print(mobility_data_andstates)
#mobility_data_andstates.to_csv('mobility_data_andstates.csv')
|
https://github.com/sebasmos/QuantumVE
|
sebasmos
|
# This code is part of qiskit-runtime.
#
# (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.
"""Source code for the QKA Qiskit Runtime program."""
# pylint: disable=invalid-name
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 FeatureMap:
"""Mapping data with the feature map."""
def __init__(self, feature_dimension, entangler_map=None):
"""
Args:
feature_dimension (int): number of features, twice the number
of qubits for this encoding
entangler_map (list[list]): connectivity of qubits with a list of [source, target],
or None for full entanglement. Note that the order in
the list is the order of applying the two-qubit gate.
Raises:
ValueError: If the value of ``feature_dimension`` is not an even integer.
"""
if isinstance(feature_dimension, int):
if feature_dimension % 2 == 0:
self._feature_dimension = feature_dimension
else:
raise ValueError("Feature dimension must be an even integer.")
else:
raise ValueError("Feature dimension must be an even integer.")
self._num_qubits = int(feature_dimension / 2)
if entangler_map is None:
self._entangler_map = [
[i, j]
for i in range(self._feature_dimension)
for j in range(i + 1, self._feature_dimension)
]
else:
self._entangler_map = entangler_map
self._num_parameters = self._num_qubits
def construct_circuit(self, x=None, parameters=None, q=None, inverse=False, name=None):
"""Construct the feature map circuit.
Args:
x (numpy.ndarray): data vector of size feature_dimension
parameters (numpy.ndarray): optional parameters in feature map
q (QauntumRegister): the QuantumRegister object for the circuit
inverse (bool): whether or not to invert the circuit
name (str): name of circuit
Returns:
QuantumCircuit: a quantum circuit transforming data x
Raises:
ValueError: If the input parameters or vector are invalid
"""
if parameters is not None:
if isinstance(parameters, (int, float)):
raise ValueError("Parameters must be a list.")
if len(parameters) == 1:
parameters = parameters * np.ones(self._num_qubits)
else:
if len(parameters) != self._num_parameters:
raise ValueError(
"The number of feature map parameters must be {}.".format(
self._num_parameters
)
)
if len(x) != self._feature_dimension:
raise ValueError(
"The input vector must be of length {}.".format(self._feature_dimension)
)
if q is None:
q = QuantumRegister(self._num_qubits, name="q")
circuit = QuantumCircuit(q, name=name)
for i in range(self._num_qubits):
circuit.ry(-parameters[i], q[i])
for source, target in self._entangler_map:
circuit.cz(q[source], q[target])
for i in range(self._num_qubits):
circuit.rz(-2 * x[2 * i + 1], q[i])
circuit.rx(-2 * x[2 * i], q[i])
if inverse:
return circuit.inverse()
else:
return circuit
def to_json(self):
"""Return JSON representation of this object.
Returns:
str: JSON string representing this object.
"""
return json.dumps(
{"feature_dimension": self._feature_dimension, "entangler_map": self._entangler_map}
)
@classmethod
def from_json(cls, data):
"""Return an instance of this class from the JSON representation.
Args:
data (str): JSON string representing an object.
Returns:
cls: An instance of this class.
"""
return cls(**json.loads(data))
class KernelMatrix:
"""Build the kernel matrix from a quantum feature map."""
def __init__(self, feature_map, backend, initial_layout=None):
"""
Args:
feature_map: the feature map object
backend (Backend): the backend instance
initial_layout (list or dict): initial position of virtual
qubits on the physical qubits
of the quantum device
"""
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):
"""Create the kernel matrix for a given feature map and input data.
With the qasm simulator or real backends, compute order 'n^2'
states Phi^dag(y)Phi(x)|0> for input vectors x and y.
Args:
x1_vec (numpy.ndarray): NxD array of training data or test data,
where N is the number of samples
and D is the feature dimension
x2_vec (numpy.ndarray): MxD array of training data or support
vectors, where M is the number of samples
and D is the feature dimension
parameters (numpy.ndarray): optional parameters in feature map
Returns:
numpy.ndarray: the kernel matrix
"""
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
class QKA:
"""The quantum kernel alignment algorithm."""
def __init__(self, feature_map, backend, initial_layout=None, user_messenger=None):
"""Constructor.
Args:
feature_map (partial obj): the quantum feature map object
backend (Backend): the backend instance
initial_layout (list or dict): initial position of virtual qubits on
the physical qubits of the quantum device
user_messenger (UserMessenger): used to publish interim results.
"""
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):
"""Return array of precomputed SPSA parameters.
The i-th optimization step, i>=0, the parameters evolve as
a_i = a / (i + 1 + A) ** alpha,
c_i = c / (i + 1) ** gamma,
for fixed coefficents a, c, alpha, gamma, A.
Returns:
numpy.ndarray: spsa parameters
"""
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):
"""Convex optimization of SVM objective using cvxopt.
Args:
K (numpy.ndarray): nxn kernel (Gram) matrix
y (numpy.ndarray): nx1 vector of labels +/-1
C (float): soft-margin penalty
max_iters (int): maximum iterations for the solver
show_progress (bool): print progress of solver
Returns:
dict: results from the solver
"""
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):
"""Evaluate +/- perturbations of kernel parameters (lambdas).
Args:
lambdas (numpy.ndarray): kernel parameters at step 'count' in SPSA optimization loop
spsa_params (numpy.ndarray): SPSA parameters
count (int): the current step in the SPSA optimization loop
Returns:
numpy.ndarray: kernel parameters in + direction
numpy.ndarray: kernel parameters in - direction
numpy.ndarray: random vector with elements {-1,1}
"""
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):
"""Evaluate one iteration of SPSA on SVM objective function F and
return updated kernel parameters.
F(alpha, lambda) = 1^T * alpha - (1/2) * alpha^T * Y * K * Y * alpha
Args:
cost_plus (float): objective function F(alpha_+, lambda_+)
cost_minus (float): objective function F(alpha_-, lambda_-)
lambdas (numpy.ndarray): kernel parameters at step 'count' in SPSA optimization loop
spsa_params (numpy.ndarray): SPSA parameters
delta (numpy.ndarray): random vector with elements {-1,1}
count(int): the current step in the SPSA optimization loop
Returns:
float: estimate of updated SVM objective function F using average
of F(alpha_+, lambda_+) and F(alpha_-, lambda_-)
numpy.ndarray: updated values of the kernel parameters
after one SPSA optimization step
"""
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):
"""Align the quantum kernel.
Uses SPSA for minimization over kernel parameters (lambdas) and
convex optimization for maximization over lagrange multipliers (alpha):
min_lambda max_alpha 1^T * alpha - (1/2) * alpha^T * Y * K_lambda * Y * alpha
Args:
data (numpy.ndarray): NxD array of training data, where N is the
number of samples and D is the feature dimension
labels (numpy.ndarray): Nx1 array of +/-1 labels of the N training samples
initial_kernel_parameters (numpy.ndarray): Initial parameters of the quantum kernel
maxiters (int): number of SPSA optimization steps
C (float): penalty parameter for the soft-margin support vector machine
Returns:
dict: the results of kernel alignment
"""
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}
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
def main(backend, user_messenger, **kwargs):
"""Entry function."""
# Reconstruct the feature map object.
feature_map = kwargs.get("feature_map")
fm = FeatureMap.from_json(feature_map)
data = kwargs.get("data")
labels = kwargs.get("labels")
initial_kernel_parameters = kwargs.get("initial_kernel_parameters", None)
maxiters = kwargs.get("maxiters", 1)
C = kwargs.get("C", 1)
initial_layout = kwargs.get("initial_layout", None)
qka = QKA(
feature_map=fm,
backend=backend,
initial_layout=initial_layout,
user_messenger=user_messenger,
)
qka_results = qka.align_kernel(
data=data,
labels=labels,
initial_kernel_parameters=initial_kernel_parameters,
maxiters=maxiters,
C=C,
)
user_messenger.publish(qka_results, final=True)
|
https://github.com/mareksubocz/QRBM-qiskit
|
mareksubocz
|
from qiskit import IBMQ
# IBMQ.save_account(MY_API_TOKEN)
import qiskit
qiskit.__version__
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info.operators import Operator
from qiskit import(QuantumCircuit, execute, Aer)
from qiskit.visualization import plot_histogram
from qiskit.extensions import Initialize # Import the Inititialize function
theta = np.pi / 6
x = 0.25
qc = QuantumCircuit(2,2)
initial_state = [np.sqrt(x), np.sqrt(1-x)]
initialize_qubit = Initialize(initial_state)
qc.append(initialize_qubit, [0])
qc.h(0)
# qc.unitary(Rz(0), [0], label='Rz')
qc.rz(theta, 0)
qc.cx(0,1)
qc.h(1)
# Map the quantum measurement to the classical bits
qc.measure([0], [0])
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(qc, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(qc)
print("\nTotal count for 0 and 1 are:",counts)
qc.draw()
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
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":
### replaced x gate ###
qc.z(qubit)
if msg[0] == "1":
### replaced z gate ###
qc.x(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
"""The following is python code utilizing the qiskit library that can be run on extant quantum
hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding,
for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find
r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1,
results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>).
To find the factor, use the equivalence a^r mod 15. From this:
(a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r
values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15
Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients,
gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15,
so the result of running shors algorithm to find the prime factors of an integer using quantum
hardware are demonstrated. Note, this is not the same as the technical implementation of shor's
algorithm described in this section for breaking the discrete log hardness assumption,
though the proof of concept remains."""
# Import libraries
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from numpy import pi
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.visualization import plot_histogram
# Initialize qubit registers
qreg_q = QuantumRegister(5, 'q')
creg_c = ClassicalRegister(5, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.reset(qreg_q[0])
circuit.reset(qreg_q[1])
circuit.reset(qreg_q[2])
circuit.reset(qreg_q[3])
circuit.reset(qreg_q[4])
# Apply Hadamard transformations to qubit registers
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
# Apply first QFT, modular exponentiation, and another QFT
circuit.h(qreg_q[1])
circuit.cx(qreg_q[2], qreg_q[3])
circuit.crx(pi/2, qreg_q[0], qreg_q[1])
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4])
circuit.h(qreg_q[0])
circuit.rx(pi/2, qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
# Measure the qubit registers 0-2
circuit.measure(qreg_q[2], creg_c[2])
circuit.measure(qreg_q[1], creg_c[1])
circuit.measure(qreg_q[0], creg_c[0])
# Get least busy quantum hardware backend to run on
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
# Run the circuit on available quantum hardware and plot histogram
from qiskit.tools.monitor import job_monitor
job = execute(circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(circuit)
plot_histogram(answer)
#largest amplitude results correspond with r values used to find the prime factor of N.
|
https://github.com/mareksubocz/QRBM-qiskit
|
mareksubocz
|
from qiskit import IBMQ
# IBMQ.save_account(MY_API_TOKEN)
import qiskit
qiskit.__version__
import scipy
import numpy as np
import random
from sklearn import preprocessing
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.quantum_info.operators import Operator
from qiskit import(QuantumCircuit, execute, Aer)
from qiskit.visualization import plot_histogram
from qiskit.extensions import Initialize # Import the Inititialize function
from qiskit.aqua.circuits.gates import multi_control_toffoli_gate
from qiskit.aqua.circuits.gates import multi_control_multi_target_gate
import torch
from torch.autograd import Function
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
import timeit
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['image.cmap'] = 'gray'
import pandas as pd
from skimage import data, color
from skimage.transform import rescale, resize, downscale_local_mean
from skimage import img_as_bool
import cv2 as cv
def exctract_single_qubit_measurment(dict_of_counts, qubit_range):
num_qubits = len(list(dict_of_counts.keys())[0])
result = np.zeros(num_qubits)
for el in dict_of_counts:
for i in range(num_qubits):
if i in qubit_range and el[i] == '1':
result[i] += dict_of_counts[el]
return result[qubit_range]
class QMLCircuit():
def __init__(self, visible, hidden, num_shots=1000):
self.visible = visible
self.hidden = hidden
self.ancilla = visible-1
self.qr = QuantumRegister((self.visible + self.hidden + self.ancilla), 'q')
self.cr = ClassicalRegister(self.hidden, 'c')
self.qc = QuantumCircuit(self.qr, self.cr)
self.num_shots = num_shots
# def run(self, thetas):
def circuit_function(self, x, weight_matrix):
self.qc.data = []
# inicjalizacja wartości qubitów wejściowych (x)
initial_state = [[np.sqrt(1-x[i]), np.sqrt(x[i])] for i in range(len(x))]
print('dlugosc initial_state: ', len(initial_state))
# inicjalizacja wartości qubitów wejściowych i bramka Hadamarda
for i in range(visible):
print('i vis: ', i)
initialize_qubit = Initialize(initial_state[i])
self.qc.append(initialize_qubit, [i])
self.qc.h(i)
# ciąg bramek CNOT i bramek rotacji R (zależnych od parametrów)
for i in range(self.hidden):
print('i hid: ', i)
for j in range(self.visible):
print('j vis: ', j)
self.qc.ry(weight_matrix[j][i], j)
print([self.qr[k] for k in range(self.visible)])
print(self.qr[self.visible + i])
print([self.qr[i] for i in range(self.visible + self.hidden, self.visible + self.hidden + self.ancilla)])
multi_control_toffoli_gate.mct(self.qc, [self.qr[k] for k in range(self.visible)], self.qr[self.visible + i], [self.qr[i] for i in range(self.visible + self.hidden, self.visible + self.hidden + self.ancilla)], mode='basic')
# pomiar linii visible
self.qc.measure(list(range(visible, visible+hidden)), list(range(hidden)))
#eksperyment:
simulator = Aer.get_backend('qasm_simulator')
job = execute(self.qc, simulator, shots=self.num_shots)
result = job.result()
counts = result.get_counts(self.qc)
ph = exctract_single_qubit_measurment(counts, list(range(self.hidden))) / self.num_shots
# print("\nProbabilities are:",ph)
return ph
visible = 2
hidden = 1
QMLC = QMLCircuit(visible, hidden, 1000)
#definicja wejścia (x)oraz inicjalizacja macierzy wag
x = np.array([random.uniform(0, 1) for n in range(visible)])
weight_matrix = np.random.rand(visible, hidden) * np.pi
print(QMLC.circuit_function(x, weight_matrix))
QMLC.qc.draw()
##Na razie zostawiam na później
class QFunction(Function):
""" Hybrid quantum - classical function definition """
@staticmethod
def forward(ctx, input, QMLC, epsilon):
""" Forward pass computation """
ctx.epsilon = epsilon
ctx.QMLC = QMLC
print(input)
ph = ctx.QMLC(input[0].tolist())
result = torch.tensor([ph])
ctx.save_for_backward(input, result)
return result
@staticmethod
def backward(ctx, grad_output):
# def update(ph, expected_ph, weight_matrix, lr):
input, ph = ctx.saved_tensors
input_list = np.array(input.tolist())
gradients = []
gradient_row = []
for j, el in enumerate(row):
weight_matrix[i][j] += epsilon
result_plus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] -= 2*epsilon
result_minus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] += epsilon
# result_zero = circuit_function(qc, weight_matrix)
# print("ph", result_zero)
# print("exp_ph", expected_ph)
# print("el final:", el)
# print(result_plus - result_minus)
result = (result_plus - result_minus)/(2*epsilon) * lr * (ph - expected_ph)
gradient_row.append(result)
gradient.append(gradient_row)
# print("gradient", gradient)
weight_matrix = weight_matrix - gradient
return weight_matrix
""" Backward pass computation """
input, ph = ctx.saved_tensors
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.epsilon
shift_left = input_list - np.ones(input_list.shape) * ctx.epsilon
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients.append(gradient)
gradients = np.array([gradients]).T
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class QuantumLayer(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, epsilon):
super(QuantumLayer, self).__init__()
self.QMLC = QMLCircuit(1, 1, 1000)
self.epsilon = epsilon
def forward(self, input):
return QFunction.apply(input, self.QMLC, self.epsilon)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 64, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(6400, 64)
self.fc2 = nn.Linear(64, 1)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(-1, 6400)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return torch.cat((x, 1 - x), -1)
# Wczytywanie danych inną metodą
# Concentrating on the first 100 samples
n_samples = 100
X_train = datasets.MNIST(root='./data', train=True, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
# 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]
train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, 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].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.item()))
n_samples_show -= 1
n_samples = 50
X_test = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
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]
test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True)
# trenowanie modelu
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
print(i for i in enumerate(train_loader))
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
# nie trzeba odpalać STARE FUNKCJE
epsilon = 0.01
def update(ph, expected_ph, weight_matrix, lr):
gradient = []
for i, row in enumerate(weight_matrix):
gradient_row = []
for j, el in enumerate(row):
weight_matrix[i][j] += epsilon
result_plus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] -= 2*epsilon
result_minus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] += epsilon
# result_zero = circuit_function(qc, weight_matrix)
# print("ph", result_zero)
# print("exp_ph", expected_ph)
# print("el final:", el)
# print(result_plus - result_minus)
result = (result_plus - result_minus)/(2*epsilon) * lr * (ph - expected_ph)
gradient_row.append(result)
gradient.append(gradient_row)
# print("gradient", gradient)
weight_matrix = weight_matrix - gradient
return weight_matrix
def create_dataset(dataset_size):
dataset = []
for i in range(dataset_size):
x = np.array([random.choice([0,1]), random.choice([0,1])])
y = 1
if np.array_equal(x, np.array([0,0])) or np.array_equal(x, np.array([1,1])):
y = 0
dataset.append({"x": x, "y": y})
return dataset
dataset = create_dataset(4)
print(dataset)
# template do uczenia
import matplotlib.pyplot as plt
%matplotlib inline
#definicja rozmiaru sieci
visible = 2
hidden = 1
ancilla = visible-1
#definicja wejścia (x)oraz inicjalizacja macierzy wag
# x = np.array([random.uniform(0, 1) for n in range(visible)])
dataset = create_dataset(10)
print(dataset[0]["x"][0])
print(dataset[0]["x"][1])
print([n for n in range(visible)])
weight_matrix = np.random.rand(visible, hidden) * np.pi
#definicja parametrów uczenia
num_shots = 1000
num_epochs = 100
QMLC = QMLCircuit(visible, hidden, 1000)
qr = QuantumRegister(visible + hidden + ancilla, 'q')
cr = ClassicalRegister(hidden, 'c')
qc = QuantumCircuit(qr, cr)
cost_function_data = []
lr = 0.05
for epoch in range(num_epochs):
print("epoch: ", epoch)
# qc.data = []
# initial_state = [[np.sqrt(1-x[i]), np.sqrt(x[i])] for i in range(len(x))]
# for i in range(visible):
# print('i vis: ', i)
# initialize_qubit = Initialize(initial_state[i])
# qc.append(initialize_qubit, [i])
# qc.h(i)
for i, element in enumerate(dataset):
# print(element)
x = np.array([dataset[i]["x"][n] for n in range(visible)])
exp_ph = dataset[i]["y"]
ph = QMLC.circuit_function(qc, weight_matrix)
weight_matrix = update(ph, exp_ph, weight_matrix, lr)
# print("exp_ph", exp_ph, "ph", ph, "weight_matrix", weight_matrix, "cost_function", 0.5 * (ph - exp_ph)**2)
cost_function_data.append(0.5 * (ph - exp_ph)**2)
qc.draw()
plt.xlabel('number of epochs')
plt.ylabel('cost')
plt.plot(cost_function_data)
for i in range(len(dataset)):
x = np.array([dataset[i]["x"][n] for n in range(visible)])
exp_ph = dataset[i]["y"]
ph = circuit_function(qc, weight_matrix)
print(ph)
print(exp_ph, "\n")
qc.draw()
ph = circuit_function(qc, weight_matrix)
print(ph)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
"""Multiple-Control, Multiple-Target Gate."""
from __future__ import annotations
from collections.abc import Callable
from qiskit import circuit
from qiskit.circuit import ControlledGate, Gate, Qubit, QuantumRegister, QuantumCircuit
from qiskit.exceptions import QiskitError
from ..standard_gates import XGate, YGate, ZGate, HGate, TGate, TdgGate, SGate, SdgGate
class MCMT(QuantumCircuit):
"""The multi-controlled multi-target gate, for an arbitrary singly controlled target gate.
For example, the H gate controlled on 3 qubits and acting on 2 target qubit is represented as:
.. parsed-literal::
───■────
│
───■────
│
───■────
┌──┴───┐
┤0 ├
│ 2-H │
┤1 ├
└──────┘
This default implementations requires no ancilla qubits, by broadcasting the target gate
to the number of target qubits and using Qiskit's generic control routine to control the
broadcasted target on the control qubits. If ancilla qubits are available, a more efficient
variant using the so-called V-chain decomposition can be used. This is implemented in
:class:`~qiskit.circuit.library.MCMTVChain`.
"""
def __init__(
self,
gate: Gate | Callable[[QuantumCircuit, Qubit, Qubit], circuit.Instruction],
num_ctrl_qubits: int,
num_target_qubits: int,
) -> None:
"""Create a new multi-control multi-target gate.
Args:
gate: The gate to be applied controlled on the control qubits and applied to the target
qubits. Can be either a Gate or a circuit method.
If it is a callable, it will be casted to a Gate.
num_ctrl_qubits: The number of control qubits.
num_target_qubits: The number of target qubits.
Raises:
AttributeError: If the gate cannot be casted to a controlled gate.
AttributeError: If the number of controls or targets is 0.
"""
if num_ctrl_qubits == 0 or num_target_qubits == 0:
raise AttributeError("Need at least one control and one target qubit.")
# set the internal properties and determine the number of qubits
self.gate = self._identify_gate(gate)
self.num_ctrl_qubits = num_ctrl_qubits
self.num_target_qubits = num_target_qubits
num_qubits = num_ctrl_qubits + num_target_qubits + self.num_ancilla_qubits
# initialize the circuit object
super().__init__(num_qubits, name="mcmt")
self._label = f"{num_target_qubits}-{self.gate.name.capitalize()}"
# build the circuit
self._build()
def _build(self):
"""Define the MCMT gate without ancillas."""
if self.num_target_qubits == 1:
# no broadcasting needed (makes for better circuit diagrams)
broadcasted_gate = self.gate
else:
broadcasted = QuantumCircuit(self.num_target_qubits, name=self._label)
for target in list(range(self.num_target_qubits)):
broadcasted.append(self.gate, [target], [])
broadcasted_gate = broadcasted.to_gate()
mcmt_gate = broadcasted_gate.control(self.num_ctrl_qubits)
self.append(mcmt_gate, self.qubits, [])
@property
def num_ancilla_qubits(self):
"""Return the number of ancillas."""
return 0
def _identify_gate(self, gate):
"""Case the gate input to a gate."""
valid_gates = {
"ch": HGate(),
"cx": XGate(),
"cy": YGate(),
"cz": ZGate(),
"h": HGate(),
"s": SGate(),
"sdg": SdgGate(),
"x": XGate(),
"y": YGate(),
"z": ZGate(),
"t": TGate(),
"tdg": TdgGate(),
}
if isinstance(gate, ControlledGate):
base_gate = gate.base_gate
elif isinstance(gate, Gate):
if gate.num_qubits != 1:
raise AttributeError("Base gate must act on one qubit only.")
base_gate = gate
elif isinstance(gate, QuantumCircuit):
if gate.num_qubits != 1:
raise AttributeError(
"The circuit you specified as control gate can only have one qubit!"
)
base_gate = gate.to_gate() # raises error if circuit contains non-unitary instructions
else:
if callable(gate): # identify via name of the passed function
name = gate.__name__
elif isinstance(gate, str):
name = gate
else:
raise AttributeError(f"Invalid gate specified: {gate}")
base_gate = valid_gates[name]
return base_gate
def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None):
"""Return the controlled version of the MCMT circuit."""
if ctrl_state is None: # TODO add ctrl state implementation by adding X gates
return MCMT(self.gate, self.num_ctrl_qubits + num_ctrl_qubits, self.num_target_qubits)
return super().control(num_ctrl_qubits, label, ctrl_state)
def inverse(self):
"""Return the inverse MCMT circuit, which is itself."""
return MCMT(self.gate, self.num_ctrl_qubits, self.num_target_qubits)
class MCMTVChain(MCMT):
"""The MCMT implementation using the CCX V-chain.
This implementation requires ancillas but is decomposed into a much shallower circuit
than the default implementation in :class:`~qiskit.circuit.library.MCMT`.
**Expanded Circuit:**
.. plot::
from qiskit.circuit.library import MCMTVChain, ZGate
from qiskit.tools.jupyter.library import _generate_circuit_library_visualization
circuit = MCMTVChain(ZGate(), 2, 2)
_generate_circuit_library_visualization(circuit.decompose())
**Examples:**
>>> from qiskit.circuit.library import HGate
>>> MCMTVChain(HGate(), 3, 2).draw()
q_0: ──■────────────────────────■──
│ │
q_1: ──■────────────────────────■──
│ │
q_2: ──┼────■──────────────■────┼──
│ │ ┌───┐ │ │
q_3: ──┼────┼──┤ H ├───────┼────┼──
│ │ └─┬─┘┌───┐ │ │
q_4: ──┼────┼────┼──┤ H ├──┼────┼──
┌─┴─┐ │ │ └─┬─┘ │ ┌─┴─┐
q_5: ┤ X ├──■────┼────┼────■──┤ X ├
└───┘┌─┴─┐ │ │ ┌─┴─┐└───┘
q_6: ─────┤ X ├──■────■──┤ X ├─────
└───┘ └───┘
"""
def _build(self):
"""Define the MCMT gate."""
control_qubits = self.qubits[: self.num_ctrl_qubits]
target_qubits = self.qubits[
self.num_ctrl_qubits : self.num_ctrl_qubits + self.num_target_qubits
]
ancilla_qubits = self.qubits[self.num_ctrl_qubits + self.num_target_qubits :]
if len(ancilla_qubits) > 0:
master_control = ancilla_qubits[-1]
else:
master_control = control_qubits[0]
self._ccx_v_chain_rule(control_qubits, ancilla_qubits, reverse=False)
for qubit in target_qubits:
self.append(self.gate.control(), [master_control, qubit], [])
self._ccx_v_chain_rule(control_qubits, ancilla_qubits, reverse=True)
@property
def num_ancilla_qubits(self):
"""Return the number of ancilla qubits required."""
return max(0, self.num_ctrl_qubits - 1)
def _ccx_v_chain_rule(
self,
control_qubits: QuantumRegister | list[Qubit],
ancilla_qubits: QuantumRegister | list[Qubit],
reverse: bool = False,
) -> None:
"""Get the rule for the CCX V-chain.
The CCX V-chain progressively computes the CCX of the control qubits and puts the final
result in the last ancillary qubit.
Args:
control_qubits: The control qubits.
ancilla_qubits: The ancilla qubits.
reverse: If True, compute the chain down to the qubit. If False, compute upwards.
Returns:
The rule for the (reversed) CCX V-chain.
Raises:
QiskitError: If an insufficient number of ancilla qubits was provided.
"""
if len(ancilla_qubits) == 0:
return
if len(ancilla_qubits) < len(control_qubits) - 1:
raise QiskitError("Insufficient number of ancilla qubits.")
iterations = list(enumerate(range(2, len(control_qubits))))
if not reverse:
self.ccx(control_qubits[0], control_qubits[1], ancilla_qubits[0])
for i, j in iterations:
self.ccx(control_qubits[j], ancilla_qubits[i], ancilla_qubits[i + 1])
else:
for i, j in reversed(iterations):
self.ccx(control_qubits[j], ancilla_qubits[i], ancilla_qubits[i + 1])
self.ccx(control_qubits[0], control_qubits[1], ancilla_qubits[0])
def inverse(self):
return MCMTVChain(self.gate, self.num_ctrl_qubits, self.num_target_qubits)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can set a color for all the bars.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
|
https://github.com/drobiu/quantum-project
|
drobiu
|
"""Example usage of the Quantum Inspire backend with the Qiskit SDK.
A simple example that demonstrates how to use the SDK to create
a circuit to demonstrate conditional gate execution.
For documentation on how to use Qiskit we refer to
[https://qiskit.org/](https://qiskit.org/).
Specific to Quantum Inspire is the creation of the QI instance, which is used to set the authentication
of the user and provides a Quantum Inspire backend that is used to execute the circuit.
Copyright 2018-19 QuTech Delft. Licensed under the Apache License, Version 2.0.
"""
import os
from qiskit import BasicAer, execute
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from coreapi.auth import BasicAuthentication
from quantuminspire.credentials import get_authentication
from quantuminspire.qiskit import QI
QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/')
email='ray.mao1999@hotmail.com'
password='Mm19991202.QUANTUM'
authentication = BasicAuthentication(email,password)
QI.set_authentication(authentication, QI_URL)
qi_backend = QI.get_backend('QX single-node simulator')
q = QuantumRegister(2, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
qc = QuantumCircuit(3, name="conditional")
qc.h([0, 2])
qc.cnot(q[0], q[1])
qc.measure_all()
qi_job = execute(qc, backend=qi_backend, shots=1024)
qi_result = qi_job.result()
histogram = qi_result.get_counts(qc)
print("\nResult from the remote Quantum Inspire backend:\n")
print('State\tCounts')
[print('{0}\t{1}'.format(state, counts)) for state, counts in histogram.items()]
print("\nResult from the local Qiskit simulator backend:\n")
backend = BasicAer.get_backend("qasm_simulator")
job = execute(qc, backend=backend, shots=1024)
result = job.result()
print(result.get_counts(qc))
qc.draw(output="latex")
|
https://github.com/Simultonian/hamilutor-qiskit
|
Simultonian
|
from math import sqrt, pi
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import oracle_simple
import composed_gates
def get_circuit(n, oracles):
"""
Build the circuit composed by the oracle black box and the other quantum gates.
:param n: The number of qubits (not including the ancillas)
:param oracles: A list of black box (quantum) oracles; each of them selects a specific state
:returns: The proper quantum circuit
:rtype: qiskit.QuantumCircuit
"""
cr = ClassicalRegister(n)
## Testing
if n > 3:
#anc = QuantumRegister(n - 1, 'anc')
# n qubits for the real number
# n - 1 qubits for the ancillas
qr = QuantumRegister(n + n - 1)
qc = QuantumCircuit(qr, cr)
else:
# We don't need ancillas
qr = QuantumRegister(n)
qc = QuantumCircuit(qr, cr)
## /Testing
print("Number of qubits is {0}".format(len(qr)))
print(qr)
# Initial superposition
for j in range(n):
qc.h(qr[j])
# The length of the oracles list, or, in other words, how many roots of the function do we have
m = len(oracles)
# Grover's algorithm is a repetition of an oracle box and a diffusion box.
# The number of repetitions is given by the following formula.
print("n is ", n)
r = int(round((pi / 2 * sqrt((2**n) / m) - 1) / 2))
print("Repetition of ORACLE+DIFFUSION boxes required: {0}".format(r))
oracle_t1 = oracle_simple.OracleSimple(n, 5)
oracle_t2 = oracle_simple.OracleSimple(n, 0)
for j in range(r):
for i in range(len(oracles)):
oracles[i].get_circuit(qr, qc)
diffusion(n, qr, qc)
for j in range(n):
qc.measure(qr[j], cr[j])
return qc, len(qr)
def diffusion(n, qr, qc):
"""
The Grover diffusion operator.
Given the arry of qiskit QuantumRegister qr and the qiskit QuantumCircuit qc, it adds the diffusion operator to the appropriate qubits in the circuit.
"""
for j in range(n):
qc.h(qr[j])
# D matrix, flips state |000> only (instead of flipping all the others)
for j in range(n):
qc.x(qr[j])
# 0..n-2 control bits, n-1 target, n..
if n > 3:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1],
[qr[j] for j in range(n, n + n - 1)])
else:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1], None)
for j in range(n):
qc.x(qr[j])
for j in range(n):
qc.h(qr[j])
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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.
"Circuit operation representing a ``for`` loop."
import warnings
from typing import Iterable, Optional, Union
from qiskit.circuit.parameter import Parameter
from qiskit.circuit.exceptions import CircuitError
from qiskit.circuit.quantumcircuit import QuantumCircuit
from .control_flow import ControlFlowOp
class ForLoopOp(ControlFlowOp):
"""A circuit operation which repeatedly executes a subcircuit
(``body``) parameterized by a parameter ``loop_parameter`` through
the set of integer values provided in ``indexset``.
Parameters:
indexset: A collection of integers to loop over.
loop_parameter: The placeholder parameterizing ``body`` to which
the values from ``indexset`` will be assigned.
body: The loop body to be repeatedly executed.
label: An optional label for identifying the instruction.
**Circuit symbol:**
.. parsed-literal::
┌───────────┐
q_0: ┤0 ├
│ │
q_1: ┤1 ├
│ for_loop │
q_2: ┤2 ├
│ │
c_0: ╡0 ╞
└───────────┘
"""
def __init__(
self,
indexset: Iterable[int],
loop_parameter: Union[Parameter, None],
body: QuantumCircuit,
label: Optional[str] = None,
):
num_qubits = body.num_qubits
num_clbits = body.num_clbits
super().__init__(
"for_loop", num_qubits, num_clbits, [indexset, loop_parameter, body], label=label
)
@property
def params(self):
return self._params
@params.setter
def params(self, parameters):
indexset, loop_parameter, body = parameters
if not isinstance(loop_parameter, (Parameter, type(None))):
raise CircuitError(
"ForLoopOp expects a loop_parameter parameter to "
"be either of type Parameter or None, but received "
f"{type(loop_parameter)}."
)
if not isinstance(body, QuantumCircuit):
raise CircuitError(
"ForLoopOp expects a body parameter to be of type "
f"QuantumCircuit, but received {type(body)}."
)
if body.num_qubits != self.num_qubits or body.num_clbits != self.num_clbits:
raise CircuitError(
"Attempted to assign a body parameter with a num_qubits or "
"num_clbits different than that of the ForLoopOp. "
f"ForLoopOp num_qubits/clbits: {self.num_qubits}/{self.num_clbits} "
f"Supplied body num_qubits/clbits: {body.num_qubits}/{body.num_clbits}."
)
if (
loop_parameter is not None
and loop_parameter not in body.parameters
and loop_parameter.name in (p.name for p in body.parameters)
):
warnings.warn(
"The Parameter provided as a loop_parameter was not found "
"on the loop body and so no binding of the indexset to loop "
"parameter will occur. A different Parameter of the same name "
f"({loop_parameter.name}) was found. If you intended to loop "
"over that Parameter, please use that Parameter instance as "
"the loop_parameter.",
stacklevel=2,
)
# Consume indexset into a tuple unless it was provided as a range.
# Preserve ranges so that they can be exported as OpenQASM3 ranges.
indexset = indexset if isinstance(indexset, range) else tuple(indexset)
self._params = [indexset, loop_parameter, body]
@property
def blocks(self):
return (self._params[2],)
def replace_blocks(self, blocks):
(body,) = blocks
return ForLoopOp(self.params[0], self.params[1], body, label=self.label)
class ForLoopContext:
"""A context manager for building up ``for`` loops onto circuits in a natural order, without
having to construct the loop body first.
Within the block, a lot of the bookkeeping is done for you; you do not need to keep track of
which qubits and clbits you are using, for example, and a loop parameter will be allocated for
you, if you do not supply one yourself. All normal methods of accessing the qubits on the
underlying :obj:`~QuantumCircuit` will work correctly, and resolve into correct accesses within
the interior block.
You generally should never need to instantiate this object directly. Instead, use
:obj:`.QuantumCircuit.for_loop` in its context-manager form, i.e. by not supplying a ``body`` or
sets of qubits and clbits.
Example usage::
import math
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 1)
with qc.for_loop(range(5)) as i:
qc.rx(i * math.pi/4, 0)
qc.cx(0, 1)
qc.measure(0, 0)
qc.break_loop().c_if(0, True)
This context should almost invariably be created by a :meth:`.QuantumCircuit.for_loop` call, and
the resulting instance is a "friend" of the calling circuit. The context will manipulate the
circuit's defined scopes when it is entered (by pushing a new scope onto the stack) and exited
(by popping its scope, building it, and appending the resulting :obj:`.ForLoopOp`).
.. warning::
This is an internal interface and no part of it should be relied upon outside of Qiskit
Terra.
"""
# Class-level variable keep track of the number of auto-generated loop variables, so we don't
# get naming clashes.
_generated_loop_parameters = 0
__slots__ = (
"_circuit",
"_generate_loop_parameter",
"_loop_parameter",
"_indexset",
"_label",
"_used",
)
def __init__(
self,
circuit: QuantumCircuit,
indexset: Iterable[int],
loop_parameter: Optional[Parameter] = None,
*,
label: Optional[str] = None,
):
self._circuit = circuit
self._generate_loop_parameter = loop_parameter is None
self._loop_parameter = loop_parameter
# We can pass through `range` instances because OpenQASM 3 has native support for this type
# of iterator set.
self._indexset = indexset if isinstance(indexset, range) else tuple(indexset)
self._label = label
self._used = False
def __enter__(self):
if self._used:
raise CircuitError("A for-loop context manager cannot be re-entered.")
self._used = True
self._circuit._push_scope()
if self._generate_loop_parameter:
self._loop_parameter = Parameter(f"_loop_i_{self._generated_loop_parameters}")
type(self)._generated_loop_parameters += 1
return self._loop_parameter
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
# If we're leaving the context manager because an exception was raised, there's nothing
# to do except restore the circuit state.
self._circuit._pop_scope()
return False
scope = self._circuit._pop_scope()
# Loops do not need to pass any further resources in, because this scope itself defines the
# extent of ``break`` and ``continue`` statements.
body = scope.build(scope.qubits, scope.clbits)
# We always bind the loop parameter if the user gave it to us, even if it isn't actually
# used, because they requested we do that by giving us a parameter. However, if they asked
# us to auto-generate a parameter, then we only add it if they actually used it, to avoid
# using unnecessary resources.
if self._generate_loop_parameter and self._loop_parameter not in body.parameters:
loop_parameter = None
else:
loop_parameter = self._loop_parameter
self._circuit.append(
ForLoopOp(self._indexset, loop_parameter, body, label=self._label),
tuple(body.qubits),
tuple(body.clbits),
)
return False
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
state = Statevector(qc)
plot_bloch_multivector(state)
|
https://github.com/abhik-99/Qiskit-Summer-School
|
abhik-99
|
#!/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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.optimizers import SLSQP
from qiskit.circuit.library import TwoLocal
num_qubits = 2
ansatz = TwoLocal(num_qubits, "ry", "cz")
optimizer = SLSQP(maxiter=1000)
ansatz.decompose().draw("mpl", style="iqx")
from qiskit.primitives import Estimator
estimator = Estimator()
from qiskit.algorithms.minimum_eigensolvers import VQE
vqe = VQE(estimator, ansatz, optimizer)
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list([
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156)
])
result = vqe.compute_minimum_eigenvalue(H2_op)
print(result)
from qiskit.algorithms.optimizers import SPSA
estimator = Estimator(options={"shots": 1000})
vqe.estimator = estimator
vqe.optimizer = SPSA(maxiter=100)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/DarrenNA/Bernstein-Vazirani_Algorithm_function
|
DarrenNA
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
secretnumber = '11100011'
circuit = QuantumCircuit(len(secretnumber)+1,len(secretnumber))
circuit.h(range(len(secretnumber)))
circuit.x(len(secretnumber))
circuit.h(len(secretnumber))
circuit.barrier()
for ii, yesno in enumerate(reversed(secretnumber)):
if yesno == '1':
circuit.cx(ii,len(secretnumber))
circuit.barrier()
circuit.h(range(len(secretnumber)))
circuit.barrier()
circuit.measure(range(len(secretnumber)),range(len(secretnumber)))
circuit.draw(output = 'mpl')
|
https://github.com/JohnBurke4/qaoa_testing_framework
|
JohnBurke4
|
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
class Mixer:
circuit = {}
def __init__(self, numQubits, layers=1, mixerType='classic'):
self.numQubits = numQubits
self.mixerType = mixerType
self.layers = layers
def build(self):
self.circuit = {}
for l in range(0, self.layers):
if (self.mixerType == 'rx_mixer'):
circuitDetails = self.__buildClassic(l)
self.circuit[l] = circuitDetails
elif (self.mixerType == "ma_rx_mixer"):
circuitDetails = self.__buildMAClassic(l)
self.circuit[l] = circuitDetails
elif (self.mixerType == "ry_mixer"):
circuitDetails = self.__buildRYMixer(l)
self.circuit[l] = circuitDetails
elif (self.mixerType == "ma_ry_mixer"):
circuitDetails = self.__buildMARYMixer(l)
self.circuit[l] = circuitDetails
elif (self.mixerType == "rz_mixer"):
circuitDetails = self.__buildRZMixer(l)
self.circuit[l] = circuitDetails
elif (self.mixerType == "ma_rz_mixer"):
circuitDetails = self.__buildMARZMixer(l)
self.circuit[l] = circuitDetails
elif (self.mixerType == "none"):
circuitDetails = self.__buildNoCircuit()
self.circuit[l] = circuitDetails
return True
def getCircuitAtLayer(self, l):
return self.circuit[l]
def getAllCircuits(self):
return self.circuit
def __buildClassic(self, l):
theta = Parameter('mix_cl_' + str(l))
qc = QuantumCircuit(self.numQubits)
for qubit in range(0, self.numQubits):
qc.rx(theta, qubit)
return (qc, [theta])
def __buildMAClassic(self, l):
theta = [Parameter('mix_cl_' + str(l) + "_" + str(i)) for i in range(0, self.numQubits)]
qc = QuantumCircuit(self.numQubits)
for qubit in range(0, self.numQubits):
qc.rx(theta[qubit], qubit)
return (qc, theta)
def __buildRYMixer(self, l):
theta = Parameter('mix_cl_' + str(l))
qc = QuantumCircuit(self.numQubits)
for qubit in range(0, self.numQubits):
qc.ry(theta, qubit)
return (qc, [theta])
def __buildMARYMixer(self, l):
theta = [Parameter('mix_cl_' + str(l) + "_" + str(i)) for i in range(0, self.numQubits)]
qc = QuantumCircuit(self.numQubits)
for qubit in range(0, self.numQubits):
qc.ry(theta[qubit], qubit)
return (qc, theta)
def __buildRZMixer(self, l):
theta = Parameter('mix_cl_' + str(l))
qc = QuantumCircuit(self.numQubits)
for qubit in range(0, self.numQubits):
qc.rz(theta, qubit)
return (qc, [theta])
def __buildMARZMixer(self, l):
theta = [Parameter('mix_cl_' + str(l) + "_" + str(i)) for i in range(0, self.numQubits)]
qc = QuantumCircuit(self.numQubits)
for qubit in range(0, self.numQubits):
qc.rz(theta[qubit], qubit)
return (qc, theta)
def __buildNoCircuit(self):
qc = QuantumCircuit(self.numQubits)
return (qc, [])
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, plot_bloch_vector, plot_histogram
from qiskit.compiler import transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.providers.ibmq import least_busy
import matplotlib
import numpy as np
%pylab inline
qc = QuantumCircuit(4,3)
qc.x(3)
qc.h(range(3))
reps = 1
for count in range(3):
for i in range (reps):
qc.cp(pi/4, count, 3)
reps *= 2
qc.barrier()
qc.draw('mpl')
def inv_qft(qc, n):
for qubit in range (n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-pi/(2*(j-m)), m, j)
qc.h(j)
inv_qft(qc, 3)
qc.barrier()
qc.measure(range(3), range(3))
qc.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
shots = 1
qobj = assemble(qc, qasm_sim)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 4 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
shots = 1024
transpiled_circuit = transpile(qc, backend)
qobj = assemble(transpiled_circuit, shots=shots)
job = backend.run(qobj)
job_monitor(job, interval=2)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
# Benchmark qiskit_alt transforming an operator from the computational- to the Pauli basis.
import qiskit_alt
qiskit_alt.project.ensure_init()
import timeit
Main = qiskit_alt.project.julia.Main
def make_setup_code(nqubits):
return f"""
import qiskit_alt
from qiskit_alt.pauli_operators import PauliSum_to_SparsePauliOp
QuantumOps = qiskit_alt.project.simple_import("QuantumOps")
import numpy as np
Main = qiskit_alt.project.julia.Main
m = np.random.rand(2**{nqubits}, 2**{nqubits})
"""
def run_one(nqubits, num_repetitions):
setup_code = make_setup_code(nqubits)
if qiskit_alt.project._calljulia_name == 'juliacall':
bench_code = "PauliSum_to_SparsePauliOp(QuantumOps.PauliSum(Main.convert(Main.Matrix, m)))"
else:
bench_code = "PauliSum_to_SparsePauliOp(QuantumOps.PauliSum(m))"
time = timeit.timeit(stmt=bench_code, setup=setup_code, number=num_repetitions)
t = 1000 * time / num_repetitions
print(f"nqubits={nqubits}, {t:0.2f}", "ms")
return t
def run_benchmarks():
qk_alt_times = []
for nqubits, num_repetitions in ((2, 50), (3, 50), (4, 10), (5, 10), (6, 10),
(7, 10),
(8, 3)):
t = run_one(nqubits, num_repetitions)
qk_alt_times.append(t)
return qk_alt_times
if __name__ == '__main__':
qk_alt_times = run_benchmarks()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import json
import time
import warnings
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import Statevector
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.circuit.library import RawFeatureVector
from qiskit_machine_learning.neural_networks import SamplerQNN
algorithm_globals.random_seed = 42
def ansatz(num_qubits):
return RealAmplitudes(num_qubits, reps=5)
num_qubits = 5
circ = ansatz(num_qubits)
circ.decompose().draw("mpl")
def auto_encoder_circuit(num_latent, num_trash):
qr = QuantumRegister(num_latent + 2 * num_trash + 1, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.compose(ansatz(num_latent + num_trash), range(0, num_latent + num_trash), inplace=True)
circuit.barrier()
auxiliary_qubit = num_latent + 2 * num_trash
# swap test
circuit.h(auxiliary_qubit)
for i in range(num_trash):
circuit.cswap(auxiliary_qubit, num_latent + i, num_latent + num_trash + i)
circuit.h(auxiliary_qubit)
circuit.measure(auxiliary_qubit, cr[0])
return circuit
num_latent = 3
num_trash = 2
circuit = auto_encoder_circuit(num_latent, num_trash)
circuit.draw("mpl")
def domain_wall(circuit, a, b):
# Here we place the Domain Wall to qubits a - b in our circuit
for i in np.arange(int(b / 2), int(b)):
circuit.x(i)
return circuit
domain_wall_circuit = domain_wall(QuantumCircuit(5), 0, 5)
domain_wall_circuit.draw("mpl")
ae = auto_encoder_circuit(num_latent, num_trash)
qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1)
qc = qc.compose(domain_wall_circuit, range(num_latent + num_trash))
qc = qc.compose(ae)
qc.draw("mpl")
# Here we define our interpret for our SamplerQNN
def identity_interpret(x):
return x
qnn = SamplerQNN(
circuit=qc,
input_params=[],
weight_params=ae.parameters,
interpret=identity_interpret,
output_shape=2,
)
def cost_func_domain(params_values):
probabilities = qnn.forward([], params_values)
# we pick a probability of getting 1 as the output of the network
cost = np.sum(probabilities[:, 1])
# plotting part
clear_output(wait=True)
objective_func_vals.append(cost)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
return cost
opt = COBYLA(maxiter=150)
initial_point = algorithm_globals.random.random(ae.num_parameters)
objective_func_vals = []
# make the plot nicer
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
opt_result = opt.minimize(cost_func_domain, initial_point)
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} seconds")
test_qc = QuantumCircuit(num_latent + num_trash)
test_qc = test_qc.compose(domain_wall_circuit)
ansatz_qc = ansatz(num_latent + num_trash)
test_qc = test_qc.compose(ansatz_qc)
test_qc.barrier()
test_qc.reset(4)
test_qc.reset(3)
test_qc.barrier()
test_qc = test_qc.compose(ansatz_qc.inverse())
test_qc.draw("mpl")
test_qc = test_qc.assign_parameters(opt_result.x)
domain_wall_state = Statevector(domain_wall_circuit).data
output_state = Statevector(test_qc).data
fidelity = np.sqrt(np.dot(domain_wall_state.conj(), output_state) ** 2)
print("Fidelity of our Output State with our Input State: ", fidelity.real)
def zero_idx(j, i):
# Index for zero pixels
return [
[i, j],
[i - 1, j - 1],
[i - 1, j + 1],
[i - 2, j - 1],
[i - 2, j + 1],
[i - 3, j - 1],
[i - 3, j + 1],
[i - 4, j - 1],
[i - 4, j + 1],
[i - 5, j],
]
def one_idx(i, j):
# Index for one pixels
return [[i, j - 1], [i, j - 2], [i, j - 3], [i, j - 4], [i, j - 5], [i - 1, j - 4], [i, j]]
def get_dataset_digits(num, draw=True):
# Create Dataset containing zero and one
train_images = []
train_labels = []
for i in range(int(num / 2)):
# First we introduce background noise
empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape(
8, 4
)
# Now we insert the pixels for the one
for i, j in one_idx(2, 6):
empty[j][i] = algorithm_globals.random.uniform(0.9, 1)
train_images.append(empty)
train_labels.append(1)
if draw:
plt.title("This is a One")
plt.imshow(train_images[-1])
plt.show()
for i in range(int(num / 2)):
empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape(
8, 4
)
# Now we insert the pixels for the zero
for k, j in zero_idx(2, 6):
empty[k][j] = algorithm_globals.random.uniform(0.9, 1)
train_images.append(empty)
train_labels.append(0)
if draw:
plt.imshow(train_images[-1])
plt.title("This is a Zero")
plt.show()
train_images = np.array(train_images)
train_images = train_images.reshape(len(train_images), 32)
for i in range(len(train_images)):
sum_sq = np.sum(train_images[i] ** 2)
train_images[i] = train_images[i] / np.sqrt(sum_sq)
return train_images, train_labels
train_images, __ = get_dataset_digits(2)
num_latent = 3
num_trash = 2
fm = RawFeatureVector(2 ** (num_latent + num_trash))
ae = auto_encoder_circuit(num_latent, num_trash)
qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1)
qc = qc.compose(fm, range(num_latent + num_trash))
qc = qc.compose(ae)
qc.draw("mpl")
def identity_interpret(x):
return x
qnn = SamplerQNN(
circuit=qc,
input_params=fm.parameters,
weight_params=ae.parameters,
interpret=identity_interpret,
output_shape=2,
)
def cost_func_digits(params_values):
probabilities = qnn.forward(train_images, params_values)
cost = np.sum(probabilities[:, 1]) / train_images.shape[0]
# plotting part
clear_output(wait=True)
objective_func_vals.append(cost)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
return cost
with open("12_qae_initial_point.json", "r") as f:
initial_point = json.load(f)
opt = COBYLA(maxiter=150)
objective_func_vals = []
# make the plot nicer
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
opt_result = opt.minimize(fun=cost_func_digits, x0=initial_point)
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} seconds")
# Test
test_qc = QuantumCircuit(num_latent + num_trash)
test_qc = test_qc.compose(fm)
ansatz_qc = ansatz(num_latent + num_trash)
test_qc = test_qc.compose(ansatz_qc)
test_qc.barrier()
test_qc.reset(4)
test_qc.reset(3)
test_qc.barrier()
test_qc = test_qc.compose(ansatz_qc.inverse())
# sample new images
test_images, test_labels = get_dataset_digits(2, draw=False)
for image, label in zip(test_images, test_labels):
original_qc = fm.assign_parameters(image)
original_sv = Statevector(original_qc).data
original_sv = np.reshape(np.abs(original_sv) ** 2, (8, 4))
param_values = np.concatenate((image, opt_result.x))
output_qc = test_qc.assign_parameters(param_values)
output_sv = Statevector(output_qc).data
output_sv = np.reshape(np.abs(output_sv) ** 2, (8, 4))
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(original_sv)
ax1.set_title("Input Data")
ax2.imshow(output_sv)
ax2.set_title("Output Data")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/AmirhoseynpowAsghari/Qiskit-Tutorials
|
AmirhoseynpowAsghari
|
import matplotlib.pyplot as plt
import numpy as np
# Define N values
N = np.arange(1, 1001)
# Calculate logarithm of N base 2
log2_N = np.log2(N)
# Generate plot
plt.figure(figsize=(8, 6))
plt.plot(N, log2_N, label="log2(N)")
plt.xlabel("N")
plt.ylabel("n = log2(N)") # number of qubits
plt.title("Logarithm of N (base 2) for N = 1 to 1000")
plt.grid(True)
plt.legend()
plt.show()
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector
import numpy as np
import matplotlib.pyplot as plt
def state_preparation_circuit(x):
"""
Create a state preparation circuit for encoding the classical data point x.
"""
n = len(x)
qc = QuantumCircuit(n)
for i, xi in enumerate(x):
angle = 2 * np.arctan(xi) # Convert the feature xi to an angle for rotation
qc.ry(angle, i) # Apply Ry rotation to the i-th qubit
return qc
# Example classical data point
x = [0.1, 0.5, 0.3]
# Create the state preparation circuit
qc = state_preparation_circuit(x)
# Visualize the circuit
qc.draw('mpl')
# Use the Aer simulator to simulate the quantum state
simulator = Aer.get_backend('statevector_simulator')
# Transpile and assemble the quantum circuit
transpiled_qc = transpile(qc, simulator)
qobj = assemble(transpiled_qc)
# Execute the circuit on the statevector simulator
result = simulator.run(qobj).result()
# Get the statevector representing the quantum state
statevector = result.get_statevector()
# Plot the Bloch sphere representation of the quantum state
plot_bloch_multivector(statevector)
# Print the statevector to see the quantum state
print("Statevector representing the quantum state:")
print(statevector)
# Define the dense angle encoding circuit for multiple features
def dense_angle_encoding_circuit(x):
"""
Create a quantum circuit to encode a feature vector x
using dense angle encoding.
"""
num_qubits = len(x) // 2
qc = QuantumCircuit(num_qubits)
for i in range(0, len(x), 2):
amplitude_angle = np.pi * x[i]
phase_angle = 2 * np.pi * x[i+1]
qc.ry(2 * amplitude_angle, i//2)
qc.rz(phase_angle, i//2)
return qc
# Example feature vector with 8 features
x = [0.3, 0.7, 0.5, 0.9, 0.2, 0.4, 0.8, 0.6]
# Create the dense angle encoding circuit
qc = dense_angle_encoding_circuit(x)
# Visualize the circuit
qc.draw('mpl')
# Use the Aer simulator to simulate the quantum state
simulator = Aer.get_backend('statevector_simulator')
# Transpile and assemble the quantum circuit
transpiled_qc = transpile(qc, simulator)
qobj = assemble(transpiled_qc)
# Execute the circuit on the statevector simulator
result = simulator.run(qobj).result()
# Get the statevector representing the quantum state
statevector = result.get_statevector()
# Plot the Bloch sphere representation of the quantum state
plot_bloch_multivector(statevector)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# transpile_parallel.py
from qiskit import QuantumCircuit
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_transpiler_service.transpiler_service import TranspilerService
from qiskit_serverless import get_arguments, save_result, distribute_task, get
from qiskit_ibm_runtime import QiskitRuntimeService
from timeit import default_timer as timer
@distribute_task(target={"cpu": 2})
def transpile_parallel(circuit: QuantumCircuit, config):
"""Distributed transpilation for an abstract circuit into an ISA circuit for a given backend."""
transpiled_circuit = config.run(circuit)
return transpiled_circuit
# Get program arguments
arguments = get_arguments()
circuits = arguments.get("circuits")
backend_name = arguments.get("backend_name")
# Get backend
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.get_backend(backend_name)
# Define Configs
optimization_levels = [1,2,3]
pass_managers = [generate_preset_pass_manager(optimization_level=level, backend=backend) for level in optimization_levels]
transpiler_services = [
{'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': False, 'optimization_level': 3},
{'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': True, 'optimization_level': 3}
]
configs = pass_managers + transpiler_services
# Start process
print("Starting timer")
start = timer()
# run distributed tasks as async function
# we get task references as a return type
sample_task_references = []
for circuit in circuits:
sample_task_references.append([transpile_parallel(circuit, config) for config in configs])
# now we need to collect results from task references
results = get([task for subtasks in sample_task_references for task in subtasks])
end = timer()
# Record execution time
execution_time_serverless = end-start
print("Execution time: ", execution_time_serverless)
save_result({
"transpiled_circuits": results,
"execution_time" : execution_time_serverless
})
|
https://github.com/KMU-quantum-classroom/qiskit-classroom-converter
|
KMU-quantum-classroom
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# pylint: disable=duplicate-code
"""
converter service class
"""
import unittest
from qiskit import QuantumCircuit
from qiskit_class_converter import ConversionService, ConversionType
from qiskit_class_converter.converters.matrix_to_quantum_circuit \
import MatrixToQuantumCircuitConverter
class TestConverterServiceClass(unittest.TestCase):
"""Tests Service Impl class implementation."""
def test_str_to_bra_ket_service(self):
"""Tests run Service method implementation."""
input_value = "|1>"
system = ConversionService(conversion_type="STR_TO_BRA_KET")
result = system.convert(input_value=input_value)
self.assertIsNotNone(result)
def test_matrix_to_quantum_circuit_service(self):
"""Tests run Service method implementation."""
input_value = [
[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0]
]
system = ConversionService(conversion_type="MATRIX_TO_QC")
result = system.convert(input_value=input_value)
self.assertIsNotNone(result)
def test_quantum_circuit_to_bra_ket_service(self):
"""Tests run Service method implementation."""
quantum_circuit = QuantumCircuit(2, 2)
quantum_circuit.h(0)
quantum_circuit.x(0)
quantum_circuit.cx(0, 1)
system = ConversionService(conversion_type="QC_TO_BRA_KET")
result = system.convert(input_value=quantum_circuit)
self.assertEqual(result, "(sqrt(2)/2)*|0> + (sqrt(2)/2)*|11>")
def test_quantum_circuit_to_raw_bra_ket_service(self):
"""Tests run Service method implementation."""
quantum_circuit = QuantumCircuit(2, 2)
quantum_circuit.h(0)
quantum_circuit.x(0)
quantum_circuit.cx(0, 1)
system = ConversionService(conversion_type="QC_TO_BRA_KET", option={"print": "raw"})
result = system.convert(input_value=quantum_circuit)
self.assertEqual(result, r"\frac{\sqrt{2}}{2} |00\rangle+\frac{\sqrt{2}}{2} |11\rangle")
def test_quantum_circuit_to_simplify_bra_ket_service(self):
"""Tests run Service method implementation."""
quantum_circuit = QuantumCircuit(2, 2)
quantum_circuit.h(0)
quantum_circuit.x(0)
quantum_circuit.cx(0, 1)
system = ConversionService(conversion_type="QC_TO_BRA_KET",
option={"expression": "simplify"})
result = system.convert(input_value=quantum_circuit)
self.assertEqual(result, "sqrt(2)*(|0> + |11>)/2")
def test_quantum_circuit_to_expand_bra_ket_service(self):
"""Tests run Service method implementation."""
quantum_circuit = QuantumCircuit(2, 2)
quantum_circuit.h(0)
quantum_circuit.x(0)
quantum_circuit.cx(0, 1)
system = ConversionService(conversion_type="QC_TO_BRA_KET",
option={"expression": "expand"})
result = system.convert(input_value=quantum_circuit)
self.assertEqual(result, "sqrt(2)*|0>/2 + sqrt(2)*|11>/2")
def test_quantum_circuit_to_simplify_raw_bra_ket_service(self):
"""Tests run Service method implementation."""
quantum_circuit = QuantumCircuit(2, 2)
quantum_circuit.h(0)
quantum_circuit.x(0)
quantum_circuit.cx(0, 1)
system = ConversionService(conversion_type="QC_TO_BRA_KET",
option={"expression": "simplify", "print": "raw"})
result = system.convert(input_value=quantum_circuit)
self.assertEqual(result, r"\frac{\sqrt{2} \left({\left|0\right\rangle } + "
r"{\left|11\right\rangle }\right)}{2}")
def test_quantum_circuit_to_expand_raw_bra_ket_service(self):
"""Tests run Service method implementation."""
quantum_circuit = QuantumCircuit(2, 2)
quantum_circuit.h(0)
quantum_circuit.x(0)
quantum_circuit.cx(0, 1)
system = ConversionService(conversion_type="QC_TO_BRA_KET",
option={"expression": "expand", "print": "raw"})
result = system.convert(input_value=quantum_circuit)
self.assertEqual(result, r"\frac{\sqrt{2} {\left|0\right\rangle }}{2} + "
r"\frac{\sqrt{2} {\left|11\right\rangle }}{2}")
def test_quantum_circuit_to_matrix_service(self):
"""Tests run Service method implementation."""
quantum_circuit = QuantumCircuit(2)
quantum_circuit.cx(0, 1)
system = ConversionService(conversion_type="QC_TO_MATRIX")
result = system.convert(input_value=quantum_circuit)
self.assertIsNotNone(result)
def test_conversion_type(self):
"""Tests run Service Type implementation."""
self.assertEqual(ConversionType.MATRIX_TO_QC.value, MatrixToQuantumCircuitConverter)
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from qiskit import *
import numpy as np
from numpy import linalg as la
from qiskit.tools.monitor import job_monitor
import qiskit.tools.jupyter
qc = QuantumCircuit(1)
#### your code goes here
# z measurement of qubit 0
measure_z = QuantumCircuit(1,1)
measure_z.measure(0,0)
# x measurement of qubit 0
measure_x = QuantumCircuit(1,1)
# your code goes here
# y measurement of qubit 0
measure_y = QuantumCircuit(1,1)
# your code goes here
shots = 2**14 # number of samples used for statistics
sim = Aer.get_backend('qasm_simulator')
bloch_vector_measure = []
for measure_circuit in [measure_x, measure_y, measure_z]:
# run the circuit with a the selected measurement and get the number of samples that output each bit value
counts = execute(qc+measure_circuit, sim, shots=shots).result().get_counts()
# calculate the probabilities for each bit value
probs = {}
for output in ['0','1']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
bloch_vector_measure.append( probs['0'] - probs['1'] )
# normalizing the bloch sphere vector
bloch_vector = bloch_vector_measure/la.norm(bloch_vector_measure)
print('The bloch sphere coordinates are [{0:4.3f}, {1:4.3f}, {2:4.3f}]'
.format(*bloch_vector))
from kaleidoscope.interactive import bloch_sphere
bloch_sphere(bloch_vector, vectors_annotation=True)
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector( bloch_vector )
# circuit for the state Tri1
Tri1 = QuantumCircuit(2)
# your code goes here
# circuit for the state Tri2
Tri2 = QuantumCircuit(2)
# your code goes here
# circuit for the state Tri3
Tri3 = QuantumCircuit(2)
# your code goes here
# circuit for the state Sing
Sing = QuantumCircuit(2)
# your code goes here
# <ZZ>
measure_ZZ = QuantumCircuit(2)
measure_ZZ.measure_all()
# <XX>
measure_XX = QuantumCircuit(2)
# your code goes here
# <YY>
measure_YY = QuantumCircuit(2)
# your code goes here
shots = 2**14 # number of samples used for statistics
A = 1.47e-6 #unit of A is eV
E_sim = []
for state_init in [Tri1,Tri2,Tri3,Sing]:
Energy_meas = []
for measure_circuit in [measure_XX, measure_YY, measure_ZZ]:
# run the circuit with a the selected measurement and get the number of samples that output each bit value
qc = state_init+measure_circuit
counts = execute(qc, sim, shots=shots).result().get_counts()
# calculate the probabilities for each computational basis
probs = {}
for output in ['00','01', '10', '11']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] )
E_sim.append(A * np.sum(np.array(Energy_meas)))
# Run this cell to print out your results
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_sim[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_sim[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_sim[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E_sim[3]))
# reduced plank constant in (eV) and the speed of light(cgs units)
hbar, c = 4.1357e-15, 3e10
# energy difference between the triplets and singlet
E_del = abs(E_sim[0] - E_sim[3])
# frequency associated with the energy difference
f = E_del/hbar
# convert frequency to wavelength in (cm)
wavelength = c/f
print('The wavelength of the radiation from the transition\
in the hyperfine structure is : {:.1f} cm'.format(wavelength))
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_athens')
# run this cell to get the backend information through the widget
backend
# assign your choice for the initial layout to the list variable `initial_layout`.
initial_layout =
qc_all = [state_init+measure_circuit for state_init in [Tri1,Tri2,Tri3,Sing]
for measure_circuit in [measure_XX, measure_YY, measure_ZZ] ]
shots = 8192
job = execute(qc_all, backend, initial_layout=initial_layout, optimization_level=3, shots=shots)
print(job.job_id())
job_monitor(job)
# getting the results of your job
results = job.result()
## To access the results of the completed job
#results = backend.retrieve_job('job_id').result()
def Energy(results, shots):
"""Compute the energy levels of the hydrogen ground state.
Parameters:
results (obj): results, results from executing the circuits for measuring a hamiltonian.
shots (int): shots, number of shots used for the circuit execution.
Returns:
Energy (list): energy values of the four different hydrogen ground states
"""
E = []
A = 1.47e-6
for ind_state in range(4):
Energy_meas = []
for ind_comp in range(3):
counts = results.get_counts(ind_state*3+ind_comp)
# calculate the probabilities for each computational basis
probs = {}
for output in ['00','01', '10', '11']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] )
E.append(A * np.sum(np.array(Energy_meas)))
return E
E = Energy(results, shots)
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E[3]))
from qiskit.ignis.mitigation.measurement import *
# your code to create the circuits, meas_calibs, goes here
meas_calibs, state_labels =
# execute meas_calibs on your choice of the backend
job = execute(meas_calibs, backend, shots = shots)
print(job.job_id())
job_monitor(job)
cal_results = job.result()
## To access the results of the completed job
#cal_results = backend.retrieve_job('job_id').result()
# your code to obtain the measurement filter object, 'meas_filter', goes here
results_new = meas_filter.apply(results)
E_new = Energy(results_new, shots)
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_new[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_new[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_new[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E_new[3]))
# results for the energy estimation from the simulation,
# execution on a quantum system without error mitigation and
# with error mitigation in numpy array format
Energy_exact, Energy_exp_orig, Energy_exp_new = np.array(E_sim), np.array(E), np.array(E_new)
# Calculate the relative errors of the energy values without error mitigation
# and assign to the numpy array variable `Err_rel_orig` of size 4
Err_rel_orig =
# Calculate the relative errors of the energy values with error mitigation
# and assign to the numpy array variable `Err_rel_new` of size 4
Err_rel_new =
np.set_printoptions(precision=3)
print('The relative errors of the energy values for four bell basis\
without measurement error mitigation : {}'.format(Err_rel_orig))
np.set_printoptions(precision=3)
print('The relative errors of the energy values for four bell basis\
with measurement error mitigation : {}'.format(Err_rel_new))
|
https://github.com/anpaschool/quantum-computing
|
anpaschool
|
from qiskit import *
from math import pi
import numpy as np
from qiskit.visualization import plot_bloch_multivector,plot_state_qsphere
import matplotlib.pyplot as plt
q = QuantumRegister(2)
qc = QuantumCircuit(2)
qc.cx(0,1)
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
qc = QuantumCircuit(2)
qc.cy(0,1)
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
qc = QuantumCircuit(2)
qc.cz(0,1)
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
qc = QuantumCircuit(2)
qc.ch(0,1)
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
qc = QuantumCircuit(2)
qc.crz(pi/2,0,1)
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
qc = QuantumCircuit(2)
qc.cu1(pi/2,0,1)
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
qc = QuantumCircuit(2)
qc.cu3(pi/2, pi/2, pi/2, 0,1)
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
qc = QuantumCircuit(2)
qc.swap(0,1)
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
|
https://github.com/LeanderThiessen/antisymmetrization-circuit
|
LeanderThiessen
|
#General Imports
import numpy as np
import matplotlib.pyplot as plt
import time
from itertools import product,permutations
from string import ascii_lowercase as asc
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
#Qiskit Imports
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile
from qiskit.circuit.library.standard_gates import MCXGate, CXGate, XGate, CSwapGate
from qiskit.circuit.library import Diagonal
from qiskit.quantum_info import partial_trace,purity
#############FUNCTIONS###########################################################################################################
#wrapper for measuring time taken by function 'func'
def timeis(func):
def wrap(*args,**kwargs):
start = time.time()
result = func(*args,**kwargs)
end = time.time()
if measure_time:
print("{} took {:.2f}s".format(func.__name__,end-start))
return result
return wrap
#check if inputs are valid
def check_inputs(n,m):
if n == 1:
print("Case n=1 currently not supported")
correct = 1
if m>2**n:
correct == 0
if correct == 1:
print("Inputs valid")
return 0
#initialize quantum circuit with electron register, swap_ancillas, record_ancillas, collision_ancillas
def initialize_circuit(n,m,L):
circuit = QuantumCircuit()
#add main electron register (seed/target)
for e in range(m):
r_q = QuantumRegister(n,'{}'.format(asc[e]))#asc[i]=ith letter of the alphabe
c = QuantumCircuit(r_q)
circuit = circuit.combine(c)
#add ancillas for comparator_swaps
for k in range(int(np.ceil(m/2))):
anc_q = QuantumRegister(n-1,'anc_{}'.format(k))
c = QuantumCircuit(anc_q)
circuit = circuit.combine(c)
#add 'record' register for storing outcomes of comparators
for l in range(L):
anc_q = QuantumRegister(1,'record_{}'.format(l))
c = QuantumCircuit(anc_q)
circuit = circuit.combine(c)
#add ancillas to store the occurence of collisions between pairs of electrons
for c in range(m-1):
anc_q = QuantumRegister(1,'coll_record_{}'.format(c))
c = QuantumCircuit(anc_q)
circuit = circuit.combine(c)
#add one ancilla to store if all other collision ancillas are '1'
anc_q = QuantumRegister(1,'collision_test')
c = QuantumCircuit(anc_q)
circuit = circuit.combine(c)
return circuit
#returns x in binary format as string of length n, incl leading zeros
def binary_n(x,n):
return bin(x)[2:].zfill(n)
#initializes j-th electron register with number x
def binary_init(circuit,n,m,input):
for k,e in enumerate(input):
e_bin = binary_n(e,n)
for i in range(n):
if e_bin[i]=='1':
circuit.append(XGate(),[i+k*n])
return circuit
#Apply a Hadamard gate to each qubit in the electron register
def Hadamard(circuit,n,m):
for q in range(n*m):
circuit.h(q)
return circuit
#Compare bits at positions x and y, only output=(x<y) to position anc
def bit_compare(circuit,cbits,control,debug=True):
x = cbits[0]
y = cbits[1]
anc = cbits[2]
if debug:
circuit.barrier()
#control='01' for initial sorting and '10' for collision detection
circuit.append(MCXGate(2,ctrl_state=control),[x,y,anc])
if debug:
circuit.barrier()
return circuit
#split the array 'index' into array of pairs of adjacent indices; first entry is (e.g.) [0] if number of entries of index is odd
def get_subsets(index):
#index = [0,1,2,3] -> result = [[0,1],[2,3]]
#index = [0,1,2,3,4] -> result = [[0],[1,2],[3,4]]
M = len(index)
result = []
if M % 2 != 0:
result.append(np.array([0]))
n_split = int((M-1)/2)
for s in np.split(index[1:M],n_split):
result.append(s)
else:
result = np.split(index,M/2)
return result
#get position of first qubit in swap_control ancilla register
def get_first_swap_ctrl(n,m):
#n_comp_parallel is the number of comparators that are applied in each layer
#n*m = main register for storing electron registers;
#(n_comp_parallel)*(n-1) = fixed ancilla register needed for compare_n
n_comp_parallel = int(np.ceil(m/2))
ctrl_0 = n*m + (n-1)*n_comp_parallel
return ctrl_0
#get position of first qubit in collision_control ancilla register
def get_first_coll_ctrl(n,m,L):
coll_0 = get_first_swap_ctrl(n,m) + L
return coll_0
#return pairs of electron indices that need to be compared in collision-detection step
def get_coll_sets(m):
ind = np.arange(m)
if m == 2:
sets_a = [np.array([0,1])]
sets_b = []
return sets_a,sets_b
if m % 2 == 0:
sets_a = np.split(ind,m/2)
sets_b = np.split(ind[1:-1],(m-2)/2)
else:
sets_a = np.split(ind[:-1],(m-1)/2)
sets_b = np.split(ind[1:],(m-1)/2)
#all gates in sets_a can be applied in parallel
#all gates in sets_b can be applied in parallel
return sets_a,sets_b
#returns the first qubit position of the ancilla register used for swap of i and j (only really tested for m<6)
def get_anc(n,m,i,j):
if abs(j-i) == 1:
anc_reg = int( np.min([i,j])/2 )
elif abs(j-i) == 2:
anc_reg = int( np.ceil( np.min([i,j])/2 ))
else:
anc_reg = int( np.min([i,j]) )
anc = n*m + anc_reg*(n-1)
return anc
#Implement 'Compare2' function (Fig 3); input: two 2bit numbers, output: two 1bit numbers with same ordering
def compare_2(circuit,x_0,x_1,y_0,y_1,anc):
#Notation: x = 2^1*x_0 + x_1 (reverse from paper!!)
#compares numbers x,y and outputs two bits x',y' (at positions x_1 and y_1) with the same ordering
circuit.append(XGate(),[anc])
circuit.append(CXGate(),[y_0,x_0])
circuit.append(CXGate(),[y_1,x_1])
circuit.append(CSwapGate(),[x_0,x_1,anc])
circuit.append(CSwapGate(),[x_0,y_0,y_1])
circuit.append(CXGate(),[y_1,x_1])
return circuit
#Generalisation of 'compare2' two nbit numbers, output: two 1bit numbers with same ordering at positions x1,y1
def compare_n(circuit,n,m,i,j,l,L,debug):
index = np.arange(n)
subsets = get_subsets(index)
M = len(subsets)
anc = get_anc(n,m,i,j)
for s in subsets:
if len(s)==2:
if debug:
circuit.barrier()
x_0 = s[0] + i*n
x_1 = s[1] + i*n
y_0 = s[0] + j*n
y_1 = s[1] + j*n
circuit = compare_2(circuit,x_0,x_1,y_0,y_1,anc)
anc += 1
while (len(subsets)>1):
index = np.array([subsets[k][-1] for k in range(M)])
subsets = get_subsets(index)
M = len(subsets)
for s in subsets:
if len(s)==2:
if debug:
circuit.barrier()
x_0 = s[0] + i*n
x_1 = s[1] + i*n
y_0 = s[0] + j*n
y_1 = s[1] + j*n
circuit = compare_2(circuit,x_0,x_1,y_0,y_1,anc)
anc += 1
########################################################################################################################################
#at this point the bits x_1 and y_1 have the same ordering as numbers stored in registers i and j
#e(i)<e(j) -> x_1=0 and y_1=1
#e(i)>e(j) -> x_1=1 and y_1=0
#e(i)=e(j) -> x_1=0 y_1=0 if e(i) even or x_1=1 y_1=1 if e(i) odd
#prepare output for bit_compare function; anc iterates through the second ancilla register (+1 for each comparator)
#l = current swap; each new swap gets a new ancilla for storing the outcome
anc = get_first_swap_ctrl(n,m) + l
cbits = x_1,y_1,anc
return circuit,cbits
#apply diagonal phase shift to qubit i, conditioned on qubit 'ctrl'
def cphase_shift(circuit,ctrl,i):
target = i*n
CDiag = Diagonal([-1,-1]).control(1)
CDiag = CDiag.to_gate()
CDiag.label = "D" #doesn't work currently
circuit.append(CDiag,[ctrl,target])
return circuit
#performs swap of registers i and j conditioned on ancilla qubit 'ctrl'
def swap_registers(circuit,n,i,j,ctrl,debug):
for g in range(n):
circuit.append(CSwapGate(),[ctrl,i*n+g,j*n+g])
if debug:
circuit.barrier()
return circuit
#compare electron registers i and j; swap registers iff e(i)<(j); l=current swap (0 to L)
def comparator_swap(n,m,i,j,l,L,phase,debug):
#Perform comparison to generate output qubits "cbits"
circuit_compute = initialize_circuit(n,m,L)
circuit_compute,cbits = compare_n(circuit_compute,n,m,i,j,l,L,debug)
#Add bit_compare between the two output qubits and store in ancilla
circuit_bit_compare = initialize_circuit(n,m,L)
circuit_bit_compare = bit_compare(circuit_bit_compare,cbits,'10',debug)
#add uncomputing step only of the comparison circuit
circuit_uncompute = circuit_compute.inverse()
#Swap registers based on control ancilla
circuit_swap = initialize_circuit(n,m,L)
#apply a conditioned phase shift to the first qubit of the register pair; is only called when sn is applied backwards, that's why it's (phase,swap) and not (swap,phase)
if phase:
circuit_swap = cphase_shift(circuit_swap,cbits[2],i)
circuit_swap = swap_registers(circuit_swap,n,i,j,cbits[2],debug)
#Combine circuits
circuit_comparator = circuit_compute + circuit_bit_compare + circuit_uncompute + circuit_swap
return circuit_comparator
#Apply the sorting network sn, where each comparator stores the outcome in ctrl_register
def apply_sorting_network(circuit,n,m,sn,L,phase,debug):
for l,swap in enumerate(sn):
#swap = [i, j, direction]; dir = 0 : descending (from the top); dir = 1 : ascending (from the top)
if swap[2]==0:
i = swap[0]
j = swap[1]
if swap[2]==1:
i = swap[1]
j = swap[0]
circuit_comparator = comparator_swap(n,m,i,j,l,L,phase,debug)
circuit = circuit + circuit_comparator
return circuit
#Apply the reverse of the sorting networkl sn for antisymmetrizing the input state
def apply_reverse_sorting_network(circuit,n,m,sn,L,phase,debug):
circuit_sn = initialize_circuit(n,m,L)
circuit_sn = apply_sorting_network(circuit_sn,n,m,sn,L,phase,debug)
#reverse all gates in the circuit
circuit_reverse_sn = circuit_sn.inverse()
circuit = circuit + circuit_reverse_sn
return circuit
#reset first register to [|0>,|0>,|0>,...] (all zeros)
def reset_electrons(circuit,n,m):
circuit.barrier()
for g in range(m):
g_indices = np.arange(g*n,(g+1)*n) #classical register positions for electron g
for g_i in g_indices:
circuit.reset(g_i)
return circuit
#reset all registers except for the main electron register
def reset_ancillas(circuit,n,m,L):
circuit.barrier()
start = n*m
end = get_first_coll_ctrl(n,m,L) + m
for q in range(start,end):
circuit.reset(q)
return circuit
#Perform comparisons between all adjacent electron registers, with ctrl ancilla in the coll_register
def collision_compare(circuit,n,m,L,debug):
#all sets in sets_a can be applied simultaneously (same for sets_b); both for loops are otherwise identical and could be combined
sets_a,sets_b = get_coll_sets(m)
c = 0
for s in sets_a:
circuit_coll_test = initialize_circuit(n,m,L)
i = s[0]
j = s[1]
circuit_coll_test,cbits = compare_n(circuit_coll_test,n,m,i,j,0,L,debug)
x_1 = cbits[0]
y_1 = cbits[1]
coll_anc = get_first_coll_ctrl(n,m,L) + c
cbits = [x_1,y_1,coll_anc]
circuit_coll_test_reverse = circuit_coll_test.inverse()
circuit = circuit + circuit_coll_test
circuit = bit_compare(circuit,cbits,'01',debug)
circuit = circuit + circuit_coll_test_reverse
c+=1
for s in sets_b:
circuit_coll_test = initialize_circuit(n,m,L)
i = s[0]
j = s[1]
circuit_coll_test,cbits = compare_n(circuit_coll_test,n,m,i,j,0,L,debug)
x_1 = cbits[0]
y_1 = cbits[1]
coll_anc = get_first_coll_ctrl(n,m,L) + c
cbits = [x_1,y_1,coll_anc]
circuit_coll_test_reverse = circuit_coll_test.inverse()
circuit = circuit + circuit_coll_test
circuit = bit_compare(circuit,cbits,'01',debug)
circuit = circuit + circuit_coll_test_reverse
c+=1
return circuit
#apply X gate on last qubit, conditioned on all other coll_ancillas being 1 (which means that all elctron registers are different)
def collision_test(circuit,n,m,L,debug):
coll_ctrl_0 = get_first_coll_ctrl(n,m,L)
control = ''
qubits = []
for i in range(m-1):
control = control + '1'
qubits.append(coll_ctrl_0+i)
qubits.append(coll_ctrl_0+m-1)
circuit.append(MCXGate(m-1,ctrl_state=control),qubits)
return circuit
#not necessary
#returns True if output contains only unique elements; returns False otherwise (if two or more elements are the same)
def collision_check_old(output):
if len(output) == len(set(output)):
return True
else:
return False
#Perform measurement on last qubit in coll_register
def measure_collisions(circuit,n,m,L):
#add classical register to store measurement result
c_q = QuantumRegister(0)
c_reg = ClassicalRegister(1,'collision_check')
c = QuantumCircuit(c_q,c_reg)
circuit = circuit.combine(c)
#perform measurements on each electron register and store in separate memorey
circuit.measure(get_first_coll_ctrl(n,m,L) + m - 1, 0)
return circuit
#Add classical registers and apply measurements on the main electron register
def measure_electrons(circuit,n,m):
circuit.barrier()
for g in range(m):
#Add classicla register to store measurement outcomes
c_q = QuantumRegister(0)
c_reg = ClassicalRegister(n,'mem_{}'.format(asc[g]))
c = QuantumCircuit(c_q,c_reg)
circuit = circuit.combine(c)
#perform measurements on each electron register and store in separate memorey
circuit.measure(np.arange(g*n,(g+1)*n),np.arange(g*n + 1,(g+1)*n + 1))
return circuit
#Build the circuit with all gates and measurements
@timeis
def build_circuit(n,m,input,sn,L,debug=True):
#Initialize the circuit with the right number of qubits and ancillas
circuit = initialize_circuit(n,m,L)
#Apply Hadamard gates to each qubit in the first register
circuit = Hadamard(circuit,n,m)
#Apply the sorting network sn
phase = False
circuit = apply_sorting_network(circuit,n,m,sn,L,phase,debug)
#apply comparisons between all adjacent electron registers and store outcome in coll_register
circuit = collision_compare(circuit,n,m,L,debug)
#check if outcome of all comparisons is "not_equal"; flip last qubit in coll_register if this is the case
circuit = collision_test(circuit,n,m,L,debug)
#measure last qubit in coll_register, which stores (no collisions = 1) or (collisions = 0); result is kept until the end of the simulation and result accepted if (no collisions == True)
circuit = measure_collisions(circuit,n,m,L)
#Measurements: classical register 0 stores the random sorted array that can still include collisions
#circuit = measure_electrons(circuit,n,m)
#Reset main electron register
circuit = reset_electrons(circuit,n,m)
#Initialize main electron register in given input product state
circuit = binary_init(circuit,n,m,input)
#Apply the reverse of 'apply_sorting_network' and add a conditioned phase shift after each swap (this antisymmetrizes the input state)
phase = True
circuit = apply_reverse_sorting_network(circuit,n,m,sn,L,phase,debug)
#Reset all ancilla qubits and only keep the main electron register (disable for testing final state for antisymmetry)
#circuit = reset_ancillas(circuit,n,m,L)
#Measure electron register (for testing)
#circuit = measure_electrons(circuit,n,m)
return circuit
#Simulate circuit using specified backend and return simulation result
@timeis
def simulate(circuit,backend,shots):
simulator = Aer.get_backend(backend)
#transpile the circuit into the supported set of gates
circuit = transpile(circuit,backend=simulator)
result = simulator.run(circuit,shots=shots).result()
return result
#turns simulation result 'counts' into list of decimal numbers corresponding to the electron registers; only use if shots=1 or all outcomes are the same
def convert_output_to_decimal(counts,n,m):
output_list = list(counts.keys())[0][::-1]
coll_test = output_list[0]
output_list = output_list[2:]
output = []
offset = 0
for g in range(m):
start = g*n + offset
end = (g+1)*n + offset
g_out = int(output_list[start:end],2)
output.append(g_out)
offset += 1
output_0 = output[0:m]
return coll_test,output_0
#draw the circuit using size,name as input if plot==True
@timeis
def draw_circuit(circuit,plot_scale,fname):
circuit.draw(output='mpl',fold=-1,scale=plot_scale,plot_barriers=True)
plt.savefig(fname,dpi=700)
return 0
def plot_circuit(circuit,plot_scale,fname,plot=True):
if plot:
draw_circuit(circuit,plot_scale,fname)
plt.show()
return 0
print("Plot disabled")
return 0
#plot sorting network by itself, using cnot as directed comparator (only for visualizationo)
def plot_sorting_network(sn,m):
circuit_sn = QuantumCircuit(m)
for s in sn:
if s[2] == 0:
i,j = s[0],s[1]
else:
i,j = s[1],s[0]
circuit_sn.cz(i,j)
circuit_sn.draw(output='mpl')
plt.show()
return 0
#Generate a bitonic sorting network for m electrons; dir=0 (descending), dir=1 (ascending)
def sorting_network_bitonic(m,dir):
sn = []
def compAndSwap(i,j,dir):
sn.append([i,j,dir])
def bitonic_sort(low, cnt, dir):
if cnt>1:
k = cnt//2
dir_n = (dir + 1) % 2
bitonic_sort(low, k, dir_n)#n_dir
bitonic_sort(low + k, cnt-k, dir)#dir
bitonic_merge(low, cnt, dir)
def bitonic_merge(low, cnt, dir):
if cnt>1:
k = greatestPowerOfTwoLessThan(cnt)
i = low
while i < low+cnt-k:
compAndSwap(i, i+k, dir)
i+=1
bitonic_merge(low,k,dir)
bitonic_merge(low+k,cnt-k,dir)
def greatestPowerOfTwoLessThan(cnt):
i=1
while (2**i)<cnt:
i+=1
return 2**(i-1)
bitonic_sort(0,m,dir)
L = len(sn)
return sn,L
#Test if sorting network correctly sorts all possible inputs
def test_sn(sn,n,m):
all_inputs = list(product(range(2**n),repeat=m))
fail = 0
count = 0
for input in all_inputs:
input = np.array(input)
temp = np.copy(input)
for s in sn:
if s[2]==0:
i = s[0]
j = s[1]
if s[2]==1:
i = s[1]
j = s[0]
if input[i]<input[j]:
input[i],input[j] = input[j],input[i]
should_be = np.sort(temp)[::-1]
if (input == should_be).all():
fail += 0
else:
fail += 1
print(f"Testing sorting network {count}/{len(all_inputs)}",end="\r")
count+=1
print(" ", end = "\r")
if fail == 0:
print("Sorting network correct\n")
return 1
else:
print("Error in sorting network\n")
return 0
#Returns all steps of sorting network with corresponding ancilla registers (for testing)
def test_sn_anc(sn,n,m):
for s in sn:
i = s[0]
j = s[1]
anc = get_anc(n,m,i,j)
anc_reg = int((anc-n*m)/(n-1))
print(f"[{i},{j}] anc_reg={anc_reg}")
return 0
#Output density matrix of electron register (target) and compute purity, doesnt actually test antisymmetry yet!
def test_antisymmetry(result,n,m,L):
sv = result.get_statevector()
trace_out = list(np.arange(n*m,get_first_coll_ctrl(n,m,L)+m))
#print(f"Tracing out qubits: {trace_out}")
rho_e = partial_trace(sv,trace_out)
if rho_e.is_valid():
print("Target state is valid density matrix\n")
else:
print("Target state is not valid density matrix")
#print(rho_e)
p = purity(rho_e)
print(f"Purity of target state = {p}\n")
return p
###################MAINPART############################################################################################################
#Parameters
#n: number of qubits per electron; N = 2^n orbitals
n=3
#m: number of electrons
m=4
#input: list of orbitals the electrons are initialized in; needs to be in descending order, without repetitions
input = [5,4,3,2]
#dir: ordering descending (dir=0) or ascending (dir=1)
dir = 0
#plot and save the circuit
plot = True
#include barriers between comparators in the circuit for visualization
debug = False
#measure time of functions: {build_circuit, simulate, draw_circuit}
measure_time = True
#size of the plot
plot_scale = 0.2
#simulation method
backend = 'statevector_simulator'#'aer_simulator'
#number of circuit repetitions in 'simulate'
shots = 1
#check valid inputs
check_inputs(n,m)
#Generate sorting network
sn,L = sorting_network_bitonic(m,dir)
#Test sorting network
test_sn(sn,n,m)
#Plot sorting network
plot_sorting_network(sn,m)
#Build circuit
circuit = build_circuit(n,m,input,sn,L,debug)
#Simulate
result = simulate(circuit,backend,shots)
counts = result.get_counts(circuit)
print(f"Counts: {counts}\n")
#Test if final state is antisymmetric
test_antisymmetry(result,n,m,L)
output_list = list(counts.keys())[0][::-1]
coll_test = output_list[0]
if coll_test == '1':
print("No collisions detected - continue\n")
else:
print("Collisions detected - repeat\n")
#plot circuit
plot_circuit(circuit,plot_scale,f"Plots/Circuit_m{m}_n{n}_debug{debug}",plot)
|
https://github.com/tstopa/Qiskit_for_high_schools
|
tstopa
|
from qiskit import *
qiskit.__qiskit_version__
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
"""
Grover's Search Benchmark Program - QSim
"""
import sys
import time
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
sys.path[1:1] = ["_common", "_common/qsim"]
sys.path[1:1] = ["../../_common", "../../_common/qsim"]
import execute as ex
import metrics as metrics
from execute import BenchmarkResult
# Benchmark Name
benchmark_name = "Grover's Search"
np.random.seed(0)
verbose = False
# saved circuits for display
QC_ = None
grover_oracle = None
diffusion_operator = None
# for validating the implementation of an mcx shim
_use_mcx_shim = False
############### Circuit Definition
def GroversSearch(num_qubits, marked_item, n_iterations):
# allocate qubits
qr = QuantumRegister(num_qubits);
cr = ClassicalRegister(num_qubits);
qc = QuantumCircuit(qr, cr, name=f"grovers-{num_qubits}-{marked_item}")
# Start with Hadamard on all qubits
for i_qubit in range(num_qubits):
qc.h(qr[i_qubit])
# loop over the estimated number of iterations
for _ in range(n_iterations):
qc.barrier()
# add the grover oracle
qc.append(add_grover_oracle(num_qubits, marked_item).to_instruction(), qr)
# add the diffusion operator
qc.append(add_diffusion_operator(num_qubits).to_instruction(), qr)
qc.barrier()
# measure all qubits
qc.measure(qr, cr) # to get the partial_probability
# qc.measure(qr, cr, basis='Ensemble', add_param='Z') # to get the ensemble_probability
# save smaller circuit example for display
global QC_
if QC_ == None or num_qubits <= 5:
if num_qubits < 9: QC_ = qc
# return a handle on the circuit
return qc
############## Grover Oracle
def add_grover_oracle(num_qubits, marked_item):
global grover_oracle
marked_item_bits = format(marked_item, f"0{num_qubits}b")[::-1]
qr = QuantumRegister(num_qubits); qc = QuantumCircuit(qr, name="oracle")
for (q, bit) in enumerate(marked_item_bits):
if not int(bit):
qc.x(q)
qc.h(num_qubits - 1)
if _use_mcx_shim:
add_mcx(qc, [x for x in range(num_qubits - 1)], num_qubits - 1)
else:
qc.mcx([x for x in range(num_qubits - 1)], num_qubits - 1)
qc.h(num_qubits - 1)
qc.barrier()
for (q, bit) in enumerate(marked_item_bits):
if not int(bit):
qc.x(q)
if grover_oracle == None or num_qubits <= 5:
if num_qubits < 9: grover_oracle = qc
return qc
############## Grover Diffusion Operator
def add_diffusion_operator(num_qubits):
global diffusion_operator
qr = QuantumRegister(num_qubits); qc = QuantumCircuit(qr, name="diffuser")
for i_qubit in range(num_qubits):
qc.h(qr[i_qubit])
for i_qubit in range(num_qubits):
qc.x(qr[i_qubit])
qc.h(num_qubits - 1)
if _use_mcx_shim:
add_mcx(qc, [x for x in range(num_qubits - 1)], num_qubits - 1)
else:
qc.mcx([x for x in range(num_qubits - 1)], num_qubits - 1)
qc.h(num_qubits - 1)
qc.barrier()
for i_qubit in range(num_qubits):
qc.x(qr[i_qubit])
for i_qubit in range(num_qubits):
qc.h(qr[i_qubit])
if diffusion_operator == None or num_qubits <= 5:
if num_qubits < 9: diffusion_operator = qc
return qc
############### MCX shim
# single cx / cu1 unit for mcx implementation
def add_cx_unit(qc, cxcu1_unit, controls, target):
num_controls = len(controls)
i_qubit = cxcu1_unit[1]
j_qubit = cxcu1_unit[0]
theta = cxcu1_unit[2]
if j_qubit != None:
qc.cx(controls[j_qubit], controls[i_qubit])
qc.cu1(theta, controls[i_qubit], target)
i_qubit = i_qubit - 1
if j_qubit == None:
j_qubit = i_qubit + 1
else:
j_qubit = j_qubit - 1
if theta < 0:
theta = -theta
new_units = []
if i_qubit >= 0:
new_units += [ [ j_qubit, i_qubit, -theta ] ]
new_units += [ [ num_controls - 1, i_qubit, theta ] ]
return new_units
# mcx recursion loop
def add_cxcu1_units(qc, cxcu1_units, controls, target):
new_units = []
for cxcu1_unit in cxcu1_units:
new_units += add_cx_unit(qc, cxcu1_unit, controls, target)
cxcu1_units.clear()
return new_units
# mcx gate implementation: brute force and inefficent
# start with a single CU1 on last control and target
# and recursively expand for each additional control
def add_mcx(qc, controls, target):
num_controls = len(controls)
theta = np.pi / 2**num_controls
qc.h(target)
cxcu1_units = [ [ None, num_controls - 1, theta] ]
while len(cxcu1_units) > 0:
cxcu1_units += add_cxcu1_units(qc, cxcu1_units, controls, target)
qc.h(target)
################ Analysis
# Analyze and print measured results
# Expected result is always the secret_int, so fidelity calc is simple
def analyze_and_print_result(qc, result, num_qubits, marked_item, num_shots):
if result.backend_name == 'dm_simulator':
benchmark_result = BenchmarkResult(result, num_shots)
probs = benchmark_result.get_probs(num_shots) # get results as measured probability
else:
probs = result.get_counts(qc) # get results as measured counts
# # setting the threhold value to avoid getting exponential values which leads to nan values
# threshold = 3e-3
# probs = {key: value if value > threshold else 0.0 for key, value in probs.items()}
# print(f"\nprobs ===== {probs}")
if verbose: print(f"For type {marked_item} measured: {probs}")
# we compare counts to analytical correct distribution
correct_dist = grovers_dist(num_qubits, marked_item)
# print(f"\ncorrect_dist ===== {correct_dist}")
if verbose: print(f"Marked item: {marked_item}, Correct dist: {correct_dist}")
# use our polarization fidelity rescaling
fidelity = metrics.polarization_fidelity(probs, correct_dist)
print(f"\nfidelity ===== {fidelity}")
return probs, fidelity
def grovers_dist(num_qubits, marked_item):
n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4)
dist = {}
for i in range(2**num_qubits):
# key = bin(i)[2:].zfill(num_qubits)
#reverse the key's bits (or) import QFT (reverse_bit()) to get the correct Probability States (in case of dm-simulator)
# check the reason --- qiskit-aakash/releasenotes/notes/0.17/qft-little-endian-d232c93e044f0063.yaml
key = bin(i)[2:].zfill(num_qubits)[::-1]
theta = np.arcsin(1/np.sqrt(2 ** num_qubits))
if i == int(marked_item):
dist[key] = np.sin((2*n_iterations+1)*theta)**2
else:
dist[key] = (np.cos((2*n_iterations+1)*theta)/(np.sqrt(2 ** num_qubits - 1)))**2
return dist
################ Benchmark Loop
# from qiskit.circuit.library import QFT
# Because this circuit size grows significantly with num_qubits (due to the mcx gate)
# limit the max_qubits here ...
MAX_QUBITS=8
# Execute program with default parameters
def run(min_qubits=2, max_qubits=6, skip_qubits=1, max_circuits=3, num_shots=1000,
use_mcx_shim=False,
backend_id='dm_simulator', provider_backend=None,
#hub="ibm-q", group="open", project="main",
exec_options=None, context=None):
print(f"{benchmark_name} Benchmark Program - QSim")
# Clamp the maximum number of qubits
if max_qubits > MAX_QUBITS:
print(f"INFO: {benchmark_name} benchmark is limited to a maximum of {MAX_QUBITS} qubits.")
max_qubits = MAX_QUBITS
# validate parameters (smallest circuit is 2 qubits)
max_qubits = max(2, max_qubits)
min_qubits = min(max(2, min_qubits), max_qubits)
skip_qubits = max(1, skip_qubits)
#print(f"min, max qubits = {min_qubits} {max_qubits}")
# create context identifier
if context is None: context = f"{benchmark_name} Benchmark"
# set the flag to use an mcx shim if given
global _use_mcx_shim
_use_mcx_shim = use_mcx_shim
if _use_mcx_shim:
print("... using MCX shim")
##########
# Initialize metrics module
metrics.init_metrics()
# Define custom result handler
def execution_handler(qc, result, num_qubits, s_int, num_shots):
# determine fidelity of result set
num_qubits = int(num_qubits)
probs, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots)
metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity)
# Initialize execution module using the execution result handler above and specified backend_id
ex.init_execution(execution_handler)
ex.set_execution_target(backend_id, provider_backend=provider_backend,
#hub=hub, group=group, project=project,
exec_options=exec_options, context=context)
##########
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits):
# determine number of circuits to execute for this group
num_circuits = min(2 ** (num_qubits), max_circuits)
print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}")
# determine range of secret strings to loop over
if 2**(num_qubits) <= max_circuits:
s_range = list(range(num_circuits))
else:
s_range = np.random.choice(2**(num_qubits), num_circuits, False)
# loop over limited # of secret strings for this
for s_int in s_range:
# create the circuit for given qubit size and secret string, store time metric
ts = time.time()
n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4)
qc = GroversSearch(num_qubits, s_int, n_iterations)
# qc = GroversSearch(num_qubits, s_int, n_iterations).reverse_bits()
print(qc)
metrics.store_metric(num_qubits, s_int, 'create_time', time.time() - ts)
# collapse the sub-circuits used in this benchmark (for qiskit)
qc2 = qc.decompose()
# submit circuit for execution on target (simulator, cloud simulator, or hardware)
ex.submit_circuit(qc2, num_qubits, s_int, num_shots)
# Wait for some active circuits to complete; report metrics when groups complete
ex.throttle_execution(metrics.finalize_group)
# Wait for all active circuits to complete; report metrics when groups complete
ex.finalize_execution(metrics.finalize_group)
##########
# print a sample circuit created (if not too large)
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
print("\nOracle ="); print(grover_oracle if grover_oracle!= None else " ... too large!")
print("\nDiffuser ="); print(diffusion_operator )
# Plot metrics for all circuit sizes
metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim")
# if main, execute method
if __name__ == '__main__': run()
|
https://github.com/stefan-woerner/qiskit_tutorial
|
stefan-woerner
|
print("Hello! I'm a code cell")
print('Set up started...')
%matplotlib notebook
import sys
sys.path.append('game_engines')
import hello_quantum
print('Set up complete!')
initialize = []
success_condition = {}
allowed_gates = {'0': {'NOT': 3}, '1': {}, 'both': {}}
vi = [[1], False, False]
qubit_names = {'0':'the only bit', '1':None}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {}
allowed_gates = {'0': {}, '1': {'NOT': 0}, 'both': {}}
vi = [[], False, False]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'IZ': -1.0}
allowed_gates = {'0': {'CNOT': 0}, '1': {'CNOT': 0}, 'both': {}}
vi = [[], False, False]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'ZI': 1.0, 'IZ': -1.0}
allowed_gates = {'0': {'CNOT': 0}, '1': {'CNOT': 0}, 'both': {}}
vi = [[], False, False]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0']]
success_condition = {'IZ': 0.0}
allowed_gates = {'0': {'CNOT': 0}, '1': {'CNOT': 0}, 'both': {}}
vi = [[], False, False]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0']]
success_condition = {'ZZ': -1.0}
allowed_gates = {'0': {'NOT': 0, 'CNOT': 0}, '1': {'NOT': 0, 'CNOT': 0}, 'both': {}}
vi = [[], False, True]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '1']]
success_condition = {'IZ': -1.0}
allowed_gates = {'0': {'NOT': 0, 'CNOT': 0}, '1': {'NOT': 0, 'CNOT': 0}, 'both': {}}
vi = [[], False, True]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [ ["x","0"] ]
success_condition = {"ZI":1.0}
allowed_gates = { "0":{"x":3}, "1":{}, "both":{} }
vi = [[1],True,True]
qubit_names = {'0':'the only qubit', '1':None}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'ZI': 1.0}
allowed_gates = {'0': {'x': 0}, '1': {}, 'both': {}}
vi = [[1], True, True]
qubit_names = {'0':'the only qubit', '1':None}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '1']]
success_condition = {'IZ': 1.0}
allowed_gates = {'0': {}, '1': {'x': 0}, 'both': {}}
vi = [[0], True, True]
qubit_names = {'0':None, '1':'the other qubit'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {'ZI': 0.0}
allowed_gates = {'0': {'h': 3}, '1': {}, 'both': {}}
vi = [[1], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '1']]
success_condition = {'IZ': 1.0}
allowed_gates = {'0': {}, '1': {'x': 3, 'h': 0}, 'both': {}}
vi = [[0], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0'], ['z', '0']]
success_condition = {'XI': 1.0}
allowed_gates = {'0': {'z': 0, 'h': 0}, '1': {}, 'both': {}}
vi = [[1], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {'ZI': -1.0}
allowed_gates = {'0': {'z': 0, 'h': 0}, '1': {}, 'both': {}}
vi = [[1], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0']]
success_condition = {'IX': 1.0}
allowed_gates = {'0': {}, '1': {'z': 0, 'h': 0}, 'both': {}}
vi = [[0], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['ry(pi/4)', '1']]
success_condition = {'IZ': -0.7071, 'IX': -0.7071}
allowed_gates = {'0': {}, '1': {'z': 0, 'h': 0}, 'both': {}}
vi = [[0], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '1']]
success_condition = {'ZI': 0.0, 'IZ': 0.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, False]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h','0'],['h','1']]
success_condition = {'ZZ': -1.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x','0']]
success_condition = {'XX': 1.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {'XZ': -1.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['ry(-pi/4)', '1'], ['ry(-pi/4)','0']]
success_condition = {'ZI': -0.7071, 'IZ': -0.7071}
allowed_gates = {'0': {'x': 0}, '1': {'x': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '1'], ['x','0']]
success_condition = {'XI':1, 'IX':1}
allowed_gates = {'0': {'z': 0, 'h': 0}, '1': {'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'ZI': 1.0, 'IZ': -1.0}
allowed_gates = {'0': {'cx': 0}, '1': {'cx': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0'],['x', '1']]
success_condition = {'XI': -1.0, 'IZ': 1.0}
allowed_gates = {'0': {'h': 0, 'cz': 0}, '1': {'cx': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0'],['x', '1'],['h', '1']]
success_condition = { }
allowed_gates = {'0':{'cz': 2}, '1':{'cz': 2}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'IZ': -1.0}
allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz': 0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0'],['h', '1']]
success_condition = {'XI': -1.0, 'IX': -1.0}
allowed_gates = {'0': {}, '1': {'z':0,'cx': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {'IZ': -1.0}
allowed_gates = {'0': {'x':0,'h':0,'cx':0}, '1': {'h':0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['ry(-pi/4)','0'],['ry(-pi/4)','0'],['ry(-pi/4)','0'],['x','0'],['x','1']]
success_condition = {'ZI': -1.0,'XI':0,'IZ':0.7071,'IX':-0.7071}
allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz': 0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x','0'],['h','1']]
success_condition = {'IX':1,'ZI':-1}
allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz':3}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names,shots=2000)
initialize = [['x','1']]
success_condition = {'IZ':1.0,'ZI':-1.0}
allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names,shots=2000)
initialize = []
success_condition = {}
allowed_gates = {'0': {'ry(pi/4)': 4}, '1': {}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x','0']]
success_condition = {'XX': 1.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = []
success_condition = {'ZI': -1.0}
allowed_gates = {'0': {'bloch':1, 'ry(pi/4)': 0}, '1':{}, 'both': {'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = [['h','0'],['h','1']]
success_condition = {'ZI': -1.0,'IZ': -1.0}
allowed_gates = {'0': {'bloch':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, '1': {'bloch':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = [['h','0']]
success_condition = {'ZZ': 1.0}
allowed_gates = {'0': {}, '1': {'bloch':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'unbloch':0,'cz':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = [['ry(pi/4)','0'],['ry(pi/4)','1']]
success_condition = {'ZI': 1.0,'IZ': 1.0}
allowed_gates = {'0': {'bloch':0, 'z':0, 'ry(pi/4)': 1}, '1': {'bloch':0, 'x':0, 'ry(pi/4)': 1}, 'both': {'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = [['x','0'],['h','1']]
success_condition = {'IZ': 1.0}
allowed_gates = {'0': {}, '1': {'bloch':0, 'cx':0, 'ry(pi/4)': 1, 'ry(-pi/4)': 1}, 'both': {'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = []
success_condition = {'IZ': 1.0,'IX': 1.0}
allowed_gates = {'0': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, '1': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'cz':0, 'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
import random
def setup_variables ():
### Replace this section with anything you want ###
r = random.random()
A = r*(2/3)
B = r*(1/3)
### End of section ###
return A, B
def hash2bit ( variable, hash ):
### Replace this section with anything you want ###
if hash=='V':
bit = (variable<0.5)
elif hash=='H':
bit = (variable<0.25)
bit = str(int(bit))
### End of section ###
return bit
shots = 8192
def calculate_P ( ):
P = {}
for hashes in ['VV','VH','HV','HH']:
# calculate each P[hashes] by sampling over `shots` samples
P[hashes] = 0
for shot in range(shots):
A, B = setup_variables()
a = hash2bit ( A, hashes[0] ) # hash type for variable `A` is the first character of `hashes`
b = hash2bit ( B, hashes[1] ) # hash type for variable `B` is the second character of `hashes`
P[hashes] += (a!=b) / shots
return P
P = calculate_P()
print(P)
def bell_test (P):
sum_P = sum(P.values())
for hashes in P:
bound = sum_P - P[hashes]
print("The upper bound for P['"+hashes+"'] is "+str(bound))
print("The value of P['"+hashes+"'] is "+str(P[hashes]))
if P[hashes]<=bound:
print("The upper bound is obeyed :)\n")
else:
if P[hashes]-bound < 0.1:
print("This seems to have gone over the upper bound, but only by a little bit :S\nProbably just rounding errors or statistical noise.\n")
else:
print("!!!!! This has gone well over the upper bound :O !!!!!\n")
bell_test(P)
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
def initialize_program ():
qubit = QuantumRegister(2)
A = qubit[0]
B = qubit[1]
bit = ClassicalRegister(2)
a = bit[0]
b = bit[1]
qc = QuantumCircuit(qubit, bit)
return A, B, a, b, qc
def hash2bit ( variable, hash, bit, qc ):
if hash=='H':
qc.h( variable )
qc.measure( variable, bit )
initialize = []
success_condition = {'ZZ':-0.7071,'ZX':-0.7071,'XZ':-0.7071,'XX':-0.7071}
allowed_gates = {'0': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, '1': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'cz':0, 'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'A', '1':'B'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
import numpy as np
def setup_variables ( A, B, qc ):
for line in puzzle.program:
eval(line)
shots = 8192
from qiskit import execute
def calculate_P ( backend ):
P = {}
program = {}
for hashes in ['VV','VH','HV','HH']:
A, B, a, b, program[hashes] = initialize_program ()
setup_variables( A, B, program[hashes] )
hash2bit ( A, hashes[0], a, program[hashes])
hash2bit ( B, hashes[1], b, program[hashes])
# submit jobs
job = execute( list(program.values()), backend, shots=shots )
# get the results
for hashes in ['VV','VH','HV','HH']:
stats = job.result().get_counts(program[hashes])
P[hashes] = 0
for string in stats.keys():
a = string[-1]
b = string[-2]
if a!=b:
P[hashes] += stats[string] / shots
return P
device = 'qasm_simulator'
from qiskit import Aer, IBMQ
try:
IBMQ.load_accounts()
except:
pass
try:
backend = Aer.get_backend(device)
except:
backend = IBMQ.get_backend(device)
print(backend.status())
P = calculate_P( backend )
print(P)
bell_test( P )
|
https://github.com/quantumgenetics/quantumgenetics
|
quantumgenetics
|
#!/usr/bin/env python3
import logging
from datetime import datetime
from qiskit import Aer, IBMQ
from qiskit import execute as qiskit_execute
from qiskit.providers.aer import noise
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import pauli_error
# List of gate times for ibmq_14_melbourne device
_EXEC_SHOTS = 1
_GATE_TIMES = [
('u1', None, 0), ('u2', None, 100), ('u3', None, 200),
('cx', [1, 0], 678), ('cx', [1, 2], 547), ('cx', [2, 3], 721),
('cx', [4, 3], 733), ('cx', [4, 10], 721), ('cx', [5, 4], 800),
('cx', [5, 6], 800), ('cx', [5, 9], 895), ('cx', [6, 8], 895),
('cx', [7, 8], 640), ('cx', [9, 8], 895), ('cx', [9, 10], 800),
('cx', [11, 10], 721), ('cx', [11, 3], 634), ('cx', [12, 2], 773),
('cx', [13, 1], 2286), ('cx', [13, 12], 1504), ('cx', [], 800)
]
_LOCAL_BACKEND_NAME = 'qasm_simulator'
_P_RESET = 0.8
_P_MEAS = 0.6
_P_GATE1 = 0.7
_REMOTE_BACKEND_NAME = 'ibmq_16_melbourne'
logger = logging.getLogger(__name__)
def ibm_noise_configuration(remote_backend=_REMOTE_BACKEND_NAME, gate_times=_GATE_TIMES):
logger.info('Produce IBM noise configuration')
logger.info('Loading IBM account...')
before = datetime.now()
provider = IBMQ.load_account()
delta = datetime.now() - before
logger.info('IBM account loaded ({} s)'.format(delta.total_seconds()))
device = provider.get_backend(remote_backend)
noise_model = noise.device.basic_device_noise_model(device.properties(),
gate_times=gate_times)
coupling_map = device.configuration().coupling_map
return (noise_model, coupling_map)
def custom_noise_configuration(remote_backend=_REMOTE_BACKEND_NAME):
logger.info('Produce custom noise configuration')
logger.info('Loading IBM account...')
before = datetime.now()
provider = IBMQ.load_account()
delta = datetime.now() - before
logger.info('IBM account loaded ({} s)'.format(delta.total_seconds()))
device = provider.get_backend(remote_backend)
coupling_map = device.configuration().coupling_map
# QuantumError objects
error_reset = pauli_error([('X', _P_RESET), ('I', 1 - _P_RESET)])
error_meas = pauli_error([('X', _P_MEAS), ('I', 1 - _P_MEAS)])
error_gate1 = pauli_error([('X', _P_GATE1), ('I', 1 - _P_GATE1)])
error_gate2 = error_gate1.tensor(error_gate1)
# Add errors to noise model
noise_bit_flip = NoiseModel()
noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset")
noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure")
noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"])
noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"])
return (noise_bit_flip, coupling_map)
def execute(circuit,
*,
configuration=None,
local_simulator=_LOCAL_BACKEND_NAME,
shots=_EXEC_SHOTS):
logger.info('Execute circuit')
simulator = Aer.get_backend(local_simulator)
logger.info('Executing...')
before = datetime.now()
if configuration:
noise_model = configuration[0]
coupling_map = configuration[1]
result = qiskit_execute(circuit,
simulator,
noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=noise_model.basis_gates,
shots=shots,
backend_options={
"max_parallel_threads":0,
'max_parallel_shots':0}
).result()
else:
result = qiskit_execute(circuit, simulator, shots=shots).result()
delta = datetime.now() - before
logger.info('Execution completed ({} s)'.format(delta.total_seconds()))
return result.get_counts(circuit)
|
https://github.com/vm6502q/qiskit-qrack-provider
|
vm6502q
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
QasmSimulator Integration Tests
"""
# pylint: disable=no-member
import copy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.library import QuantumVolume, QFT
from qiskit.compiler import assemble, transpile
from qiskit.providers.qrack import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import (ReadoutError,
depolarizing_error,
amplitude_damping_error)
class QasmFusionTests:
"""QasmSimulator fusion tests."""
SIMULATOR = QasmSimulator()
def create_statevector_circuit(self):
""" Creates a simple circuit for running in the statevector """
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
circuit = QuantumCircuit(qr, cr)
circuit.u(0.1, 0.1, 0.1, qr[0])
circuit.barrier(qr)
circuit.x(qr[0])
circuit.barrier(qr)
circuit.x(qr[1])
circuit.barrier(qr)
circuit.x(qr[0])
circuit.barrier(qr)
circuit.u(0.1, 0.1, 0.1, qr[0])
circuit.barrier(qr)
circuit.measure(qr, cr)
return circuit
def noise_model_depol(self):
""" Creates a new noise model for testing purposes """
readout_error = [0.01, 0.1]
params = {'u': (1, 0.001), 'cx': (2, 0.02)}
noise = NoiseModel()
readout = [[1.0 - readout_error[0], readout_error[0]],
[readout_error[1], 1.0 - readout_error[1]]]
noise.add_all_qubit_readout_error(ReadoutError(readout))
for gate, (num_qubits, gate_error) in params.items():
noise.add_all_qubit_quantum_error(
depolarizing_error(gate_error, num_qubits), gate)
return noise
def noise_model_kraus(self):
""" Creates a new noise model for testing purposes """
readout_error = [0.01, 0.1]
params = {'u': (1, 0.001), 'cx': (2, 0.02)}
noise = NoiseModel()
readout = [[1.0 - readout_error[0], readout_error[0]],
[readout_error[1], 1.0 - readout_error[1]]]
noise.add_all_qubit_readout_error(ReadoutError(readout))
for gate, (num_qubits, gate_error) in params.items():
noise.add_all_qubit_quantum_error(
amplitude_damping_error(gate_error, num_qubits), gate)
return noise
def fusion_options(self, enabled=None, threshold=None, verbose=None):
"""Return default backend_options dict."""
backend_options = self.BACKEND_OPTS.copy()
if enabled is not None:
backend_options['fusion_enable'] = enabled
if verbose is not None:
backend_options['fusion_verbose'] = verbose
if threshold is not None:
backend_options['fusion_threshold'] = threshold
return backend_options
def fusion_metadata(self, result):
"""Return fusion metadata dict"""
metadata = result.results[0].metadata
return metadata.get('fusion', {})
def test_fusion_theshold(self):
"""Test fusion threhsold"""
shots = 100
threshold = 6
backend_options = self.fusion_options(enabled=True, threshold=threshold)
with self.subTest(msg='below fusion threshold'):
circuit = transpile(QFT(threshold - 1),
self.SIMULATOR, basis_gates=['u1', 'u2', 'u', 'cx', 'cz'],
optimization_level=0)
circuit.measure_all()
qobj = assemble(circuit, self.SIMULATOR, shots=shots)
result = self.SIMULATOR.run(
qobj, **backend_options).result()
self.assertSuccess(result)
#meta = self.fusion_metadata(result)
#self.assertTrue(meta.get('enabled'))
#self.assertFalse(meta.get('applied'))
with self.subTest(msg='at fusion threshold'):
circuit = transpile(QFT(threshold),
self.SIMULATOR, basis_gates=['u1', 'u2', 'u', 'cx', 'cz'],
optimization_level=0)
circuit.measure_all()
qobj = assemble(circuit, self.SIMULATOR, shots=shots)
result = self.SIMULATOR.run(
qobj, **backend_options).result()
self.assertSuccess(result)
#meta = self.fusion_metadata(result)
#self.assertTrue(meta.get('enabled'))
#self.assertFalse(meta.get('applied'))
with self.subTest(msg='above fusion threshold'):
circuit = transpile(QFT(threshold + 1),
self.SIMULATOR, basis_gates=['u1', 'u2', 'u', 'cx', 'cz'],
optimization_level=0)
circuit.measure_all()
qobj = assemble(circuit, self.SIMULATOR, shots=shots)
result = self.SIMULATOR.run(
qobj, **backend_options).result()
self.assertSuccess(result)
#meta = self.fusion_metadata(result)
#self.assertTrue(meta.get('enabled'))
#self.assertTrue(meta.get('applied'))
def test_fusion_verbose(self):
"""Test Fusion with verbose option"""
circuit = self.create_statevector_circuit()
shots = 100
qobj = assemble(transpile([circuit], self.SIMULATOR, optimization_level=0),
shots=shots)
with self.subTest(msg='verbose enabled'):
backend_options = self.fusion_options(enabled=True, verbose=True, threshold=1)
result = self.SIMULATOR.run(
qobj, **backend_options).result()
# Assert fusion applied succesfully
self.assertSuccess(result)
#meta = self.fusion_metadata(result)
#self.assertTrue(meta.get('applied', False))
# Assert verbose meta data in output
#self.assertIn('input_ops', meta)
#self.assertIn('output_ops', meta)
with self.subTest(msg='verbose disabled'):
backend_options = self.fusion_options(enabled=True, verbose=False, threshold=1)
result = self.SIMULATOR.run(
qobj, **backend_options).result()
# Assert fusion applied succesfully
self.assertSuccess(result)
#meta = self.fusion_metadata(result)
#self.assertTrue(meta.get('applied', False))
# Assert verbose meta data not in output
#self.assertNotIn('input_ops', meta)
#self.assertNotIn('output_ops', meta)
with self.subTest(msg='verbose default'):
backend_options = self.fusion_options(enabled=True, threshold=1)
result = self.SIMULATOR.run(
qobj, **backend_options).result()
# Assert fusion applied succesfully
self.assertSuccess(result)
#meta = self.fusion_metadata(result)
#self.assertTrue(meta.get('applied', False))
# Assert verbose meta data not in output
#self.assertNotIn('input_ops', meta)
#self.assertNotIn('output_ops', meta)
#def test_kraus_noise_fusion(self):
# """Test Fusion with kraus noise model option"""
# shots = 100
# circuit = self.create_statevector_circuit()
# noise_model = self.noise_model_kraus()
# circuit = transpile([circuit],
# backend=self.SIMULATOR,
# basis_gates=noise_model.basis_gates,
# optimization_level=0)
# qobj = assemble([circuit],
# self.SIMULATOR,
# shots=shots,
# seed_simulator=1)
# backend_options = self.fusion_options(enabled=True, threshold=1)
# result = self.SIMULATOR.run(qobj,
# noise_model=noise_model,
# **backend_options).result()
# method = result.results[0].metadata.get('method')
# #meta = self.fusion_metadata(result)
# if method in ['density_matrix', 'density_matrix_thrust', 'density_matrix_gpu']:
# target_method = 'superop'
# else:
# target_method = 'kraus'
# self.assertSuccess(result)
# #self.assertTrue(meta.get('applied', False),
# # msg='fusion should have been applied.')
# #self.assertEqual(meta.get('method', None), target_method)
#def test_non_kraus_noise_fusion(self):
# """Test Fusion with non-kraus noise model option"""
# shots = 100
# circuit = self.create_statevector_circuit()
# noise_model = self.noise_model_depol()
# circuit = transpile([circuit],
# backend=self.SIMULATOR,
# basis_gates=noise_model.basis_gates,
# optimization_level=0)
# qobj = assemble([circuit],
# self.SIMULATOR,
# shots=shots,
# seed_simulator=1)
# backend_options = self.fusion_options(enabled=True, threshold=1)
# result = self.SIMULATOR.run(qobj,
# noise_model=noise_model,
# **backend_options).result()
# #meta = self.fusion_metadata(result)
# method = result.results[0].metadata.get('method')
# if method in ['density_matrix', 'density_matrix_thrust', 'density_matrix_gpu']:
# target_method = 'superop'
# else:
# target_method = 'unitary'
# self.assertSuccess(result)
# #self.assertTrue(meta.get('applied', False),
# # msg='fusion should have been applied.')
# #self.assertEqual(meta.get('method', None), target_method)
def test_control_fusion(self):
"""Test Fusion enable/disable option"""
shots = 100
circuit = transpile(self.create_statevector_circuit(),
backend=self.SIMULATOR,
optimization_level=0)
qobj = assemble([circuit],
self.SIMULATOR,
shots=shots,
seed_simulator=1)
with self.subTest(msg='fusion enabled'):
backend_options = self.fusion_options(enabled=True, threshold=1)
result = self.SIMULATOR.run(
copy.deepcopy(qobj), **backend_options).result()
#meta = self.fusion_metadata(result)
self.assertSuccess(result)
#self.assertTrue(meta.get('enabled'))
#self.assertTrue(meta.get('applied', False))
with self.subTest(msg='fusion disabled'):
backend_options = backend_options = self.fusion_options(enabled=False, threshold=1)
result = self.SIMULATOR.run(
copy.deepcopy(qobj), **backend_options).result()
#meta = self.fusion_metadata(result)
self.assertSuccess(result)
#self.assertFalse(meta.get('enabled'))
with self.subTest(msg='fusion default'):
backend_options = self.fusion_options()
result = self.SIMULATOR.run(
copy.deepcopy(qobj), **backend_options).result()
#meta = self.fusion_metadata(result)
self.assertSuccess(result)
#self.assertTrue(meta.get('enabled'))
#self.assertFalse(meta.get('applied', False), msg=meta)
def test_fusion_operations(self):
"""Test Fusion enable/disable option"""
shots = 100
num_qubits = 8
qr = QuantumRegister(num_qubits)
cr = ClassicalRegister(num_qubits)
circuit = QuantumCircuit(qr, cr)
circuit.h(qr)
circuit.barrier(qr)
circuit.u(0.1, 0.1, 0.1, qr[0])
circuit.barrier(qr)
circuit.u(0.1, 0.1, 0.1, qr[1])
circuit.barrier(qr)
circuit.cx(qr[1], qr[0])
circuit.barrier(qr)
circuit.u(0.1, 0.1, 0.1, qr[0])
circuit.barrier(qr)
circuit.u(0.1, 0.1, 0.1, qr[1])
circuit.barrier(qr)
circuit.u(0.1, 0.1, 0.1, qr[3])
circuit.barrier(qr)
circuit.x(qr[0])
circuit.barrier(qr)
circuit.x(qr[1])
circuit.barrier(qr)
circuit.x(qr[0])
circuit.barrier(qr)
circuit.x(qr[1])
circuit.barrier(qr)
circuit.cx(qr[2], qr[3])
circuit.barrier(qr)
circuit.u(0.1, 0.1, 0.1, qr[3])
circuit.barrier(qr)
circuit.u(0.1, 0.1, 0.1, qr[3])
circuit.barrier(qr)
circuit.x(qr[0])
circuit.barrier(qr)
circuit.x(qr[1])
circuit.barrier(qr)
circuit.x(qr[0])
circuit.barrier(qr)
circuit.x(qr[1])
circuit.barrier(qr)
circuit.cx(qr[2], qr[3])
circuit.barrier(qr)
circuit.u(0.1, 0.1, 0.1, qr[3])
circuit.barrier(qr)
circuit.u(0.1, 0.1, 0.1, qr[3])
circuit.barrier(qr)
circuit.measure(qr, cr)
circuit = transpile(circuit,
backend=self.SIMULATOR,
optimization_level=0)
qobj = assemble([circuit],
self.SIMULATOR,
shots=shots,
seed_simulator=1)
backend_options = self.fusion_options(enabled=False, threshold=1)
result_disabled = self.SIMULATOR.run(
qobj, **backend_options).result()
#meta_disabled = self.fusion_metadata(result_disabled)
backend_options = self.fusion_options(enabled=True, threshold=1)
result_enabled = self.SIMULATOR.run(
qobj, **backend_options).result()
#meta_enabled = self.fusion_metadata(result_enabled)
#self.assertTrue(getattr(result_disabled, 'success', 'False'))
#self.assertTrue(getattr(result_enabled, 'success', 'False'))
#self.assertFalse(meta_disabled.get('enabled'))
#self.assertTrue(meta_enabled.get('enabled'))
#self.assertTrue(meta_enabled.get('applied'))
#self.assertDictAlmostEqual(result_enabled.get_counts(circuit),
# result_disabled.get_counts(circuit),
# delta=0.0,
# msg="fusion for qft was failed")
def test_fusion_qv(self):
"""Test Fusion with quantum volume"""
shots = 100
num_qubits = 6
depth = 2
circuit = transpile(QuantumVolume(num_qubits, depth, seed=0),
backend=self.SIMULATOR,
optimization_level=0)
circuit.measure_all()
qobj_disabled = assemble([circuit], self.SIMULATOR, shots=shots,
**self.fusion_options(enabled=False, threshold=1, verbose=True))
result_disabled = self.SIMULATOR.run(qobj_disabled).result()
#meta_disabled = self.fusion_metadata(result_disabled)
qobj_enabled = assemble([circuit], self.SIMULATOR, shots=shots,
**self.fusion_options(enabled=True, threshold=1, verbose=True))
result_enabled = self.SIMULATOR.run(qobj_enabled).result()
#meta_enabled = self.fusion_metadata(result_enabled)
#self.assertTrue(getattr(result_disabled, 'success', 'False'))
#self.assertTrue(getattr(result_enabled, 'success', 'False'))
#self.assertFalse(meta_disabled.get('applied', False))
#self.assertTrue(meta_enabled.get('applied', False))
#self.assertDictAlmostEqual(result_enabled.get_counts(circuit),
# result_disabled.get_counts(circuit),
# delta=0.0,
# msg="fusion for qft was failed")
def test_fusion_qft(self):
"""Test Fusion with qft"""
shots = 100
num_qubits = 8
circuit = transpile(QFT(num_qubits),
backend=self.SIMULATOR,
basis_gates=['u1', 'u2', 'u', 'cx', 'cz'],
optimization_level=0)
circuit.measure_all()
qobj = assemble([circuit],
self.SIMULATOR,
shots=shots,
seed_simulator=1)
backend_options = self.fusion_options(enabled=False, threshold=1)
result_disabled = self.SIMULATOR.run(
qobj, **backend_options).result()
#meta_disabled = self.fusion_metadata(result_disabled)
backend_options = self.fusion_options(enabled=True, threshold=1)
result_enabled = self.SIMULATOR.run(
qobj, **backend_options).result()
#meta_enabled = self.fusion_metadata(result_enabled)
#self.assertTrue(getattr(result_disabled, 'success', 'False'))
#self.assertTrue(getattr(result_enabled, 'success', 'False'))
#self.assertFalse(meta_disabled.get('enabled'))
#self.assertTrue(meta_enabled.get('enabled'))
#self.assertTrue(meta_enabled.get('applied'))
#self.assertDictAlmostEqual(result_enabled.get_counts(circuit),
# result_disabled.get_counts(circuit),
# delta=0.0,
# msg="fusion for qft was failed")
|
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.
"""Class for an Imaginary McLachlan's Variational Principle."""
from __future__ import annotations
import warnings
from collections.abc import Sequence
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.primitives import Estimator
from qiskit.quantum_info.operators.base_operator import BaseOperator
from .imaginary_variational_principle import ImaginaryVariationalPrinciple
from ....exceptions import AlgorithmError
from ....gradients import (
BaseEstimatorGradient,
BaseQGT,
DerivativeType,
LinCombQGT,
LinCombEstimatorGradient,
)
class ImaginaryMcLachlanPrinciple(ImaginaryVariationalPrinciple):
"""Class for an Imaginary McLachlan's Variational Principle. It aims to minimize the distance
between both sides of the Wick-rotated Schrödinger equation with a quantum state given as a
parametrized trial state. The principle leads to a system of linear equations handled by a
linear solver. The imaginary variant means that we consider imaginary time dynamics.
"""
def __init__(
self,
qgt: BaseQGT | None = None,
gradient: BaseEstimatorGradient | None = None,
) -> None:
"""
Args:
qgt: Instance of a the GQT class used to compute the QFI.
If ``None`` provided, ``LinCombQGT`` is used.
gradient: Instance of a class used to compute the state gradient.
If ``None`` provided, ``LinCombEstimatorGradient`` is used.
Raises:
AlgorithmError: If the gradient instance does not contain an estimator.
"""
self._validate_grad_settings(gradient)
if gradient is not None:
try:
estimator = gradient._estimator
except Exception as exc:
raise AlgorithmError(
"The provided gradient instance does not contain an estimator primitive."
) from exc
else:
estimator = Estimator()
gradient = LinCombEstimatorGradient(estimator)
if qgt is None:
qgt = LinCombQGT(estimator)
super().__init__(qgt, gradient)
def evolution_gradient(
self,
hamiltonian: BaseOperator,
ansatz: QuantumCircuit,
param_values: Sequence[float],
gradient_params: Sequence[Parameter] | None = None,
) -> np.ndarray:
"""
Calculates an evolution gradient according to the rules of this variational principle.
Args:
hamiltonian: Operator used for Variational Quantum Time Evolution.
ansatz: Quantum state in the form of a parametrized quantum circuit.
param_values: Values of parameters to be bound.
gradient_params: List of parameters with respect to which gradients should be computed.
If ``None`` given, gradients w.r.t. all parameters will be computed.
Returns:
An evolution gradient.
Raises:
AlgorithmError: If a gradient job fails.
"""
try:
evolution_grad_lse_rhs = (
self.gradient.run([ansatz], [hamiltonian], [param_values], [gradient_params])
.result()
.gradients[0]
)
except Exception as exc:
raise AlgorithmError("The gradient primitive job failed!") from exc
return -0.5 * evolution_grad_lse_rhs
@staticmethod
def _validate_grad_settings(gradient):
if (
gradient is not None
and hasattr(gradient, "_derivative_type")
and gradient._derivative_type != DerivativeType.REAL
):
warnings.warn(
"A gradient instance with a setting for calculating imaginary part of "
"the gradient was provided. This variational principle requires the"
"real part. The setting to real was changed automatically."
)
gradient._derivative_type = DerivativeType.REAL
|
https://github.com/ShabaniLab/q-camp
|
ShabaniLab
|
import numpy as np
v = np.array([1, 1])
v2 = np.array([[1], [1]])
u = np.array([0, -1, 2, 3, -0.3])
r = np.zeros(5)
r2 = np.zeros((5, 1))
print(v)
print(v2)
print(u)
print(r)
print(r2)
print(u[3])
u2 = u[:3]
print(u2)
u3 = u[3:]
print(u3)
def norm(x):
sum = 0
for val in x:
sum = sum + val**2
return np.sqrt(sum)
v = np.array([3, -1, 0, 1, 2, -1])
v_norm = norm(v)
print(v_norm)
def dot_product(x, y):
sum = 0
for i in range(len(x)):
sum = sum + x[i]*y[i]
return sum
v = np.array([3, -1, 0, 1, 2, -1])
u = np.array([1, 2, 3, -4, 0.2, 1])
print(dot_product(u, v))
v = np.array([1, -1, 3])
print(norm(v))
print(dot_product(v, v))
print(np.sqrt(dot_product(v, v)))
X = np.array([[0, 1], [1, 0]])
print(X)
Y = np.array([[1, 3, 1], [0, -0.4, 5]])
print(Y)
Z = np.array([[2, -1, 2, 7],[-1.1, 3.3, 4, 0.7],[9, -8, 2, 0]])
print(Z)
print(np.shape(Y))
def mult(A, B):
C = np.zeros((np.shape(A)[0], np.shape(B)[1]))
if np.shape(A)[1] == np.shape(B)[0]:
for i in range(np.shape(A)[0]):
row = A[i, :]
for j in range(np.shape(B)[1]):
col = B[:, j]
C[i, j] = dot_product(row, col)
else:
raise ValueError("dimensions do not match!")
return C
X = np.array([[0, 1, 3], [2, 4, 8]])
Y = np.array([[0], [2], [-5]])
print(mult(X, Y))
def equal(A, B):
if np.shape(A)[0] != np.shape(B)[0]:
return False
if np.shape(A)[1] != np.shape(B)[1]:
return False
for i in range(np.shape(A)[0]):
for j in range(np.shape(A)[1]):
if A[i, j] != B[i, j]:
return False
return True
print(equal(X, X))
def transpose(A):
A_T = np.zeros((np.shape(A)[1], np.shape(A)[0]), dtype=np.complex128)
for i in range(np.shape(A)[0]):
for j in range(np.shape(A)[1]):
A_T[j, i] = A[i, j]
return A_T
print(transpose(np.array([[1, 3, 0], [-1, 2, 4]], dtype=np.complex128)))
def conjugate(A):
A_C = np.zeros_like(A, dtype=np.complex128)
for i in range(np.shape(A)[0]):
for j in range(np.shape(A)[1]):
A_C[i, j] = np.conjugate(A[i, j])
return A_C
A = np.array([[1, 3j, 0], [-1j + 1, 2, 4]], dtype=np.complex128)
print(conjugate(transpose(A)))
def is_hermitian(A):
A_TC = conjugate(transpose(A))
return equal(A, A_TC)
print(is_hermitian(A))
B = np.array([[2, 1 + 1j], [1 - 1j, 3]])
print(is_hermitian(B))
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.transpiler import CouplingMap
from qiskit.converters import dag_to_circuit
from qiskit.transpiler.layout import Layout
import numpy as np
from qiskit.transpiler.passes import Unroller
from qiskit.transpiler.passes import (
TrivialLayout,
BasicSwap,
ApplyLayout,
SetLayout,
SabreLayout,
FullAncillaAllocation,
EnlargeWithAncilla,
)
from qiskit.transpiler.passmanager import PassManager
from virtual_swap.deprecated.cns_sabre import CNS_SabreSwap
# load a dummy circuit
# generate network of random cnots
n, M = 3, 8
N = n**2
register = QuantumRegister(N)
qc = QuantumCircuit(register)
for _ in range(M):
qc.cx(*np.random.choice(N, 2, replace=False))
qc.decompose().draw("mpl")
# load a dummy coupling map and layout
coupling = CouplingMap.from_line(N)
layout = Layout({q: i for q, i in zip(register, range(N))})
# print DAG
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(qc)
dag.draw("mpl")
set_pass = SetLayout(layout)
dag_p = set_pass.run(dag)
apply_pass = ApplyLayout()
apply_pass.property_set = set_pass.property_set
dag_p = apply_pass.run(dag_p)
dag_p.draw("mpl")
# get layers of the DAG
"""A layer is a circuit whose gates act on disjoint qubits, i.e., a layer has depth 1. The total number of layers equals the circuit depth d. The layers are indexed from 0 to d-1 with the earliest layer at index 0. The layers are constructed using a greedy algorithm. Each returned layer is a dict containing {“graph”: circuit graph, “partition”: list of qubit lists}.
The returned layer contains new (but semantically equivalent) DAGOpNodes, DAGInNodes, and DAGOutNodes. These are not the same as nodes of the original dag, but are equivalent via DAGNode.semantic_eq(node1, node2)."""
# convert generator to list
layers = list(dag_p.layers())
for layer in layers:
print(layer)
# # get serial layers
# """A serial layer is a circuit with one gate. The layers have the same structure as in layers()."""
# serial_layers = dag.serial_layers()
# for layer in serial_layers:
# print(layer)
# # get multigraph layers
# multi_layers = dag.multigraph_layers()
# for layer in multi_layers:
# print(layer)
# want to get topological distance from output F and inputs to F'
cns_sub = False
F = layers[0]["graph"]
F_prime = layers[1]["graph"]
F.draw()
# F.output_map
from virtual_swap.cns_transform import cns_transform
from qiskit.circuit.library.standard_gates import CXGate
# get cx from F
cns_sub = True
cns_cx = F.op_nodes(CXGate)[0]
F_cns = cns_transform(F, cns_cx)
F_cns.draw()
# def evaluate_layer(F, F_prime):
# # cost from F:output -> F':input
# work on getting output permutations from a single layer
# this includes virtual swaps + slack swaps that don't affect the depth
v_to_p = layout.get_virtual_bits()
# FIXME, SABRE does meet in middle to increase parallelism
# we need to implement our own here,
# tests both CNS subs and slack swaps
swapper = BasicSwap(coupling)
if cns_sub:
F_swapped = swapper.run(F_cns)
else:
F_swapped = swapper.run(F)
F_swapped.draw()
# swapper.property_set
# XXX this needs to be manually set following a swap pass
f_layout = swapper.property_set["final_layout"]
if cns_sub:
temp = f_layout[cns_cx.qargs[0]]
f_layout[cns_cx.qargs[0]] = f_layout[cns_cx.qargs[1]]
f_layout[cns_cx.qargs[1]] = temp
print(f_layout)
f_v_to_p = f_layout.get_virtual_bits()
print(f_v_to_p)
# for x in F_swapped.output_map.items():
# print(x)
F_prime.draw()
trial_cost = 0
for x in F_prime.two_qubit_ops():
print(f_v_to_p[x.qargs[0]], f_v_to_p[x.qargs[1]])
print(coupling.distance(f_v_to_p[x.qargs[0]], f_v_to_p[x.qargs[1]]))
trial_cost += coupling.distance(f_v_to_p[x.qargs[0]], f_v_to_p[x.qargs[1]])
# FIXME do we want to return sum or max?
print(f"Trial cost", trial_cost)
# we need to define a cost function, intermediate layer to front layer
# the intermediate layer are gates that are physical on the topology
# the intermediate layer considers CNS subs and placement of SWAP gates
# once a permutation of the intermediate layer is found that minimizes cost to the front layer
# move the intermediate layer to the mapped dag, and front layer to intermediate layer
# once the front layer is empty, we are done
# open question, do we resolve all dependencies between intermediate and front layer at once?
# maybe we find a route for one gate, then pop the next gate in
# if we have a dynamic layer, makes reasoning about cost and when to move gates harder
# but that is how SABRE works, just by iteratively checking what is physical
# repeat pushing things over until we can't push anymore
# idk, I think conceptually treating it as a set of layers that need to be resolved is easier
# we define the minimum about of gates that add to the depth of the circuit for data movement
# types of SWAP paths we could take
# if 2 qubits can meet, they can SWAP together to meet at midpoint between them
# however, we might prefer to meet biased towards one qubit (for sake of lookahead)
# then, we incur a higher depth cost on this layer, but hopefully reduces lookahead cost
# so define a depth cost on the layer,
# maybe we just do the thing that tells us which decomp to use first
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
# ******************************************************************************
# Copyright (c) 2020-2024 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 time import sleep
from qiskit import QiskitError, QuantumRegister, execute, Aer
from qiskit.compiler import assemble
from qiskit.providers.exceptions import JobError, JobTimeoutError
from qiskit.providers.ibmq import IBMQ
from qiskit.providers.jobstatus import JOB_FINAL_STATES
from qiskit.utils.mitigation import CompleteMeasFitter, complete_meas_cal
def get_qpu(token, qpu_name, url='https://auth.quantum-computing.ibm.com/api', hub='ibm-q', group='open',
project='main'):
"""Load account from token. Get backend."""
try:
IBMQ.disable_account()
except:
pass
provider = IBMQ.enable_account(token=token, url=url, hub=hub, group=group, project=project)
if 'simulator' in qpu_name:
backend = Aer.get_backend('aer_simulator')
else:
backend = provider.get_backend(qpu_name)
return backend
def delete_token():
"""Delete account."""
IBMQ.delete_account()
def execute_job(transpiled_circuits, shots, backend, noise_model):
"""Generate qObject from transpiled circuit and execute it. Return result."""
try:
job = backend.run(assemble(transpiled_circuits, shots=shots), noise_model=noise_model)
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 (JobError, JobTimeoutError):
return None
def get_meas_fitter(token, qpu_name, shots):
"""Execute the calibration circuits on the given backend and calculate resulting matrix."""
print("Starting calculation of calibration matrix for QPU: ", qpu_name)
backend = get_qpu(token, qpu_name)
# Generate a calibration circuit for each state
qr = QuantumRegister(len(backend.properties().qubits))
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# Execute each calibration circuit and store results
print('Executing ' + str(len(meas_calibs)) + ' circuits to create calibration matrix...')
cal_results = []
for circuit in meas_calibs:
print('Executing circuit ' + circuit.name)
cal_results.append(execute_calibration_circuit(circuit, shots, backend))
# Generate calibration matrix out of measurement results
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
return meas_fitter.filter
def execute_calibration_circuit(circuit, shots, backend):
"""Execute a calibration circuit on the specified backend"""
job = execute(circuit, backend=backend, shots=shots)
job_status = job.status()
while job_status not in JOB_FINAL_STATES:
print('The execution is still running')
sleep(20)
job_status = job.status()
return job.result()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_qsphere(state)
|
https://github.com/strangequarkkk/BB84-Protocol-for-QKD
|
strangequarkkk
|
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
qc.barrier()
# Alice now sends the qubit to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
# Alice now sends the qubit to Bob
# but Eve intercepts and tries to read it
qc.measure(0, 0)
qc.barrier()
# Eve then passes this on to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
n = 100
## Step 1
# Alice generates bits.
alice_bits = np.random.randint(0,2,n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = np.random.randint(0,2,n)
# Function to compare the bits & bases generated by alice, and then 'encode' the message. Basically determines the state of the qubit/photon to send.
def encode_message(bits, bases):
message = []
for i in range(n):
qc = QuantumCircuit(1,1)
if bases[i] == 0: # Prepare qubit in Z-basis
if bits[i] == 0:
pass
else:
qc.x(0)
else: # Prepare qubit in X-basis
if bits[i] == 0:
qc.h(0)
else:
qc.x(0)
qc.h(0)
qc.barrier()
message.append(qc)
return message
# Alice computes the encoded message using the function defined above.
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = np.random.randint(0,2,n)
# Function to decode the message sent by alice by comparing qubit/photon states with Bob's generated bases.
def measure_message(message, bases):
backend = Aer.get_backend('aer_simulator')
measurements = []
for q in range(n):
if bases[q] == 0: # measuring in Z-basis
message[q].measure(0,0)
if bases[q] == 1: # measuring in X-basis
message[q].h(0)
message[q].measure(0,0)
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(message[q], shots=1, memory=True)
result = aer_sim.run(qobj).result()
measured_bit = int(result.get_memory()[0])
measurements.append(measured_bit)
return measurements
# Decode the message according to his bases
bob_results = measure_message(message, bob_bases)
## Step 4
# Function to perform sifting i.e. disregard the bits for which Bob's & A;ice's bases didnot match.
def remove_garbage(a_bases, b_bases, bits):
good_bits = []
for q in range(n):
if a_bases[q] == b_bases[q]:
# If both used the same basis, add
# this to the list of 'good' bits
good_bits.append(bits[q])
return good_bits
# Performing sifting for Alice's and Bob's bits.
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
print("Alice's key after sifting (without interception)", alice_key)
print("Bob's key after sifting (without interception) ", bob_key)
# # Step 5
# # Function for parameter estimation i.e. determining the error rate by comparing subsets taen from both Alice's key & Bob's key.
# def sample_bits(bits, selection):
# sample = []
# for i in selection:
# # use np.mod to make sure the
# # bit we sample is always in
# # the list range
# i = np.mod(i, len(bits))
# # pop(i) removes the element of the
# # list at index 'i'
# sample.append(bits.pop(i))
# return sample
# # Performing parameter estimation & disregarding the bits used for comparison from Alice's & Bob's key.
# sample_size = 15
# bit_selection = np.random.randint(0,n,size=sample_size)
# bob_sample = sample_bits(bob_key, bit_selection)
# alice_sample = sample_bits(alice_key, bit_selection)
num = 0
for i in range(0,len(bob_key)):
if alice_key[i] == bob_key[i]:
num = num + 1
matching_bits = (num/len(bob_key))*100
print(matching_bits,"% of the bits match.")
## Step 1
alice_bits = np.random.randint(2, size=n)
## Step 2
alice_bases = np.random.randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = np.random.randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = np.random.randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
print("Alice's key after sifting (with interception)", alice_key)
print("Bob's key after sifting (with interception) ", bob_key)
# ## Step 5
# sample_size = 15
# bit_selection = np.random.randint(n, size=sample_size)
# bob_sample = sample_bits(bob_key, bit_selection)
# alice_sample = sample_bits(alice_key, bit_selection)
num = 0
for i in range(0,len(bob_key)):
if alice_key[i] == bob_key[i]:
num = num + 1
matching_bits = (num/len(bob_key))*100
print(matching_bits,"% of the bits match.")
plt.rcParams['axes.linewidth'] = 2
mpl.rcParams['font.family'] = ['Georgia']
plt.figure(figsize=(10.5,6))
ax=plt.axes()
ax.set_title('')
ax.set_xlabel('$n$ (Number of bits drawn from the sifted keys for determining error rate)',fontsize = 18,labelpad=10)
ax.set_ylabel(r'$P(Eve\ detected)$',fontsize = 18,labelpad=10)
ax.xaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on')
ax.yaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on')
ax.tick_params(axis='x', labelsize=20)
ax.tick_params(axis='y', labelsize=20)
ax. xaxis. label. set_size(20)
ax. yaxis. label. set_size(20)
n = 30
x = np.arange(n+1)
y = 1 - 0.75**x
ax.plot(x,y,color = plt.cm.rainbow(np.linspace(0, 1, 5))[0], marker = "s", markerfacecolor='r')
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
import numpy as np
from qiskit import QuantumCircuit, execute, Aer
from qiskit.quantum_info import Statevector
import kaleidoscope.qiskit
from kaleidoscope import qsphere, probability_distribution
# import basic plot tools
from qiskit.visualization import plot_histogram, plot_state_qsphere
# A Circuit is something as simple as a Qubit with a 0 or a 1.
qc = QuantumCircuit(1)
state = Statevector.from_instruction(qc)
qsphere(state)
# Or a 1
qc.x(0)
state = Statevector.from_instruction(qc)
qsphere(state)
# Now we simulate 3 Qubits
qc = QuantumCircuit(3)
qc.h(range(3))
qc.cz(0,1)
state = Statevector.from_instruction(qc)
qsphere(state)
qc.draw()
# Representing 5 Qubits
qc2 = QuantumCircuit(5)
qc2.h(range(4))
qc2.x(4)
qc2.h(4)
#qc2.barrier()
# "Mark" |11011>
qc2.x(2)
qc2.mct([0,1,2,3], 4)
qc2.x(2)
# "Mark" |11110>
#qc2.x(0)
#qc2.mct([0,1,2,3], 4)
#qc2.x(0)
qc2.h(4)
#qc2.barrier()
qc2.draw('mpl')
statevector = Statevector.from_instruction(qc2)
qsphere(statevector)
qc2.measure_all()
backend = Aer.get_backend("qasm_simulator")
result = execute(qc2, backend=backend, shots=1000).result()
probability_distribution(result.get_counts(qc2))
# Very simple circuit explanation
qc3 = QuantumCircuit(3)
# 1: No Gates
qc3.i(range(3))
# 2: Some Gates
#qc3.x(0)
#qc3.x(1)
# 3: X on all gates
#qc3.x(range(3))
# 4: Superposition
#qc3.x(range(3))
# 5: With some X as well
#qc3.h(range(3))
qc3.draw('mpl')
statevector = Statevector.from_instruction(qc3)
qsphere(statevector)
qc3.measure_all()
backend = Aer.get_backend("qasm_simulator")
result = execute(qc3, backend=backend, shots=1000).result()
probability_distribution(result.get_counts(qc3))
### NEW CIRCUIT WITH 3 QUBITS
### SOLUTIONS: 101 AND 110
def phase_oracle(circuit):
circuit.cz(0, 2)
circuit.cz(1, 2)
def diffuser(circuit):
"""Apply inversion about the average step of Grover's algorithm."""
qubits = circuit.qubits
nqubits = len(qubits)
for q in range(nqubits):
circuit.h(q)
circuit.x(q)
# Do controlled-Z
circuit.h(2)
circuit.ccx(0,1,2)
circuit.h(2)
for q in range(nqubits):
circuit.x(q)
circuit.h(q)
## First we create superposition
n = 3
grover_circuit = QuantumCircuit(n)
grover_circuit.h(range(n))
grover_circuit.barrier()
grover_circuit.draw(output="mpl")
statevector = Statevector.from_instruction(grover_circuit)
qsphere(statevector)
# The Quantum Computer "marks" the solutions
phase_oracle(grover_circuit)
grover_circuit.draw(output="mpl")
statevector = Statevector.from_instruction(grover_circuit)
qsphere(statevector)
# User interference to keep only the solution states
grover_circuit.barrier()
diffuser(grover_circuit)
grover_circuit.draw(output="mpl")
statevector = Statevector.from_instruction(grover_circuit)
qsphere(statevector)
grover_circuit.measure_all()
backend = Aer.get_backend('qasm_simulator')
results = execute(grover_circuit, backend=backend, shots=1000).result()
probability_distribution(results.get_counts(grover_circuit))
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
filepath = "../datasets/universal_error/ThermalOnly/U3_14.csv"
df = pd.read_csv(filepath)
# reorder columns
df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'p0_0', 'p0_1', 'p1_0', 'p1_1']]
# filter out inf values
df = df[np.isfinite]
df.info()
df.head()
sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]})
sns.distplot(df['E'], norm_hist=False, kde=False, bins=50, hist_kws={'alpha': 1}).set(xlabel="'Expected Value", ylabel='Count')
df.hist(bins=100, figsize=(20,15), layout=(3,4));
sns.scatterplot(x=df['theta'], y=df['E']);
sns.jointplot(x=df['theta'], y=df['E']);
sns.scatterplot(x=df['phi'], y=df['E']);
sns.scatterplot(x=df['lam'], y=df['E']);
sns.scatterplot(x=df['theta'], y=df['phi']);
sns.scatterplot(x=df['depol_prob'], y=df['E']);
sns.jointplot(x=df['t1'], y=df['E']);
sns.jointplot(x=df['t2'], y=df['E']);
sns.scatterplot(x=df['t1'], y=df['E']);
sns.scatterplot(x=df['t2'], y=df['E']);
sns.pairplot(data=df);
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from math import pi
import numpy as np
from qiskit_nature.operators.second_quantization.fermionic_op import FermionicOp
from qiskit_nature.problems.second_quantization.lattice import HyperCubicLattice, LineLattice, SquareLattice, TriangularLattice
from qiskit_nature.problems.second_quantization.lattice import FermiHubbardModel
num_nodes = 6
boundary_condition = 'open'
line = LineLattice(
num_nodes = num_nodes,
boundary_condition=boundary_condition
)
line.draw()
num_nodes = 11
boundary_condition = 'periodic' # `boundary_condition` must be 'open' or 'periodic'.
line_p = LineLattice(
num_nodes = num_nodes,
boundary_condition=boundary_condition
)
line_p.draw()
rows = 4
cols = 3
boundary_condition = 'open'
square = SquareLattice(
rows=rows,
cols=cols,
boundary_condition=boundary_condition
)
square.draw()
rows = 4
cols = 3
boundary_condition = ('open', 'periodic') # open in the x-direction, periodic in the y-direction
square_op = SquareLattice(
rows=rows,
cols=cols,
boundary_condition=boundary_condition
)
square_op.draw()
size = (3, 4, 5)
boundary_condition = ('open', 'open', 'open')
hypercubic = HyperCubicLattice(
size=size,
boundary_condition=boundary_condition
)
# function for setting the positions
def indextocoord_3d(index:int, size:tuple, angle) -> list:
z = index // (size[0]*size[1])
a = index % (size[0]*size[1])
y = a // size[0]
x = a % size[0]
vec_x = np.array([1, 0])
vec_y = np.array([np.cos(angle), np.sin(angle)])
vec_z = np.array([0, 1])
return_coord = x*vec_x + y*vec_y + z*vec_z
return return_coord.tolist()
pos = dict([(index, indextocoord_3d(index, size, angle=pi/4)) for index in range(np.prod(size))])
hypercubic.draw(pos=pos)
rows = 4
cols = 3
boundary_condition = 'open'
triangular = TriangularLattice(
rows=rows,
cols=cols,
boundary_condition=boundary_condition
)
triangular.draw()
line = LineLattice(
num_nodes=3,
boundary_condition='open'
)
line.draw()
t = -1.0
t_onsite = 0.0
U = 5.0
fhm = FermiHubbardModel.uniform_parameters(
lattice=line,
uniform_hopping=t,
uniform_onsite_potential=t_onsite,
onsite_interaction=U)
FermionicOp.set_truncation(0)
print(fhm.second_q_ops(display_format='sparse'))
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import SLSQP
from qiskit.circuit.library import RealAmplitudes
from qiskit.opflow import AerPauliExpectation
from qiskit.providers.aer import AerSimulator
# make a lattice
line = LineLattice(
num_nodes=3,
boundary_condition='open'
)
# the FHM
t = -1.0
t_onsite = 0.0
U = 5.0
fhm = FermiHubbardModel.uniform_parameters(
lattice=line,
uniform_hopping=t,
uniform_onsite_potential=t_onsite,
onsite_interaction=U
)
# the FHM in terms of `FermionicOp`
ham = fhm.second_q_ops(display_format='sparse')
print(ham.reduce())
# convert the Hamiltonian to qubits
qubit_converter = QubitConverter(mapper=JordanWignerMapper())
qubit_op = qubit_converter.convert(ham)
# define the quantum circuit
circ = RealAmplitudes(num_qubits=ham.register_length, reps=2)
print('Quantum circuit')
print(circ.decompose().draw())
# make the vqe instance
vqe = VQE(
ansatz=circ,
optimizer=SLSQP(),
expectation=AerPauliExpectation(),
max_evals_grouped=9999,
quantum_instance=AerSimulator()
)
result = vqe.compute_minimum_eigenvalue(operator=qubit_op)
energy = np.real(result.eigenvalue)
print(f'Energy: {energy}')
|
https://github.com/JayRGopal/Quantum-Error-Correction
|
JayRGopal
|
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, execute
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()
y_target = 3
def f(x):
return x # can be any function!
def oracle(x):
return f(x) == y_target # logic to determine this oracle can be anything ! This is just the simplest example ... but hopefully only ONE satisfying value or answers are inconsistent
N = 10
for i in range(N):
if oracle(i):
print("%i satisfies f(x)" % i)
oracle = QuantumCircuit(2,name='oracle')
oracle.cz(0,1)
oracle.to_gate()
oracle.draw()
grover = QuantumCircuit(2,2)
grover.h([0,1])
grover.append(oracle,[0,1])
grover.draw()
backend = Aer.get_backend('statevector_simulator')
job = execute(grover,backend)
result = job.result()
sv = result.get_statevector()
np.around(sv,2)
reflection = QuantumCircuit(2,name='reflection')
reflection.h([0,1])
reflection.z([0,1])
reflection.cz(0,1)
reflection.h([0,1])
reflection.to_gate()
reflection.draw()
backend = Aer.get_backend('qasm_simulator')
grover = QuantumCircuit(2,2)
grover.h([0,1])
grover.append(oracle,[0,1])
grover.append(reflection,[0,1]) # repeat sqrt(N) times...
grover.measure([0,1],[0,1])
grover.draw()
job = execute(grover,backend,shots=1)
job.result().get_counts()
|
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
|
vandnaChaturvedi
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
import math
# importing Qiskit
####################################################################################################################### qiskit_edit_1
import qiskit
from qiskit import QuantumCircuit, execute
from qiskit import QuantumRegister, ClassicalRegister
from qiskit.tools.monitor import job_monitor
from qiskit import *
import time
import matplotlib.pyplot as plt
import argparse
import sys
from concurrent.futures import ThreadPoolExecutor
import resource
from time import sleep
#########################################################################################################################
# import basic plot tools
from qiskit.visualization import plot_histogram
qpe = QuantumCircuit(4, 3)
qpe.x(3)
qpe.draw()
for qubit in range(3):
qpe.h(qubit)
qpe.draw()
repetitions = 1
for counting_qubit in range(3):
for i in range(repetitions):
qpe.cp(math.pi/4, counting_qubit, 3); # This is CU
repetitions *= 2
qpe.draw()
def qft_dagger(qc, n):
"""n-qubit QFTdagger the first n qubits in circ"""
# Don't forget the Swaps!
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-math.pi/float(2**(j-m)), m, j)
qc.h(j)
qpe.barrier()
# Apply inverse QFT
qft_dagger(qpe, 3)
# Measure
qpe.barrier()
for n in range(3):
qpe.measure(n,n)
qpe.draw()
aer_sim = Aer.get_backend('aer_simulator')
shots = 2048
t_qpe = transpile(qpe, aer_sim)
qobj = assemble(t_qpe, shots=shots)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
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:
qft_dagger(qpe2, 3)
# Measure of course!
for n in range(3):
qpe2.measure(n,n)
qpe2.draw()
# Let's see the results!
aer_sim = Aer.get_backend('aer_simulator')
shots = 4096
t_qpe2 = transpile(qpe2, aer_sim)
qobj = assemble(t_qpe2, shots=shots)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
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:
qft_dagger(qpe3, 5)
# Measure of course!
qpe3.barrier()
for n in range(5):
qpe3.measure(n,n)
qpe3.draw()
# Let's see the results!
aer_sim = Aer.get_backend('aer_simulator')
shots = 4096
t_qpe3 = transpile(qpe3, aer_sim)
qobj = assemble(t_qpe3, shots=shots)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
qpe.draw()
IBMQ.load_account()
from qiskit.tools.monitor import job_monitor
provider = IBMQ.get_provider(hub='ibm-q')
santiago = provider.get_backend('ibmq_santiago')
# Run with 2048 shots
shots = 2048
t_qpe = transpile(qpe, santiago, optimization_level=3)
job = santiago.run(t_qpe, shots=shots)
job_monitor(job)
# get the results from the computation
results = job.result()
answer = results.get_counts(qpe)
plot_histogram(answer)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
ghz.draw(output='mpl')
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
device = 'ibmq_16_melbourne'
from qiskit import IBMQ
IBMQ.load_accounts()
backend = IBMQ.get_backend(device)
num = backend.configuration()['n_qubits']
coupling_map = backend.configuration()['coupling_map']
print('number of qubits\n',num,'\n')
print('list of pairs of qubits that are directly connected\n',coupling_map)
if device in ['ibmqx2','ibmqx4']:
pos = { 0: (1,1), 1: (1,0), 2: (0.5,0.5), 3: (0,0), 4: (0,1) }
elif device in ['ibmqx5']:
pos = { 0: (0,0), 1: (0,1), 2: (1,1), 3: (2,1), 4: (3,1), 5: (4,1), 6: (5,1), 7: (6,1),
8: (7,1), 9: (7,0), 10: (6,0), 11: (5,0), 12: (4,0), 13: (3,0), 14: (2,0), 15: (1,0) }
elif device in ['ibmq_16_melbourne']:
pos = { 0: (0,1), 1: (1,1), 2: (2,1), 3: (3,1), 4: (4,1), 5: (5,1), 6: (6,1),
7: (7,0), 8: (6,0), 9: (5,0), 10: (4,0), 11: (3,0), 12: (2,0), 13: (1,0) }
import sys
sys.path.append('game_engines')
from universal import layout
grid = layout(num,coupling_map,pos)
grid.plot()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
import numpy as np
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qp = QuantumCircuit(qr,cr)
qp.rx( np.pi/2,qr[0])
qp.cx(qr[0],qr[1])
qp.measure(qr,cr)
circuit_drawer(qp)
from qiskit import execute
from qiskit import Aer
job = execute(qp,backend=Aer.get_backend('qasm_simulator'))
results = job.result().get_counts()
print(results)
pairs = grid.matching()
print(pairs)
import random
qr = QuantumRegister(num)
cr = ClassicalRegister(num)
qp = QuantumCircuit(qr,cr)
for pair in pairs:
qp.ry( (1+2*random.random())*np.pi/4,qr[pair[0]]) # angle generated randonly between pi/4 and 3pi/4
qp.cx(qr[pair[0]],qr[pair[1]])
qp.measure(qr,cr)
from qiskit import execute
job = execute(qp,backend=IBMQ.get_backend('ibmq_qasm_simulator'))
results = job.result().get_counts()
probs = grid.calculate_probs(results)
grid.plot(probs=probs)
job = execute(qp,backend=backend)
results = job.result().get_counts()
probs = grid.calculate_probs(results)
grid.plot(probs=probs)
def mitigate(probs):
av_prob = {}
for j in range(num): # for each qubit, work out which neighbour it agrees with most
neighbours = []
for pair in grid.links:
if j in grid.links[pair]:
neighbours.append(pair)
(guessed_pair,val) = (None,1)
for pair in neighbours:
if probs[pair]<val:
guessed_pair = pair
val = probs[pair]
# then find the average probability of a 1 for the two
av_prob[j] = (probs[grid.links[guessed_pair][0]]+probs[grid.links[guessed_pair][1]])/2
# replace the probabilities for all qubits with these averages
for j in range(num):
probs[j] = av_prob[j]
return probs
probs = mitigate(probs)
grid.plot(probs=probs)
pair_labels = {}
colors = {}
for node in grid.pos:
if type(node)==str:
pair_labels[node] = node
colors[node] = (0.5,0.5,0.5)
chosen_pairs = []
m = 0
while len(chosen_pairs)<len(pairs):
m += 1
print('\nMOVE',m)
grid.plot(probs=probs,labels=pair_labels,colors=colors)
pair = str.upper(input(" > Type the name of a pair of qubits whose numbers are the same (or very similar)...\n"))
chosen_pairs.append( pair )
colors[pair] = (0.5,0.5,0.5)
for j in range(2):
colors[grid.links[pair][j]] = (0.5,0.5,0.5)
grid.plot(probs=probs,labels=pair_labels,colors=colors)
success = True
for pair in chosen_pairs:
success = success and ( (grid.links[pair] in pairs) or (grid.links[pair][::-1] in pairs) )
if success:
input("\n ** You got all the correct pairs! :) **\n\n Press any key to continue\n")
else:
input("\n ** You didn't get all the correct pairs! :( **\n\n Press any key to continue\n")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
|
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# 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.
# pylint: disable=invalid-name
"""
Simplified noise models for devices backends.
"""
import logging
from warnings import warn, catch_warnings, filterwarnings
from numpy import inf, exp, allclose
import qiskit.quantum_info as qi
from .parameters import readout_error_values
from .parameters import gate_param_values
from .parameters import thermal_relaxation_values
from .parameters import _NANOSECOND_UNITS
from ..errors.readout_error import ReadoutError
from ..errors.standard_errors import depolarizing_error
from ..errors.standard_errors import thermal_relaxation_error
logger = logging.getLogger(__name__)
def basic_device_readout_errors(properties):
"""
Return readout error parameters from a devices BackendProperties.
Args:
properties (BackendProperties): device backend properties
Returns:
list: A list of pairs ``(qubits, ReadoutError)`` for qubits with
non-zero readout error values.
"""
errors = []
for qubit, value in enumerate(readout_error_values(properties)):
if value is not None and not allclose(value, [0, 0]):
probabilities = [[1 - value[0], value[0]], [value[1], 1 - value[1]]]
errors.append(([qubit], ReadoutError(probabilities)))
return errors
def basic_device_gate_errors(properties,
gate_error=True,
thermal_relaxation=True,
gate_lengths=None,
gate_length_units='ns',
temperature=0,
standard_gates=None,
warnings=True):
"""
Return QuantumErrors derived from a devices BackendProperties.
If non-default values are used gate_lengths should be a list
of tuples ``(name, qubits, value)`` where ``name`` is the gate
name string, ``qubits`` is either a list of qubits or ``None``
to apply gate time to this gate one any set of qubits,
and ``value`` is the gate time in nanoseconds.
Args:
properties (BackendProperties): device backend properties
gate_error (bool): Include depolarizing gate errors (Default: True).
thermal_relaxation (Bool): Include thermal relaxation errors
(Default: True).
gate_lengths (list): Override device gate times with custom
values. If None use gate times from
backend properties. (Default: None).
gate_length_units (str): Time units for gate length values in gate_lengths.
Can be 'ns', 'ms', 'us', or 's' (Default: 'ns').
temperature (double): qubit temperature in milli-Kelvin (mK)
(Default: 0).
standard_gates (bool): DEPRECATED, If true return errors as standard
qobj gates. If false return as unitary
qobj instructions (Default: None).
warnings (bool): Display warnings (Default: True).
Returns:
list: A list of tuples ``(label, qubits, QuantumError)``, for gates
with non-zero quantum error terms, where `label` is the label of the
noisy gate, `qubits` is the list of qubits for the gate.
"""
if standard_gates is not None:
warn(
'"standard_gates" option has been deprecated as of qiskit-aer 0.10.0'
' and will be removed no earlier than 3 months from that release date.',
DeprecationWarning, stacklevel=2)
# Initilize empty errors
depol_error = None
relax_error = None
# Generate custom gate time dict
custom_times = {}
relax_params = []
if thermal_relaxation:
# If including thermal relaxation errors load
# T1, T2, and frequency values from properties
relax_params = thermal_relaxation_values(properties)
# If we are specifying custom gate times include
# them in the custom times dict
if gate_lengths:
for name, qubits, value in gate_lengths:
# Convert all gate lengths to nanosecond units
time = value * _NANOSECOND_UNITS[gate_length_units]
if name in custom_times:
custom_times[name].append((qubits, time))
else:
custom_times[name] = [(qubits, time)]
# Get the device gate parameters from properties
device_gate_params = gate_param_values(properties)
# Construct quantum errors
errors = []
for name, qubits, gate_length, error_param in device_gate_params:
# Check for custom gate time
relax_time = gate_length
# Override with custom value
if name in custom_times:
filtered = [
val for q, val in custom_times[name]
if q is None or q == qubits
]
if filtered:
# get first value
relax_time = filtered[0]
# Get relaxation error
if thermal_relaxation:
relax_error = _device_thermal_relaxation_error(
qubits, relax_time, relax_params, temperature,
thermal_relaxation)
# Get depolarizing error channel
if gate_error:
with catch_warnings():
filterwarnings(
"ignore",
category=DeprecationWarning,
module="qiskit.providers.aer.noise.errors.errorutils"
)
depol_error = _device_depolarizing_error(
qubits, error_param, relax_error, standard_gates, warnings=warnings)
# Combine errors
if depol_error is None and relax_error is None:
# No error for this gate
pass
elif depol_error is not None and relax_error is None:
# Append only the depolarizing error
errors.append((name, qubits, depol_error))
# Append only the relaxation error
elif relax_error is not None and depol_error is None:
errors.append((name, qubits, relax_error))
else:
# Append a combined error of depolarizing error
# followed by a relaxation error
combined_error = depol_error.compose(relax_error)
errors.append((name, qubits, combined_error))
return errors
def _device_depolarizing_error(qubits,
error_param,
relax_error=None,
standard_gates=True,
warnings=True):
"""Construct a depolarizing_error for device"""
# We now deduce the depolarizing channel error parameter in the
# presence of T1/T2 thermal relaxation. We assume the gate error
# parameter is given by e = 1 - F where F is the average gate fidelity,
# and that this average gate fidelity is for the composition
# of a T1/T2 thermal relaxation channel and a depolarizing channel.
# For the n-qubit depolarizing channel E_dep = (1-p) * I + p * D, where
# I is the identity channel and D is the completely depolarizing
# channel. To compose the errors we solve for the equation
# F = F(E_dep * E_relax)
# = (1 - p) * F(I * E_relax) + p * F(D * E_relax)
# = (1 - p) * F(E_relax) + p * F(D)
# = F(E_relax) - p * (dim * F(E_relax) - 1) / dim
# Hence we have that the depolarizing error probability
# for the composed depolarization channel is
# p = dim * (F(E_relax) - F) / (dim * F(E_relax) - 1)
if relax_error is not None:
relax_fid = qi.average_gate_fidelity(relax_error)
relax_infid = 1 - relax_fid
else:
relax_fid = 1
relax_infid = 0
if error_param is not None and error_param > relax_infid:
num_qubits = len(qubits)
dim = 2 ** num_qubits
error_max = dim / (dim + 1)
# Check if reported error param is un-physical
# The minimum average gate fidelity is F_min = 1 / (dim + 1)
# So the maximum gate error is 1 - F_min = dim / (dim + 1)
if error_param > error_max:
if warnings:
logger.warning(
'Device reported a gate error parameter greater'
' than maximum allowed value (%f > %f). Truncating to'
' maximum value.', error_param, error_max)
error_param = error_max
# Model gate error entirely as depolarizing error
num_qubits = len(qubits)
dim = 2 ** num_qubits
depol_param = dim * (error_param - relax_infid) / (dim * relax_fid - 1)
max_param = 4**num_qubits / (4**num_qubits - 1)
if depol_param > max_param:
if warnings:
logger.warning(
'Device model returned a depolarizing error parameter greater'
' than maximum allowed value (%f > %f). Truncating to'
' maximum value.', depol_param, max_param)
depol_param = min(depol_param, max_param)
return depolarizing_error(
depol_param, num_qubits, standard_gates=standard_gates)
return None
def _device_thermal_relaxation_error(qubits,
gate_time,
relax_params,
temperature,
thermal_relaxation=True):
"""Construct a thermal_relaxation_error for device"""
# Check trivial case
if not thermal_relaxation or gate_time is None or gate_time == 0:
return None
# Construct a tensor product of single qubit relaxation errors
# for any multi qubit gates
first = True
error = None
for qubit in qubits:
t1, t2, freq = relax_params[qubit]
t2 = _truncate_t2_value(t1, t2)
population = _excited_population(freq, temperature)
if first:
error = thermal_relaxation_error(t1, t2, gate_time, population)
first = False
else:
single = thermal_relaxation_error(t1, t2, gate_time, population)
error = error.expand(single)
return error
def _truncate_t2_value(t1, t2):
"""Return t2 value truncated to 2 * t1 (for t2 > 2 * t1)"""
new_t2 = t2
if t2 > 2 * t1:
new_t2 = 2 * t1
warn("Device model returned an invalid T_2 relaxation time greater than"
f" the theoretical maximum value 2 * T_1 ({t2} > 2 * {t1})."
" Truncating to maximum value.", UserWarning)
return new_t2
def _excited_population(freq, temperature):
"""Return excited state population"""
population = 0
if freq != inf and temperature != 0:
# Compute the excited state population from qubit
# frequency and temperature
# Boltzman constant kB = 8.617333262-5 (eV/K)
# Planck constant h = 4.135667696e-15 (eV.s)
# qubit temperature temperatue = T (mK)
# qubit frequency frequency = f (GHz)
# excited state population = 1/(1+exp((2*h*f*1e9)/(kb*T*1e-3)))
exp_param = exp((95.9849 * freq) / abs(temperature))
population = 1 / (1 + exp_param)
if temperature < 0:
# negative temperate implies |1> is thermal ground
population = 1 - population
return population
|
https://github.com/Jaybsoni/QuantumCompiler
|
Jaybsoni
|
# Main file for Quantum Compiler Utility Functions
from qiskit import *
import numpy as np
import random
# Constants ------------------------------------------------------------------------------------------------
# All of the 'basic' qiskit gate types
Id = qiskit.circuit.library.standard_gates.i.IGate
H = qiskit.circuit.library.standard_gates.h.HGate
X = qiskit.circuit.library.standard_gates.x.XGate
Y = qiskit.circuit.library.standard_gates.y.YGate
Z = qiskit.circuit.library.standard_gates.z.ZGate
Rx = qiskit.circuit.library.standard_gates.rx.RXGate
Ry = qiskit.circuit.library.standard_gates.ry.RYGate
Rz = qiskit.circuit.library.standard_gates.rz.RZGate
Cx = qiskit.circuit.library.standard_gates.x.CXGate
Cz = qiskit.circuit.library.standard_gates.z.CZGate
S = qiskit.circuit.library.standard_gates.swap.SwapGate
list_of_gates = [Id, H, X, Y, Z, Rx, Ry, Rz, Cx, Cz, S] # storing the gate types in list
gate_str_dict = {0: 'I', 1: 'H', 2: 'X', 3: 'Y', 4: 'Z', 5: 'Rx', 6: 'Ry', 7: 'Rz', 8: 'Cx', 9: 'Cz', 10: 'S'}
gate_func_dict = {'I': qiskit.QuantumCircuit.id, # A dict relating the gate (str) to its qiskit func call
'H': qiskit.QuantumCircuit.h, # I use this to create the final (compiled) qiskit circuit object
'X': qiskit.QuantumCircuit.x,
'Y': qiskit.QuantumCircuit.y,
'Z': qiskit.QuantumCircuit.z,
'Rx': qiskit.QuantumCircuit.rx,
'Ry': qiskit.QuantumCircuit.ry,
'Rz': qiskit.QuantumCircuit.rz,
'Cx': qiskit.QuantumCircuit.cx,
'Cz': qiskit.QuantumCircuit.cz,
'S': qiskit.QuantumCircuit.swap}
# Functions ------------------------------------------------------------------------------------------------
def read_circ(circ):
"""
Takes a qiskit circuit and creates list of tuples (gate_lst),
returns the gate_lst along with the num of qbits.
This list will be used to re-construct the circuit afterwards.
:param circ: Qiskit QuantumCircuit object
:return: gate_lst, num_qbits: a list of tuples and an int
"""
gate_lst = []
num_qbits = circ.num_qubits
meta_data = circ.data # read circuit meta data
for element in meta_data:
gate_type = type(element[0]) # read the gate type
gate_str = gate_str_dict[list_of_gates.index(gate_type)] # determine the gate_str from its type
qbit_lst = [qbit.index for qbit in element[1]] # list of the qbit indicies that the gate acts on
parameter_lst = element[0].params # list of parameters used by the gate
gate_lst.append((gate_str, qbit_lst, parameter_lst)) # store these directly into tuple
# store all such tuples in a list (in order)
return gate_lst, num_qbits
def write_circ(gate_lst, num_qbits):
"""
Takes a gate_lst and num_qbits to create a qiskit quantum circuit object.
We assume that the circuit has the same number of qbits and bits, and we measure
each qbit to its associated bit at the end of the circuit for simplicity
:param gate_lst: list of tuples, containing the meta_data of the circuit
:param num_qbits: int, number of qbits in circuit
:return: circ: Qiskit QuantumCircuit object
"""
circ = qiskit.QuantumCircuit(num_qbits) # construct an empty circuit with specified number of qbits
for gate in gate_lst: # iterate over list of gate information
gate_str = gate[0]
qbits = gate[1]
if gate_str in ['Cx', 'Cz', 'S']: # apply Cx, Cz, or S gates
gate_func_dict[gate_str](circ, qbits[0], qbits[1])
elif gate_str in ['Rx', 'Ry', 'Rz']: # apply Rx, Ry or Rz gates with parameter
parameter = gate[2][0]
gate_func_dict[gate_str](circ, parameter, qbits)
else: # apply single qbit non parameterized gates
gate_func_dict[gate_str](circ, qbits)
return circ # return final circuit
# a means to augment the gates in the circuit
def general_replace(gate_lst, gate_name, replacement_gates):
"""
searches through gate_lst for all instances of 'gate_name' gate and
replaces them with the set of gates stored in replacement_gates which is
a list of gate tuples.
A gate tuple will contain ('new_gate_str', [new_qbits] or func, [params] or func)
where 'new_gate_str' is the name of the new gate, [new_qbits] is a list of qbits
the new gate will act on. Note if this is empty, then it acts on the same qbits
as the old gate. if a func is provided, then it applies that func to the
old list of qbits to determine the new list of qbits. Finally, [params] is
a list of new parameters or a function which will be applied to the old parameters
in order to determine the new parameters
:param gate_lst: a list containing tuples eg. ('gate_str', [qbits], [params])
:param gate_name: a str, represents the quantum gate being applied
:param replacement_gates: a list of tuples, ('new_gate_str', [new_qbits] or func, [params] or func)
:return: None
"""
for index, gate in enumerate(gate_lst): # iterate through the gate list
gate_str = gate[0]
if gate_str == gate_name: # find and delete the gate tuple with name 'gate_name'
qbits = gate[1]
parms = gate[2]
del gate_lst[index]
for i, new_gate_tuple in enumerate(replacement_gates): # replace it with the set of gates provided
replacement_gate_name = new_gate_tuple[0]
replacement_qbits = new_gate_tuple[1]
replacement_params = new_gate_tuple[2]
if type(replacement_qbits) != list: # in some cases we may want the replacement_qbits to be a
# function of the current params, in this case replacement_params is not a list, but a function
replacement_qbits = [replacement_qbits(qbits)]
elif not replacement_qbits: # if no replacement qbit indicies have been specified,
replacement_qbits = qbits # just apply the replacement gate on the same qbits as the old gate
if type(replacement_params) != list: # in some cases we may want the replacement_params to be a
# function of the current params, in this case replacement_params is not a list, but a function
replacement_params = [replacement_params(parms)]
new_gate = (replacement_gate_name, replacement_qbits, replacement_params)
gate_lst.insert(index + i, new_gate)
return
def random_circ_generator(num_qbits=0, num_gates=0):
"""
Generate a random qiskit circuit made up of the given 'simple'
gates. One can specify the num of qbits and num of gates in the circuit.
If unspecified, they will be randomly determined
:param num_qbits: int, optional number of qbits in circuit
:param num_gates: int, optional number of gates
:return: qiskit QuantumCircuit object
"""
if num_qbits == 0:
num_qbits = random.randint(1, 5) # randomly pick # of qbits 1 - 5
if num_gates == 0:
num_gates = random.randint(5, 25) # randomly pick # of gates 5 - 25
gate_lst = []
for i in range(num_gates): # iterate over the number of gates
if num_qbits == 1: # if there is only 1 qbit then,
gate_index = random.randint(0, 7) # pick a single qbit gate at random
else:
gate_index = random.randint(0, 9) # pick any gate at random
gate_str = gate_str_dict[gate_index]
control_index = random.randint(0, num_qbits - 1) # pick a qbit to apply gate too
parameter = []
qbits = [control_index]
if gate_str in ['Cx', 'Cz']: # if the gate is a ControlX or ControlZ
target_index = random.randint(0, num_qbits - 1) # pick target qbit
if target_index == control_index: # make sure its not the same as the control qbit
if control_index == num_qbits - 1:
target_index = control_index - 1
else:
target_index = control_index + 1
qbits.append(target_index)
elif gate_str in ['Rx', 'Ry']: # if the gate has a theta parameter
parameter.append(random.random() * (2 * np.pi)) # randomly select parameter
elif gate_str == 'Rz': # if the gate has a phi parameter
parameter.append(random.random() * np.pi) # randomly select parameter
gate_lst.append((gate_str, qbits, parameter)) # add the meta_data to the gate_lst
circ = write_circ(gate_lst, num_qbits) # construct qiskit circuit
return circ
def circ_equal(circ1, circ2):
"""
Checks if two circuits generate the same statevector.
If they are different it prints them.
:param circ1: Qiskit QuantumCircuit object
:param circ2: Qiskit QuantumCircuit object
:return: Bool, True if the state vectors are equal
"""
backend = Aer.get_backend('statevector_simulator') # get simulator
job1 = execute(circ1, backend)
job2 = execute(circ2, backend)
result1 = job1.result()
result2 = job2.result()
circ1_statevect = result1.get_statevector(circ1)
mag_circ1_statevect = np.sqrt(circ1_statevect * np.conj(circ1_statevect))
circ2_statevect = result2.get_statevector(circ2)
mag_circ2_statevect = np.sqrt(circ2_statevect * np.conj(circ2_statevect))
equal = np.isclose(mag_circ1_statevect, mag_circ2_statevect) # check if entries are within tolerance of each other
if not equal.all():
print(np.round(circ1_statevect, decimals=3))
print(np.round(mag_circ1_statevect, decimals=3))
print(np.round(circ2_statevect, decimals=3))
print(np.round(mag_circ2_statevect, decimals=3))
return equal
def get_first(lst):
return lst[0] # kinda self explanatory
def get_second(lst):
return lst[1] # equally self explanatory
def main():
return
if __name__ == '__main__':
main()
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
# https://github.com/Qiskit/qiskit-terra/issues/2036
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, transpiler
import numpy as np
q = QuantumRegister(6, name='qn')
c = ClassicalRegister(2, name='cn')
zz = QuantumCircuit(q, c)
zz.h(q[0])
zz.h(q[5])
zz.cx(q[0], q[5])
zz.u1(2 * np.pi, q[5])
zz.cx(q[0], q[5])
zz.h(q[0])
zz.h(q[5])
zz.barrier(q)
zz.measure(q[0], c[0])
zz.measure(q[5], c[1])
print(zz)
new_zz = transpiler.transpile(zz, basis_gates='u1, u2, u3, cx, id',
coupling_map=[[0, 1], [0, 5], [1, 0], [1, 2], [2, 1], [2, 3],
[3, 2], [3, 4], [4, 3], [4, 9], [5, 0], [5, 6],
[5, 10], [6, 5], [6, 7], [7, 6], [7, 8], [7, 12],
[8, 7], [8, 9], [9, 4], [9, 8], [9, 14], [10, 5],
[10, 11], [10, 15], [11, 10], [11, 12], [12, 7],
[12, 11], [12, 13], [13, 12], [13, 14], [14, 9],
[14, 13], [14, 19], [15, 10], [15, 16], [16, 15],
[16, 17], [17, 16], [17, 18], [18, 17], [18, 19],
[19, 14], [19, 18]], initial_layout = {("qn", 0): ("q", 0), ("qn", 1): ("q", 1),
("qn", 2): ("q", 2), ("qn", 3): ("q", 3), ("qn", 4): ("q", 4), ("qn", 5): ("q", 5)})
print(new_zz)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
#!pip install pylatexenc # para desenhar os circuitos quânticos
from qiskit import QuantumCircuit
qc = QuantumCircuit(1,1)
qc.barrier()
qc.measure(0,0)
qc.draw('mpl') # Para medidas de Z
# Para medidas de X
qc = QuantumCircuit(1,1)
qc.barrier()
qc.h(0)
qc.measure(0,0)
qc.draw('mpl')
# Para medidas de Y
qc = QuantumCircuit(1,1)
qc.barrier()
qc.sdg(0)
qc.h(0)
qc.measure(0,0)
qc.draw('mpl')
# Calculo da inversa da matrix de Hadamard
from sympy import Matrix
H2 = Matrix([[1,1],[1,-1]]); H2
H2.inv()
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import SamplerV2 as Sampler
import numpy as np
def tomo_rho_1qb_sim(nqb, qbt, qct, nshots, backend):
# qct = quantum circuit for tomography
# nqb = number of qubits
# qbt = qubit to be tomographed
sampler = Sampler(backend=backend)
avgs = []
for j in range(0,3):
qc_list = []
qc = QuantumCircuit(nqb,1)
qc.append(qct,list(range(nqb)))
if j == 0: # medida de X
qc.h(qbt)
elif j == 1: # medida de Y
qc.sdg(qbt)
qc.h(qbt)
qc.measure(qbt,0)
qc_list.append(qc.decompose())
job = sampler.run(qc_list, shots=nshots)
counts = job.result()[0].data.c.get_counts()
if '0' in counts:
avg = counts['0']
if '1' in counts:
avg -= counts['1']
avg = avg/nshots
avgs.append(avg)
s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]])
s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]])
rho_1qb = 0.5*(s0 + avgs[0]*s1 + avgs[1]*s2 + avgs[2]*s3)
return rho_1qb
nqb = 2; qbt = 0
qct = QuantumCircuit(nqb)
qct.h(0)
qct.cx(0,1)
nshots = 2**13
backend = AerSimulator()
rho = tomo_rho_1qb(nqb, qbt, qct, nshots, backend)
print(rho)
from sympy.physics.quantum import TensorProduct as tp
H4 = tp(H2,H2); H4
H4i = H4.inv(); H4i
def hadarmard_inv():
return (1/4)*np.array([[1,1,1,1],[1,-1,1,-1],[1,1,-1,-1],[1,-1,-1,1]])
#hadarmard_inv()
def tomo_rho_2qb(nqb, qbt, qct, nshots, backend):
# qct = quantum circuit for tomography
# nqb = number of qubits
# qbt = list with the 2 qubits to be tomographed
sampler = Sampler(backend=backend)
avgs = []
for j in range(1,4):
for k in range(1,4):
qc_list = []
qc = QuantumCircuit(nqb,2)
qc.append(qct,list(range(nqb)))
if j == 1: # medida de X_0
qc.h(qbt[0])
elif j == 2: # medida de Y_0
qc.sdg(qbt[0])
qc.h(qbt[0])
if k == 1: # medida de X_1
qc.h(qbt[1])
elif k == 2: # medida de Y_1
qc.sdg(qbt[1])
qc.h(qbt[1])
qc.measure(qbt,[0,1]) # medida de ZZ
qc_list.append(qc.decompose())
job = sampler.run(qc_list, shots=nshots)
counts = job.result()[0].data.c.get_counts()
labels = ['00','01','10','11']
probs = np.zeros(4)
for l in range(0,4):
if labels[l] in counts:
probs[l] = counts[labels[l]]/nshots
print(probs)
s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]])
s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]])
rho_2qb = 0.5*(s0 + avgs[0]*s1 + avgs[1]*s2 + avgs[2]*s3)
return rho_2qb
def tomo_2qb(avgs):
# avgs e uma lista com 16 valores medios na seguinte ordem [II,IX,IY,IZ,XI,XX,XY,XZ,YI,YX,YY,YZ,ZI,ZX,ZY,ZZ]
import numpy as np
s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]])
s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]])
paulis = [s0,s1,s2,s3] # lista com as matrizes de Pauli
rho = np.zeros([4,4],dtype=complex)
l = 0
for j in range(0,3):
for k in range(0,3):
l += 1
rho += avgs[l]*tp(paulis[j],paulis[k])
return 0.25*rho
nqb = 2; qbt = [0,1]
qct = QuantumCircuit(nqb)
qct.h(0)
qct.cx(0,1)
nshots = 2**13
backend = AerSimulator()
rho = tomo_rho_2qb(nqb, qbt, qct, nshots, backend)
print(rho)
print(np.zeros(4))
def tomo_2qb(avgs):
# avgs e uma lista com 16 valores medios na seguinte ordem [II,IX,IY,IZ,XI,XX,XY,XZ,YI,YX,YY,YZ,ZI,ZX,ZY,ZZ]
import numpy as np
s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]])
s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]])
paulis = [s0,s1,s2,s3] # lista com as matrizes de Pauli
rho = np.zeros([4,4],dtype=complex)
l = 0
for j in range(0,3):
for k in range(0,3):
l += 1
rho += avgs[l]*tp(paulis[j],paulis[k])
return 0.25*rho
avgs = [1,0.1,0,0,0.1,0.3,0,0,0.3,0,0.2,0,0,0.1,0,0.5] #[II,IX,IY,IZ,XI,XX,XY,XZ,YI,YX,YY,YZ,ZI,ZX,ZY,ZZ]
rho = tomo_2qb(avgs); rho
# Inversa da matriz de Hadamard 4x4 (sem o multiplo 1/4)
H4i = np.array([[1,1,1,1],[1,-1,1,-1],[1,1,-1,-1],[1,-1,-1,1]]); H4i
def qc_test_2qb():
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, name='qc2qb')
qc.h(0); qc.cx(0,1)
return qc
def tomo_2qb(avgs):
# avgs e uma lista com 64 valores medios na seguinte ordem [III,IIX,IIY,IIZ,IXI,IXX,IXY,IXZ,...]
import numpy as np
s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]])
s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]])
paulis = [s0,s1,s2,s3]
rho = np.zeros([4,4],dtype=complex)
m = 0
for j in range(0,4):
for k in range(0,4):
for l in range(0,4):
rho += avgs[m]*np.kron(np.kron(paulis[j],paulis[k]),paulis[l])
m += 1
return 0.25*rho
from qiskit import QuantumCircuit, execute
from qiskit import Aer
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
qct = qc_test_2qb() # circuito quantico principal
# medida de XX
qc = QuantumCircuit(2,2); qc.append(qct,[0,1]); qc.h([0,1]); qc.measure([0,1],[0,1]); qcxx = qc
job = execute(qc, backend = simulator, shots = nshots); counts_xx = job.result().get_counts()
pr_xx = np.zeros(4); cb2_labels = ['00','10','01','11']
for j in range(0,4):
if cb2_labels[j] in counts_xx:
pr_xx[j] = counts_xx[cb2_labels[j]]/nshots
print('counts_xx=',counts_xx, pr_xx)
XX_vec = np.matmul(H4i,pr_xx); print('XX_vec=',XX_vec) # =[II,IX,XI,XX]
qcxx.draw('mpl')
ss_vecs = [] # list with the averages of the observables
obs = ['x','y','z']
for j in range(0,3):
lo = obs[j] # left observable
for k in range(0,3):
ro = obs[k] # right observable
qc = QuantumCircuit(2,2)
qc.append(qct,[0,1]) # the quantum circuit for preparing psi
if lo == 'x' and ro = 'x':
qc.h([0,1])
elif lo == 'x' and ro = 'y':
qc.sdg(1); qc.h([0,1])
elif lo == 'y' and ro = 'x':
qc.sdg(0); qc.h([0,1])
elif lo == 'y' and ro = 'y':
qc.sdg([0,1]); qc.h([0,1])
qc.measure([0,1],[0,1])
job = execute(qc, backend = simulator, shots = nshots)
counts = job.result().get_counts()
pr = np.zeros(4); cb2_labels = ['00','10','01','11']
for j in range(0,4):
if cb2_labels[j] in counts_xx:
pr_xx[j] = counts_xx[cb2_labels[j]]/nshots
ss_vec = np.matmul(H4i,pr)
ss_vecs.append(ss_vec)
# matriz de Hadamard
H8 = tp(H2,H4); H8
H8i = H8.inv(); H8i
from sympy import symbols
f000,f001,f010,f011,f100,f101,f110,f111 = symbols('f_{000},f_{001},f_{010},f_{011},f_{100},f_{101},f_{110},f_{111}')
f = Matrix([[f000],[f001],[f010],[f011],[f100],[f101],[f110],[f111]])
f.T
al = 8*H8i*f; al
import numpy as np
s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]]); s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]])
paulis = [s0,s1,s2,s3] # lista com as matrizes de Pauli
list_avgs = []
m = 0
for j in range(0,4):
for k in range(0,4):
for l in range(0,4):
list_avgs.append((j,k,l))
m += 1
|
https://github.com/Tojarieh97/VQE
|
Tojarieh97
|
from qiskit.opflow import X, Z, I
H2_molecule_hamiltonian = -0.5053051899926562*(I^I) + \
-0.3277380754984016*(Z^I) + \
0.15567463610622564*(Z^Z) + \
-0.3277380754984016*(I^Z)
print("========== H2 Molecule Hamiltonian for Two Qubits ==========\n")
print(H2_molecule_hamiltonian.to_matrix())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer
from qiskit.compiler import transpile
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit.quantum_info import process_fidelity
from qiskit.extensions import RXGate, XGate, CXGate
XX = Operator([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])
XX
XX.data
input_dim, output_dim = XX.dim
input_dim, output_dim
op = Operator(np.random.rand(2 ** 1, 2 ** 2))
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
op = Operator(np.random.rand(6, 6))
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
# Force input dimension to be (4,) rather than (2, 2)
op = Operator(np.random.rand(2 ** 1, 2 ** 2), input_dims=[4])
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
# Specify system is a qubit and qutrit
op = Operator(np.random.rand(6, 6),
input_dims=[2, 3], output_dims=[2, 3])
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
print('Dimension of input system 0:', op.input_dims([0]))
print('Dimension of input system 1:', op.input_dims([1]))
# Create an Operator from a Pauli object
pauliXX = Pauli('XX')
Operator(pauliXX)
# Create an Operator for a Gate object
Operator(CXGate())
# Create an operator from a parameterized Gate object
Operator(RXGate(np.pi / 2))
# Create an operator from a QuantumCircuit object
circ = QuantumCircuit(10)
circ.h(0)
for j in range(1, 10):
circ.cx(j-1, j)
# Convert circuit to an operator by implicit unitary simulation
Operator(circ)
# Create an operator
XX = Operator(Pauli('XX'))
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(XX, [0, 1])
circ.measure([0,1], [0,1])
circ.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
circ = transpile(circ, backend, basis_gates=['u1','u2','u3','cx'])
job = backend.run(circ)
job.result().get_counts(0)
# Add to a circuit
circ2 = QuantumCircuit(2, 2)
circ2.append(Pauli('XX'), [0, 1])
circ2.measure([0,1], [0,1])
circ2.draw()
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.tensor(B)
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.expand(B)
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.compose(B)
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.compose(B, front=True)
# Compose XZ with an 3-qubit identity operator
op = Operator(np.eye(2 ** 3))
XZ = Operator(Pauli('XZ'))
op.compose(XZ, qargs=[0, 2])
# Compose YX in front of the previous operator
op = Operator(np.eye(2 ** 3))
YX = Operator(Pauli('YX'))
op.compose(XZ, qargs=[0, 2], front=True)
XX = Operator(Pauli('XX'))
YY = Operator(Pauli('YY'))
ZZ = Operator(Pauli('ZZ'))
op = 0.5 * (XX + YY - 3 * ZZ)
op
op.is_unitary()
# Compose with a matrix passed as a list
Operator(np.eye(2)).compose([[0, 1], [1, 0]])
Operator(Pauli('X')) == Operator(XGate())
Operator(XGate()) == np.exp(1j * 0.5) * Operator(XGate())
# Two operators which differ only by phase
op_a = Operator(XGate())
op_b = np.exp(1j * 0.5) * Operator(XGate())
# Compute process fidelity
F = process_fidelity(op_a, op_b)
print('Process fidelity =', F)
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.timeline import draw, IQXDebugging
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, style=IQXDebugging())
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
import os
import unittest
import qiskit.providers.aer.noise as AerNoise
from orquestra.quantum.circuits.layouts import CircuitConnectivity
from qiskit.providers.exceptions import QiskitBackendNotFoundError
from orquestra.integrations.qiskit.noise.basic import (
create_amplitude_damping_noise,
create_phase_and_amplitude_damping_error,
create_phase_damping_noise,
create_pta_channel,
get_kraus_matrices_from_ibm_noise_model,
get_qiskit_noise_model,
)
class TestBasic(unittest.TestCase):
def setUp(self):
self.ibmq_api_token = os.getenv("ZAPATA_IBMQ_API_TOKEN")
self.all_devices = ["ibm_kyoto"]
self.T_1 = 10e-7
self.T_2 = 30e-7
self.t_step = 10e-9
self.t_1_t_2_models = [
create_phase_and_amplitude_damping_error,
create_pta_channel,
]
def test_get_qiskit_noise_model(self):
# Given
for device in self.all_devices:
# When
noise_model, coupling_map = get_qiskit_noise_model(
device, api_token=self.ibmq_api_token
)
# Then
self.assertIsInstance(noise_model, AerNoise.NoiseModel)
self.assertIsInstance(coupling_map, list)
def test_get_qiskit_noise_model_no_device(self):
# Given
not_real_devices = ["THIS IS NOT A REAL DEVICE", "qasm_simulator"]
for device in not_real_devices:
# When/then
self.assertRaises(
QiskitBackendNotFoundError,
lambda: get_qiskit_noise_model(device, api_token=self.ibmq_api_token),
)
def test_t_1_t_2_noise_models(self):
for noise in self.t_1_t_2_models:
self.assertIsInstance(
noise(self.T_1, self.T_2, self.t_step), AerNoise.NoiseModel
)
def test_amplitude_damping_model(self):
self.assertIsInstance(
create_amplitude_damping_noise(self.T_1, self.t_step), AerNoise.NoiseModel
)
def test_phase_damping_noise(self):
self.assertIsInstance(
create_phase_damping_noise(self.T_2, self.t_step), AerNoise.NoiseModel
)
def test_getting_kraus_matrices_from_noise_model(self):
noise_model = create_amplitude_damping_noise(self.T_1, self.t_step)
kraus_dict = get_kraus_matrices_from_ibm_noise_model(noise_model)
# Test to see if basis gates are in
self.assertEqual("id" in kraus_dict, True)
self.assertEqual("u3" in kraus_dict, True)
self.assertEqual("cx" in kraus_dict, True)
# Test to see if the number of kraus operators is right for a basis gate
self.assertEqual(len(kraus_dict["id"]), 2)
self.assertEqual(len(kraus_dict["u3"]), 2)
self.assertEqual(len(kraus_dict["cx"]), 4)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.barrier()
circuit.h(0)
circuit = RemoveBarriers()(circuit)
circuit.draw('mpl')
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.wrapper import available_backends, get_backend
from qiskit.wrapper import execute as q_execute
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q,c)
qc.h(q[0])
qc.h(q[1])
qc.cx(q[0], q[1])
qc.measure(q, c)
z = 0.995004165 + 1j * 0.099833417
z = z / abs(z)
u_error = np.array([[1, 0], [0, z]])
noise_params = {'U':
{'gate_time': 1,
'p_depol': 0.001,
'p_pauli': [0, 0, 0.01],
'U_error': u_error
}
}
config = {"noise_params": noise_params}
ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config)
ret = ret.result()
print(ret.get_counts())
|
https://github.com/abbarreto/qiskit3
|
abbarreto
|
list_bin = []
for j in range(0,2**4):
b = "{:04b}".format(j)
list_bin.append(b)
print(list_bin)
list_int = []
for j in range(0,2**4):
list_int.append(int(list_bin[j],2))
print(list_int)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/Fergus-Hayes/qiskit_tools
|
Fergus-Hayes
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
import qiskit_tools as qt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from qiskit.circuit.library.standard_gates import RYGate
matplotlib.rcParams['mathtext.fontset'] = 'stix'
matplotlib.rcParams['font.family'] = 'STIXGeneral'
width=0.75
color='black'
fontsize=28
ticksize=22
figsize=(10,8)
def targ_dist(x, bias=0):
y = (x+bias)**(-7./6)
return y/np.sqrt(np.sum(np.abs(y)**2))
nx = 6
nintx = 4
xmin = -2.**(nintx)
xmax = 2.**(nintx) - 2.**(-nx+nintx+1)
xs = np.linspace(xmin, xmax, 2**nx)
amps = targ_dist(xs, bias=2.**(nintx+1))
probs = np.abs(amps)**2
fig = plt.figure(figsize=figsize)
ax = fig.gca()
ax.plot(xs, probs, color='black')
ax.set_xlabel(r'$x$', fontsize=fontsize);
ax.set_ylabel(r'$\sqrt{p(x)}$', fontsize=fontsize);
ax.set_xlim(xmin,xmax);
ax.tick_params(axis='both', labelsize=ticksize);
def GR_func(j, probs, m, n):
j = np.array(j).astype(int)
As = []
for i in np.arange(2**m):
As.append(np.sum(probs[i*2**(n-m):(i+1)*2**(n-m)]))
As1 = []
for i in np.arange(2**(m+1)):
As1.append(np.sum(probs[i*2**(n-(m+1)):(i+1)*2**(n-(m+1))]))
return np.arccos(np.sqrt(np.array(As1)[::2][j]/np.array(As)[j]))
qx = QuantumRegister(nx, 'x')
circ = QuantumCircuit(qx)
coeffs = np.arccos(np.sqrt(np.sum(probs[:2**(nx-1)])))
circ.ry(2*coeffs, qx[nx-1]);
for m in np.arange(1,nx):
js = np.arange(2**m)
coeffs = GR_func(js, probs, m, nx)
for j in np.arange(2**m):
control_bits = qt.my_binary_repr(j, m, nint=None, phase=False)
if j>0:
control_bits_ = qt.my_binary_repr(j-1, m, nint=None, phase=False)[::-1]
else:
control_bits_ = np.ones(m).astype(int).astype(str)
for i,control_bit in enumerate(control_bits[::-1]):
if control_bit=='0' and control_bits_[i]=='1':
circ.x(qx[nx-i-1]);
R_gate = RYGate(2*coeffs[j]).control(int(m))
circ.append(R_gate, [*qx[nx-m-1:][::-1]]);
if j<2**m-1:
control_bits_ = qt.my_binary_repr(j+1, m, nint=None, phase=False)[::-1]
else:
control_bits_ = np.ones(m).astype(int).astype(str)
for i,control_bit in enumerate(control_bits[::-1]):
if control_bit=='0' and control_bits_[i]=='1':
circ.x(qx[nx-i-1]);
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
state_vector = np.asarray(result.get_statevector())
if np.any(state_vector.imag>0.):
state_v = np.copy(state_vector)
else:
state_v = state_vector.real
fig = plt.figure(figsize=figsize)
ax = fig.gca()
ax.scatter(xs, np.abs(state_v)**2, color='black')
ax.plot(xs, probs, color='black')
ax.set_xlabel(r'$x$', fontsize=fontsize);
ax.set_ylabel(r'$\sqrt{p(x)}$', fontsize=fontsize);
ax.set_xlim(xmin,xmax);
ax.tick_params(axis='both', labelsize=ticksize);
circ.draw('latex')
# Register size for storing the zeta angles
nanc = 8
# Register size for storing the linear coefficients for the piecewise function
ncoff = 8
# Register size for the label register
nlab = 4
print('Qubits:', nx, nanc, ncoff, nlab,'total:',nanc+ncoff+nx+nlab)
print('Memory:', 16*(2**(nanc+ncoff+nx+nlab))/2**20)
qx = QuantumRegister(nx, 'x')
qanc = QuantumRegister(nanc, 'anc')
qlab = QuantumRegister(nlab, 'l')
qcoff = QuantumRegister(ncoff, 'c')
circ = QuantumCircuit(qx, qanc, qlab, qcoff)
mlow = 4
probs_ = []
for i in np.arange(2**mlow):
probs_.append(np.sum(probs[i*2**(nx-mlow):(i+1)*2**(nx-mlow)]))
probs_ = np.array(probs_)
GRl_gate = qt.Grover_Rudolph_load(circ, qx[nx-mlow:], probs_, wrap=True)
circ.append(GRl_gate, qx[nx-mlow:]);
for m in np.arange(mlow,nx):
js = np.arange(2**m)
coeffs = GR_func(js, probs, m, nx)
f_x = lambda x: GR_func(x, probs, m, nx)
bounds_ = np.linspace(0,2**m,(2**nlab)+1).astype(int)
coeffs = qt.get_bound_coeffs(f_x, bounds_, 1, reterr=False).T#[::-1]
bounds = bounds_[1:]
max_list0 = np.array([coeffs[0], coeffs[1], coeffs[0]*2**nx, (coeffs[0]*2**nx)+coeffs[-1]])
max_list1 = max_list0
nintcs = []
nintcs.append(int(np.ceil(np.log2(np.max(np.abs(max_list0))))))
nintcs.append(int(np.ceil(np.log2(np.max(np.abs(max_list1))))))
nint = nintcs[-1]
nintcs = np.array([nintcs])
func_gate = qt.linear_piecewise_approx(circ, qx[nx-m:], qanc, qlab, qcoff, coeffs, bounds, nint=nint, nintx=nx, nintcs=nintcs, phase=False, wrap=True)
circ.append(func_gate, [*qx[nx-m:], *qanc, *qlab, *qcoff]);
rot_gate = qt.CRotation(circ, qanc, qx[nx-m-1], nint=nint, wrap=True)
circ.append(rot_gate, [*qanc, qx[nx-m-1]])
func_gate_inv = qt.linear_piecewise_approx(circ, qx[nx-m:], qanc, qlab, qcoff, coeffs, bounds, nint=nint, nintx=nx, nintcs=nintcs, phase=False, wrap=True, inverse=True)
circ.append(func_gate_inv, [*qx[nx-m:], *qanc, *qlab, *qcoff]);
circ.draw('latex')
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
state_vector = np.asarray(result.get_statevector())
if np.any(state_vector.imag>0.):
state_v = np.copy(state_vector)
else:
state_v = state_vector.real
state_v = np.asarray(state_vector).reshape((2**ncoff,2**nlab,2**nanc,2**nx)).T
state_v = np.sum(state_v, axis=(1,2,3))
fig = plt.figure(figsize=figsize)
ax = fig.gca()
ax.scatter(xs, np.abs(state_v)**2, color='black')
ax.plot(xs, probs, color='black')
ax.set_xlabel(r'$x$', fontsize=fontsize);
ax.set_ylabel(r'$\sqrt{p(x)}$', fontsize=fontsize);
ax.set_xlim(xmin,xmax);
ax.tick_params(axis='both', labelsize=ticksize);
|
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))
ghz.draw(output='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 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/joemoorhouse/quantum-mc
|
joemoorhouse
|
from math import pi
from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister
from .qft import qft, iqft, cqft, ciqft, ccu1
from .arithmetic import cadd, full_qr, add_ripple_in_place, add_ripple_in_place_padding, add_ripple_in_place_cq
def classical_add_mult(circ, a, b, qr_in, qr_res, qr_anc):
"""qr_res = qr_res + a * qr_in + b where a and b are integers"""
classical_mult(circ, a, qr_in, qr_res, qr_anc)
classical_add(circ, b, qr_res, qr_anc)
def classical_mult(circ, a, qr_in, qr_res, qr_anc):
"""qr_res = a * qr_in where a is an integer and qr_in is a quantum register
res must have at least na + nin qubits where na is the number of bits required to represent a and nin the number of qubits in qr_in
"""
l_a = _to_bool_list(a)
na = len(l_a)
nin = len(qr_in)
nres = len(qr_res)
for i in range (0, na):
if l_a[i] == 1:
add_ripple_in_place_padding(circ, qr_in, _sub_qr(qr_res, i, nres - 1), qr_anc, nres - 1 - i)
#add_ripple_in_place(circ, qr_in, _sub_qr(qr_res, i, nin + i), qr_anc, nin)
def cond_classical_add_mult(a, b, qr_in, qr_res, qr_anc):
"""qr_res = qr_res + a* qr_in + b if control is set where a and b are integers"""
temp_qr_in = QuantumRegister(len(qr_in))
temp_qr_res = QuantumRegister(len(qr_res))
temp_qr_anc = AncillaRegister(len(qr_anc))
temp_circuit = QuantumCircuit(temp_qr_in, temp_qr_res, temp_qr_anc, name = "inplace_mult_add")
classical_add_mult(temp_circuit, a, b, temp_qr_in, temp_qr_res, temp_qr_anc)
temp_circuit = temp_circuit.control(1)
return temp_circuit
def classical_add(circ, a, qr_b, qr_anc):
"""qr_b = a + qr_b where a is an integer and qr_b is a quantum register """
nb = len(qr_b)
if a >= 0:
l_a = _to_bool_list(a)
if len(l_a) > nb - 1:
raise Exception("number of classical integer bits cannot exceed number of register qubits - 1")
else:
l_a = _to_bool_list(twos_comp(a, nb))
l_a = l_a + [0 for i in range(nb - len(l_a))] # pad with zeros
add_ripple_in_place_cq(circ, l_a, qr_b, qr_anc, nb - 1)
if a < 0:
circ.x(qr_b[nb - 1])
def _to_bool_list(a):
s = a
res = []
while (s > 0):
res.append(s & 1)
s = s >> 1
return res
def _sub_qr(qr, x, y):
""" Take a subset of a quantum register from index x to y, inclusive. """
sub = []
for i in range (x, y + 1):
sub = sub + [(qr[i])]
return sub
def scalar_mult_plot(control, a, b, c, anc, na, nb):
qa = QuantumRegister(len(a), name = "input")
qc = QuantumRegister(len(c), name = "output")
qanc = AncillaRegister(len(anc), name = "ancilla")
tempCircuit = QuantumCircuit(qa, qc, qanc)
#scalar_mult(tempCircuit, qa, b, qc, qanc, na, nb)
return tempCircuit
def twos_comp(val, bits):
if (val < 0):
return (1 << bits) - abs(val)
else:
return val
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import *
from qiskit.circuit import Gate
my_gate = Gate(name='my_gate', num_qubits=2, params=[])
qr = QuantumRegister(3, 'q')
circ = QuantumCircuit(qr)
circ.append(my_gate, [qr[0], qr[1]])
circ.append(my_gate, [qr[1], qr[2]])
circ.draw()
# Build a sub-circuit
sub_q = QuantumRegister(2)
sub_circ = QuantumCircuit(sub_q, name='sub_circ')
sub_circ.h(sub_q[0])
sub_circ.crz(1, sub_q[0], sub_q[1])
sub_circ.barrier()
sub_circ.id(sub_q[1])
sub_circ.u(1, 2, -2, sub_q[0])
# Convert to a gate and stick it into an arbitrary place in the bigger circuit
sub_inst = sub_circ.to_instruction()
qr = QuantumRegister(3, 'q')
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.cx(qr[1], qr[2])
circ.append(sub_inst, [qr[1], qr[2]])
circ.draw()
decomposed_circ = circ.decompose() # Does not modify original circuit
decomposed_circ.draw()
from qiskit.circuit import Parameter
theta = Parameter('θ')
n = 5
qc = QuantumCircuit(5, 1)
qc.h(0)
for i in range(n-1):
qc.cx(i, i+1)
qc.barrier()
qc.rz(theta, range(5))
qc.barrier()
for i in reversed(range(n-1)):
qc.cx(i, i+1)
qc.h(0)
qc.measure(0, 0)
qc.draw('mpl')
print(qc.parameters)
import numpy as np
theta_range = np.linspace(0, 2 * np.pi, 128)
circuits = [qc.bind_parameters({theta: theta_val})
for theta_val in theta_range]
circuits[-1].draw()
backend = BasicAer.get_backend('qasm_simulator')
job = backend.run(transpile(circuits, backend))
counts = job.result().get_counts()
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)
ax.plot(theta_range, list(map(lambda c: c.get('0', 0), counts)), '.-', label='0')
ax.plot(theta_range, list(map(lambda c: c.get('1', 0), counts)), '.-', label='1')
ax.set_xticks([i * np.pi / 2 for i in range(5)])
ax.set_xticklabels(['0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'], fontsize=14)
ax.set_xlabel('θ', fontsize=14)
ax.set_ylabel('Counts', fontsize=14)
ax.legend(fontsize=14)
import time
from itertools import combinations
from qiskit.compiler import assemble
from qiskit.test.mock import FakeVigo
start = time.time()
qcs = []
theta_range = np.linspace(0, 2*np.pi, 32)
for n in theta_range:
qc = QuantumCircuit(5)
for k in range(8):
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qc.rz(n, range(5))
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qcs.append(qc)
compiled_circuits = transpile(qcs, backend=FakeVigo())
qobj = assemble(compiled_circuits, backend=FakeVigo())
end = time.time()
print('Time compiling over set of bound circuits: ', end-start)
start = time.time()
qc = QuantumCircuit(5)
theta = Parameter('theta')
for k in range(8):
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qc.rz(theta, range(5))
for i,j in combinations(range(5), 2):
qc.cx(i,j)
transpiled_qc = transpile(qc, backend=FakeVigo())
qobj = assemble([transpiled_qc.bind_parameters({theta: n})
for n in theta_range], backend=FakeVigo())
end = time.time()
print('Time compiling over parameterized circuit, then binding: ', end-start)
phi = Parameter('phi')
sub_circ1 = QuantumCircuit(2, name='sc_1')
sub_circ1.rz(phi, 0)
sub_circ1.rx(phi, 1)
sub_circ2 = QuantumCircuit(2, name='sc_2')
sub_circ2.rx(phi, 0)
sub_circ2.rz(phi, 1)
qc = QuantumCircuit(4)
qr = qc.qregs[0]
qc.append(sub_circ1.to_instruction(), [qr[0], qr[1]])
qc.append(sub_circ2.to_instruction(), [qr[0], qr[1]])
qc.append(sub_circ2.to_instruction(), [qr[2], qr[3]])
print(qc.draw())
# The following raises an error: "QiskitError: 'Name conflict on adding parameter: phi'"
# phi2 = Parameter('phi')
# qc.u3(0.1, phi2, 0.3, 0)
p = Parameter('p')
qc = QuantumCircuit(3, name='oracle')
qc.rz(p, 0)
qc.cx(0, 1)
qc.rz(p, 1)
qc.cx(1, 2)
qc.rz(p, 2)
theta = Parameter('theta')
phi = Parameter('phi')
gamma = Parameter('gamma')
qr = QuantumRegister(9)
larger_qc = QuantumCircuit(qr)
larger_qc.append(qc.to_instruction({p: theta}), qr[0:3])
larger_qc.append(qc.to_instruction({p: phi}), qr[3:6])
larger_qc.append(qc.to_instruction({p: gamma}), qr[6:9])
print(larger_qc.draw())
print(larger_qc.decompose().draw())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization.problems import QuadraticProgram
# define a problem
qp = QuadraticProgram()
qp.binary_var("x")
qp.integer_var(name="y", lowerbound=-1, upperbound=4)
qp.maximize(quadratic={("x", "y"): 1})
qp.linear_constraint({"x": 1, "y": -1}, "<=", 0)
print(qp.prettyprint())
from qiskit_optimization.algorithms import CplexOptimizer, GurobiOptimizer
cplex_result = CplexOptimizer().solve(qp)
gurobi_result = GurobiOptimizer().solve(qp)
print("cplex")
print(cplex_result.prettyprint())
print()
print("gurobi")
print(gurobi_result.prettyprint())
result = CplexOptimizer(disp=True, cplex_parameters={"threads": 1, "timelimit": 0.1}).solve(qp)
print(result.prettyprint())
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_aer import Aer
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
meo = MinimumEigenOptimizer(QAOA(sampler=Sampler(), optimizer=COBYLA(maxiter=100)))
result = meo.solve(qp)
print(result.prettyprint())
print("\ndisplay the best 5 solution samples")
for sample in result.samples[:5]:
print(sample)
# docplex model
from docplex.mp.model import Model
docplex_model = Model("docplex")
x = docplex_model.binary_var("x")
y = docplex_model.integer_var(-1, 4, "y")
docplex_model.maximize(x * y)
docplex_model.add_constraint(x <= y)
docplex_model.prettyprint()
# gurobi model
import gurobipy as gp
gurobipy_model = gp.Model("gurobi")
x = gurobipy_model.addVar(vtype=gp.GRB.BINARY, name="x")
y = gurobipy_model.addVar(vtype=gp.GRB.INTEGER, lb=-1, ub=4, name="y")
gurobipy_model.setObjective(x * y, gp.GRB.MAXIMIZE)
gurobipy_model.addConstr(x - y <= 0)
gurobipy_model.update()
gurobipy_model.display()
from qiskit_optimization.translators import from_docplex_mp, from_gurobipy
qp = from_docplex_mp(docplex_model)
print("QuadraticProgram obtained from docpblex")
print(qp.prettyprint())
print("-------------")
print("QuadraticProgram obtained from gurobipy")
qp2 = from_gurobipy(gurobipy_model)
print(qp2.prettyprint())
from qiskit_optimization.translators import to_gurobipy, to_docplex_mp
gmod = to_gurobipy(from_docplex_mp(docplex_model))
print("convert docplex to gurobipy via QuadraticProgram")
gmod.display()
dmod = to_docplex_mp(from_gurobipy(gurobipy_model))
print("\nconvert gurobipy to docplex via QuadraticProgram")
print(dmod.export_as_lp_string())
ind_mod = Model("docplex")
x = ind_mod.binary_var("x")
y = ind_mod.integer_var(-1, 2, "y")
z = ind_mod.integer_var(-1, 2, "z")
ind_mod.maximize(3 * x + y - z)
ind_mod.add_indicator(x, y >= z, 1)
print(ind_mod.export_as_lp_string())
qp = from_docplex_mp(ind_mod)
result = meo.solve(qp) # apply QAOA to QuadraticProgram
print("QAOA")
print(result.prettyprint())
print("-----\nCPLEX")
print(ind_mod.solve()) # apply CPLEX directly to the Docplex model
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/matheusmtta/Quantum-Computing
|
matheusmtta
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit.circuit.library.standard_gates import XGate, HGate
from operator import *
n = 3
N = 8 #2**n
index_colour_table = {}
colour_hash_map = {}
index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"}
colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'}
def database_oracle(index_colour_table, colour_hash_map):
circ_database = QuantumCircuit(n + n)
for i in range(N):
circ_data = QuantumCircuit(n)
idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
# qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0
# we therefore reverse the index string -> q0, ..., qn
data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour)
circ_database.append(data_gate, list(range(n+n)))
return circ_database
# drawing the database oracle circuit
print("Database Encoding")
database_oracle(index_colour_table, colour_hash_map).draw()
circ_data = QuantumCircuit(n)
m = 4
idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
print("Internal colour encoding for the colour green (as an example)");
circ_data.draw()
def oracle_grover(database, data_entry):
circ_grover = QuantumCircuit(n + n + 1)
circ_grover.append(database, list(range(n+n)))
target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target")
# control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()'
# The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.
circ_grover.append(target_reflection_gate, list(range(n, n+n+1)))
circ_grover.append(database, list(range(n+n)))
return circ_grover
print("Grover Oracle (target example: orange)")
oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw()
def mcz_gate(num_qubits):
num_controls = num_qubits - 1
mcz_gate = QuantumCircuit(num_qubits)
target_mcz = QuantumCircuit(1)
target_mcz.z(0)
target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ")
mcz_gate.append(target_mcz, list(range(num_qubits)))
return mcz_gate.reverse_bits()
print("Multi-controlled Z (MCZ) Gate")
mcz_gate(n).decompose().draw()
def diffusion_operator(num_qubits):
circ_diffusion = QuantumCircuit(num_qubits)
qubits_list = list(range(num_qubits))
# Layer of H^n gates
circ_diffusion.h(qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of Multi-controlled Z (MCZ) Gate
circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of H^n gates
circ_diffusion.h(qubits_list)
return circ_diffusion
print("Diffusion Circuit")
diffusion_operator(n).draw()
# Putting it all together ... !!!
item = "green"
print("Searching for the index of the colour", item)
circuit = QuantumCircuit(n + n + 1, n)
circuit.x(n + n)
circuit.barrier()
circuit.h(list(range(n)))
circuit.h(n+n)
circuit.barrier()
unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator")
unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator")
M = countOf(index_colour_table.values(), item)
Q = int(np.pi * np.sqrt(N/M) / 4)
for i in range(Q):
circuit.append(unitary_oracle, list(range(n + n + 1)))
circuit.append(unitary_diffuser, list(range(n)))
circuit.barrier()
circuit.measure(list(range(n)), list(range(n)))
circuit.draw()
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
if M==1:
print("Index of the colour", item, "is the index with most probable outcome")
else:
print("Indices of the colour", item, "are the indices the most probable outcomes")
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
c3h_gate = HGate().control(2)
qc.append(c3h_gate, qr)
qc.draw('mpl')
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder(qc, targets=[0,1,2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
t1 = time.perf_counter()
qc = qc.bind_parameters({dt: target_time / num_steps})
t2 = time.perf_counter()
print("created qc,", t2 - t1, "s")
# Generate state tomography circuits to evaluate fidelity of simulation
t1 = time.perf_counter()
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
t2 = time.perf_counter()
print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s")
# remove barriers
t1 = time.perf_counter()
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
t2 = time.perf_counter()
print("removed barriers from st_qcs,", t2 - t1, "s")
# optimize circuit
t1 = time.perf_counter()
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s")
t3_st_qcs[0].draw("mpl")
# zne wrapping
t1 = time.perf_counter()
zne_qcs = zne_wrapper(t3_st_qcs)
t2 = time.perf_counter()
print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
t2 = time.perf_counter()
print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
# QREM
shots = 1 << 13
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level = 0) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
jobs.append(job)
dt_now = datetime.datetime.now()
print(dt_now)
import pickle
with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results)
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fidelity = state_fidelity(rho, target_state)
print(fidelity)
|
https://github.com/qiskit-community/prototype-zne
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 4, seed=1).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.quantum_info import SparsePauliOp
observable = SparsePauliOp("ZZ")
from qiskit.primitives import Estimator
estimator = Estimator()
job = estimator.run(circuit, observable)
simulation = job.result()
from zne.utils.serialization import EstimatorResultEncoder
print(EstimatorResultEncoder.dumps(simulation, indent=2))
from qiskit.primitives import BackendEstimator
from qiskit.providers.fake_provider import FakeNairobi # We need noise!
from zne import zne
ZNEEstimator = zne(BackendEstimator) # Any implementation of BaseEstimator is valid
backend = FakeNairobi()
estimator = ZNEEstimator(backend=backend)
from zne import ZNEStrategy
from zne.noise_amplification import LocalFoldingAmplifier
from zne.extrapolation import PolynomialExtrapolator
## NOISE FACTORS
noise_factors = range(1,9)
## NOISE AMPLIFIER
noise_amplifier = LocalFoldingAmplifier(
gates_to_fold=2,
)
## EXTRPOLATOR
extrapolator = PolynomialExtrapolator(
degree=2,
)
## ZNE STRATEGY
zne_strategy = ZNEStrategy(
noise_factors=noise_factors,
noise_amplifier=noise_amplifier,
extrapolator=extrapolator,
)
job = estimator.run(circuit, observable, zne_strategy=zne_strategy)
result = job.result()
print(EstimatorResultEncoder.dumps(result, indent=2))
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams["figure.dpi"] = 300
plt.rcParams.update({"text.usetex": True, "font.family": "Computer Modern Roman"})
############################ DATA ############################
exact = simulation.values[0]
mitigated = result.values[0]
noise_factors = result.metadata[0]["zne"]["noise_amplification"]["noise_factors"]
noisy_values = result.metadata[0]["zne"]["noise_amplification"]["values"]
############################ PLOT ############################
plt.rcParams["figure.figsize"] = (5,3.5)
plt.grid(which='major',axis='both')
plt.plot([0, noise_factors[-1]], [exact, exact], "--", label=f"Exact", color="#000000")
plt.scatter(0, mitigated, label=f"Mitigated", marker="x", color="#785ef0")
if noise_factors[0] == 1:
plt.scatter(
noise_factors[0], noisy_values[0],
label=f"Unmitigated", marker="s", color="#dc267f",
)
plt.plot(
noise_factors, noisy_values,
label=f"Amplified", marker="o", color="#dc267f",
)
plt.title("Zero noise extrapolation")
plt.xlabel("Noise Factor ($n$)")
plt.ylabel(f"Expectation Value ($\langle ZZ \\rangle$)")
plt.legend()
plt.show()
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
noise_amplifier = LocalFoldingAmplifier(
gates_to_fold = 2,
sub_folding_option = "from_first",
random_seed = None,
)
noisy_circuit = noise_amplifier.amplify_circuit_noise(circuit=circuit, noise_factor=2)
display(noisy_circuit.draw("mpl", plot_barriers=False))
from zne.extrapolation import Extrapolator, ReckoningResult
from zne.noise_amplification import NoiseAmplifier
############################ NOISE AMPLIFIER ############################
class CustomAmplifier(NoiseAmplifier):
def amplify_circuit_noise(self, circuit, noise_factor):
return circuit.copy() # Dummy, nonperforming
def amplify_dag_noise(self, dag, noise_factor):
return super().amplify_dag_noise(dag, noise_factor)
############################ EXTRAPOLATOR ############################
class CustomExtrapolator(Extrapolator):
@property
def min_points(self):
return 2
def _extrapolate_zero(self, x_data, y_data, sigma_x, sigma_y):
value = 1.0
std_error = 1.0
metadata = {"meta": "data"}
return ReckoningResult(value, std_error, metadata) # Dummy, nonperforming
zne_strategy = ZNEStrategy(
noise_amplifier=CustomAmplifier(),
noise_factors=(1, 3),
extrapolator=CustomExtrapolator(),
)
job = estimator.run(circuit, observable, zne_strategy=zne_strategy)
result = job.result()
print(EstimatorResultEncoder.dumps(result, indent=2))
import qiskit.tools.jupyter # pylint: disable=unused-import,wrong-import-order
%qiskit_version_table
%qiskit_copyright
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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 the Check Map pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit.library import CXGate
from qiskit.transpiler.passes import CheckMap
from qiskit.transpiler import CouplingMap, Target
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestCheckMapCX(QiskitTestCase):
"""Tests the CheckMap pass with CX gates"""
def test_trivial_nop_map(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_trivial_nop_map_target(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
target = Target()
dag = circuit_to_dag(circuit)
pass_ = CheckMap(target)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_true(self):
"""Mapped is easy to check
qr0:--(+)-[H]-(+)-
| |
qr1:---.-------|--
|
qr2:-----------.--
CouplingMap map: [1]--[0]--[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_false(self):
"""Needs [0]-[1] in a [0]--[2]--[1]
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]--[2]--[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
coupling = CouplingMap([[0, 2], [2, 1]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_false_target(self):
"""Needs [0]-[1] in a [0]--[2]--[1]
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]--[2]--[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
target = Target(num_qubits=2)
target.add_instruction(CXGate(), {(0, 2): None, (2, 1): None})
dag = circuit_to_dag(circuit)
pass_ = CheckMap(target)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_true(self):
"""Check control flow blocks are mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr, cr)
true_body.swap(0, 1)
true_body.cx(2, 1)
circuit.if_else((cr[0], 0), true_body, None, qr, cr)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_false(self):
"""Check control flow blocks are not mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr)
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr, [])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_layout_change_false(self):
"""Check control flow blocks with layout change are not mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr, cr)
true_body.cx(1, 2)
circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], cr)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_layout_change_true(self):
"""Check control flow blocks with layout change are mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr)
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], [])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_different_bits(self):
"""Check control flow blocks with layout change are mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(3, 1)
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], [cr[0]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_disjoint_controlflow_bits(self):
"""test control flow on with different registers"""
num_qubits = 4
coupling = CouplingMap.from_line(num_qubits)
qr1 = QuantumRegister(4, "qr")
qr2 = QuantumRegister(3, "qrif")
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr1, cr)
true_body = QuantumCircuit(qr2, [cr[0]])
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr1[[1, 0, 2]], [cr[0]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_nested_controlflow_true(self):
"""Test nested controlflow with true evaluation."""
num_qubits = 4
coupling = CouplingMap.from_line(num_qubits)
qr1 = QuantumRegister(4, "qr")
qr2 = QuantumRegister(3, "qrif")
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(1)
circuit = QuantumCircuit(qr1, cr1)
true_body = QuantumCircuit(qr2, cr2)
for_body = QuantumCircuit(3)
for_body.cx(0, 2)
true_body.for_loop(range(5), body=for_body, qubits=qr2, clbits=[])
circuit.if_else((cr1[0], 0), true_body, None, qr1[[1, 0, 2]], cr1)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_nested_controlflow_false(self):
"""Test nested controlflow with true evaluation."""
num_qubits = 4
coupling = CouplingMap.from_line(num_qubits)
qr1 = QuantumRegister(4, "qr")
qr2 = QuantumRegister(3, "qrif")
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(1)
circuit = QuantumCircuit(qr1, cr1)
true_body = QuantumCircuit(qr2, cr2)
for_body = QuantumCircuit(3)
for_body.cx(0, 2)
true_body.for_loop(range(5), body=for_body, qubits=qr2, clbits=[])
circuit.if_else((cr1[0], 0), true_body, None, qr1[[0, 1, 2]], cr1)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_nested_conditional_unusual_bit_order(self):
"""Test that `CheckMap` succeeds when inner conditional blocks have clbits that are involved
in their own (nested conditionals), and the binding order is not the same as the
bit-definition order. See gh-10394."""
qr = QuantumRegister(2, "q")
cr1 = ClassicalRegister(2, "c1")
cr2 = ClassicalRegister(2, "c2")
# Note that the bits here are not in the same order as in the outer circuit object, but they
# are the same as the binding order in the `if_test`, so everything maps `{x: x}` and it
# should all be fine. This kind of thing is a staple of the control-flow builders.
inner_order = [cr2[0], cr1[0], cr2[1], cr1[1]]
inner = QuantumCircuit(qr, inner_order, cr1, cr2)
inner.cx(0, 1).c_if(cr2, 3)
outer = QuantumCircuit(qr, cr1, cr2)
outer.if_test((cr1, 3), inner, outer.qubits, inner_order)
pass_ = CheckMap(CouplingMap.from_line(2))
pass_(outer)
self.assertTrue(pass_.property_set["is_swap_mapped"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/kurtchahn/QiskitPrx
|
kurtchahn
|
import qiskit as qk
import qiskit_aer as qaer
import numpy as np
import math
sSimulator = qaer.Aer.backends(name="statevector_simulator")[0]
mSimulator = qaer.Aer.backends(name="qasm_simulator")[0]
qr = qk.QuantumRegister(1, name="qr")
qc = qk.QuantumCircuit(qr, name="qc")
qc.h(qr[0])
sSimulator.run(qc).result().get_statevector()
qc.draw("mpl")
qc.p(math.pi/4, qr[0])
sSimulator.run(qc).result().get_statevector()
qc.draw("mpl")
qr = qk.QuantumRegister(1, name="qr")
qc = qk.QuantumCircuit(qr, name="qc")
qc.rx(math.pi/2, qr[0])
sSimulator.run(qc).result().get_statevector()
qc.draw("mpl")
qr = qk.QuantumRegister(3, name="qr")
qc = qk.QuantumCircuit(qr, name="qc")
qc.h(qr[0])
qc.x(qr[1])
qc.id(qr[2])
qc.cswap(qr[0], qr[1], qr[2])
sSimulator.run(qc).result().get_statevector()
qc.draw("mpl")
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
a= 1 + 1
a
#print(a)
a = 1
b = 0.5
a + b
an_integer = 42 # Just an integer
a_float = 0.1 # A non-integer number, up to a fixed precision
a_boolean = True # A value that can be True or False
a_string = '''just enclose text between two 's, or two "s, or do what we did for this string''' # Text
none_of_the_above = None # The absence of any actual value or variable type
a_list = [0,1,2,3]
a_list = [ 42, 0.5, True, [0,1], None, 'Banana' ]
a_list[0]
a_tuple = ( 42, 0.5, True, [0,1], None, 'Banana' )
a_tuple[0]
a_list[5] = 'apple'
print(a_list)
a_tuple[5] = 'apple'
a_list.append( 3.14 )
print(a_list)
a_dict = { 1:'This is the value, for the key 1', 'This is the key for a value 1':1, False:':)', (0,1):256 }
a_dict['This is the key for a value 1']
a_dict['new key'] = 'new_value'
for j in range(5):
print(j)
for j in a_list:
print(j)
for key in a_dict:
value = a_dict[key]
print('key =',key)
print('value =',value)
print()
if 'strawberry' in a_list:
print('We have a strawberry!')
elif a_list[5]=='apple':
print('We have an apple!')
else:
print('Not much fruit here!')
import numpy
numpy.sin( numpy.pi/2 )
import numpy as np
np.sin( np.pi/2 )
from numpy import *
sin( pi/2 )
def do_some_maths ( Input1, Input2 ):
the_answer = Input1 + Input2
return the_answer
x = do_some_maths(1,72)
print(x)
def add_sausages ( input_list ):
if 'sausages' not in input_list:
input_list.append('sausages')
print('List before the function')
print(a_list)
add_sausages(a_list) # function called without an output
print('\nList after the function')
print(a_list)
import random
for j in range(5):
print('* Results from sample',j+1)
print('\n Random number from 0 to 1:', random.random() )
print("\n Random choice from our list:", random.choice( a_list ) )
print('\n')
|
https://github.com/Soumyo2121/Basic-Quantum-Algorithms
|
Soumyo2121
|
from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver
import numpy as np
import pylab
import copy
from qiskit import BasicAer
from qiskit.chemistry.components.variational_forms import UCCSD
from qiskit.chemistry.components.initial_states import HartreeFock
from qiskit.aqua.components.optimizers import COBYLA, SPSA, SLSQP
from qiskit.aqua.operators import Z2Symmetries
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry import FermionicOperator
from qiskit.chemistry.core import Hamiltonian,QubitMappingType
from qiskit.aqua import QuantumInstance, aqua_globals
molecule = 'H .0 .0 -{0}; Li .0 .0 {0}'
distances = np.arange(0.5,4.25,0.25)
vqe_energies = []
hf_energies = [] # initial guess from Hartree-Fock
exact_energies = []
for i,d in enumerate(distances):
print('step',i)
# set up experiment
driver = PySCFDriver(molecule.format(d/2), basis = 'sto3g')
qmolecule = driver.run()
operator = Hamiltonian(qubit_mapping=QubitMappingType.PARITY,
two_qubit_reduction=True,
freeze_core=True,
orbital_reduction=[-3,-2])
qubit_op, aux_ops = operator.run(qmolecule)
# exact classical result
exact_result = NumPyMinimumEigensolver(qubit_op, aux_operators=aux_ops).run()
exact_result = operator.process_algorithm_result(exact_result)
# VQE
optimizer = SLSQP(maxiter=1000)
initial_state = HartreeFock(operator.molecule_info['num_orbitals'],
operator.molecule_info['num_particles'],
qubit_mapping=operator._qubit_mapping,
two_qubit_reduction=operator._two_qubit_reduction)
var_form = UCCSD(num_orbitals=operator.molecule_info['num_orbitals'],
num_particles=operator.molecule_info['num_particles'],
initial_state=initial_state,
qubit_mapping=operator._qubit_mapping,
two_qubit_reduction=operator._two_qubit_reduction)
algo=VQE(qubit_op, var_form, optimizer, aux_operators=aux_ops)
vqe_result=algo.run(QuantumInstance(BasicAer.get_backend('statevector_simulator')))
vqe_result=operator.process_algorithm_result(vqe_result)
exact_energies.append(exact_result.energy)
vqe_energies.append(vqe_result.energy)
hf_energies.append(vqe_result.hartree_fock_energy)
pylab.plot(distances,hf_energies, label='Hartree_Fock')
pylab.plot(distances, vqe_energies, 'o', label='VQE')
pylab.plot(distances, exact_energies, '^', label='Exact')
pylab.xlabel('Interatomic Distance')
pylab.ylabel('Energy')
pylab.title('LiH Ground State Energy')
pylab.legend()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.circuit.library import UCCSD
ansatz = UCCSD()
ansatz.num_spin_orbitals = 10
from qiskit_nature.second_q.circuit.library import UCCSD
ansatz = UCCSD()
ansatz.num_spatial_orbitals = 5
from qiskit_nature.circuit.library import UCC, UVCC
ucc = UCC(qubit_converter=None, num_particles=None, num_spin_orbitals=None, excitations=None)
uvcc = UVCC(qubit_converter=None, num_modals=None, excitations=None)
from qiskit_nature.second_q.circuit.library import UCC, UVCC
ucc = UCC(num_spatial_orbitals=None, num_particles=None, excitations=None, qubit_converter=None)
uvcc = UVCC(num_modals=None, excitations=None, qubit_converter=None)
from qiskit_nature.circuit.library import HartreeFock, VSCF
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import DirectMapper, JordanWignerMapper
hf = HartreeFock(
num_spin_orbitals=4, num_particles=(1, 1), qubit_converter=QubitConverter(JordanWignerMapper())
)
vscf = VSCF(num_modals=[2, 2])
from qiskit_nature.second_q.circuit.library import HartreeFock, VSCF
from qiskit_nature.second_q.mappers import DirectMapper, JordanWignerMapper, QubitConverter
hf = HartreeFock()
hf.num_spatial_orbitals = 2
hf.num_particles = (1, 1)
hf.qubit_converter = QubitConverter(JordanWignerMapper())
vscf = VSCF()
vscf.num_modals = [2, 2]
from qiskit.providers.basicaer import BasicAer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms.ground_state_solvers import VQEUCCFactory
quantum_instance = QuantumInstance(BasicAer.get_backend("statevector_simulator"))
vqe_factory = VQEUCCFactory(quantum_instance=quantum_instance)
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.circuit.library import UCCSD
from qiskit_nature.second_q.algorithms.ground_state_solvers import VQEUCCFactory
estimator = Estimator()
ansatz = UCCSD()
optimizer = SLSQP()
vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer)
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver, VQEUCCFactory
from qiskit_nature.algorithms.excited_states_solvers import QEOM
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
vqe_factory = VQEUCCFactory()
converter = QubitConverter(JordanWignerMapper())
ground_state_solver = GroundStateEigensolver(converter, vqe_factory)
qeom = QEOM(ground_state_solver)
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.circuit.library import UCCSD
from qiskit_nature.second_q.algorithms.ground_state_solvers import (
GroundStateEigensolver,
VQEUCCFactory,
)
from qiskit_nature.second_q.algorithms.excited_states_solvers import QEOM
from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter
estimator = Estimator()
ansatz = UCCSD()
optimizer = SLSQP()
vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer)
converter = QubitConverter(JordanWignerMapper())
ground_state_solver = GroundStateEigensolver(converter, vqe_factory)
qeom = QEOM(ground_state_solver, estimator)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.