repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/Qiskit/feedback
|
Qiskit
|
import numpy as np
from qiskit_nature.operators.second_quantization import QuadraticHamiltonian
# create Hamiltonian
hermitian_part = np.array(
[
[1.0, 2.0, 0.0, 0.0],
[2.0, 1.0, 2.0, 0.0],
[0.0, 2.0, 1.0, 2.0],
[0.0, 0.0, 2.0, 1.0],
]
)
antisymmetric_part = np.array(
[
[0.0, 3.0, 0.0, 0.0],
[-3.0, 0.0, 3.0, 0.0],
[0.0, -3.0, 0.0, 3.0],
[0.0, 0.0, -3.0, 0.0],
]
)
constant = 4.0
hamiltonian = QuadraticHamiltonian(
hermitian_part=hermitian_part,
antisymmetric_part=antisymmetric_part,
constant=constant,
)
# convert it to a FermionicOp and print it
hamiltonian_ferm = hamiltonian.to_fermionic_op()
hamiltonian_ferm.display_format = "sparse"
hamiltonian_ferm.set_truncation(0)
print(hamiltonian_ferm)
# get the transformation matrix W and orbital energies {epsilon_j}
(
transformation_matrix,
orbital_energies,
transformed_constant,
) = hamiltonian.diagonalizing_bogoliubov_transform()
print("Shape of matrix W:")
print(transformation_matrix.shape)
print()
print("Orbital energies:")
print(orbital_energies)
print()
print("Transformed constant:")
print(transformed_constant)
from qiskit_nature.circuit.library import FermionicGaussianState
occupied_orbitals = (0, 2)
eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant
print("Eigenvalue:")
print(eig)
circuit = FermionicGaussianState(
transformation_matrix, occupied_orbitals=occupied_orbitals
)
circuit.draw("mpl")
from qiskit.quantum_info import Statevector
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
# simulate the circuit to get the final state
state = np.array(Statevector(circuit))
# convert the Hamiltonian to a matrix
hamiltonian_jw = JordanWignerMapper().map(hamiltonian_ferm).to_matrix()
# check that the state is an eigenvector with the expected eigenvalue
np.testing.assert_allclose(hamiltonian_jw @ state, eig * state, atol=1e-8)
# create Hamiltonian
hermitian_part = np.array(
[
[1.0, 2.0, 0.0, 0.0],
[2.0, 1.0, 2.0, 0.0],
[0.0, 2.0, 1.0, 2.0],
[0.0, 0.0, 2.0, 1.0],
]
)
constant = 4.0
hamiltonian = QuadraticHamiltonian(
hermitian_part=hermitian_part,
constant=constant,
)
print("Hamiltonian conserves particle number:")
print(hamiltonian.conserves_particle_number())
# get the transformation matrix W and orbital energies {epsilon_j}
(
transformation_matrix,
orbital_energies,
transformed_constant,
) = hamiltonian.diagonalizing_bogoliubov_transform()
print("Shape of matrix W:")
print(transformation_matrix.shape)
print()
print("Orbital energies:")
print(orbital_energies)
print()
print("Transformed constant:")
print(transformed_constant)
from qiskit_nature.circuit.library import SlaterDeterminant
occupied_orbitals = (0, 2)
eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant
print("Eigenvalue:")
print(eig)
circuit = SlaterDeterminant(transformation_matrix[list(occupied_orbitals)])
circuit.draw("mpl")
from qiskit.quantum_info import random_hermitian
# construct and display some larger circuits
N = 8
n_particles = 4
hermitian_part = np.array(random_hermitian(N))
hamiltonian = QuadraticHamiltonian(hermitian_part)
transformation_matrix, _, _ = hamiltonian.diagonalizing_bogoliubov_transform()
occupied_orbitals = range(n_particles)
circuit = SlaterDeterminant(transformation_matrix[list(occupied_orbitals)])
circuit.draw("mpl")
|
https://github.com/ionq-samples/Ion-Q-Thruster
|
ionq-samples
|
import os
from qiskit.converters import circuit_to_dag
from qiskit import transpile
from qiskit_ionq import IonQProvider
from custom_transpiler import IonQ_Transpiler
from qiskit.circuit.random import random_circuit
def compare_circuits(original_circuit, optimized_circuit):
original_dag = circuit_to_dag(original_circuit)
optimized_dag = circuit_to_dag(optimized_circuit)
original_metrics = {
'depth': original_dag.depth(),
'size': original_dag.size(),
'gpi2_count': original_dag.count_ops().get('gpi2', 0),
'gpi_count': original_dag.count_ops().get('gpi', 0),
'ms_count': original_dag.count_ops().get('ms', 0),
'zz_count': original_dag.count_ops().get('zz', 0)
}
optimized_metrics = {
'depth': optimized_dag.depth(),
'size': optimized_dag.size(),
'gpi2_count': optimized_dag.count_ops().get('gpi2', 0),
'gpi_count': optimized_dag.count_ops().get('gpi', 0),
'ms_count': optimized_dag.count_ops().get('ms', 0),
'zz_count': optimized_dag.count_ops().get('zz', 0)
}
print(f"The circuit size has reduced from {original_metrics.get('size')} to {optimized_metrics.get('size')}")
return original_metrics, optimized_metrics
def print_metrics(metrics):
print(f"- Depth: {metrics['depth']}")
print(f"- Size: {metrics['size']}")
print(f"- GPI2 Count: {metrics['gpi2_count']}")
print(f"- GPI Count: {metrics['gpi_count']}")
print(f"- MS Count: {metrics['ms_count']}")
print(f"- ZZ Count: {metrics['zz_count']}")
def run_test_case(qc, backend):
original_circuit = transpile(qc, backend=backend, optimization_level=3)
print("IBM transpiled circuit:")
#print(original_circuit.draw())
custom_transpiler = IonQ_Transpiler(backend)
optimized_circuit = custom_transpiler.transpile(qc)
print("\nCustom transpiled circuit:")
#print(optimized_circuit.draw())
original_metrics, optimized_metrics = compare_circuits(original_circuit, optimized_circuit)
print("\nIBM transpiled circuit metrics:")
print_metrics(original_metrics)
print("\nCustom transpiled circuit metrics:")
print_metrics(optimized_metrics)
return original_circuit, optimized_circuit
# Initialize the IonQ provider and backend
#api_key = os.getenv("IONQ_API_KEY") or input("Enter your IonQ API key: ")
#provider = IonQProvider(token=api_key)
#backend = provider.get_backend("simulator", gateset="native")
# Generate random circuits
#num_qubits = 5
#depth = 10
#num_circuits = 5
#random_circuits = [random_circuit(num_qubits, depth, measure=True) for _ in range(num_circuits)]
# Run test cases
#for i, qc in enumerate(random_circuits):
# print(f"\nTest Case {i+1}:")
# run_test_case(qc, backend)
|
https://github.com/MonitSharma/Qiskit-Hindi-Tutorials
|
MonitSharma
|
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()
!pip install qutip -q
!pip install qiskit -q
!pip install qiskit[visualization] -q
!pip install git+https://github.com/qiskit-community/qiskit-textbook.git#subdirectory=qiskit-textbook-src -q
import numpy as np
np.set_printoptions(precision=3, suppress=True)
import qutip as qt
from matplotlib import pyplot as plt
%matplotlib inline
import pandas as pd
import sklearn as sk
import qiskit as qk
# Remember that qiskit has to be already installed in the Python environment.
# Otherwise the import command will fail
import qiskit as qk
# A circuit composed of just one qubit
qc = qk.QuantumCircuit(1)
qc.draw('mpl')
import qiskit as qiskit
# A qubit initialized in the state |0>
qc = qk.QuantumCircuit(1)
qc.initialize([1,0])
qc.draw('mpl')
import qiskit as qiskit
# A qubit initialized in the state |0>
qc = qk.QuantumCircuit(1)
qc.initialize([1,0])
qc.draw('mpl')
import qiskit as qiskit
# A qubit initialized in the state |0>
qc = qk.QuantumCircuit(1)
qc.initialize([1,0])
qc.draw('mpl')
import qiskit as qk
qc = qk.QuantumCircuit(1)
qc.initialize([1,0],0)
qc.measure_all()
# Let's choose the statevector simulator from the Aer backend
backend = qk.Aer.get_backend('statevector_simulator')
# And execute the circuit qc in the simulator backend
# getting as final result the counts from 1.000 measures
# of the qubit state
result = qk.execute(qc, backend, shots=1000).result().get_counts()
result
import qiskit as qk
qc = qk.QuantumCircuit(1)
qc.initialize([1,0],0)
qc.measure_all()
backend = qk.Aer.get_backend('statevector_simulator')
result = qk.execute(qc, backend, shots=1000).result().get_counts()
qk.visualization.plot_histogram(result)
import qiskit as qk
qr = qk.QuantumRegister(1,'q0')
cr = qk.ClassicalRegister(1,'c0')
qc = qk.QuantumCircuit(qr, cr)
qc.initialize([1,0],0)
qc.measure(0,0)
qc.draw('mpl')
backend = qk.Aer.get_backend('statevector_simulator')
result = qk.execute(qc, backend, shots=1000).result().get_counts()
qk.visualization.plot_histogram(result)
import numpy as np
v0 = np.array([[1],[0]]);v0
v1 = np.array([[0],[1]]); v1
X = np.array([[0,1],[1,0]]); X
X.dot(v0)
X.dot(v1)
import qiskit as qk
qr = qk.QuantumRegister(1,"q0")
cr = qk.ClassicalRegister(1,"c0")
qc = qk.QuantumCircuit(qr, cr)
qc.initialize([1,0],0)
qc.x(0)
qc.measure(qr[0], cr[0])
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc, simulator, shots=1000).result().get_counts()
results
qk.visualization.plot_histogram(results)
import numpy as np
# Notice that we are creating the v0 matrix using the transpose operation
v0 = np.array([[1,0]]).T; v0
# Here it is created again de X matrix
X = np.array([[0,1],[1,0]]); X
# Multiplying v0 by the X matrix twice you get again v0
X.dot(X).dot(v0)
# Multiplying the X matrix by itself you get the Identity matrix
X.dot(X)
import qiskit as qk
qr = qk.QuantumRegister(1,'q0')
cr = qk.ClassicalRegister(1,'c0')
qc = qk.QuantumCircuit(qr, cr)
qc.initialize([1,0],0)
qc.x(0)
qc.x(0)
qc.measure(qr[0],cr[0])
qc.draw('mpl')
# The result of 1000 measures of the qubit above gives the |0> state as result
# in all measures
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=1000).result().get_counts()
results
qk.visualization.plot_histogram(results)
import qiskit as qk
qr = qk.QuantumRegister(1,'q0')
cr = qk.ClassicalRegister(1,'c0')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([2**-0.5,2**-0.5],0)
qc.measure(qr[0],cr[0])
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import numpy as np
v0 = np.array([[1,0]]).T; v0
H = np.array([[1,1],[1,-1]])/np.sqrt(2); H
H.dot(v0)
import qiskit as qk
qr = qk.QuantumRegister(1,'q0')
cr = qk.ClassicalRegister(1,'c0')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([1,0],0)
qc.h(qr[0])
qc.measure(qr[0],cr[0])
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc, simulator, shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import qiskit as qk
qr = qk.QuantumRegister(1,'q0')
cr = qk.ClassicalRegister(1,'c0')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([2**-0.5,-(2**-0.5)],0)
qc.measure(qr[0],cr[0])
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import qiskit as qk
qr = qk.QuantumRegister(1,'q0')
cr = qk.ClassicalRegister(1,'c0')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([2**-0.5,-(2**-0.5)],0)
qc.h(0)
qc.measure(qr[0],cr[0])
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import qiskit as qk
qr = qk.QuantumRegister(1,'q0')
cr = qk.ClassicalRegister(1,'c0')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([0,1],0)
qc.h(0)
qc.h(0)
qc.measure(qr[0],cr[0])
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import numpy as np
# First let's start with the qubit in the state |psi> = (|0> - |1>)/sqrt(2)
psi = np.array([[1,-1]]).T/(2**0.5); psi
H = np.array([[1,1],[1,-1]])/2**0.5; H
# Now let's pass the qubit Psi through an Hadamard gate.
# The result is a qubit in the state |1>
H.dot(psi)
# Let's start with a qubit in the state |1>, pass it through a
# a hadamard gate twice and check the result
v0 = np.array([[0,1]]).T; v0
H.dot(H).dot(v0)
# This means that if we multiply the H gate by itself the result
# will be an Identity matrix. Let's check it.
H.dot(H)
import qiskit as qk
qr = qk.QuantumRegister(2,'q')
cr = qk.ClassicalRegister(2,'c')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([1,0],0)
qc.initialize([1,0],1)
qc.measure(qr,cr)
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import numpy as np
psi1 = np.array([[1,0]]).T; psi1
psi2 = np.array([[1,0]]).T; psi2
# In numpy the tensor product is calculated with the function kron
np.kron(psi1,psi2)
import qiskit as qk
qr = qk.QuantumRegister(2,'q')
cr = qk.ClassicalRegister(2,'c')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([1,0],0)
qc.initialize([1,0],1)
qc.h(0)
qc.h(1)
qc.measure(qr,cr)
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import numpy as np
psi1 = np.array([[1,0]]).T;psi1
psi2 = np.array([[1,0]]).T;psi2
H = np.array([[1,1],[1,-1]])/2**0.5;H
# When we want to combine two vector states or gate matrices we tensor product them.
psi3 = np.kron(psi1,psi2);psi3
H2 = np.kron(H,H);H2
# When we want to pass a vetor through a gate we calculate the dot product
# of the total gate matrix with the total vector.
# As we have predicted, the resulting vector state has a=b=c=d=1/2
psi4 = H2.dot(psi3); psi4
import qiskit as qk
qr = qk.QuantumRegister(2,'q')
cr = qk.ClassicalRegister(2,'c')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([0,1],0)
qc.initialize([0,1],1)
qc.h(0)
qc.h(1)
qc.measure(qr,cr)
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import numpy as np
psi1 = np.array([[0,1]]).T;psi1
psi2 = np.array([[0,1]]).T;psi2
H = np.array([[1,1],[1,-1]])/2**0.5;H
# When we want to combine two vector states or gate matrices we tensor product them.
psi3 = np.kron(psi1,psi2);psi3
H2 = np.kron(H,H);H2
# When we want to pass a vetor through a gate we calculate the dot product
# of the total gate matrix with the total vector.
# As we have predicted, the resulting vector state has a=b=c=d=1/2
psi4 = H2.dot(psi3); psi4
import qiskit as qk
qr = qk.QuantumRegister(2,'q')
cr = qk.ClassicalRegister(2,'c')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([1,0],0)
qc.initialize([1,0],1)
qc.cnot(0,1)
qc.measure(qr,cr)
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc, simulator, shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import numpy as np
C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C
v00 = np.array([[1,0,0,0]]).T;v00
# C.v00 = v00
C.dot(v00)
import qiskit as qk
qr = qk.QuantumRegister(2,'q')
cr = qk.ClassicalRegister(2,'c')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([1,0],0)
qc.initialize([0,1],1)
qc.cnot(0,1)
qc.measure(qr,cr)
qc.draw('mpl')
# Please notice that Qiskit's qubits presentation order is reversed.
# Therefore 10 in the histogram's x axis should be read as 01 (from
# inside out or right to left).
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc, simulator, shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import numpy as np
C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C
v01 = np.array([[0,1,0,0]]).T;v01
C.dot(v01)
import qiskit as qk
qr = qk.QuantumRegister(2,'q')
cr = qk.ClassicalRegister(2,'c')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([0,1],0)
qc.initialize([1,0],1)
qc.cnot(0,1)
qc.measure(qr,cr)
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc, simulator, shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import numpy as np
C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C
v10 = np.array([[0,0,1,0]]).T; v10
C.dot(v10)
import qiskit as qk
qr = qk.QuantumRegister(2,'q')
cr = qk.ClassicalRegister(2,'c')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([0,1],0)
qc.initialize([0,1],1)
qc.cnot(0,1)
qc.measure(qr,cr)
qc.draw('mpl')
# Again remember to read qiskit qubits state presentation order
# from right to left. Therefore 01 in the x axis is in fact 10
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc, simulator, shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import numpy as np
C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C
v11 = np.array([[0,0,0,1]]).T; v11
# C.v11 = v10
C.dot(v11)
import qiskit as qk
qr = qk.QuantumRegister(2, 'q')
cr = qk.ClassicalRegister(2, 'c')
qc = qk.QuantumCircuit(qr, cr)
qc.initialize([1,0],0)
qc.initialize([1,0],1)
qc.h(qr[0])
qc.cx(qr[0],qr[1])
qc.measure(qr, cr)
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import numpy as np
va = np.array([[1,0]]).T; va
vb = np.array([[1,0]]).T; vb
H = np.array([[1,1],[1,-1]])/2**0.5;H
vaH = H.dot(va); vaH
vaHvb = np.kron(vaH,vb); vaHvb
C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C
vout = C.dot(vaHvb); vout
import qiskit as qk
qr = qk.QuantumRegister(2, 'q')
cr = qk.ClassicalRegister(2, 'c')
qc = qk.QuantumCircuit(qr, cr)
qc.initialize([0,1],0)
qc.initialize([1,0],1)
qc.h(qr[0])
qc.cx(qr[0],qr[1])
qc.measure(qr, cr)
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import numpy as np
va = np.array([[0,1]]).T; va
vb = np.array([[1,0]]).T; vb
H = np.array([[1,1],[1,-1]])/2**0.5;H
vaH = H.dot(va); vaH
vaHvb = np.kron(vaH,vb); vaHvb
vout = C.dot(vaHvb); vout
vout = C.dot(vaHvb); vout
# Get the IBM API key in: https://quantum-computing.ibm.com
# chave = 'My key is already saved in this environment'
# qk.IBMQ.save_account(chave)
# Load the account in the active session
qk.IBMQ.load_account()
# The default provider is é hub='ibm-q', group='open, project='main'
# The code below is executed as an example
provider_1 = qk.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
# In the public provider we will use a cloud simulator.
backend_1 = provider_1.get_backend('ibmq_qasm_simulator')
# The provider listed below has unlimited jobs
provider_2 = qk.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
# For this provider we will use the ibmq_jakarta machine
backend_2 = provider_2.get_backend('ibmq_manila')
# With n Qubits we can generate a random number from 0 to 2^n - 1
n = 3
qr = qk.QuantumRegister(n,'q')
cr = qk.ClassicalRegister(n,'c')
qc = qk.QuantumCircuit(qr, cr)
# Applying a Hadamard to each of the three qubits
for i in range(n):
qc.h(i)
# Measuring the three qubits
qc.measure(qr,cr)
# Visualizing the circuit
qc.draw('mpl')
new_job = qk.execute(qc, backend_2, shots=1)
# this result is stored on the local machine. However, it will only be available
# after the job has been executed. It returns a python dictionary.
new_job.result().get_counts()
int(list(new_job.result().get_counts().keys())[0],2)
from qiskit import QuantumCircuit
circuit = QuantumCircuit(2, 2)
circuit.h(0)
circuit.cx(0,1)
circuit.measure([0,1], [0,1])
display(circuit.draw('mpl'))
from qiskit.providers.aer import AerSimulator
print(AerSimulator().run(circuit, shots=1000).result().get_counts())
print(AerSimulator().run(circuit, shots=1000).result().get_counts())
from qiskit import QuantumCircuit
circuito = QuantumCircuit(3,3)
for i in range(3):
circuito.h(i)
circuito.measure(i,i)
display(circuito.draw('mpl'))
from qiskit.providers.aer import AerSimulator
AerSimulator().run(circuito, shots = 1000).result().get_counts()
from qiskit import QuantumCircuit
qc = QuantumCircuit(4,4)
qc.x([0,1])
qc.cx([0,1],[2,2])
qc.ccx(0,1,3)
qc.measure([0,1,2,3],[0,1,2,3])
display(qc.draw(output='mpl'))
from qiskit.providers.aer import AerSimulator
AerSimulator().run(qc, shots = 10000).result().get_counts()
import qiskit as qk
qr = qk.QuantumRegister(1,'q')
cr = qk.ClassicalRegister(1,'c')
qc = qk.QuantumCircuit(qr, cr)
qc.initialize([1,0],0)
print("Circuit 1 - Registers Only")
display(qc.draw('mpl'))
qc.x(qr)
print("Circuit 1 - Quantum Register with a Gate X ")
display(qc.draw('mpl'))
job = qk.execute(experiments = qc,
backend = qk.Aer.get_backend('statevector_simulator'))
result1 = job.result().get_statevector()
print("Quantum Register Vector State")
from qiskit.tools.visualization import plot_bloch_multivector
display(plot_bloch_multivector(result1))
job = qk.execute(experiments = qc,
backend = qk.Aer.get_backend('unitary_simulator'))
print("Transformation Matrix (up to this stage)")
print(job.result().get_unitary())
qc.measure(qr, cr)
print()
print("Circuit 1 - Registers, Gate X and Quantum Register Measure")
display(qc.draw('mpl'))
print("Quantum Register Thousand Measures")
job = qk.execute(experiments = qc,
backend = qk.Aer.get_backend('statevector_simulator'),
shots = 1000)
print(job.result().get_counts())
print()
print("Result's Histogram")
from qiskit.tools.visualization import plot_histogram
plot_histogram(data = job.result().get_counts(), figsize=(4,3))
import qiskit as qk
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qr = qk.QuantumRegister(3,'q')
cr = qk.ClassicalRegister(3,'c')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([1,0],0)
qc.initialize([1,0],1)
qc.initialize([1,0],2)
display(qc.draw('mpl'))
sv = Statevector.from_label('000')
state_data = lambda qc,sv: np.round(np.asarray(sv.evolve(qc).data),4)
state_bloch = lambda qc,sv: plot_bloch_multivector(sv.evolve(qc).data, reverse_bits=True)
print(state_data(qc,sv))
state_bloch(qc,sv)
qc.x(0)
qc.barrier()
display(qc.draw('mpl'))
print(state_data(qc,sv))
display(state_bloch(qc,sv))
qc.h(1)
display(qc.draw('mpl'))
print(state_data(qc,sv))
state_bloch(qc,sv)
qc.cnot(1,2)
display(qc.draw("mpl"))
state_data(qc,sv)
state_bloch(qc,sv)
qc.cnot(0,1)
display(qc.draw('mpl'))
state_data(qc,sv)
qc.h(0)
qc.barrier()
display(qc.draw('mpl'))
state_data(qc,sv)
qc.measure(0,0)
qc.measure(1,1)
qc.barrier()
qc.cnot(1,2)
qc.cz(0,2)
qc.measure(2,2)
display(qc.draw('mpl'))
simulador = qk.Aer.get_backend('statevector_simulator')
resultado = qk.execute(qc, simulador, shots=10000).result()
qk.visualization.plot_histogram(resultado.get_counts())
import numpy as np
V = np.array([[3+2j],[4-2j]])
modV = np.real(V.T.conjugate().dot(V)[0,0])**0.5
Vn = V/modV; Vn
v0 = np.array([[1,0]]).T
v1 = np.array([[0,1]]).T
Vn[0,0]*v0 + Vn[1,0]*v1
import qiskit as qk
qr = qk.QuantumRegister(1,'q')
cr = qk.ClassicalRegister(1,'c')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([Vn[0,0],Vn[1,0]],0)
qc.measure(qr[0],cr[0])
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
Vn[0,0].conjugate()*Vn[0,0]
Vn[1,0].conjugate()*Vn[1,0]
import numpy as np
CNOT = np.array([[1,0,0,0],
[0,1,0,0],
[0,0,0,1],
[0,0,1,0]])
CNOT.dot(CNOT)
import numpy as np
H = np.array([[1,1],[1,-1]])/2**0.5
H.dot(H)
import qiskit as qk
qr = qk.QuantumRegister(2,'q')
cr = qk.ClassicalRegister(2,'c')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([1,0],0)
qc.initialize([1,0],1)
qc.measure(qr,cr)
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import qiskit as qk
qr = qk.QuantumRegister(2,'q')
cr = qk.ClassicalRegister(2,'c')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([1,0],0)
qc.initialize([1,0],1)
qc.h(0)
qc.measure(qr,cr)
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import qiskit as qk
qr = qk.QuantumRegister(2,'q')
cr = qk.ClassicalRegister(2,'c')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([1,0],0)
qc.initialize([1,0],1)
qc.h(0)
qc.cnot(qr[0],qr[1])
qc.measure(qr,cr)
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import qiskit as qk
qr = qk.QuantumRegister(2,'q')
cr = qk.ClassicalRegister(2,'c')
qc = qk.QuantumCircuit(qr,cr)
qc.initialize([1,0],0)
qc.initialize([1,0],1)
qc.h(0)
qc.cnot(qr[0],qr[1])
qc.cnot(qr[0],qr[1])
qc.measure(qr,cr)
qc.draw('mpl')
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
simulator = qk.Aer.get_backend('statevector_simulator')
results = qk.execute(qc,simulator,shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import numpy as np
X = np.array([[0,1],
[1,0]])
X
X.conj().T.dot(X)
Y = np.array([[0,-1j],
[1j,0]])
Y
Y.conj().T.dot(Y)
Z = np.array([[1,0],
[0,-1]])
Z
Z.conj().T.dot(Z)
H = (X+Z)/np.sqrt(2); H
H.dot(Z).dot(H)
H.dot(X).dot(H)
-H.dot(Y).dot(H)
import numpy as np
S = np.array([[1,0],
[0,1j]])
S
S.conj().T.dot(S)
T = np.array([[1,0],
[0,np.exp(1j*np.pi/4)]])
T
T.conj().T.dot(T)
S = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]]); S
S.dot(v00)
S.dot(v01)
S.dot(v10)
S.dot(v11)
C_ = np.array([[1,0,0,0],
[0,0,0,1],
[0,0,1,0],
[0,1,0,0]]);C_
C_ = np.array([[1,0,0,0],
[0,0,0,1],
[0,0,1,0],
[0,1,0,0]]);C_
C.dot(C_).dot(C)
v = v0 + v1; v
n = np.array([[0,0],[0,1]]); n
n.dot(v)
n_ = np.array([[1,0],[0,0]]);n_
I2 = np.identity(2); I2
I2 - n
n_.dot(v)
n.dot(n)
n_.dot(n_)
n.dot(n_)
n_.dot(n)
n.dot(X)
n+n_
X.dot(n_)
import numpy as np
n = np.array([[0,0],[0,1]]); n
n_ = np.array([[1,0],[0,0]]);n_
np.kron(n,n)
np.kron(n_,n_)
np.kron(n,n_)
np.kron(n_,n)
np.kron(X,X)
np.kron(X,X).dot(np.kron(n,n_)+np.kron(n_,n))
np.kron(n,n) + np.kron(n_,n_) + np.kron(X,X).dot(np.kron(n,n_)+np.kron(n_,n))
np.kron(n,n)
np.kron(n_,n_)
np.kron(n_,n)
np.kron(n,n_)
nn = np.kron(n,n)
nn_ = np.kron(n,n_)
n_n = np.kron(n_,n)
n_n_ = np.kron(n_,n_)
nn + nn_ + n_n + n_n_
import numpy as np
n = np.array([[0,0],[0,1]]); n
n_ = np.array([[1,0],[0,0]]);n_
#(n x n).(n_ x n_)
np.kron(n,n).dot(np.kron(n_,n_))
np.kron(n,n).dot(np.kron(n_,n_))
np.kron(n.dot(n_),n.dot(n_))
nn.dot(n_n_)
# (n_ x n).(n x n_)
np.kron(n_,n).dot(np.kron(n,n_))
n_n.dot(nn_)
# (n x n_).(n_ x n)
np.kron(n, n_).dot(np.kron(n_,n))
n_n_.dot(nn)
NOT = np.array([[0,1],[1,0]]); NOT
D0 = np.array([[1],[0]])
D1 = np.array([[0],[1]])
NOT.dot(D0)
NOT.dot(D1)
AND = np.array([[1,1,1,0],[0,0,0,1]]); AND
AND.dot(np.kron(D0,D0))
AND.dot(np.kron(D0,D1))
AND.dot(np.kron(D1,D0))
AND.dot(np.kron(D1,D1))
OR = np.array([[1,0,0,0],[0,1,1,1]]); OR
OR.dot(np.kron(D0,D0))
OR.dot(np.kron(D0,D1))
OR.dot(np.kron(D1,D0))
OR.dot(np.kron(D1,D1))
NAND = np.array([[0,0,0,1],[1,1,1,0]]); NAND
NOT.dot(AND)
NOR = np.array([[0,1,1,1],[1,0,0,0]]);NOR
NOT.dot(OR)
np.kron(NOT,AND)
OR.dot(np.kron(NOT,AND))
NOT.dot(AND).dot(np.kron(NOT,NOT))
OR
NOT.dot(OR).dot(np.kron(NOT,NOT))
AND
import numpy as np
k = np.kron
XOR = np.array([[1,0,0,1],
[0,1,1,0]])
AND = np.array(([1,1,1,0],
[0,0,0,1]))
k(XOR,AND)
def criaCompat(nbits,nvezes):
nlins = 2**(nbits*nvezes)
ncols = 2**nbits
compat = np.zeros(nlins*ncols).reshape(nlins,ncols)
for i in range(ncols):
formato = "0" + str(nbits) + "b"
binario = format(i,formato)*nvezes
decimal = int(binario,2)
compat[decimal,i] = 1
return(compat)
criaCompat(2,2)
k(XOR,AND).dot(criaCompat(2,2))
import numpy as np
k = np.kron
def criaCompat(nbits,nvezes):
nlins = 2**(nbits*nvezes)
ncols = 2**nbits
compat = np.zeros(nlins*ncols).reshape(nlins,ncols)
for i in range(ncols):
formato = "0" + str(nbits) + "b"
binario = format(i,formato)*nvezes
decimal = int(binario,2)
compat[decimal,i] = 1
return(compat)
criaCompat(2,2)
NOT = np.array([[0,1],
[1,0]])
AND3 = np.array([[1,1,1,1,1,1,1,0],
[0,0,0,0,0,0,0,1]])
OR4 = np.array([[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]])
I2 = np.array([[1,0],
[0,1]])
t1z = k(NOT,k(NOT,I2))
t2z = k(NOT,k(I2,NOT))
t3z = k(I2,k(NOT,NOT))
t4z = k(I2,k(I2,I2))
ORz = k(AND3,k(AND3,k(AND3,AND3)))
ORz = OR4.dot(ORz).dot(k(t1z,k(t2z,k(t3z,t4z))))
t1c = k(NOT,k(I2,I2))
t2c = k(I2,k(NOT,I2))
t3c = k(I2,k(I2,NOT))
t4c = k(I2,k(I2,I2))
ORc = k(AND3,k(AND3,k(AND3,AND3)))
ORc = OR4.dot(ORc).dot(k(t1c,k(t2c,k(t3c,t4c))))
compat = criaCompat(3,8)
k(ORz,ORc).dot(compat)
import numpy as np
TOFFOLI = np.array([[1,0,0,0,0,0,0,0],
[0,1,0,0,0,0,0,0],
[0,0,1,0,0,0,0,0],
[0,0,0,1,0,0,0,0],
[0,0,0,0,1,0,0,0],
[0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1],
[0,0,0,0,0,0,1,0]])
TOFFOLI.dot(TOFFOLI)
Z1 = np.array([[0,0,0,0,0,0,0,0],
[0,1,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,1,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,1]])
Z1
ZpY = np.zeros([8,8])
ZpY[0,0] = 1; ZpY[1,2] = 1; ZpY[2,1] = 1; ZpY[3,3] = 1
ZpY[4,4] = 1; ZpY[5,6] = 1; ZpY[6,5] = 1; ZpY[7,7] = 1
ZpY
Z1I4 = np.array([[0,0,0,0],
[1,0,0,0],
[0,0,0,0],
[0,1,0,0],
[0,0,0,0],
[0,0,1,0],
[0,0,0,0],
[0,0,0,1]])
TOFFOLI.dot(ZpY).dot(TOFFOLI).dot(Z1I4)
Zfim = np.array([[1,0,1,0,1,0,1,0],
[0,1,0,1,0,1,0,1]])
Zfim = np.array([[1,0,1,0,1,0,1,0],
[0,1,0,1,0,1,0,1]])
Zfim.dot(TOFFOLI).dot(ZpY).dot(TOFFOLI).dot(Z1I4)
import numpy as np
fred = np.identity(8)
fred[5,5] = 0; fred[5,6] = 1
fred[6,5] = 1; fred[6,6] = 0
fred
fred.dot(fred)
import numpy as np
Fy0 = np.zeros([8,4])
Fy0[0,0] = 1; Fy0[1,1] = 1; Fy0[4,2] = 1; Fy0[5,3] = 1
Fy0
xYz = np.array([[1,1,0,0,1,1,0,0],
[0,0,1,1,0,0,1,1]])
xYz.dot(fred).dot(Fy0)
|
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
|
Qiskit-Extensions
|
# This code is a Qiskit project.
# (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.
"""Tests for cutting_decomposition module."""
import unittest
import pytest
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import CircuitInstruction, Barrier, Clbit
from qiskit.circuit.library import EfficientSU2, RXXGate
from qiskit.circuit.library.standard_gates import CXGate
from qiskit.quantum_info import PauliList
from circuit_knitting.cutting import (
partition_circuit_qubits,
partition_problem,
cut_gates,
)
from circuit_knitting.cutting.instructions import Move
from circuit_knitting.cutting.qpd import (
QPDBasis,
TwoQubitQPDGate,
BaseQPDGate,
)
class TestCuttingDecomposition(unittest.TestCase):
def setUp(self):
# Use HWEA for simplicity and easy visualization
circuit = EfficientSU2(4, entanglement="linear", reps=2).decompose()
qpd_circuit = EfficientSU2(4, entanglement="linear", reps=2).decompose()
# We will instantiate 2 QPDBasis objects using from_instruction
rxx_gate = RXXGate(np.pi / 3)
rxx_decomp = QPDBasis.from_instruction(rxx_gate)
# Create two QPDGates and specify each of their bases
# Labels are only used for visualizations
qpd_gate1 = TwoQubitQPDGate(rxx_decomp, label=f"cut_{rxx_gate.name}")
qpd_gate2 = TwoQubitQPDGate(rxx_decomp, label=f"cut_{rxx_gate.name}")
qpd_gate1.basis_id = 0
qpd_gate2.basis_id = 0
# Create the circuit instructions
qpd_inst1 = CircuitInstruction(qpd_gate1, qubits=[1, 2])
qpd_inst2 = CircuitInstruction(qpd_gate2, qubits=[1, 2])
inst1 = CircuitInstruction(rxx_gate, qubits=[1, 2])
inst2 = CircuitInstruction(rxx_gate, qubits=[1, 2])
# Hard-coded overwrite of the two CNOTS with our decomposed RXX gates
qpd_circuit.data[9] = qpd_inst1
qpd_circuit.data[20] = qpd_inst2
circuit.data[9] = inst1
circuit.data[20] = inst2
self.qpd_circuit = qpd_circuit
self.circuit = circuit
def test_partition_circuit_qubits(self):
with self.subTest("Empty circuit"):
compare_circuit = QuantumCircuit()
partitioned_circuit = partition_circuit_qubits(compare_circuit, [])
self.assertEqual(partitioned_circuit, compare_circuit)
with self.subTest("Circuit with parameters"):
# Split 4q HWEA in middle of qubits
partition_labels = [0, 0, 1, 1]
# Get a QPD circuit based on partitions, and set the basis for each gate
# to match the basis_ids of self.qpd_circuit's QPDGates
circuit = partition_circuit_qubits(self.circuit, partition_labels)
for inst in circuit.data:
if isinstance(inst.operation, TwoQubitQPDGate):
inst.operation.basis_id = 0
# Terra doesn't consider params with same name to be equivalent, so
# we need to copy the comparison circuit and bind parameters to test
# equivalence.
compare_circuit = self.qpd_circuit.copy()
compare_qpd_circuit = partition_circuit_qubits(
compare_circuit, partition_labels
)
parameter_vals = [np.pi / 4] * len(circuit.parameters)
circuit.assign_parameters(parameter_vals, inplace=True)
compare_qpd_circuit.assign_parameters(parameter_vals, inplace=True)
self.assertEqual(circuit, compare_qpd_circuit)
with self.subTest("Circuit with barriers"):
# Split 4q HWEA in middle of qubits
partition_labels = [0, 0, 1, 1]
bar1 = CircuitInstruction(Barrier(4), qubits=[0, 1, 2, 3])
bar2 = CircuitInstruction(Barrier(4), qubits=[0, 1, 2, 3])
bar_circuit = self.circuit.copy()
bar_circuit.data.insert(10, bar1)
bar_circuit.data.insert(22, bar2)
# Get a QPD circuit based on partitions, and set the basis for each gate
# to match the basis_ids of self.qpd_circuit's QPDGates
circuit = partition_circuit_qubits(bar_circuit, partition_labels)
for inst in circuit.data:
if isinstance(inst.operation, TwoQubitQPDGate):
inst.operation.basis_id = 0
# Terra doesn't consider params with same name to be equivalent, so
# we need to copy the comparison circuit and bind parameters to test
# equivalence.
compare_circuit = self.qpd_circuit.copy()
compare_qpd_circuit = partition_circuit_qubits(
compare_circuit, partition_labels
)
bar1 = CircuitInstruction(Barrier(4), qubits=[0, 1, 2, 3])
bar2 = CircuitInstruction(Barrier(4), qubits=[0, 1, 2, 3])
compare_qpd_circuit.data.insert(10, bar1)
compare_qpd_circuit.data.insert(22, bar2)
parameter_vals = [np.pi / 4] * len(circuit.parameters)
circuit.assign_parameters(parameter_vals, inplace=True)
compare_qpd_circuit.assign_parameters(parameter_vals, inplace=True)
self.assertEqual(circuit, compare_qpd_circuit)
with self.subTest("Partition IDs the wrong size"):
compare_circuit = QuantumCircuit()
with pytest.raises(ValueError) as e_info:
partition_circuit_qubits(compare_circuit, [0])
assert (
e_info.value.args[0]
== "Length of partition_labels (1) does not equal the number of qubits in the input circuit (0)."
)
with self.subTest("Unsupported gate"):
compare_circuit = QuantumCircuit(3)
compare_circuit.ccx(0, 1, 2)
partitions = [0, 1, 1]
with pytest.raises(ValueError) as e_info:
partition_circuit_qubits(compare_circuit, partitions)
assert (
e_info.value.args[0]
== "Decomposition is only supported for two-qubit gates. Cannot decompose (ccx)."
)
with self.subTest("Toffoli gate in a single partition"):
circuit = QuantumCircuit(4)
circuit.ccx(0, 1, 2)
circuit.rzz(np.pi / 7, 2, 3)
partition_circuit_qubits(circuit, "AAAB")
def test_partition_problem(self):
with self.subTest("simple circuit and observable"):
# Split 4q HWEA in middle of qubits
partition_labels = "AABB"
observable = PauliList(["ZZXX"])
subcircuits, _, subobservables = partition_problem(
self.circuit, partition_labels, observables=observable
)
for subcircuit in subcircuits.values():
parameter_vals = [np.pi / 4] * len(subcircuit.parameters)
subcircuit.assign_parameters(parameter_vals, inplace=True)
for inst in subcircuit.data:
if isinstance(inst.operation, BaseQPDGate):
inst.operation.basis_id = 0
compare_obs = {"A": PauliList(["XX"]), "B": PauliList(["ZZ"])}
self.assertEqual(subobservables, compare_obs)
with self.subTest("test mismatching inputs"):
# Split 4q HWEA in middle of qubits
partition_labels = "AB"
with pytest.raises(ValueError) as e_info:
subcircuits, _, subobservables = partition_problem(
self.circuit, partition_labels
)
assert (
e_info.value.args[0]
== "The number of partition labels (2) must equal the number of qubits in the circuit (4)."
)
partition_labels = "AABB"
observable = PauliList(["ZZ"])
with pytest.raises(ValueError) as e_info:
subcircuits, _, subobservables = partition_problem(
self.circuit, partition_labels, observable
)
assert (
e_info.value.args[0]
== "An input observable acts on a different number of qubits than the input circuit."
)
with self.subTest("Classical bit on input"):
# Split 4q HWEA in middle of qubits
partition_labels = "AABB"
observable = PauliList(["ZZXX"])
# Add a clbit
circuit = self.circuit.copy()
circuit.add_bits([Clbit()])
with pytest.raises(ValueError) as e_info:
partition_problem(circuit, partition_labels, observables=observable)
assert (
e_info.value.args[0]
== "Circuits input to partition_problem should contain no classical registers or bits."
)
with self.subTest("Unsupported phase"):
# Split 4q HWEA in middle of qubits
partition_labels = "AABB"
observable = PauliList(["-ZZXX"])
with pytest.raises(ValueError) as e_info:
partition_problem(
self.circuit, partition_labels, observables=observable
)
assert (
e_info.value.args[0]
== "An input observable has a phase not equal to 1."
)
with self.subTest("Unlabeled TwoQubitQPDGates (smoke test)"):
qc = QuantumCircuit(4)
qc.rx(np.pi / 4, 0)
qc.rx(np.pi / 4, 1)
qc.rx(np.pi / 4, 3)
qc.cx(0, 1)
qc.append(TwoQubitQPDGate(QPDBasis.from_instruction(Move())), [1, 2])
qc.cx(2, 3)
qc.append(TwoQubitQPDGate(QPDBasis.from_instruction(Move())), [2, 1])
qc.cx(0, 1)
subcircuits, bases, subobservables = partition_problem(
qc, "AABB", observables=PauliList(["IZIZ"])
)
assert len(subcircuits) == len(bases) == len(subobservables) == 2
with self.subTest("Automatic partition_labels"):
qc = QuantumCircuit(4)
qc.h(0)
qc.cx(0, 2)
qc.cx(0, 1)
qc.s(3)
# Add a TwoQubitQPDGate that, when cut, allows the circuit to
# separate
qc.append(TwoQubitQPDGate.from_instruction(CXGate()), [1, 3])
# Add a TwoQubitQPDGate that, when cut, does *not* allow the
# circuit to separate
qc.append(TwoQubitQPDGate.from_instruction(CXGate()), [2, 0])
subcircuit, *_ = partition_problem(qc)
assert subcircuit.keys() == {0, 1}
assert subcircuit[0].num_qubits == 3
assert subcircuit[1].num_qubits == 1
def test_cut_gates(self):
with self.subTest("simple circuit"):
compare_qc = QuantumCircuit(2)
compare_qc.append(TwoQubitQPDGate.from_instruction(CXGate()), [0, 1])
qc = QuantumCircuit(2)
qc.cx(0, 1)
qpd_qc, _ = cut_gates(qc, [0])
self.assertEqual(qpd_qc, compare_qc)
with self.subTest("classical bit on input"):
qc = QuantumCircuit(2, 1)
qc.cx(0, 1)
with pytest.raises(ValueError) as e_info:
cut_gates(qc, [0])
assert (
e_info.value.args[0]
== "Circuits input to cut_gates should contain no classical registers or bits."
)
def test_unused_qubits(self):
"""Issue #218"""
qc = QuantumCircuit(2)
subcircuits, _, subobservables = partition_problem(
circuit=qc, partition_labels="AB", observables=PauliList(["XX"])
)
assert subcircuits.keys() == {"A", "B"}
assert subobservables.keys() == {"A", "B"}
|
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
|
JessicaJohnBritto
|
pip install pennylane
import pennylane as qml
from pennylane import numpy as np
import matplotlib.pyplot as plt
dev = qml.device('default.qubit', wires=3)
@qml.qnode(dev)
def make_basis_state(basis_id):
"""Produce the 3-qubit basis state corresponding to |basis_id>.
Note that the system starts in |000>.
Args:
basis_id (int): An integer value identifying the basis state to construct.
Returns:
array[complex]: The computational basis state |basis_id>.
"""
##################
# YOUR CODE HERE #
##################
# CREATE THE BASIS STATE
k = np.binary_repr(basis_id, width = 3)
l = [int(x) for x in k]
print(l)
print(np.arange(3))
qml.BasisStatePreparation(l, wires=range(3))
return qml.state()
basis_id = 3
print(f"Output state = {make_basis_state(basis_id)}")
# Creates a device with *two* qubits
dev = qml.device('default.qubit', wires=2)
@qml.qnode(dev)
def two_qubit_circuit():
##################
# YOUR CODE HERE #
##################
# PREPARE |+>|1>
qml.Hadamard(wires=0)
qml.PauliX(wires=1)
# RETURN TWO EXPECTATION VALUES, Y ON FIRST QUBIT, Z ON SECOND QUBIT
k = qml.expval(qml.PauliY(wires=0))
m = qml.expval(qml.PauliZ(wires=1))
l = [k,m]
return l
print(two_qubit_circuit())
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def create_one_minus():
##################
# YOUR CODE HERE #
##################
# PREPARE |1>|->
qml.PauliX(wires=0)
qml.PauliX(wires=1)
qml.Hadamard(wires=1)
# RETURN A SINGLE EXPECTATION VALUE Z \otimes X
return qml.expval(qml.PauliZ(0)@qml.PauliX(1))
print(create_one_minus())
dev = qml.device('default.qubit', wires=2)
@qml.qnode(dev)
def circuit_1(theta):
"""Implement the circuit and measure Z I and I Z.
Args:
theta (float): a rotation angle.
Returns:
float, float: The expectation values of the observables Z I, and I Z
"""
##################
# YOUR CODE HERE #
##################
qml.RX(theta, wires=0)
qml.RY(2*theta, wires=1)
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))
@qml.qnode(dev)
def circuit_2(theta):
"""Implement the circuit and measure Z Z.
Args:
theta (float): a rotation angle.
Returns:
float: The expectation value of the observable Z Z
"""
##################
# YOUR CODE HERE #
##################
qml.RX(theta, wires=0)
qml.RY(2*theta, wires=1)
return qml.expval(qml.PauliZ(0) @qml.PauliZ(1))
def zi_iz_combination(ZI_results, IZ_results):
"""Implement a function that acts on the ZI and IZ results to
produce the ZZ results. How do you think they should combine?
Args:
ZI_results (array[float]): Results from the expectation value of
ZI in circuit_1.
IZ_results (array[float]): Results from the expectation value of
IZ in circuit_2.
Returns:
array[float]: A combination of ZI_results and IZ_results that
produces results equivalent to measuring ZZ.
"""
combined_results = np.zeros(len(ZI_results))
##################
# YOUR CODE HERE #
##################
return ZI_results*IZ_results
theta = np.linspace(0, 2 * np.pi, 100)
# Run circuit 1, and process the results
circuit_1_results = np.array([circuit_1(t) for t in theta])
ZI_results = circuit_1_results[:, 0]
IZ_results = circuit_1_results[:, 1]
combined_results = zi_iz_combination(ZI_results, IZ_results)
# Run circuit 2
ZZ_results = np.array([circuit_2(t) for t in theta])
# Plot your results
plot = plotter(theta, ZI_results, IZ_results, ZZ_results, combined_results)
dev = qml.device('default.qubit', wires=2)
@qml.qnode(dev)
def apply_cnot(basis_id):
"""Apply a CNOT to |basis_id>.
Args:
basis_id (int): An integer value identifying the basis state to construct.
Returns:
array[complex]: The resulting state after applying CNOT|basis_id>.
"""
# Prepare the basis state |basis_id>
bits = [int(x) for x in np.binary_repr(basis_id, width=dev.num_wires)]
qml.BasisStatePreparation(bits, wires=[0, 1])
##################
# YOUR CODE HERE #
##################
# APPLY THE CNOT
qml.CNOT(wires=[0,1])
return qml.state()
##################
# YOUR CODE HERE #
##################
# REPLACE THE BIT STRINGS VALUES BELOW WITH THE CORRECT ONES
cnot_truth_table = {
"00" : "00",
"01" : "01",
"10" : "11",
"11" : "10"
}
# Run your QNode with various inputs to help fill in your truth table
# for k in cnot_truth_table:
for k in range(4):
print(apply_cnot(k))
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def apply_h_cnot():
##################
# YOUR CODE HERE #
##################
# APPLY THE OPERATIONS IN THE CIRCUIT
qml.Hadamard(wires=0)
qml.CNOT(wires=[0,1])
return qml.state()
print(apply_h_cnot())
##################
# YOUR CODE HERE #
##################
# SET THIS AS 'separable' OR 'entangled' BASED ON YOUR OUTCOME
state_status = "entangled"
dev = qml.device('default.qubit', wires=3)
@qml.qnode(dev)
def controlled_rotations(theta, phi, omega):
"""Implement the circuit above and return measurement outcome probabilities.
Args:
theta (float): A rotation angle
phi (float): A rotation angle
omega (float): A rotation angle
Returns:
array[float]: Measurement outcome probabilities of the 3-qubit
computational basis states.
"""
qml.Hadamard(wires=0)
qml.CRX(theta, wires=[0,1])
qml.CRY(phi, wires=[1,2])
qml.CRZ(omega, wires=[2,0])
##################
# YOUR CODE HERE #
##################
# APPLY THE OPERATIONS IN THE CIRCUIT AND RETURN MEASUREMENT PROBABILITIES
return qml.probs(wires=[0,1,2])
theta, phi, omega = 0.1, 0.2, 0.3
print(controlled_rotations(theta, phi, omega))
dev = qml.device("default.qubit", wires=2)
# Prepare a two-qubit state; change up the angles if you like
phi, theta, omega = 1.2, 2.3, 3.4
@qml.qnode(device=dev)
def true_cz(phi, theta, omega):
prepare_states(phi, theta, omega)
##################
# YOUR CODE HERE #
##################
# IMPLEMENT THE REGULAR CZ GATE HERE
qml.CZ(wires=[0,1])
return qml.state()
@qml.qnode(dev)
def imposter_cz(phi, theta, omega):
prepare_states(phi, theta, omega)
# qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.CNOT(wires=[0,1])
qml.Hadamard(wires=1)
# qml.Hadamard(wires=0)
##################
# YOUR CODE HERE #
##################
# IMPLEMENT CZ USING ONLY H AND CNOT
return qml.state()
print(f"True CZ output state {true_cz(phi, theta, omega)}")
print(f"Imposter CZ output state {imposter_cz(phi, theta, omega)}")
dev = qml.device("default.qubit", wires=2)
# Prepare a two-qubit state; change up the angles if you like
phi, theta, omega = 1.2, 2.3, 3.4
@qml.qnode(dev)
def apply_swap(phi, theta, omega):
prepare_states(phi, theta, omega)
##################
# YOUR CODE HERE #
##################
# IMPLEMENT THE REGULAR SWAP GATE HERE
qml.SWAP(wires=[0,1])
return qml.state()
@qml.qnode(dev)
def apply_swap_with_cnots(phi, theta, omega):
prepare_states(phi, theta, omega)
##################
# YOUR CODE HERE #
##################
qml.CNOT(wires=[0,1])
qml.CNOT(wires=[1,0])
qml.CNOT(wires=[0,1])
# IMPLEMENT THE SWAP GATE USING A SEQUENCE OF CNOTS
return qml.state()
print(f"Regular SWAP state = {apply_swap(phi, theta, omega)}")
print(f"CNOT SWAP state = {apply_swap_with_cnots(phi, theta, omega)}")
dev = qml.device("default.qubit", wires=3)
# Prepare first qubit in |1>, and arbitrary states on the second two qubits
phi, theta, omega = 1.2, 2.3, 3.4
# A helper function just so you can visualize the initial state
# before the controlled SWAP occurs.
@qml.qnode(dev)
def no_swap(phi, theta, omega):
prepare_states(phi, theta, omega)
return qml.state()
@qml.qnode(dev)
def controlled_swap(phi, theta, omega):
prepare_states(phi, theta, omega)
##################
# YOUR CODE HERE #
##################
# PERFORM A CONTROLLED SWAP USING A SEQUENCE OF TOFFOLIS
qml.Toffoli(wires=[0, 1, 2])
qml.Toffoli(wires=[0, 2, 1])
qml.Toffoli(wires=[0, 1, 2])
# qml.Toffoli(wires=[control1, control2, target])
return qml.state()
print(no_swap(phi, theta, omega))
print(controlled_swap(phi, theta, omega))
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the HoareOptimizer pass"""
import unittest
from numpy import pi
from qiskit.utils import optionals
from qiskit.transpiler.passes import HoareOptimizer
from qiskit.converters import circuit_to_dag
from qiskit import QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.circuit.library import XGate, RZGate, CSwapGate, SwapGate
from qiskit.dagcircuit import DAGOpNode
from qiskit.quantum_info import Statevector
@unittest.skipUnless(optionals.HAS_Z3, "z3-solver needs to be installed to run these tests")
class TestHoareOptimizer(QiskitTestCase):
"""Test the HoareOptimizer pass"""
def test_phasegate_removal(self):
"""Should remove the phase on a classical state,
but not on a superposition state.
"""
# ┌───┐
# q_0: ┤ Z ├──────
# ├───┤┌───┐
# q_1:─┤ H ├┤ Z ├─
# └───┘└───┘
circuit = QuantumCircuit(3)
circuit.z(0)
circuit.h(1)
circuit.z(1)
# q_0: ───────────
# ┌───┐┌───┐
# q_1:─┤ H ├┤ Z ├─
# └───┘└───┘
expected = QuantumCircuit(3)
expected.h(1)
expected.z(1)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=0)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_cswap_removal(self):
"""Should remove Fredkin gates because the optimizer
can deduce the targets are in the same state
"""
# ┌───┐┌───┐ ┌───┐ ┌───┐ ┌───┐
# q_0: ┤ X ├┤ X ├──■──┤ X ├──■──┤ X ├──■────■──┤ X ├─────────────────────────────────
# └───┘└─┬─┘┌─┴─┐└─┬─┘ │ └─┬─┘┌─┴─┐ │ └─┬─┘
# q_1: ───────┼──┤ X ├──■────┼────┼──┤ X ├──┼────■───■──■──■──■─────■─────■──────────
# │ └─┬─┘ ┌─┴─┐ │ └─┬─┘┌─┴─┐ │ │ │ │ │ │ │
# q_2: ───────┼────┼───────┤ X ├──■────┼──┤ X ├──■───┼──┼──┼──┼──■──┼──■──┼──■──■──■─
# ┌───┐ │ │ └─┬─┘ │ └─┬─┘ │ │ │ │ │ │ │ │ │ │ │
# q_3: ┤ H ├──■────┼─────────┼─────────┼────┼────────┼──┼──X──X──┼──┼──X──┼──┼──X──┼─
# ├───┤ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │
# q_4: ┤ H ├───────■─────────┼─────────┼────┼────────┼──┼──┼──X──┼──X──┼──┼──X──┼──X─
# ├───┤ │ │ │ │ │ │ │ │ │ │ │ │ │
# q_5: ┤ H ├─────────────────■─────────┼────┼────────┼──┼──┼─────┼──X──┼──X──┼──X──┼─
# ├───┤ │ │ │ │ │ │ │ │ │ │
# q_6: ┤ H ├───────────────────────────■────■────────┼──┼──┼─────┼─────┼──X──┼─────X─
# └───┘ │ │ │ │ │ │
# q_7: ──────────────────────────────────────────────X──┼──┼─────X─────┼─────┼───────
# │ │ │ │ │ │
# q_8: ──────────────────────────────────────────────X──X──┼─────┼─────X─────┼───────
# │ │ │ │
# q_9: ─────────────────────────────────────────────────X──X─────X───────────X───────
circuit = QuantumCircuit(10)
# prep
circuit.x(0)
circuit.h(3)
circuit.h(4)
circuit.h(5)
circuit.h(6)
# find first non-zero bit of reg(3-6), store position in reg(1-2)
circuit.cx(3, 0)
circuit.ccx(0, 4, 1)
circuit.cx(1, 0)
circuit.ccx(0, 5, 2)
circuit.cx(2, 0)
circuit.ccx(0, 6, 1)
circuit.ccx(0, 6, 2)
circuit.ccx(1, 2, 0)
# shift circuit
circuit.cswap(1, 7, 8)
circuit.cswap(1, 8, 9)
circuit.cswap(1, 9, 3)
circuit.cswap(1, 3, 4)
circuit.cswap(1, 4, 5)
circuit.cswap(1, 5, 6)
circuit.cswap(2, 7, 9)
circuit.cswap(2, 8, 3)
circuit.cswap(2, 9, 4)
circuit.cswap(2, 3, 5)
circuit.cswap(2, 4, 6)
# ┌───┐┌───┐ ┌───┐ ┌───┐ ┌───┐
# q_0: ┤ X ├┤ X ├──■──┤ X ├──■──┤ X ├──■────■──┤ X ├───────────────
# └───┘└─┬─┘┌─┴─┐└─┬─┘ │ └─┬─┘┌─┴─┐ │ └─┬─┘
# q_1: ───────┼──┤ X ├──■────┼────┼──┤ X ├──┼────■───■──■──■───────
# │ └─┬─┘ ┌─┴─┐ │ └─┬─┘┌─┴─┐ │ │ │ │
# q_2: ───────┼────┼───────┤ X ├──■────┼──┤ X ├──■───┼──┼──┼──■──■─
# ┌───┐ │ │ └─┬─┘ │ └─┬─┘ │ │ │ │ │
# q_3: ┤ H ├──■────┼─────────┼─────────┼────┼────────X──┼──┼──X──┼─
# ├───┤ │ │ │ │ │ │ │ │ │
# q_4: ┤ H ├───────■─────────┼─────────┼────┼────────X──X──┼──┼──X─
# ├───┤ │ │ │ │ │ │ │
# q_5: ┤ H ├─────────────────■─────────┼────┼───────────X──X──X──┼─
# ├───┤ │ │ │ │
# q_6: ┤ H ├───────────────────────────■────■──────────────X─────X─
# └───┘
# q_7: ────────────────────────────────────────────────────────────
#
# q_8: ────────────────────────────────────────────────────────────
#
# q_9: ────────────────────────────────────────────────────────────
expected = QuantumCircuit(10)
# prep
expected.x(0)
expected.h(3)
expected.h(4)
expected.h(5)
expected.h(6)
# find first non-zero bit of reg(3-6), store position in reg(1-2)
expected.cx(3, 0)
expected.ccx(0, 4, 1)
expected.cx(1, 0)
expected.ccx(0, 5, 2)
expected.cx(2, 0)
expected.ccx(0, 6, 1)
expected.ccx(0, 6, 2)
expected.ccx(1, 2, 0)
# optimized shift circuit
expected.cswap(1, 3, 4)
expected.cswap(1, 4, 5)
expected.cswap(1, 5, 6)
expected.cswap(2, 3, 5)
expected.cswap(2, 4, 6)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=0)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_lnn_cnot_removal(self):
"""Should remove some cnots from swaps introduced
because of linear nearest architecture. Only uses
single-gate optimization techniques.
"""
# ┌───┐ ┌───┐ »
# q_0: ┤ H ├──■──┤ X ├──■────────────────────────────────────────────────────»
# └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ »
# q_1: ─────┤ X ├──■──┤ X ├──■──┤ X ├──■──────────────────────────────────■──»
# └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ ┌───┐┌─┴─┐»
# q_2: ────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■─────────■──┤ X ├┤ X ├»
# └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘└───┘»
# q_3: ───────────────────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■───────»
# └───┘ └───┘┌─┴─┐└───┘ »
# q_4: ──────────────────────────────────────────────────┤ X ├───────────────»
# └───┘ »
# « ┌───┐
# «q_0: ───────■──┤ X ├
# « ┌───┐┌─┴─┐└─┬─┘
# «q_1: ┤ X ├┤ X ├──■──
# « └─┬─┘└───┘
# «q_2: ──■────────────
# «
# «q_3: ───────────────
# «
# «q_4: ───────────────
circuit = QuantumCircuit(5)
circuit.h(0)
for i in range(0, 3):
circuit.cx(i, i + 1)
circuit.cx(i + 1, i)
circuit.cx(i, i + 1)
circuit.cx(3, 4)
for i in range(3, 0, -1):
circuit.cx(i - 1, i)
circuit.cx(i, i - 1)
# ┌───┐ ┌───┐ ┌───┐
# q_0: ┤ H ├──■──┤ X ├───────────────────────────────────┤ X ├
# └───┘┌─┴─┐└─┬─┘ ┌───┐ ┌───┐└─┬─┘
# q_1: ─────┤ X ├──■────■──┤ X ├────────────────────┤ X ├──■──
# └───┘ ┌─┴─┐└─┬─┘ ┌───┐ ┌───┐└─┬─┘
# q_2: ───────────────┤ X ├──■────■──┤ X ├─────┤ X ├──■───────
# └───┘ ┌─┴─┐└─┬─┘ └─┬─┘
# q_3: ─────────────────────────┤ X ├──■────■────■────────────
# └───┘ ┌─┴─┐
# q_4: ───────────────────────────────────┤ X ├───────────────
# └───┘
expected = QuantumCircuit(5)
expected.h(0)
for i in range(0, 3):
expected.cx(i, i + 1)
expected.cx(i + 1, i)
expected.cx(3, 4)
for i in range(3, 0, -1):
expected.cx(i, i - 1)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=0)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_lnncnot_advanced_removal(self):
"""Should remove all cnots from swaps introduced
because of linear nearest architecture. This time
using multi-gate optimization techniques.
"""
# ┌───┐ ┌───┐ »
# q_0: ┤ H ├──■──┤ X ├──■────────────────────────────────────────────────────»
# └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ »
# q_1: ─────┤ X ├──■──┤ X ├──■──┤ X ├──■──────────────────────────────────■──»
# └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ ┌───┐┌─┴─┐»
# q_2: ────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■─────────■──┤ X ├┤ X ├»
# └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘└───┘»
# q_3: ───────────────────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■───────»
# └───┘ └───┘┌─┴─┐└───┘ »
# q_4: ──────────────────────────────────────────────────┤ X ├───────────────»
# └───┘ »
# « ┌───┐
# «q_0: ───────■──┤ X ├
# « ┌───┐┌─┴─┐└─┬─┘
# «q_1: ┤ X ├┤ X ├──■──
# « └─┬─┘└───┘
# «q_2: ──■────────────
# «
# «q_3: ───────────────
# «
# «q_4: ───────────────
circuit = QuantumCircuit(5)
circuit.h(0)
for i in range(0, 3):
circuit.cx(i, i + 1)
circuit.cx(i + 1, i)
circuit.cx(i, i + 1)
circuit.cx(3, 4)
for i in range(3, 0, -1):
circuit.cx(i - 1, i)
circuit.cx(i, i - 1)
# ┌───┐
# q_0: ┤ H ├──■─────────────────
# └───┘┌─┴─┐
# q_1: ─────┤ X ├──■────────────
# └───┘┌─┴─┐
# q_2: ──────────┤ X ├──■───────
# └───┘┌─┴─┐
# q_3: ───────────────┤ X ├──■──
# └───┘┌─┴─┐
# q_4: ────────────────────┤ X ├
# └───┘
expected = QuantumCircuit(5)
expected.h(0)
for i in range(0, 4):
expected.cx(i, i + 1)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=6)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_successive_identity_removal(self):
"""Should remove a successive pair of H gates applying
on the same qubit.
"""
circuit = QuantumCircuit(1)
circuit.h(0)
circuit.h(0)
circuit.h(0)
expected = QuantumCircuit(1)
expected.h(0)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=4)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_targetsuccessive_identity_removal(self):
"""Should remove pair of controlled target successive
which are the inverse of each other, if they can be
identified to be executed as a unit (either both or none).
"""
# ┌───┐ ┌───┐┌───┐
# q_0: ┤ H ├──■──┤ X ├┤ X ├──■──
# ├───┤ │ └─┬─┘└───┘ │
# q_1: ┤ H ├──■────■─────────■──
# ├───┤┌─┴─┐ ┌─┴─┐
# q_2: ┤ H ├┤ X ├──────────┤ X ├
# └───┘└───┘ └───┘
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.ccx(0, 1, 2)
circuit.cx(1, 0)
circuit.x(0)
circuit.ccx(0, 1, 2)
# ┌───┐┌───┐┌───┐
# q_0: ┤ H ├┤ X ├┤ X ├
# ├───┤└─┬─┘└───┘
# q_1: ┤ H ├──■───────
# ├───┤
# q_2: ┤ H ├──────────
# └───┘
expected = QuantumCircuit(3)
expected.h(0)
expected.h(1)
expected.h(2)
expected.cx(1, 0)
expected.x(0)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=4)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_targetsuccessive_identity_advanced_removal(self):
"""Should remove target successive identity gates
with DIFFERENT sets of control qubits.
In this case CCCX(4,5,6,7) & CCX(5,6,7).
"""
# ┌───┐┌───┐ »
# q_0: ┤ H ├┤ X ├───────■─────────────────────────────■───────────────────■──»
# ├───┤└─┬─┘ │ │ │ »
# q_1: ┤ H ├──■─────────■─────────────────────────────■───────────────────■──»
# ├───┤┌───┐ │ ┌───┐ │ │ »
# q_2: ┤ H ├┤ X ├───────┼──┤ X ├──■──────────────■────┼───────────────────┼──»
# ├───┤└─┬─┘ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐ ┌─┴─┐»
# q_3: ┤ H ├──■────■──┤ X ├──■────■──────────────■──┤ X ├──■─────────■──┤ X ├»
# ├───┤┌───┐ │ └───┘ │ ┌───┐ │ └───┘ │ │ └───┘»
# q_4: ┤ H ├┤ X ├──┼──────────────┼──┤ X ├──■────┼─────────┼─────────┼───────»
# ├───┤└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘ │ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ »
# q_5: ┤ H ├──■──┤ X ├──────────┤ X ├──■────■──┤ X ├─────┤ X ├──■──┤ X ├─────»
# └───┘ └───┘ └───┘ ┌─┴─┐└───┘ └───┘┌─┴─┐├───┤ »
# q_6: ───────────────────────────────────┤ X ├───────────────┤ X ├┤ X ├─────»
# └───┘ └───┘└───┘ »
# q_7: ──────────────────────────────────────────────────────────────────────»
# »
# « ┌───┐┌───┐ »
# «q_0: ──────────────────────■──┤ X ├┤ X ├──■─────────────────────────────■──»
# « │ └─┬─┘└─┬─┘ │ │ »
# «q_1: ──────────────────────■────■────■────■─────────────────────────────■──»
# « ┌───┐ │ │ │ ┌───┐ │ »
# «q_2: ──■─────────■──┤ X ├──┼─────────┼────┼──┤ X ├──■──────────────■────┼──»
# « │ │ └─┬─┘┌─┴─┐ │ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐»
# «q_3: ──■─────────■────■──┤ X ├───────┼──┤ X ├──■────■──────────────■──┤ X ├»
# « │ ┌───┐ │ └───┘ │ └───┘ │ │ ┌───┐ │ └───┘»
# «q_4: ──┼──┤ X ├──┼───────────────────┼─────────┼────┼──┤ X ├──■────┼───────»
# « ┌─┴─┐└─┬─┘┌─┴─┐ │ │ ┌─┴─┐└─┬─┘ │ ┌─┴─┐ »
# «q_5: ┤ X ├──■──┤ X ├─────────────────┼─────────┼──┤ X ├──■────■──┤ X ├─────»
# « └───┘ └───┘ │ │ └───┘ │ │ └───┘ »
# «q_6: ────────────────────────────────■─────────■─────────■────■────────────»
# « ┌─┴─┐ »
# «q_7: ───────────────────────────────────────────────────────┤ X ├──────────»
# « └───┘ »
# «
# «q_0: ───────────────
# «
# «q_1: ───────────────
# « ┌───┐
# «q_2: ─────┤ X ├─────
# « └─┬─┘
# «q_3: ──■────■───────
# « │ ┌───┐
# «q_4: ──┼──┤ X ├─────
# « ┌─┴─┐└─┬─┘
# «q_5: ┤ X ├──■────■──
# « └───┘ │
# «q_6: ────────────■──
# « ┌─┴─┐
# «q_7: ──────────┤ X ├
# « └───┘
circuit = QuantumCircuit(8)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
circuit.h(4)
circuit.h(5)
for i in range(3):
circuit.cx(i * 2 + 1, i * 2)
circuit.cx(3, 5)
for i in range(2):
circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3)
circuit.cx(i * 2 + 3, i * 2 + 2)
circuit.ccx(4, 5, 6)
for i in range(1, -1, -1):
circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3)
circuit.cx(3, 5)
circuit.cx(5, 6)
circuit.cx(3, 5)
circuit.x(6)
for i in range(2):
circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3)
for i in range(1, -1, -1):
circuit.cx(i * 2 + 3, i * 2 + 2)
circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3)
circuit.cx(1, 0)
circuit.ccx(6, 1, 0)
circuit.ccx(0, 1, 3)
circuit.ccx(6, 3, 2)
circuit.ccx(2, 3, 5)
circuit.ccx(6, 5, 4)
circuit.append(XGate().control(3), [4, 5, 6, 7], [])
for i in range(1, -1, -1):
circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3)
circuit.cx(3, 5)
for i in range(1, 3):
circuit.cx(i * 2 + 1, i * 2)
circuit.ccx(5, 6, 7)
# ┌───┐┌───┐ »
# q_0: ┤ H ├┤ X ├───────■─────────────────────────────■───────────────────■──»
# ├───┤└─┬─┘ │ │ │ »
# q_1: ┤ H ├──■─────────■─────────────────────────────■───────────────────■──»
# ├───┤┌───┐ │ ┌───┐ │ │ »
# q_2: ┤ H ├┤ X ├───────┼──┤ X ├──■──────────────■────┼───────────────────┼──»
# ├───┤└─┬─┘ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐ ┌─┴─┐»
# q_3: ┤ H ├──■────■──┤ X ├──■────■──────────────■──┤ X ├──■─────────■──┤ X ├»
# ├───┤┌───┐ │ └───┘ │ ┌───┐ │ └───┘ │ │ └───┘»
# q_4: ┤ H ├┤ X ├──┼──────────────┼──┤ X ├──■────┼─────────┼─────────┼───────»
# ├───┤└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘ │ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ »
# q_5: ┤ H ├──■──┤ X ├──────────┤ X ├──■────■──┤ X ├─────┤ X ├──■──┤ X ├─────»
# └───┘ └───┘ └───┘ ┌─┴─┐└───┘ └───┘┌─┴─┐├───┤ »
# q_6: ───────────────────────────────────┤ X ├───────────────┤ X ├┤ X ├─────»
# └───┘ └───┘└───┘ »
# q_7: ──────────────────────────────────────────────────────────────────────»
# »
# « ┌───┐┌───┐ »
# «q_0: ──────────────────────■──┤ X ├┤ X ├──■────────────────────────■───────»
# « │ └─┬─┘└─┬─┘ │ │ »
# «q_1: ──────────────────────■────■────■────■────────────────────────■───────»
# « ┌───┐ │ │ │ ┌───┐ │ »
# «q_2: ──■─────────■──┤ X ├──┼─────────┼────┼──┤ X ├──■─────────■────┼───────»
# « │ │ └─┬─┘┌─┴─┐ │ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐ »
# «q_3: ──■─────────■────■──┤ X ├───────┼──┤ X ├──■────■─────────■──┤ X ├──■──»
# « │ ┌───┐ │ └───┘ │ └───┘ │ │ ┌───┐ │ └───┘ │ »
# «q_4: ──┼──┤ X ├──┼───────────────────┼─────────┼────┼──┤ X ├──┼─────────┼──»
# « ┌─┴─┐└─┬─┘┌─┴─┐ │ │ ┌─┴─┐└─┬─┘┌─┴─┐ ┌─┴─┐»
# «q_5: ┤ X ├──■──┤ X ├─────────────────┼─────────┼──┤ X ├──■──┤ X ├─────┤ X ├»
# « └───┘ └───┘ │ │ └───┘ │ └───┘ └───┘»
# «q_6: ────────────────────────────────■─────────■─────────■─────────────────»
# « »
# «q_7: ──────────────────────────────────────────────────────────────────────»
# « »
# «
# «q_0: ─────
# «
# «q_1: ─────
# « ┌───┐
# «q_2: ┤ X ├
# « └─┬─┘
# «q_3: ──■──
# « ┌───┐
# «q_4: ┤ X ├
# « └─┬─┘
# «q_5: ──■──
# «
# «q_6: ─────
# «
# «q_7: ─────
# «
expected = QuantumCircuit(8)
expected.h(0)
expected.h(1)
expected.h(2)
expected.h(3)
expected.h(4)
expected.h(5)
for i in range(3):
expected.cx(i * 2 + 1, i * 2)
expected.cx(3, 5)
for i in range(2):
expected.ccx(i * 2, i * 2 + 1, i * 2 + 3)
expected.cx(i * 2 + 3, i * 2 + 2)
expected.ccx(4, 5, 6)
for i in range(1, -1, -1):
expected.ccx(i * 2, i * 2 + 1, i * 2 + 3)
expected.cx(3, 5)
expected.cx(5, 6)
expected.cx(3, 5)
expected.x(6)
for i in range(2):
expected.ccx(i * 2, i * 2 + 1, i * 2 + 3)
for i in range(1, -1, -1):
expected.cx(i * 2 + 3, i * 2 + 2)
expected.ccx(i * 2, i * 2 + 1, i * 2 + 3)
expected.cx(1, 0)
expected.ccx(6, 1, 0)
expected.ccx(0, 1, 3)
expected.ccx(6, 3, 2)
expected.ccx(2, 3, 5)
expected.ccx(6, 5, 4)
for i in range(1, -1, -1):
expected.ccx(i * 2, i * 2 + 1, i * 2 + 3)
expected.cx(3, 5)
for i in range(1, 3):
expected.cx(i * 2 + 1, i * 2)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=5)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_control_removal(self):
"""Should replace CX by X."""
# ┌───┐
# q_0: ┤ X ├──■──
# └───┘┌─┴─┐
# q_1: ─────┤ X ├
# └───┘
circuit = QuantumCircuit(2)
circuit.x(0)
circuit.cx(0, 1)
# ┌───┐
# q_0: ┤ X ├
# ├───┤
# q_1: ┤ X ├
# └───┘
expected = QuantumCircuit(2)
expected.x(0)
expected.x(1)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=5)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
# Should replace CZ by Z
#
# ┌───┐ ┌───┐
# q_0: ┤ H ├─■─┤ H ├
# ├───┤ │ └───┘
# q_1: ┤ X ├─■──────
# └───┘
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.x(1)
circuit.cz(0, 1)
circuit.h(0)
# ┌───┐┌───┐┌───┐
# q_0: ┤ H ├┤ Z ├┤ H ├
# ├───┤└───┘└───┘
# q_1: ┤ X ├──────────
# └───┘
expected = QuantumCircuit(2)
expected.h(0)
expected.x(1)
expected.z(0)
expected.h(0)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=5)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_is_identity(self):
"""The is_identity function determines whether a pair of gates
forms the identity, when ignoring control qubits.
"""
seq = [DAGOpNode(op=XGate().control()), DAGOpNode(op=XGate().control(2))]
self.assertTrue(HoareOptimizer()._is_identity(seq))
seq = [
DAGOpNode(op=RZGate(-pi / 2).control()),
DAGOpNode(op=RZGate(pi / 2).control(2)),
]
self.assertTrue(HoareOptimizer()._is_identity(seq))
seq = [DAGOpNode(op=CSwapGate()), DAGOpNode(op=SwapGate())]
self.assertTrue(HoareOptimizer()._is_identity(seq))
def test_multiple_pass(self):
"""Verify that multiple pass can be run
with the same Hoare instance.
"""
# ┌───┐┌───┐
# q_0:─┤ H ├┤ Z ├─
# ├───┤└───┘
# q_1: ┤ Z ├──────
# └───┘
circuit1 = QuantumCircuit(2)
circuit1.z(0)
circuit1.h(1)
circuit1.z(1)
circuit2 = QuantumCircuit(2)
circuit2.z(1)
circuit2.h(0)
circuit2.z(0)
# ┌───┐┌───┐
# q_0:─┤ H ├┤ Z ├─
# └───┘└───┘
# q_1: ───────────
expected = QuantumCircuit(2)
expected.h(0)
expected.z(0)
pass_ = HoareOptimizer()
pass_.run(circuit_to_dag(circuit1))
result2 = pass_.run(circuit_to_dag(circuit2))
self.assertEqual(result2, circuit_to_dag(expected))
if __name__ == "__main__":
unittest.main()
|
https://github.com/drobiu/quantum-project
|
drobiu
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.aer import QasmSimulator
from qiskit.visualization import plot_histogram
# Use Aer's qasm_simulator
simulator = QasmSimulator()
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# compile the circuit down to low-level QASM instructions
# supported by the backend (not needed for simple circuits)
compiled_circuit = transpile(circuit, simulator)
# Execute the circuit on the qasm simulator
job = simulator.run(compiled_circuit, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(compiled_circuit)
# print("\nTotal count for 00 and 11 are:",counts)
# Draw the ci
circuit.draw(output="latex", filename="printing.png")
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
#
# your code is here
#
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
#
# your code is here
#
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# first we import a procedure for picking a random number
from random import randrange
# randrange(m) returns a number randomly from the list {0,1,...,m-1}
# randrange(10) returns a number randomly from the list {0,1,...,9}
# here is an example
r=randrange(5)
print("I picked a random number between 0 and 4, which is ",r)
#
# your solution is here
#
# first we import a procedure for picking a random number
from random import randrange
#
# your solution is here
#
|
https://github.com/scaleway/qiskit-scaleway
|
scaleway
|
# Copyright 2024 Scaleway
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import io
import collections
import numpy as np
from typing import (
Any,
List,
Callable,
Iterable,
Mapping,
Optional,
Sequence,
Tuple,
Union,
cast,
)
from qiskit import qasm2, QuantumCircuit
from qiskit.providers import JobError
from qiskit.result import Result
from qiskit.transpiler.passes import RemoveBarriers
from qiskit.result.models import ExperimentResult, ExperimentResultData
from ..utils import QaaSClient
from ..versions import USER_AGENT
from .scaleway_job import ScalewayJob
from .scaleway_models import (
JobPayload,
ClientPayload,
BackendPayload,
RunPayload,
SerializationType,
CircuitPayload,
)
def _tuple_of_big_endian_int(bit_groups: Iterable[Any]) -> Tuple[int, ...]:
return tuple(_big_endian_bits_to_int(bits) for bits in bit_groups)
def _big_endian_bits_to_int(bits: Iterable[Any]) -> int:
result = 0
for e in bits:
result <<= 1
if e:
result |= 1
return result
def _unpack_digits(
packed_digits: str,
binary: bool,
dtype: Optional[str],
shape: Optional[Sequence[int]],
) -> np.ndarray:
if binary:
dtype = cast(str, dtype)
shape = cast(Sequence[int], shape)
return _unpack_bits(packed_digits, dtype, shape)
buffer = io.BytesIO()
buffer.write(bytes.fromhex(packed_digits))
buffer.seek(0)
digits = np.load(buffer, allow_pickle=False)
buffer.close()
return digits
def _unpack_bits(packed_bits: str, dtype: str, shape: Sequence[int]) -> np.ndarray:
bits_bytes = bytes.fromhex(packed_bits)
bits = np.unpackbits(np.frombuffer(bits_bytes, dtype=np.uint8))
return bits[: np.prod(shape).item()].reshape(shape).astype(dtype)
class QsimJob(ScalewayJob):
def __init__(
self,
name: str,
backend,
client: QaaSClient,
circuits,
config,
) -> None:
super().__init__(name, backend, client)
assert circuits is QuantumCircuit or list
self._circuits = circuits
self._config = config
def submit(self, session_id: str) -> None:
if self._job_id:
raise RuntimeError(f"Job already submitted (ID: {self._job_id})")
options = self._config.copy()
# Note 1: Barriers are only visual elements
# Barriers are not managed by Cirq deserialization
# Note 2: Qsim can only handle one circuit at a time
circuit = RemoveBarriers()(self._circuits[0])
run_opts = RunPayload(
options={"shots": options.pop("shots")},
circuits=[
CircuitPayload(
serialization_type=SerializationType.QASM_V2,
circuit_serialization=qasm2.dumps(circuit),
)
],
)
options.pop("circuit_memoization_size")
backend_opts = BackendPayload(
name=self.backend().name,
version=self.backend().version,
options=options,
)
client_opts = ClientPayload(
user_agent=USER_AGENT,
)
job_payload = JobPayload.schema().dumps(
JobPayload(
backend=backend_opts,
run=run_opts,
client=client_opts,
)
)
self._job_id = self._client.create_job(
name=self._name,
session_id=session_id,
circuits=job_payload,
)
def __to_cirq_result(self, job_results) -> "cirq.Result":
try:
import cirq
except:
raise Exception("Cannot get Cirq result: Cirq not installed")
from cirq.study import ResultDict
if len(job_results) == 0:
raise Exception("Empty result list")
payload = self._extract_payload_from_response(job_results[0])
payload_dict = json.loads(payload)
cirq_result = ResultDict._from_json_dict_(**payload_dict)
return cirq_result
def __to_qiskit_result(self, job_results):
def __make_hex_from_result_array(result: Tuple):
str_value = "".join(map(str, result))
integer_value = int(str_value, 2)
return hex(integer_value)
def __make_expresult_from_cirq_result(
cirq_result: CirqResult,
) -> ExperimentResult:
hist = dict(
cirq_result.multi_measurement_histogram(
keys=cirq_result.measurements.keys()
)
)
return ExperimentResult(
shots=cirq_result.repetitions,
success=True,
data=ExperimentResultData(
counts={
__make_hex_from_result_array(key): value
for key, value in hist.items()
},
),
)
def __make_result_from_payload(payload: str) -> Result:
payload_dict = json.loads(payload)
cirq_result = CirqResult._from_json_dict_(**payload_dict)
return Result(
backend_name=self.backend().name,
backend_version=self.backend().version,
job_id=self._job_id,
qobj_id=", ".join(x.name for x in self._circuits),
success=True,
results=[__make_expresult_from_cirq_result(cirq_result)],
status=None, # TODO
header=None, # TODO
date=None, # TODO
cirq_result=payload,
)
qiskit_results = list(
map(
lambda r: __make_result_from_payload(
self._extract_payload_from_response(r)
),
job_results,
)
)
if len(qiskit_results) == 1:
return qiskit_results[0]
return qiskit_results
def result(
self,
timeout=None,
fetch_interval: int = 3,
format: str = "qiskit",
) -> Union[Result, List[Result], "cirq.Result"]:
if self._job_id == None:
raise JobError("Job ID error")
match = {
"qiskit": self.__to_qiskit_result,
"cirq": self.__to_cirq_result,
}
job_results = self._wait_for_result(timeout, fetch_interval)
return match.get(format, self.__to_qiskit_result)(job_results)
class CirqResult:
def __init__(
self,
*,
measurements: Optional[Mapping[str, np.ndarray]] = None,
records: Optional[Mapping[str, np.ndarray]] = None,
) -> None:
if measurements is None and records is None:
measurements = {}
records = {}
self._params = None
self._measurements = measurements
self._records = records
@property
def measurements(self) -> Mapping[str, np.ndarray]:
if self._measurements is None:
assert self._records is not None
self._measurements = {}
for key, data in self._records.items():
reps, instances, qubits = data.shape
if instances != 1:
raise ValueError("Cannot extract 2D measurements for repeated keys")
self._measurements[key] = data.reshape((reps, qubits))
return self._measurements
@property
def records(self) -> Mapping[str, np.ndarray]:
if self._records is None:
assert self._measurements is not None
self._records = {
key: data[:, np.newaxis, :] for key, data in self._measurements.items()
}
return self._records
@property
def repetitions(self) -> int:
if self._records is not None:
if not self._records:
return 0
return len(next(iter(self._records.values())))
else:
if not self._measurements:
return 0
return len(next(iter(self._measurements.values())))
def multi_measurement_histogram(
self,
*,
keys: Iterable,
fold_func: Callable = cast(Callable, _tuple_of_big_endian_int),
) -> collections.Counter:
fixed_keys = tuple(key for key in keys)
samples: Iterable[Any] = zip(
*(self.measurements[sub_key] for sub_key in fixed_keys)
)
if len(fixed_keys) == 0:
samples = [()] * self.repetitions
c: collections.Counter = collections.Counter()
for sample in samples:
c[fold_func(sample)] += 1
return c
@classmethod
def _from_packed_records(cls, records, **kwargs):
return cls(
records={key: _unpack_digits(**val) for key, val in records.items()},
**kwargs,
)
@classmethod
def _from_json_dict_(cls, **kwargs):
if "measurements" in kwargs:
measurements = kwargs["measurements"]
return cls(
params=None,
measurements={
key: _unpack_digits(**val) for key, val in measurements.items()
},
)
return cls._from_packed_records(records=kwargs["records"])
@property
def repetitions(self) -> int:
if not self.records:
return 0
# Get the length quickly from one of the keyed results.
return len(next(iter(self.records.values())))
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.draw("mpl")
|
https://github.com/C2QA/bosonic-qiskit
|
C2QA
|
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa.
import os
import sys
module_path = os.path.abspath(os.path.join("../.."))
if module_path not in sys.path:
sys.path.append(module_path)
# Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv
module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages"))
if module_path not in sys.path:
sys.path.append(module_path)
import c2qa
import qiskit
def build_circuit(dist = 2, num_qumodes = 1, num_qubits_per_qumode = 4):
qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, 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])
return circuit
circuit = build_circuit()
state, result, _ = c2qa.util.simulate(circuit)
wigner = c2qa.wigner.wigner(state)
c2qa.wigner.plot(wigner)
circuit = build_circuit()
states, result, _ = c2qa.util.simulate(circuit, per_shot_state_vector=True)
wigner = c2qa.wigner.wigner_mle(states)
c2qa.wigner.plot(wigner)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
"""Test the SetLayout pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.transpiler import CouplingMap, Layout
from qiskit.transpiler.passes import SetLayout, ApplyLayout, FullAncillaAllocation
from qiskit.test import QiskitTestCase
from qiskit.transpiler import PassManager, TranspilerError
class TestSetLayout(QiskitTestCase):
"""Tests the SetLayout pass"""
def assertEqualToReference(self, result_to_compare):
"""Compare result_to_compare to a reference
┌───┐ ░ ┌─┐
q_0 -> 0 ┤ H ├─░─┤M├───────────────
├───┤ ░ └╥┘┌─┐
q_1 -> 1 ┤ H ├─░──╫─┤M├────────────
├───┤ ░ ║ └╥┘ ┌─┐
q_4 -> 2 ┤ H ├─░──╫──╫───────┤M├───
├───┤ ░ ║ ║ ┌─┐ └╥┘
q_2 -> 3 ┤ H ├─░──╫──╫─┤M├────╫────
└───┘ ░ ║ ║ └╥┘ ║
ancilla_0 -> 4 ─────────╫──╫──╫─────╫────
┌───┐ ░ ║ ║ ║ ┌─┐ ║
q_3 -> 5 ┤ H ├─░──╫──╫──╫─┤M├─╫────
├───┤ ░ ║ ║ ║ └╥┘ ║ ┌─┐
q_5 -> 6 ┤ H ├─░──╫──╫──╫──╫──╫─┤M├
└───┘ ░ ║ ║ ║ ║ ║ └╥┘
meas: 6/═════════╩══╩══╩══╩══╩══╩═
0 1 2 3 4 5
"""
qr = QuantumRegister(6, "q")
ancilla = QuantumRegister(1, "ancilla")
cl = ClassicalRegister(6, "meas")
reference = QuantumCircuit(qr, ancilla, cl)
reference.h(qr)
reference.barrier(qr)
reference.measure(qr, cl)
pass_manager = PassManager()
pass_manager.append(
SetLayout(
Layout({qr[0]: 0, qr[1]: 1, qr[4]: 2, qr[2]: 3, ancilla[0]: 4, qr[3]: 5, qr[5]: 6})
)
)
pass_manager.append(ApplyLayout())
self.assertEqual(result_to_compare, pass_manager.run(reference))
def test_setlayout_as_Layout(self):
"""Construct SetLayout with a Layout."""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr)
circuit.measure_all()
pass_manager = PassManager()
pass_manager.append(
SetLayout(Layout.from_intlist([0, 1, 3, 5, 2, 6], QuantumRegister(6, "q")))
)
pass_manager.append(FullAncillaAllocation(CouplingMap.from_line(7)))
pass_manager.append(ApplyLayout())
result = pass_manager.run(circuit)
self.assertEqualToReference(result)
def test_setlayout_as_list(self):
"""Construct SetLayout with a list."""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr)
circuit.measure_all()
pass_manager = PassManager()
pass_manager.append(SetLayout([0, 1, 3, 5, 2, 6]))
pass_manager.append(FullAncillaAllocation(CouplingMap.from_line(7)))
pass_manager.append(ApplyLayout())
result = pass_manager.run(circuit)
self.assertEqualToReference(result)
def test_raise_when_layout_len_does_not_match(self):
"""Test error is raised if layout defined as list does not match the circuit size."""
qr = QuantumRegister(42, "q")
circuit = QuantumCircuit(qr)
pass_manager = PassManager()
pass_manager.append(SetLayout([0, 1, 3, 5, 2, 6]))
pass_manager.append(FullAncillaAllocation(CouplingMap.from_line(7)))
pass_manager.append(ApplyLayout())
with self.assertRaises(TranspilerError):
pass_manager.run(circuit)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 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.
"""Time evolution problem class."""
from __future__ import annotations
from collections.abc import Mapping
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter, ParameterExpression
from qiskit.opflow import PauliSumOp
from ..list_or_dict import ListOrDict
from ...quantum_info import Statevector
from ...quantum_info.operators.base_operator import BaseOperator
class TimeEvolutionProblem:
"""Time evolution problem class.
This class is the input to time evolution algorithms and must contain information on the total
evolution time, a quantum state to be evolved and under which Hamiltonian the state is evolved.
Attributes:
hamiltonian (BaseOperator | PauliSumOp): The Hamiltonian under which to evolve the system.
initial_state (QuantumCircuit | Statevector | None): The quantum state to be evolved for
methods like Trotterization. For variational time evolutions, where the evolution
happens in an ansatz, this argument is not required.
aux_operators (ListOrDict[BaseOperator | PauliSumOp] | None): Optional list of auxiliary
operators to be evaluated with the evolved ``initial_state`` and their expectation
values returned.
truncation_threshold (float): Defines a threshold under which values can be assumed to be 0.
Used when ``aux_operators`` is provided.
t_param (Parameter | None): Time parameter in case of a time-dependent Hamiltonian. This
free parameter must be within the ``hamiltonian``.
param_value_map (dict[Parameter, complex] | None): Maps free parameters in the problem to
values. Depending on the algorithm, it might refer to e.g. a Hamiltonian or an initial
state.
"""
def __init__(
self,
hamiltonian: BaseOperator | PauliSumOp,
time: float,
initial_state: QuantumCircuit | Statevector | None = None,
aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None,
truncation_threshold: float = 1e-12,
t_param: Parameter | None = None,
param_value_map: Mapping[Parameter, complex] | None = None,
):
"""
Args:
hamiltonian: The Hamiltonian under which to evolve the system.
time: Total time of evolution.
initial_state: The quantum state to be evolved for methods like Trotterization.
For variational time evolutions, where the evolution happens in an ansatz,
this argument is not required.
aux_operators: Optional list of auxiliary operators to be evaluated with the
evolved ``initial_state`` and their expectation values returned.
truncation_threshold: Defines a threshold under which values can be assumed to be 0.
Used when ``aux_operators`` is provided.
t_param: Time parameter in case of a time-dependent Hamiltonian. This
free parameter must be within the ``hamiltonian``.
param_value_map: Maps free parameters in the problem to values. Depending on the
algorithm, it might refer to e.g. a Hamiltonian or an initial state.
Raises:
ValueError: If non-positive time of evolution is provided.
"""
self.t_param = t_param
self.param_value_map = param_value_map
self.hamiltonian = hamiltonian
self.time = time
if isinstance(initial_state, Statevector):
circuit = QuantumCircuit(initial_state.num_qubits)
circuit.prepare_state(initial_state.data)
initial_state = circuit
self.initial_state: QuantumCircuit | None = initial_state
self.aux_operators = aux_operators
self.truncation_threshold = truncation_threshold
@property
def time(self) -> float:
"""Returns time."""
return self._time
@time.setter
def time(self, time: float) -> None:
"""
Sets time and validates it.
"""
self._time = time
def validate_params(self) -> None:
"""
Checks if all parameters present in the Hamiltonian are also present in the dictionary
that maps them to values.
Raises:
ValueError: If Hamiltonian parameters cannot be bound with data provided.
"""
if isinstance(self.hamiltonian, PauliSumOp) and isinstance(
self.hamiltonian.coeff, ParameterExpression
):
raise ValueError("A global parametrized coefficient for PauliSumOp is not allowed.")
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (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.
r"""
.. _pulse_builder:
=============
Pulse Builder
=============
..
We actually want people to think of these functions as being defined within the ``qiskit.pulse``
namespace, not the submodule ``qiskit.pulse.builder``.
.. currentmodule: qiskit.pulse
Use the pulse builder DSL to write pulse programs with an imperative syntax.
.. warning::
The pulse builder interface is still in active development. It may have
breaking API changes without deprecation warnings in future releases until
otherwise indicated.
The pulse builder provides an imperative API for writing pulse programs
with less difficulty than the :class:`~qiskit.pulse.Schedule` API.
It contextually constructs a pulse schedule and then emits the schedule for
execution. For example, to play a series of pulses on channels is as simple as:
.. plot::
:include-source:
from qiskit import pulse
dc = pulse.DriveChannel
d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4)
with pulse.build(name='pulse_programming_in') as pulse_prog:
pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3)
pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4)
pulse_prog.draw()
To begin pulse programming we must first initialize our program builder
context with :func:`build`, after which we can begin adding program
statements. For example, below we write a simple program that :func:`play`\s
a pulse:
.. plot::
:include-source:
from qiskit import execute, pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), d0)
pulse_prog.draw()
The builder initializes a :class:`.pulse.Schedule`, ``pulse_prog``
and then begins to construct the program within the context. The output pulse
schedule will survive after the context is exited and can be executed like a
normal Qiskit schedule using ``qiskit.execute(pulse_prog, backend)``.
Pulse programming has a simple imperative style. This leaves the programmer
to worry about the raw experimental physics of pulse programming and not
constructing cumbersome data structures.
We can optionally pass a :class:`~qiskit.providers.Backend` to
:func:`build` to enable enhanced functionality. Below, we prepare a Bell state
by automatically compiling the required pulses from their gate-level
representations, while simultaneously applying a long decoupling pulse to a
neighboring qubit. We terminate the experiment with a measurement to observe the
state we prepared. This program which mixes circuits and pulses will be
automatically lowered to be run as a pulse program:
.. plot::
:include-source:
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
# TODO: This example should use a real mock backend.
backend = FakeOpenPulse3Q()
d2 = pulse.DriveChannel(2)
with pulse.build(backend) as bell_prep:
pulse.u2(0, math.pi, 0)
pulse.cx(0, 1)
with pulse.build(backend) as decoupled_bell_prep_and_measure:
# We call our bell state preparation schedule constructed above.
with pulse.align_right():
pulse.call(bell_prep)
pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2)
pulse.barrier(0, 1, 2)
registers = pulse.measure_all()
decoupled_bell_prep_and_measure.draw()
With the pulse builder we are able to blend programming on qubits and channels.
While the pulse schedule is based on instructions that operate on
channels, the pulse builder automatically handles the mapping from qubits to
channels for you.
In the example below we demonstrate some more features of the pulse builder:
.. code-block::
import math
from qiskit import pulse, QuantumCircuit
from qiskit.pulse import library
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
# Create a pulse.
gaussian_pulse = library.gaussian(10, 1.0, 2)
# Get the qubit's corresponding drive channel from the backend.
d0 = pulse.drive_channel(0)
d1 = pulse.drive_channel(1)
# Play a pulse at t=0.
pulse.play(gaussian_pulse, d0)
# Play another pulse directly after the previous pulse at t=10.
pulse.play(gaussian_pulse, d0)
# The default scheduling behavior is to schedule pulses in parallel
# across channels. For example, the statement below
# plays the same pulse on a different channel at t=0.
pulse.play(gaussian_pulse, d1)
# We also provide pulse scheduling alignment contexts.
# The default alignment context is align_left.
# The sequential context schedules pulse instructions sequentially in time.
# This context starts at t=10 due to earlier pulses above.
with pulse.align_sequential():
pulse.play(gaussian_pulse, d0)
# Play another pulse after at t=20.
pulse.play(gaussian_pulse, d1)
# We can also nest contexts as each instruction is
# contained in its local scheduling context.
# The output of a child context is a context-schedule
# with the internal instructions timing fixed relative to
# one another. This is schedule is then called in the parent context.
# Context starts at t=30.
with pulse.align_left():
# Start at t=30.
pulse.play(gaussian_pulse, d0)
# Start at t=30.
pulse.play(gaussian_pulse, d1)
# Context ends at t=40.
# Alignment context where all pulse instructions are
# aligned to the right, ie., as late as possible.
with pulse.align_right():
# Shift the phase of a pulse channel.
pulse.shift_phase(math.pi, d1)
# Starts at t=40.
pulse.delay(100, d0)
# Ends at t=140.
# Starts at t=130.
pulse.play(gaussian_pulse, d1)
# Ends at t=140.
# Acquire data for a qubit and store in a memory slot.
pulse.acquire(100, 0, pulse.MemorySlot(0))
# We also support a variety of macros for common operations.
# Measure all qubits.
pulse.measure_all()
# Delay on some qubits.
# This requires knowledge of which channels belong to which qubits.
# delay for 100 cycles on qubits 0 and 1.
pulse.delay_qubits(100, 0, 1)
# Call a quantum circuit. The pulse builder lazily constructs a quantum
# circuit which is then transpiled and scheduled before inserting into
# a pulse schedule.
# NOTE: Quantum register indices correspond to physical qubit indices.
qc = QuantumCircuit(2, 2)
qc.cx(0, 1)
pulse.call(qc)
# Calling a small set of standard gates and decomposing to pulses is
# also supported with more natural syntax.
pulse.u3(0, math.pi, 0, 0)
pulse.cx(0, 1)
# It is also be possible to call a preexisting schedule
tmp_sched = pulse.Schedule()
tmp_sched += pulse.Play(gaussian_pulse, d0)
pulse.call(tmp_sched)
# We also support:
# frequency instructions
pulse.set_frequency(5.0e9, d0)
# phase instructions
pulse.shift_phase(0.1, d0)
# offset contexts
with pulse.phase_offset(math.pi, d0):
pulse.play(gaussian_pulse, d0)
The above is just a small taste of what is possible with the builder. See the rest of the module
documentation for more information on its capabilities.
.. autofunction:: build
Channels
========
Methods to return the correct channels for the respective qubit indices.
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
print(d0)
.. parsed-literal::
DriveChannel(0)
.. autofunction:: acquire_channel
.. autofunction:: control_channels
.. autofunction:: drive_channel
.. autofunction:: measure_channel
Instructions
============
Pulse instructions are available within the builder interface. Here's an example:
.. plot::
:include-source:
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
a0 = pulse.acquire_channel(0)
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.delay(20, d0)
pulse.shift_phase(3.14/2, d0)
pulse.set_phase(3.14, d0)
pulse.shift_frequency(1e7, d0)
pulse.set_frequency(5e9, d0)
with pulse.build() as temp_sched:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0)
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0)
pulse.call(temp_sched)
pulse.acquire(30, a0, pulse.MemorySlot(0))
drive_sched.draw()
.. autofunction:: acquire
.. autofunction:: barrier
.. autofunction:: call
.. autofunction:: delay
.. autofunction:: play
.. autofunction:: reference
.. autofunction:: set_frequency
.. autofunction:: set_phase
.. autofunction:: shift_frequency
.. autofunction:: shift_phase
.. autofunction:: snapshot
Contexts
========
Builder aware contexts that modify the construction of a pulse program. For
example an alignment context like :func:`align_right` may
be used to align all pulses as late as possible in a pulse program.
.. plot::
:include-source:
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog.draw()
.. autofunction:: align_equispaced
.. autofunction:: align_func
.. autofunction:: align_left
.. autofunction:: align_right
.. autofunction:: align_sequential
.. autofunction:: circuit_scheduler_settings
.. autofunction:: frequency_offset
.. autofunction:: phase_offset
.. autofunction:: transpiler_settings
Macros
======
Macros help you add more complex functionality to your pulse program.
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as measure_sched:
mem_slot = pulse.measure(0)
print(mem_slot)
.. parsed-literal::
MemorySlot(0)
.. autofunction:: measure
.. autofunction:: measure_all
.. autofunction:: delay_qubits
Circuit Gates
=============
To use circuit level gates within your pulse program call a circuit
with :func:`call`.
.. warning::
These will be removed in future versions with the release of a circuit
builder interface in which it will be possible to calibrate a gate in
terms of pulses and use that gate in a circuit.
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as u3_sched:
pulse.u3(math.pi, 0, math.pi, 0)
.. autofunction:: cx
.. autofunction:: u1
.. autofunction:: u2
.. autofunction:: u3
.. autofunction:: x
Utilities
=========
The utility functions can be used to gather attributes about the backend and modify
how the program is built.
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as u3_sched:
print('Number of qubits in backend: {}'.format(pulse.num_qubits()))
samples = 160
print('There are {} samples in {} seconds'.format(
samples, pulse.samples_to_seconds(160)))
seconds = 1e-6
print('There are {} seconds in {} samples.'.format(
seconds, pulse.seconds_to_samples(1e-6)))
.. parsed-literal::
Number of qubits in backend: 1
There are 160 samples in 3.5555555555555554e-08 seconds
There are 1e-06 seconds in 4500 samples.
.. autofunction:: active_backend
.. autofunction:: active_transpiler_settings
.. autofunction:: active_circuit_scheduler_settings
.. autofunction:: num_qubits
.. autofunction:: qubit_channels
.. autofunction:: samples_to_seconds
.. autofunction:: seconds_to_samples
"""
import collections
import contextvars
import functools
import itertools
import uuid
import warnings
from contextlib import contextmanager
from functools import singledispatchmethod
from typing import (
Any,
Callable,
ContextManager,
Dict,
Iterable,
List,
Mapping,
Optional,
Set,
Tuple,
TypeVar,
Union,
NewType,
)
import numpy as np
from qiskit import circuit
from qiskit.circuit.library import standard_gates as gates
from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType
from qiskit.pulse import (
channels as chans,
configuration,
exceptions,
instructions,
macros,
library,
transforms,
)
from qiskit.providers.backend import BackendV2
from qiskit.pulse.instructions import directives
from qiskit.pulse.schedule import Schedule, ScheduleBlock
from qiskit.pulse.transforms.alignments import AlignmentKind
#: contextvars.ContextVar[BuilderContext]: active builder
BUILDER_CONTEXTVAR = contextvars.ContextVar("backend")
T = TypeVar("T")
StorageLocation = NewType("StorageLocation", Union[chans.MemorySlot, chans.RegisterSlot])
def _compile_lazy_circuit_before(function: Callable[..., T]) -> Callable[..., T]:
"""Decorator thats schedules and calls the lazily compiled circuit before
executing the decorated builder method."""
@functools.wraps(function)
def wrapper(self, *args, **kwargs):
self._compile_lazy_circuit()
return function(self, *args, **kwargs)
return wrapper
def _requires_backend(function: Callable[..., T]) -> Callable[..., T]:
"""Decorator a function to raise if it is called without a builder with a
set backend.
"""
@functools.wraps(function)
def wrapper(self, *args, **kwargs):
if self.backend is None:
raise exceptions.BackendNotSet(
'This function requires the builder to have a "backend" set.'
)
return function(self, *args, **kwargs)
return wrapper
class _PulseBuilder:
"""Builder context class."""
__alignment_kinds__ = {
"left": transforms.AlignLeft(),
"right": transforms.AlignRight(),
"sequential": transforms.AlignSequential(),
}
def __init__(
self,
backend=None,
block: Optional[ScheduleBlock] = None,
name: Optional[str] = None,
default_alignment: Union[str, AlignmentKind] = "left",
default_transpiler_settings: Mapping = None,
default_circuit_scheduler_settings: Mapping = None,
):
"""Initialize the builder context.
.. note::
At some point we may consider incorporating the builder into
the :class:`~qiskit.pulse.Schedule` class. However, the risk of
this is tying the user interface to the intermediate
representation. For now we avoid this at the cost of some code
duplication.
Args:
backend (Backend): Input backend to use in
builder. If not set certain functionality will be unavailable.
block: Initital ``ScheduleBlock`` to build on.
name: Name of pulse program to be built.
default_alignment: Default scheduling alignment for builder.
One of ``left``, ``right``, ``sequential`` or an instance of
:class:`~qiskit.pulse.transforms.alignments.AlignmentKind` subclass.
default_transpiler_settings: Default settings for the transpiler.
default_circuit_scheduler_settings: Default settings for the
circuit to pulse scheduler.
Raises:
PulseError: When invalid ``default_alignment`` or `block` is specified.
"""
#: Backend: Backend instance for context builder.
self._backend = backend
#: Union[None, ContextVar]: Token for this ``_PulseBuilder``'s ``ContextVar``.
self._backend_ctx_token = None
#: QuantumCircuit: Lazily constructed quantum circuit
self._lazy_circuit = None
#: Dict[str, Any]: Transpiler setting dictionary.
self._transpiler_settings = default_transpiler_settings or {}
#: Dict[str, Any]: Scheduler setting dictionary.
self._circuit_scheduler_settings = default_circuit_scheduler_settings or {}
#: List[ScheduleBlock]: Stack of context.
self._context_stack = []
#: str: Name of the output program
self._name = name
# Add root block if provided. Schedule will be built on top of this.
if block is not None:
if isinstance(block, ScheduleBlock):
root_block = block
elif isinstance(block, Schedule):
root_block = self._naive_typecast_schedule(block)
else:
raise exceptions.PulseError(
f"Input `block` type {block.__class__.__name__} is "
"not a valid format. Specify a pulse program."
)
self._context_stack.append(root_block)
# Set default alignment context
alignment = _PulseBuilder.__alignment_kinds__.get(default_alignment, default_alignment)
if not isinstance(alignment, AlignmentKind):
raise exceptions.PulseError(
f"Given `default_alignment` {repr(default_alignment)} is "
"not a valid transformation. Set one of "
f'{", ".join(_PulseBuilder.__alignment_kinds__.keys())}, '
"or set an instance of `AlignmentKind` subclass."
)
self.push_context(alignment)
def __enter__(self) -> ScheduleBlock:
"""Enter this builder context and yield either the supplied schedule
or the schedule created for the user.
Returns:
The schedule that the builder will build on.
"""
self._backend_ctx_token = BUILDER_CONTEXTVAR.set(self)
output = self._context_stack[0]
output._name = self._name or output.name
return output
@_compile_lazy_circuit_before
def __exit__(self, exc_type, exc_val, exc_tb):
"""Exit the builder context and compile the built pulse program."""
self.compile()
BUILDER_CONTEXTVAR.reset(self._backend_ctx_token)
@property
def backend(self):
"""Returns the builder backend if set.
Returns:
Optional[Backend]: The builder's backend.
"""
return self._backend
@_compile_lazy_circuit_before
def push_context(self, alignment: AlignmentKind):
"""Push new context to the stack."""
self._context_stack.append(ScheduleBlock(alignment_context=alignment))
@_compile_lazy_circuit_before
def pop_context(self) -> ScheduleBlock:
"""Pop the last context from the stack."""
if len(self._context_stack) == 1:
raise exceptions.PulseError("The root context cannot be popped out.")
return self._context_stack.pop()
def get_context(self) -> ScheduleBlock:
"""Get current context.
Notes:
New instruction can be added by `.append_subroutine` or `.append_instruction` method.
Use above methods rather than directly accessing to the current context.
"""
return self._context_stack[-1]
@property
@_requires_backend
def num_qubits(self):
"""Get the number of qubits in the backend."""
# backendV2
if isinstance(self.backend, BackendV2):
return self.backend.num_qubits
return self.backend.configuration().n_qubits
@property
def transpiler_settings(self) -> Mapping:
"""The builder's transpiler settings."""
return self._transpiler_settings
@transpiler_settings.setter
@_compile_lazy_circuit_before
def transpiler_settings(self, settings: Mapping):
self._compile_lazy_circuit()
self._transpiler_settings = settings
@property
def circuit_scheduler_settings(self) -> Mapping:
"""The builder's circuit to pulse scheduler settings."""
return self._circuit_scheduler_settings
@circuit_scheduler_settings.setter
@_compile_lazy_circuit_before
def circuit_scheduler_settings(self, settings: Mapping):
self._compile_lazy_circuit()
self._circuit_scheduler_settings = settings
@_compile_lazy_circuit_before
def compile(self) -> ScheduleBlock:
"""Compile and output the built pulse program."""
# Not much happens because we currently compile as we build.
# This should be offloaded to a true compilation module
# once we define a more sophisticated IR.
while len(self._context_stack) > 1:
current = self.pop_context()
self.append_subroutine(current)
return self._context_stack[0]
def _compile_lazy_circuit(self):
"""Call a context QuantumCircuit (lazy circuit) and append the output pulse schedule
to the builder's context schedule.
Note that the lazy circuit is not stored as a call instruction.
"""
if self._lazy_circuit:
lazy_circuit = self._lazy_circuit
# reset lazy circuit
self._lazy_circuit = self._new_circuit()
self.call_subroutine(self._compile_circuit(lazy_circuit))
def _compile_circuit(self, circ) -> Schedule:
"""Take a QuantumCircuit and output the pulse schedule associated with the circuit."""
from qiskit import compiler # pylint: disable=cyclic-import
transpiled_circuit = compiler.transpile(circ, self.backend, **self.transpiler_settings)
sched = compiler.schedule(
transpiled_circuit, self.backend, **self.circuit_scheduler_settings
)
return sched
def _new_circuit(self):
"""Create a new circuit for lazy circuit scheduling."""
return circuit.QuantumCircuit(self.num_qubits)
@_compile_lazy_circuit_before
def append_instruction(self, instruction: instructions.Instruction):
"""Add an instruction to the builder's context schedule.
Args:
instruction: Instruction to append.
"""
self._context_stack[-1].append(instruction)
def append_reference(self, name: str, *extra_keys: str):
"""Add external program as a :class:`~qiskit.pulse.instructions.Reference` instruction.
Args:
name: Name of subroutine.
extra_keys: Assistance keys to uniquely specify the subroutine.
"""
inst = instructions.Reference(name, *extra_keys)
self.append_instruction(inst)
@_compile_lazy_circuit_before
def append_subroutine(self, subroutine: Union[Schedule, ScheduleBlock]):
"""Append a :class:`ScheduleBlock` to the builder's context schedule.
This operation doesn't create a reference. Subroutine is directly
appended to current context schedule.
Args:
subroutine: ScheduleBlock to append to the current context block.
Raises:
PulseError: When subroutine is not Schedule nor ScheduleBlock.
"""
if not isinstance(subroutine, (ScheduleBlock, Schedule)):
raise exceptions.PulseError(
f"'{subroutine.__class__.__name__}' is not valid data format in the builder. "
"'Schedule' and 'ScheduleBlock' can be appended to the builder context."
)
if len(subroutine) == 0:
return
if isinstance(subroutine, Schedule):
subroutine = self._naive_typecast_schedule(subroutine)
self._context_stack[-1].append(subroutine)
@singledispatchmethod
def call_subroutine(
self,
subroutine: Union[circuit.QuantumCircuit, Schedule, ScheduleBlock],
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
"""Call a schedule or circuit defined outside of the current scope.
The ``subroutine`` is appended to the context schedule as a call instruction.
This logic just generates a convenient program representation in the compiler.
Thus, this doesn't affect execution of inline subroutines.
See :class:`~pulse.instructions.Call` for more details.
Args:
subroutine: Target schedule or circuit to append to the current context.
name: Name of subroutine if defined.
value_dict: Parameter object and assigned value mapping. This is more precise way to
identify a parameter since mapping is managed with unique object id rather than
name. Especially there is any name collision in a parameter table.
kw_params: Parameter values to bind to the target subroutine
with string parameter names. If there are parameter name overlapping,
these parameters are updated with the same assigned value.
Raises:
PulseError:
- When input subroutine is not valid data format.
"""
raise exceptions.PulseError(
f"Subroutine type {subroutine.__class__.__name__} is "
"not valid data format. Call QuantumCircuit, "
"Schedule, or ScheduleBlock."
)
@call_subroutine.register
def _(
self,
target_block: ScheduleBlock,
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
if len(target_block) == 0:
return
# Create local parameter assignment
local_assignment = {}
for param_name, value in kw_params.items():
params = target_block.get_parameters(param_name)
if not params:
raise exceptions.PulseError(
f"Parameter {param_name} is not defined in the target subroutine. "
f'{", ".join(map(str, target_block.parameters))} can be specified.'
)
for param in params:
local_assignment[param] = value
if value_dict:
if local_assignment.keys() & value_dict.keys():
warnings.warn(
"Some parameters provided by 'value_dict' conflict with one through "
"keyword arguments. Parameter values in the keyword arguments "
"are overridden by the dictionary values.",
UserWarning,
)
local_assignment.update(value_dict)
if local_assignment:
target_block = target_block.assign_parameters(local_assignment, inplace=False)
if name is None:
# Add unique string, not to accidentally override existing reference entry.
keys = (target_block.name, uuid.uuid4().hex)
else:
keys = (name,)
self.append_reference(*keys)
self.get_context().assign_references({keys: target_block}, inplace=True)
@call_subroutine.register
def _(
self,
target_schedule: Schedule,
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
if len(target_schedule) == 0:
return
self.call_subroutine(
self._naive_typecast_schedule(target_schedule),
name=name,
value_dict=value_dict,
**kw_params,
)
@call_subroutine.register
def _(
self,
target_circuit: circuit.QuantumCircuit,
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
if len(target_circuit) == 0:
return
self._compile_lazy_circuit()
self.call_subroutine(
self._compile_circuit(target_circuit),
name=name,
value_dict=value_dict,
**kw_params,
)
@_requires_backend
def call_gate(self, gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True):
"""Call the circuit ``gate`` in the pulse program.
The qubits are assumed to be defined on physical qubits.
If ``lazy == True`` this circuit will extend a lazily constructed
quantum circuit. When an operation occurs that breaks the underlying
circuit scheduling assumptions such as adding a pulse instruction or
changing the alignment context the circuit will be
transpiled and scheduled into pulses with the current active settings.
Args:
gate: Gate to call.
qubits: Qubits to call gate on.
lazy: If false the circuit will be transpiled and pulse scheduled
immediately. Otherwise, it will extend the active lazy circuit
as defined above.
"""
try:
iter(qubits)
except TypeError:
qubits = (qubits,)
if lazy:
self._call_gate(gate, qubits)
else:
self._compile_lazy_circuit()
self._call_gate(gate, qubits)
self._compile_lazy_circuit()
def _call_gate(self, gate, qargs):
if self._lazy_circuit is None:
self._lazy_circuit = self._new_circuit()
self._lazy_circuit.append(gate, qargs=qargs)
@staticmethod
def _naive_typecast_schedule(schedule: Schedule):
# Naively convert into ScheduleBlock
from qiskit.pulse.transforms import inline_subroutines, flatten, pad
preprocessed_schedule = inline_subroutines(flatten(schedule))
pad(preprocessed_schedule, inplace=True, pad_with=instructions.TimeBlockade)
# default to left alignment, namely ASAP scheduling
target_block = ScheduleBlock(name=schedule.name)
for _, inst in preprocessed_schedule.instructions:
target_block.append(inst, inplace=True)
return target_block
def get_dt(self):
"""Retrieve dt differently based on the type of Backend"""
if isinstance(self.backend, BackendV2):
return self.backend.dt
return self.backend.configuration().dt
def build(
backend=None,
schedule: Optional[ScheduleBlock] = None,
name: Optional[str] = None,
default_alignment: Optional[Union[str, AlignmentKind]] = "left",
default_transpiler_settings: Optional[Dict[str, Any]] = None,
default_circuit_scheduler_settings: Optional[Dict[str, Any]] = None,
) -> ContextManager[ScheduleBlock]:
"""Create a context manager for launching the imperative pulse builder DSL.
To enter a building context and starting building a pulse program:
.. code-block::
from qiskit import execute, pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 0.5), d0)
While the output program ``pulse_prog`` cannot be executed as we are using
a mock backend. If a real backend is being used, executing the program is
done with:
.. code-block:: python
qiskit.execute(pulse_prog, backend)
Args:
backend (Backend): A Qiskit backend. If not supplied certain
builder functionality will be unavailable.
schedule: A pulse ``ScheduleBlock`` in which your pulse program will be built.
name: Name of pulse program to be built.
default_alignment: Default scheduling alignment for builder.
One of ``left``, ``right``, ``sequential`` or an alignment context.
default_transpiler_settings: Default settings for the transpiler.
default_circuit_scheduler_settings: Default settings for the
circuit to pulse scheduler.
Returns:
A new builder context which has the active builder initialized.
"""
return _PulseBuilder(
backend=backend,
block=schedule,
name=name,
default_alignment=default_alignment,
default_transpiler_settings=default_transpiler_settings,
default_circuit_scheduler_settings=default_circuit_scheduler_settings,
)
# Builder Utilities
def _active_builder() -> _PulseBuilder:
"""Get the active builder in the active context.
Returns:
The active active builder in this context.
Raises:
exceptions.NoActiveBuilder: If a pulse builder function is called
outside of a builder context.
"""
try:
return BUILDER_CONTEXTVAR.get()
except LookupError as ex:
raise exceptions.NoActiveBuilder(
"A Pulse builder function was called outside of "
"a builder context. Try calling within a builder "
'context, eg., "with pulse.build() as schedule: ...".'
) from ex
def active_backend():
"""Get the backend of the currently active builder context.
Returns:
Backend: The active backend in the currently active
builder context.
Raises:
exceptions.BackendNotSet: If the builder does not have a backend set.
"""
builder = _active_builder().backend
if builder is None:
raise exceptions.BackendNotSet(
'This function requires the active builder to have a "backend" set.'
)
return builder
def append_schedule(schedule: Union[Schedule, ScheduleBlock]):
"""Call a schedule by appending to the active builder's context block.
Args:
schedule: Schedule or ScheduleBlock to append.
"""
_active_builder().append_subroutine(schedule)
def append_instruction(instruction: instructions.Instruction):
"""Append an instruction to the active builder's context schedule.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.builder.append_instruction(pulse.Delay(10, d0))
print(pulse_prog.instructions)
.. parsed-literal::
((0, Delay(10, DriveChannel(0))),)
"""
_active_builder().append_instruction(instruction)
def num_qubits() -> int:
"""Return number of qubits in the currently active backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.num_qubits())
.. parsed-literal::
2
.. note:: Requires the active builder context to have a backend set.
"""
if isinstance(active_backend(), BackendV2):
return active_backend().num_qubits
return active_backend().configuration().n_qubits
def seconds_to_samples(seconds: Union[float, np.ndarray]) -> Union[int, np.ndarray]:
"""Obtain the number of samples that will elapse in ``seconds`` on the
active backend.
Rounds down.
Args:
seconds: Time in seconds to convert to samples.
Returns:
The number of samples for the time to elapse
"""
dt = _active_builder().get_dt()
if isinstance(seconds, np.ndarray):
return (seconds / dt).astype(int)
return int(seconds / dt)
def samples_to_seconds(samples: Union[int, np.ndarray]) -> Union[float, np.ndarray]:
"""Obtain the time in seconds that will elapse for the input number of
samples on the active backend.
Args:
samples: Number of samples to convert to time in seconds.
Returns:
The time that elapses in ``samples``.
"""
return samples * _active_builder().get_dt()
def qubit_channels(qubit: int) -> Set[chans.Channel]:
"""Returns the set of channels associated with a qubit.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.qubit_channels(0))
.. parsed-literal::
{MeasureChannel(0), ControlChannel(0), DriveChannel(0), AcquireChannel(0), ControlChannel(1)}
.. note:: Requires the active builder context to have a backend set.
.. note:: A channel may still be associated with another qubit in this list
such as in the case where significant crosstalk exists.
"""
# implement as the inner function to avoid API change for a patch release in 0.24.2.
def get_qubit_channels_v2(backend: BackendV2, qubit: int):
r"""Return a list of channels which operate on the given ``qubit``.
Returns:
List of ``Channel``\s operated on my the given ``qubit``.
"""
channels = []
# add multi-qubit channels
for node_qubits in backend.coupling_map:
if qubit in node_qubits:
control_channel = backend.control_channel(node_qubits)
if control_channel:
channels.extend(control_channel)
# add single qubit channels
channels.append(backend.drive_channel(qubit))
channels.append(backend.measure_channel(qubit))
channels.append(backend.acquire_channel(qubit))
return channels
# backendV2
if isinstance(active_backend(), BackendV2):
return set(get_qubit_channels_v2(active_backend(), qubit))
return set(active_backend().configuration().get_qubit_channels(qubit))
def _qubits_to_channels(*channels_or_qubits: Union[int, chans.Channel]) -> Set[chans.Channel]:
"""Returns the unique channels of the input qubits."""
channels = set()
for channel_or_qubit in channels_or_qubits:
if isinstance(channel_or_qubit, int):
channels |= qubit_channels(channel_or_qubit)
elif isinstance(channel_or_qubit, chans.Channel):
channels.add(channel_or_qubit)
else:
raise exceptions.PulseError(
f'{channel_or_qubit} is not a "Channel" or qubit (integer).'
)
return channels
def active_transpiler_settings() -> Dict[str, Any]:
"""Return the current active builder context's transpiler settings.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
transpiler_settings = {'optimization_level': 3}
with pulse.build(backend,
default_transpiler_settings=transpiler_settings):
print(pulse.active_transpiler_settings())
.. parsed-literal::
{'optimization_level': 3}
"""
return dict(_active_builder().transpiler_settings)
def active_circuit_scheduler_settings() -> Dict[str, Any]:
"""Return the current active builder context's circuit scheduler settings.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
circuit_scheduler_settings = {'method': 'alap'}
with pulse.build(
backend,
default_circuit_scheduler_settings=circuit_scheduler_settings):
print(pulse.active_circuit_scheduler_settings())
.. parsed-literal::
{'method': 'alap'}
"""
return dict(_active_builder().circuit_scheduler_settings)
# Contexts
@contextmanager
def align_left() -> ContextManager[None]:
"""Left alignment pulse scheduling context.
Pulse instructions within this context are scheduled as early as possible
by shifting them left to the earliest available time.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_left():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=0
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_start_time(d0) == pulse_prog.ch_start_time(d1)
Yields:
None
"""
builder = _active_builder()
builder.push_context(transforms.AlignLeft())
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_right() -> AlignmentKind:
"""Right alignment pulse scheduling context.
Pulse instructions within this context are scheduled as late as possible
by shifting them right to the latest available time.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_stop_time(d1)
Yields:
None
"""
builder = _active_builder()
builder.push_context(transforms.AlignRight())
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_sequential() -> AlignmentKind:
"""Sequential alignment pulse scheduling context.
Pulse instructions within this context are scheduled sequentially in time
such that no two instructions will be played at the same time.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_sequential():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will also start at t=100
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_start_time(d1)
Yields:
None
"""
builder = _active_builder()
builder.push_context(transforms.AlignSequential())
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_equispaced(duration: Union[int, ParameterExpression]) -> AlignmentKind:
"""Equispaced alignment pulse scheduling context.
Pulse instructions within this context are scheduled with the same interval spacing such that
the total length of the context block is ``duration``.
If the total free ``duration`` cannot be evenly divided by the number of instructions
within the context, the modulo is split and then prepended and appended to
the returned schedule. Delay instructions are automatically inserted in between pulses.
This context is convenient to write a schedule for periodical dynamic decoupling or
the Hahn echo sequence.
Examples:
.. plot::
:include-source:
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
with pulse.build() as hahn_echo:
with pulse.align_equispaced(duration=100):
pulse.play(x90, d0)
pulse.play(x180, d0)
pulse.play(x90, d0)
hahn_echo.draw()
Args:
duration: Duration of this context. This should be larger than the schedule duration.
Yields:
None
Notes:
The scheduling is performed for sub-schedules within the context rather than
channel-wise. If you want to apply the equispaced context for each channel,
you should use the context independently for channels.
"""
builder = _active_builder()
builder.push_context(transforms.AlignEquispaced(duration=duration))
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_func(
duration: Union[int, ParameterExpression], func: Callable[[int], float]
) -> AlignmentKind:
"""Callback defined alignment pulse scheduling context.
Pulse instructions within this context are scheduled at the location specified by
arbitrary callback function `position` that takes integer index and returns
the associated fractional location within [0, 1].
Delay instruction is automatically inserted in between pulses.
This context may be convenient to write a schedule of arbitrary dynamical decoupling
sequences such as Uhrig dynamical decoupling.
Examples:
.. plot::
:include-source:
import numpy as np
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
def udd10_pos(j):
return np.sin(np.pi*j/(2*10 + 2))**2
with pulse.build() as udd_sched:
pulse.play(x90, d0)
with pulse.align_func(duration=300, func=udd10_pos):
for _ in range(10):
pulse.play(x180, d0)
pulse.play(x90, d0)
udd_sched.draw()
Args:
duration: Duration of context. This should be larger than the schedule duration.
func: A function that takes an index of sub-schedule and returns the
fractional coordinate of of that sub-schedule.
The returned value should be defined within [0, 1].
The pulse index starts from 1.
Yields:
None
Notes:
The scheduling is performed for sub-schedules within the context rather than
channel-wise. If you want to apply the numerical context for each channel,
you need to apply the context independently to channels.
"""
builder = _active_builder()
builder.push_context(transforms.AlignFunc(duration=duration, func=func))
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def general_transforms(alignment_context: AlignmentKind) -> ContextManager[None]:
"""Arbitrary alignment transformation defined by a subclass instance of
:class:`~qiskit.pulse.transforms.alignments.AlignmentKind`.
Args:
alignment_context: Alignment context instance that defines schedule transformation.
Yields:
None
Raises:
PulseError: When input ``alignment_context`` is not ``AlignmentKind`` subclasses.
"""
if not isinstance(alignment_context, AlignmentKind):
raise exceptions.PulseError("Input alignment context is not `AlignmentKind` subclass.")
builder = _active_builder()
builder.push_context(alignment_context)
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def transpiler_settings(**settings) -> ContextManager[None]:
"""Set the currently active transpiler settings for this context.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.active_transpiler_settings())
with pulse.transpiler_settings(optimization_level=3):
print(pulse.active_transpiler_settings())
.. parsed-literal::
{}
{'optimization_level': 3}
"""
builder = _active_builder()
curr_transpiler_settings = builder.transpiler_settings
builder.transpiler_settings = collections.ChainMap(settings, curr_transpiler_settings)
try:
yield
finally:
builder.transpiler_settings = curr_transpiler_settings
@contextmanager
def circuit_scheduler_settings(**settings) -> ContextManager[None]:
"""Set the currently active circuit scheduler settings for this context.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.active_circuit_scheduler_settings())
with pulse.circuit_scheduler_settings(method='alap'):
print(pulse.active_circuit_scheduler_settings())
.. parsed-literal::
{}
{'method': 'alap'}
"""
builder = _active_builder()
curr_circuit_scheduler_settings = builder.circuit_scheduler_settings
builder.circuit_scheduler_settings = collections.ChainMap(
settings, curr_circuit_scheduler_settings
)
try:
yield
finally:
builder.circuit_scheduler_settings = curr_circuit_scheduler_settings
@contextmanager
def phase_offset(phase: float, *channels: chans.PulseChannel) -> ContextManager[None]:
"""Shift the phase of input channels on entry into context and undo on exit.
Examples:
.. code-block::
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
with pulse.phase_offset(math.pi, d0):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 3
Args:
phase: Amount of phase offset in radians.
channels: Channels to offset phase of.
Yields:
None
"""
for channel in channels:
shift_phase(phase, channel)
try:
yield
finally:
for channel in channels:
shift_phase(-phase, channel)
@contextmanager
def frequency_offset(
frequency: float, *channels: chans.PulseChannel, compensate_phase: bool = False
) -> ContextManager[None]:
"""Shift the frequency of inputs channels on entry into context and undo on exit.
Examples:
.. code-block:: python
:emphasize-lines: 7, 16
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build(backend) as pulse_prog:
# shift frequency by 1GHz
with pulse.frequency_offset(1e9, d0):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 3
with pulse.build(backend) as pulse_prog:
# Shift frequency by 1GHz.
# Undo accumulated phase in the shifted frequency frame
# when exiting the context.
with pulse.frequency_offset(1e9, d0, compensate_phase=True):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 4
Args:
frequency: Amount of frequency offset in Hz.
channels: Channels to offset frequency of.
compensate_phase: Compensate for accumulated phase accumulated with
respect to the channels' frame at its initial frequency.
Yields:
None
"""
builder = _active_builder()
# TODO: Need proper implementation of compensation. t0 may depend on the parent context.
# For example, the instruction position within the equispaced context depends on
# the current total number of instructions, thus adding more instruction after
# offset context may change the t0 when the parent context is transformed.
t0 = builder.get_context().duration
for channel in channels:
shift_frequency(frequency, channel)
try:
yield
finally:
if compensate_phase:
duration = builder.get_context().duration - t0
accumulated_phase = 2 * np.pi * ((duration * builder.get_dt() * frequency) % 1)
for channel in channels:
shift_phase(-accumulated_phase, channel)
for channel in channels:
shift_frequency(-frequency, channel)
# Channels
def drive_channel(qubit: int) -> chans.DriveChannel:
"""Return ``DriveChannel`` for ``qubit`` on the active builder backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.drive_channel(0) == pulse.DriveChannel(0)
.. note:: Requires the active builder context to have a backend set.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().drive_channel(qubit)
return active_backend().configuration().drive(qubit)
def measure_channel(qubit: int) -> chans.MeasureChannel:
"""Return ``MeasureChannel`` for ``qubit`` on the active builder backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.measure_channel(0) == pulse.MeasureChannel(0)
.. note:: Requires the active builder context to have a backend set.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().measure_channel(qubit)
return active_backend().configuration().measure(qubit)
def acquire_channel(qubit: int) -> chans.AcquireChannel:
"""Return ``AcquireChannel`` for ``qubit`` on the active builder backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.acquire_channel(0) == pulse.AcquireChannel(0)
.. note:: Requires the active builder context to have a backend set.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().acquire_channel(qubit)
return active_backend().configuration().acquire(qubit)
def control_channels(*qubits: Iterable[int]) -> List[chans.ControlChannel]:
"""Return ``ControlChannel`` for ``qubit`` on the active builder backend.
Return the secondary drive channel for the given qubit -- typically
utilized for controlling multi-qubit interactions.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.control_channels(0, 1) == [pulse.ControlChannel(0)]
.. note:: Requires the active builder context to have a backend set.
Args:
qubits: Tuple or list of ordered qubits of the form
`(control_qubit, target_qubit)`.
Returns:
List of control channels associated with the supplied ordered list
of qubits.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().control_channel(qubits)
return active_backend().configuration().control(qubits=qubits)
# Base Instructions
def delay(duration: int, channel: chans.Channel, name: Optional[str] = None):
"""Delay on a ``channel`` for a ``duration``.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.delay(10, d0)
Args:
duration: Number of cycles to delay for on ``channel``.
channel: Channel to delay on.
name: Name of the instruction.
"""
append_instruction(instructions.Delay(duration, channel, name=name))
def play(
pulse: Union[library.Pulse, np.ndarray], channel: chans.PulseChannel, name: Optional[str] = None
):
"""Play a ``pulse`` on a ``channel``.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(10, 1.0), d0)
Args:
pulse: Pulse to play.
channel: Channel to play pulse on.
name: Name of the pulse.
"""
if not isinstance(pulse, library.Pulse):
pulse = library.Waveform(pulse)
append_instruction(instructions.Play(pulse, channel, name=name))
def acquire(
duration: int,
qubit_or_channel: Union[int, chans.AcquireChannel],
register: StorageLocation,
**metadata: Union[configuration.Kernel, configuration.Discriminator],
):
"""Acquire for a ``duration`` on a ``channel`` and store the result
in a ``register``.
Examples:
.. code-block::
from qiskit import pulse
acq0 = pulse.AcquireChannel(0)
mem0 = pulse.MemorySlot(0)
with pulse.build() as pulse_prog:
pulse.acquire(100, acq0, mem0)
# measurement metadata
kernel = pulse.configuration.Kernel('linear_discriminator')
pulse.acquire(100, acq0, mem0, kernel=kernel)
.. note:: The type of data acquire will depend on the execution ``meas_level``.
Args:
duration: Duration to acquire data for
qubit_or_channel: Either the qubit to acquire data for or the specific
:class:`~qiskit.pulse.channels.AcquireChannel` to acquire on.
register: Location to store measured result.
metadata: Additional metadata for measurement. See
:class:`~qiskit.pulse.instructions.Acquire` for more information.
Raises:
exceptions.PulseError: If the register type is not supported.
"""
if isinstance(qubit_or_channel, int):
qubit_or_channel = chans.AcquireChannel(qubit_or_channel)
if isinstance(register, chans.MemorySlot):
append_instruction(
instructions.Acquire(duration, qubit_or_channel, mem_slot=register, **metadata)
)
elif isinstance(register, chans.RegisterSlot):
append_instruction(
instructions.Acquire(duration, qubit_or_channel, reg_slot=register, **metadata)
)
else:
raise exceptions.PulseError(f'Register of type: "{type(register)}" is not supported')
def set_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Set the ``frequency`` of a pulse ``channel``.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.set_frequency(1e9, d0)
Args:
frequency: Frequency in Hz to set channel to.
channel: Channel to set frequency of.
name: Name of the instruction.
"""
append_instruction(instructions.SetFrequency(frequency, channel, name=name))
def shift_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Shift the ``frequency`` of a pulse ``channel``.
Examples:
.. code-block:: python
:emphasize-lines: 6
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.shift_frequency(1e9, d0)
Args:
frequency: Frequency in Hz to shift channel frequency by.
channel: Channel to shift frequency of.
name: Name of the instruction.
"""
append_instruction(instructions.ShiftFrequency(frequency, channel, name=name))
def set_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Set the ``phase`` of a pulse ``channel``.
Examples:
.. code-block:: python
:emphasize-lines: 8
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.set_phase(math.pi, d0)
Args:
phase: Phase in radians to set channel carrier signal to.
channel: Channel to set phase of.
name: Name of the instruction.
"""
append_instruction(instructions.SetPhase(phase, channel, name=name))
def shift_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Shift the ``phase`` of a pulse ``channel``.
Examples:
.. code-block::
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.shift_phase(math.pi, d0)
Args:
phase: Phase in radians to shift channel carrier signal by.
channel: Channel to shift phase of.
name: Name of the instruction.
"""
append_instruction(instructions.ShiftPhase(phase, channel, name))
def snapshot(label: str, snapshot_type: str = "statevector"):
"""Simulator snapshot.
Examples:
.. code-block::
from qiskit import pulse
with pulse.build() as pulse_prog:
pulse.snapshot('first', 'statevector')
Args:
label: Label for snapshot.
snapshot_type: Type of snapshot.
"""
append_instruction(instructions.Snapshot(label, snapshot_type=snapshot_type))
def call(
target: Optional[Union[circuit.QuantumCircuit, Schedule, ScheduleBlock]],
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterValueType, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
"""Call the subroutine within the currently active builder context with arbitrary
parameters which will be assigned to the target program.
.. note::
If the ``target`` program is a :class:`.ScheduleBlock`, then a :class:`.Reference`
instruction will be created and appended to the current context.
The ``target`` program will be immediately assigned to the current scope as a subroutine.
If the ``target`` program is :class:`.Schedule`, it will be wrapped by the
:class:`.Call` instruction and appended to the current context to avoid
a mixed representation of :class:`.ScheduleBlock` and :class:`.Schedule`.
If the ``target`` program is a :class:`.QuantumCircuit` it will be scheduled
and the new :class:`.Schedule` will be added as a :class:`.Call` instruction.
Examples:
1. Calling a schedule block (recommended)
.. code-block::
from qiskit import circuit, pulse
from qiskit.providers.fake_provider import FakeBogotaV2
backend = FakeBogotaV2()
with pulse.build() as x_sched:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
with pulse.build() as pulse_prog:
pulse.call(x_sched)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.1+0j), sigma=40),
DriveChannel(0)
),
name="block0",
transform=AlignLeft()
),
name="block1",
transform=AlignLeft()
)
The actual program is stored in the reference table attached to the schedule.
.. code-block::
print(pulse_prog.references)
.. parsed-literal::
ReferenceManager:
- ('block0', '634b3b50bd684e26a673af1fbd2d6c81'): ScheduleBlock(Play(Gaussian(...
In addition, you can call a parameterized target program with parameter assignment.
.. code-block::
amp = circuit.Parameter("amp")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
with pulse.build() as pulse_prog:
pulse.call(subroutine, amp=0.1)
pulse.call(subroutine, amp=0.3)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.1+0j), sigma=40),
DriveChannel(0)
),
name="block2",
transform=AlignLeft()
),
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.3+0j), sigma=40),
DriveChannel(0)
),
name="block2",
transform=AlignLeft()
),
name="block3",
transform=AlignLeft()
)
If there is a name collision between parameters, you can distinguish them by specifying
each parameter object in a python dictionary. For example,
.. code-block::
amp1 = circuit.Parameter('amp')
amp2 = circuit.Parameter('amp')
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, amp2, 40), pulse.DriveChannel(1))
with pulse.build() as pulse_prog:
pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.3})
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
ScheduleBlock(
Play(Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0)),
Play(Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(1)),
name="block4",
transform=AlignLeft()
),
name="block5",
transform=AlignLeft()
)
2. Calling a schedule
.. code-block::
x_sched = backend.instruction_schedule_map.get("x", (0,))
with pulse.build(backend) as pulse_prog:
pulse.call(x_sched)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
Call(
Schedule(
(
0,
Play(
Drag(
duration=160,
amp=(0.18989731546729305+0j),
sigma=40,
beta=-1.201258305015517,
name='drag_86a8'
),
DriveChannel(0),
name='drag_86a8'
)
),
name="x"
),
name='x'
),
name="block6",
transform=AlignLeft()
)
Currently, the backend calibrated gates are provided in the form of :class:`~.Schedule`.
The parameter assignment mechanism is available also for schedules.
However, the called schedule is not treated as a reference.
3. Calling a quantum circuit
.. code-block::
backend = FakeBogotaV2()
qc = circuit.QuantumCircuit(1)
qc.x(0)
with pulse.build(backend) as pulse_prog:
pulse.call(qc)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
Call(
Schedule(
(
0,
Play(
Drag(
duration=160,
amp=(0.18989731546729305+0j),
sigma=40,
beta=-1.201258305015517,
name='drag_86a8'
),
DriveChannel(0),
name='drag_86a8'
)
),
name="circuit-87"
),
name='circuit-87'
),
name="block7",
transform=AlignLeft()
)
.. warning::
Calling a circuit from a schedule is not encouraged. Currently, the Qiskit execution model
is migrating toward the pulse gate model, where schedules are attached to
circuits through the :meth:`.QuantumCircuit.add_calibration` method.
Args:
target: Target circuit or pulse schedule to call.
name: Optional. A unique name of subroutine if defined. When the name is explicitly
provided, one cannot call different schedule blocks with the same name.
value_dict: Optional. Parameters assigned to the ``target`` program.
If this dictionary is provided, the ``target`` program is copied and
then stored in the main built schedule and its parameters are assigned to the given values.
This dictionary is keyed on :class:`~.Parameter` objects,
allowing parameter name collision to be avoided.
kw_params: Alternative way to provide parameters.
Since this is keyed on the string parameter name,
the parameters having the same name are all updated together.
If you want to avoid name collision, use ``value_dict`` with :class:`~.Parameter`
objects instead.
"""
_active_builder().call_subroutine(target, name, value_dict, **kw_params)
def reference(name: str, *extra_keys: str):
"""Refer to undefined subroutine by string keys.
A :class:`~qiskit.pulse.instructions.Reference` instruction is implicitly created
and a schedule can be separately registered to the reference at a later stage.
.. code-block:: python
from qiskit import pulse
with pulse.build() as main_prog:
pulse.reference("x_gate", "q0")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
main_prog.assign_references(subroutine_dict={("x_gate", "q0"): subroutine})
Args:
name: Name of subroutine.
extra_keys: Helper keys to uniquely specify the subroutine.
"""
_active_builder().append_reference(name, *extra_keys)
# Directives
def barrier(*channels_or_qubits: Union[chans.Channel, int], name: Optional[str] = None):
"""Barrier directive for a set of channels and qubits.
This directive prevents the compiler from moving instructions across
the barrier. Consider the case where we want to enforce that one pulse
happens after another on separate channels, this can be done with:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build(backend) as barrier_pulse_prog:
pulse.play(pulse.Constant(10, 1.0), d0)
pulse.barrier(d0, d1)
pulse.play(pulse.Constant(10, 1.0), d1)
Of course this could have been accomplished with:
.. code-block::
from qiskit.pulse import transforms
with pulse.build(backend) as aligned_pulse_prog:
with pulse.align_sequential():
pulse.play(pulse.Constant(10, 1.0), d0)
pulse.play(pulse.Constant(10, 1.0), d1)
barrier_pulse_prog = transforms.target_qobj_transform(barrier_pulse_prog)
aligned_pulse_prog = transforms.target_qobj_transform(aligned_pulse_prog)
assert barrier_pulse_prog == aligned_pulse_prog
The barrier allows the pulse compiler to take care of more advanced
scheduling alignment operations across channels. For example
in the case where we are calling an outside circuit or schedule and
want to align a pulse at the end of one call:
.. code-block::
import math
d0 = pulse.DriveChannel(0)
with pulse.build(backend) as pulse_prog:
with pulse.align_right():
pulse.x(1)
# Barrier qubit 1 and d0.
pulse.barrier(1, d0)
# Due to barrier this will play before the gate on qubit 1.
pulse.play(pulse.Constant(10, 1.0), d0)
# This will end at the same time as the pulse above due to
# the barrier.
pulse.x(1)
.. note:: Requires the active builder context to have a backend set if
qubits are barriered on.
Args:
channels_or_qubits: Channels or qubits to barrier.
name: Name for the barrier
"""
channels = _qubits_to_channels(*channels_or_qubits)
if len(channels) > 1:
append_instruction(directives.RelativeBarrier(*channels, name=name))
# Macros
def macro(func: Callable):
"""Wrap a Python function and activate the parent builder context at calling time.
This enables embedding Python functions as builder macros. This generates a new
:class:`pulse.Schedule` that is embedded in the parent builder context with
every call of the decorated macro function. The decorated macro function will
behave as if the function code was embedded inline in the parent builder context
after parameter substitution.
Examples:
.. plot::
:include-source:
from qiskit import pulse
@pulse.macro
def measure(qubit: int):
pulse.play(pulse.GaussianSquare(16384, 256, 15872), pulse.measure_channel(qubit))
mem_slot = pulse.MemorySlot(qubit)
pulse.acquire(16384, pulse.acquire_channel(qubit), mem_slot)
return mem_slot
with pulse.build(backend=backend) as sched:
mem_slot = measure(0)
print(f"Qubit measured into {mem_slot}")
sched.draw()
Args:
func: The Python function to enable as a builder macro. There are no
requirements on the signature of the function, any calls to pulse
builder methods will be added to builder context the wrapped function
is called from.
Returns:
Callable: The wrapped ``func``.
"""
func_name = getattr(func, "__name__", repr(func))
@functools.wraps(func)
def wrapper(*args, **kwargs):
_builder = _active_builder()
# activate the pulse builder before calling the function
with build(backend=_builder.backend, name=func_name) as built:
output = func(*args, **kwargs)
_builder.call_subroutine(built)
return output
return wrapper
def measure(
qubits: Union[List[int], int],
registers: Union[List[StorageLocation], StorageLocation] = None,
) -> Union[List[StorageLocation], StorageLocation]:
"""Measure a qubit within the currently active builder context.
At the pulse level a measurement is composed of both a stimulus pulse and
an acquisition instruction which tells the systems measurement unit to
acquire data and process it. We provide this measurement macro to automate
the process for you, but if desired full control is still available with
:func:`acquire` and :func:`play`.
To use the measurement it is as simple as specifying the qubit you wish to
measure:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
qubit = 0
with pulse.build(backend) as pulse_prog:
# Do something to the qubit.
qubit_drive_chan = pulse.drive_channel(0)
pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan)
# Measure the qubit.
reg = pulse.measure(qubit)
For now it is not possible to do much with the handle to ``reg`` but in the
future we will support using this handle to a result register to build
up ones program. It is also possible to supply this register:
.. code-block::
with pulse.build(backend) as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan)
# Measure the qubit.
mem0 = pulse.MemorySlot(0)
reg = pulse.measure(qubit, mem0)
assert reg == mem0
.. note:: Requires the active builder context to have a backend set.
Args:
qubits: Physical qubit to measure.
registers: Register to store result in. If not selected the current
behavior is to return the :class:`MemorySlot` with the same
index as ``qubit``. This register will be returned.
Returns:
The ``register`` the qubit measurement result will be stored in.
"""
backend = active_backend()
try:
qubits = list(qubits)
except TypeError:
qubits = [qubits]
if registers is None:
registers = [chans.MemorySlot(qubit) for qubit in qubits]
else:
try:
registers = list(registers)
except TypeError:
registers = [registers]
measure_sched = macros.measure(
qubits=qubits,
backend=backend,
qubit_mem_slots={qubit: register.index for qubit, register in zip(qubits, registers)},
)
# note this is not a subroutine.
# just a macro to automate combination of stimulus and acquisition.
# prepare unique reference name based on qubit and memory slot index.
qubits_repr = "&".join(map(str, qubits))
mslots_repr = "&".join((str(r.index) for r in registers))
_active_builder().call_subroutine(measure_sched, name=f"measure_{qubits_repr}..{mslots_repr}")
if len(qubits) == 1:
return registers[0]
else:
return registers
def measure_all() -> List[chans.MemorySlot]:
r"""Measure all qubits within the currently active builder context.
A simple macro function to measure all of the qubits in the device at the
same time. This is useful for handling device ``meas_map`` and single
measurement constraints.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
# Measure all qubits and return associated registers.
regs = pulse.measure_all()
.. note::
Requires the active builder context to have a backend set.
Returns:
The ``register``\s the qubit measurement results will be stored in.
"""
backend = active_backend()
qubits = range(num_qubits())
registers = [chans.MemorySlot(qubit) for qubit in qubits]
measure_sched = macros.measure(
qubits=qubits,
backend=backend,
qubit_mem_slots={qubit: qubit for qubit in qubits},
)
# note this is not a subroutine.
# just a macro to automate combination of stimulus and acquisition.
_active_builder().call_subroutine(measure_sched, name="measure_all")
return registers
def delay_qubits(duration: int, *qubits: Union[int, Iterable[int]]):
r"""Insert delays on all of the :class:`channels.Channel`\s that correspond
to the input ``qubits`` at the same time.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
with pulse.build(backend) as pulse_prog:
# Delay for 100 cycles on qubits 0, 1 and 2.
regs = pulse.delay_qubits(100, 0, 1, 2)
.. note:: Requires the active builder context to have a backend set.
Args:
duration: Duration to delay for.
qubits: Physical qubits to delay on. Delays will be inserted based on
the channels returned by :func:`pulse.qubit_channels`.
"""
qubit_chans = set(itertools.chain.from_iterable(qubit_channels(qubit) for qubit in qubits))
with align_left():
for chan in qubit_chans:
delay(duration, chan)
# Gate instructions
def call_gate(gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True):
"""Call a gate and lazily schedule it to its corresponding
pulse instruction.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.pulse import builder
from qiskit.circuit.library import standard_gates as gates
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
builder.call_gate(gates.CXGate(), (0, 1))
We can see the role of the transpiler in scheduling gates by optimizing
away two consecutive CNOT gates:
.. code-block::
with pulse.build(backend) as pulse_prog:
with pulse.transpiler_settings(optimization_level=3):
builder.call_gate(gates.CXGate(), (0, 1))
builder.call_gate(gates.CXGate(), (0, 1))
assert pulse_prog == pulse.Schedule()
.. note:: If multiple gates are called in a row they may be optimized by
the transpiler, depending on the
:func:`pulse.active_transpiler_settings``.
.. note:: Requires the active builder context to have a backend set.
Args:
gate: Circuit gate instance to call.
qubits: Qubits to call gate on.
lazy: If ``false`` the gate will be compiled immediately, otherwise
it will be added onto a lazily evaluated quantum circuit to be
compiled when the builder is forced to by a circuit assumption
being broken, such as the inclusion of a pulse instruction or
new alignment context.
"""
_active_builder().call_gate(gate, qubits, lazy=lazy)
def cx(control: int, target: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.CXGate` on the
input physical qubits.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.cx(0, 1)
"""
call_gate(gates.CXGate(), (control, target))
def u1(theta: float, qubit: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.U1Gate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.u1(math.pi, 1)
"""
call_gate(gates.U1Gate(theta), qubit)
def u2(phi: float, lam: float, qubit: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.U2Gate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.u2(0, math.pi, 1)
"""
call_gate(gates.U2Gate(phi, lam), qubit)
def u3(theta: float, phi: float, lam: float, qubit: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.U3Gate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.u3(math.pi, 0, math.pi, 1)
"""
call_gate(gates.U3Gate(theta, phi, lam), qubit)
def x(qubit: int):
"""Call a :class:`~qiskit.circuit.library.standard_gates.XGate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.x(0)
"""
call_gate(gates.XGate(), qubit)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit.utils import algorithm_globals
from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.applications.vertex_cover import VertexCover
import networkx as nx
seed = 123
algorithm_globals.random_seed = seed
graph = nx.random_regular_graph(d=3, n=6, seed=seed)
pos = nx.spring_layout(graph, seed=seed)
prob = VertexCover(graph)
prob.draw(pos=pos)
qp = prob.to_quadratic_program()
print(qp.prettyprint())
# Numpy Eigensolver
meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver())
result = meo.solve(qp)
print(result.prettyprint())
print("\nsolution:", prob.interpret(result))
prob.draw(result, pos=pos)
# QAOA
meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, sampler=Sampler(), optimizer=COBYLA()))
result = meo.solve(qp)
print(result.prettyprint())
print("\nsolution:", prob.interpret(result))
print("\ntime:", result.min_eigen_solver_result.optimizer_time)
prob.draw(result, pos=pos)
from qiskit_optimization.applications import Knapsack
prob = Knapsack(values=[3, 4, 5, 6, 7], weights=[2, 3, 4, 5, 6], max_weight=10)
qp = prob.to_quadratic_program()
print(qp.prettyprint())
# Numpy Eigensolver
meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver())
result = meo.solve(qp)
print(result.prettyprint())
print("\nsolution:", prob.interpret(result))
# QAOA
meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, sampler=Sampler(), optimizer=COBYLA()))
result = meo.solve(qp)
print(result.prettyprint())
print("\nsolution:", prob.interpret(result))
print("\ntime:", result.min_eigen_solver_result.optimizer_time)
from qiskit_optimization.converters import QuadraticProgramToQubo
# the same knapsack problem instance as in the previous section
prob = Knapsack(values=[3, 4, 5, 6, 7], weights=[2, 3, 4, 5, 6], max_weight=10)
qp = prob.to_quadratic_program()
print(qp.prettyprint())
# intermediate QUBO form of the optimization problem
conv = QuadraticProgramToQubo()
qubo = conv.convert(qp)
print(qubo.prettyprint())
# qubit Hamiltonian and offset
op, offset = qubo.to_ising()
print(f"num qubits: {op.num_qubits}, offset: {offset}\n")
print(op)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
# of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
"""Progress bars module"""
import time
import datetime
import sys
from qiskit.tools.events.pubsub import Subscriber
class BaseProgressBar(Subscriber):
"""An abstract progress bar with some shared functionality."""
def __init__(self):
super().__init__()
self.type = "progressbar"
self.touched = False
self.iter = None
self.t_start = None
self.t_done = None
def start(self, iterations):
"""Start the progress bar.
Parameters:
iterations (int): Number of iterations.
"""
self.touched = True
self.iter = int(iterations)
self.t_start = time.time()
def update(self, n):
"""Update status of progress bar."""
pass
def time_elapsed(self):
"""Return the time elapsed since start.
Returns:
elapsed_time: Time since progress bar started.
"""
return "%6.2fs" % (time.time() - self.t_start)
def time_remaining_est(self, completed_iter):
"""Estimate the remaining time left.
Parameters:
completed_iter (int): Number of iterations completed.
Returns:
est_time: Estimated time remaining.
"""
if completed_iter:
t_r_est = (time.time() - self.t_start) / completed_iter * (self.iter - completed_iter)
else:
t_r_est = 0
date_time = datetime.datetime(1, 1, 1) + datetime.timedelta(seconds=t_r_est)
time_string = "%02d:%02d:%02d:%02d" % (
date_time.day - 1,
date_time.hour,
date_time.minute,
date_time.second,
)
return time_string
def finished(self):
"""Run when progress bar has completed."""
pass
class TextProgressBar(BaseProgressBar):
"""
A simple text-based progress bar.
output_handler : the handler the progress bar should be written to, default
is sys.stdout, another option is sys.stderr
Examples:
The progress bar can be used to track the progress of a `parallel_map`.
.. code-block:: python
import numpy as np
import qiskit.tools.jupyter
from qiskit.tools.parallel import parallel_map
from qiskit.tools.events import TextProgressBar
TextProgressBar()
%qiskit_progress_bar -t text
parallel_map(np.sin, np.linspace(0,10,100));
And it can also be used individually.
.. code-block:: python
from qiskit.tools.events import TextProgressBar
iterations = 100
t = TextProgressBar()
t.start(iterations=iterations)
for i in range(iterations):
# step i of heavy calculation ...
t.update(i + 1) # update progress bar
"""
def __init__(self, output_handler=None):
super().__init__()
self._init_subscriber()
self.output_handler = output_handler if output_handler else sys.stdout
def _init_subscriber(self):
def _initialize_progress_bar(num_tasks):
self.start(num_tasks)
self.subscribe("terra.parallel.start", _initialize_progress_bar)
def _update_progress_bar(progress):
self.update(progress)
self.subscribe("terra.parallel.done", _update_progress_bar)
def _finish_progress_bar():
self.unsubscribe("terra.parallel.start", _initialize_progress_bar)
self.unsubscribe("terra.parallel.done", _update_progress_bar)
self.unsubscribe("terra.parallel.finish", _finish_progress_bar)
self.finished()
self.subscribe("terra.parallel.finish", _finish_progress_bar)
def start(self, iterations):
self.touched = True
self.iter = int(iterations)
self.t_start = time.time()
pbar = "-" * 50
self.output_handler.write("\r|{}| {}{}{} [{}]".format(pbar, 0, "/", self.iter, ""))
def update(self, n):
# Don't update if we are not initialized or
# the update iteration number is greater than the total iterations set on start.
if not self.touched or n > self.iter:
return
filled_length = int(round(50 * n / self.iter))
pbar = "█" * filled_length + "-" * (50 - filled_length)
time_left = self.time_remaining_est(n)
self.output_handler.write("\r|{}| {}{}{} [{}]".format(pbar, n, "/", self.iter, time_left))
if n == self.iter:
self.output_handler.write("\n")
self.output_handler.flush()
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 2量子ビット回路を用意
q = QuantumCircuit(2,2) # 2量子ビット回路と2ビットの古典レジスターを用意します。
# 回路を描画
q.draw(output="mpl")
# q0, q1が0の場合
q.cx(0,1) # CNOTゲートの制御ゲートをq0、目標ゲートをq1にセットします。
# 回路を描画
q.draw(output="mpl")
## First, simulate the circuit
## 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q, vector_sim )
result = job.result().get_statevector(q, decimals=3)
print(result)
# 2量子ビット回路を用意
q1 = QuantumCircuit(2,2) # 2量子ビット回路と2ビットの古典レジスターを用意します。
# 回路を描画
q1.draw(output="mpl")
# q0=1, q1=0の場合
q1.x(0) # q0を1にします。
q1.cx(0,1) # CNOTゲートの制御ゲートをq0、目標ゲートをq1にセットします。
# 回路を描画
q1.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q1, vector_sim )
result = job.result().get_statevector(q1, decimals=3)
print(result)
# 回路を測定
q1.measure(0,0)
q1.measure(1,1)
# 回路を描画
q1.draw(output="mpl")
# QASMシミュレーターで実験
simulator = Aer.get_backend('qasm_simulator')
job = execute(q1, backend=simulator, shots=1024)
result = job.result()
# 測定された回数を表示
counts = result.get_counts(q1)
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXDebugging(), backend=FakeBoeblingen())
|
https://github.com/Bikramaditya0154/Quantum-Simulation-of-the-ground-states-of-Li-and-Li-2-using-Variational-Quantum-EIgensolver
|
Bikramaditya0154
|
from qiskit import Aer
from qiskit_nature.drivers import UnitsType, Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureDriverType,
ElectronicStructureMoleculeDriver,
)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
molecule = Molecule(
geometry=[["Li", [0.0, 0.0, 0.0]]], charge=2, multiplicity=2
)
driver = ElectronicStructureMoleculeDriver(
molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF
)
es_problem = ElectronicStructureProblem(driver)
qubit_converter = QubitConverter(JordanWignerMapper())
from qiskit.providers.aer import StatevectorSimulator
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms import VQEUCCFactory
quantum_instance = QuantumInstance(backend=Aer.get_backend("aer_simulator_statevector"))
vqe_solver = VQEUCCFactory(quantum_instance=quantum_instance)
from qiskit.algorithms import VQE
from qiskit.circuit.library import TwoLocal
tl_circuit = TwoLocal(
rotation_blocks=["h", "rx"],
entanglement_blocks="cz",
entanglement="full",
reps=2,
parameter_prefix="y",
)
another_solver = VQE(
ansatz=tl_circuit,
quantum_instance=QuantumInstance(Aer.get_backend("aer_simulator_statevector")),
)
from qiskit_nature.algorithms import GroundStateEigensolver
calc = GroundStateEigensolver(qubit_converter, vqe_solver)
res = calc.solve(es_problem)
print(res)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# If you introduce a list with less colors than bars, the color of the bars will
# alternate following the sequence from the list.
import numpy as np
from qiskit.quantum_info import DensityMatrix
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0, 1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
matrix = DensityMatrix(qc)
plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
#Program 2.1 Initialize qubit state
from qiskit import QuantumCircuit
import math
qc = QuantumCircuit(4)
qc.initialize([1,0],0)
qc.initialize([0,1],1)
qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)],2)
qc.initialize([1/math.sqrt(2), -1/math.sqrt(2)],3)
qc.draw('mpl')
#Program 2.2 Initialize qubit state and show Bloch sphere
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
import math
qc = QuantumCircuit(4)
qc.initialize([1,0],0)
qc.initialize([0,1],1)
qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)],2)
qc.initialize([1/math.sqrt(2), -1/math.sqrt(2)],3)
state = Statevector.from_instruction(qc)
display(qc.draw('mpl'))
display(state.draw('bloch'))
#Program 2.3 Show Bloch sphere
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
state = Statevector.from_instruction(qc)
plot_bloch_multivector(state)
#Program 2.4 Measure qubit state
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
qc = QuantumCircuit(4,4)
qc.initialize([1,0],0)
qc.initialize([1,0],1)
qc.initialize([0,1],2)
qc.initialize([0,1],3)
qc.measure([0,1,2,3],[0,1,2,3])
print(qc)
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
#Program 2.5 Measure qubit state again
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
import math
qc = QuantumCircuit(4,4)
qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)],0)
qc.initialize([1/math.sqrt(2), -1/math.sqrt(2)],1)
qc.initialize([1/math.sqrt(2), 1j/math.sqrt(2)],2)
qc.initialize([1/math.sqrt(2), -1j/math.sqrt(2)],3)
qc.measure([0,1,2,3],[0,1,2,3])
print(qc)
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
|
https://github.com/arnavdas88/QuGlassyIsing
|
arnavdas88
|
!pip install qiskit
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer import AerSimulator
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import EfficientSU2
# opflow is Qiskit's module for creating operators like yours
from qiskit import *
from qiskit.opflow import OperatorBase
from qiskit.opflow import Z, X, I # Pauli Z, X matrices and identity
import pylab
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
def run(B_X = 1, J_z = 1, B_Z = 1):
master_counts = []
master_values = []
# for h in range (1,5,1):
# h=+h
# Initialization
B_X = B_X
J_z = J_z
B_Z = B_Z
# or whatever value you have for h
#H = - B_X * ((X ^ I ^ I ^ I) + (I ^ X ^ I ^ I) + (I ^ I ^ X ^ I) + (I ^ I ^ I ^ X)) + J_z * ((Z ^ Z ^ I ^ I ) + (I ^ Z ^ Z ^ I) + (I ^ I ^ Z ^ Z) + (Z ^ I ^ I ^ Z)) - B_Z * ((Z ^ I ^ I ^ I) + (I ^ Z ^ I ^ I) + (I ^ I ^ Z ^ I ) + (I ^ I ^ I ^ Z))
# for 25 qubits
H = - 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ Z ^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COBYLA usually works well for small problems like this one
optimizer = COBYLA(maxiter=200)
# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library
#ansatz = EfficientSU2(4, reps=1)
# for 25 qubits
# ansatz = EfficientSU2(25, reps=1)
ansatz = TwoLocal(num_qubits=25, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)
# set the algorithm
vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)
# run it with the Hamiltonian we defined above
result = vqe.compute_minimum_eigenvalue(H)
# print the result (it contains lot's of information)
return result
result = run()
print(result)
print(result.optimal_value)
print(result.eigenvalue)
counts_values = {}
for i in range(0, 20, 1):
for j in range(0, 20, 1):
print(f"Running VQE for BX : {i/10} & BZ : {j/10}, \t\t Optimal Value : {result.optimal_value}")
counts = []
values = []
result = run(B_X = i/10, J_z = 1, B_Z = j/10)
# counts_values[f"BX_{i/10} BZ_{j/10}"] = {"counts": counts, "values": values}
counts_values[f"BX_{i/10} BZ_{j/10}"] = {'result': result}
import pickle
print("Saving Optimization History")
with open('optimization_data.pickle', 'wb') as handle:
pickle.dump(counts_values, handle, protocol=pickle.HIGHEST_PROTOCOL)
print("Loading Optimization History")
with open('optimization_data.pickle', 'rb') as handle:
counts_values = pickle.load(handle)
arr = []
for i in range(0, 20, 1):
r = []
for j in range(0, 20, 1):
cv = counts_values[f"BX_{i/10} BZ_{j/10}"]['result']
r += [cv.optimal_value]
arr += [r]
data = np.asarray(arr)
data.shape
X = np.asarray([ x for x in range(0, 20, 1) ])
Y = np.asarray([ y for y in range(-10, 10, 1) ])
Z = data
import numpy as np
import seaborn as sns
import matplotlib.pylab as plt
plt.imshow(Z, cmap='hot', interpolation='nearest')
plt.colorbar()
plt.show()
import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
nx, ny = 20, 20
x = range(nx)
y = range(ny)
hf = plt.figure()
ha = hf.add_subplot(111, projection='3d')
X, Y = numpy.meshgrid(x, y)
ha.plot_surface(X, Y, Z)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
x = np.arange(0,20)
y = np.arange(0,20)
xs, ys = np.meshgrid(x, y)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(xs, ys, Z, rstride=1, cstride=1, cmap='hot')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
# if using a Jupyter notebook, include:
%matplotlib inline
fig = plt.figure(figsize=(12, 6))
ax1 = fig.add_subplot(121, projection='3d')
ax2 = fig.add_subplot(122, projection='3d')
x = np.arange(0,20)
y = np.arange(0,20)
X,Y = np.meshgrid(x,y)
# Plot a basic wireframe
ax1.plot_wireframe(Y, X, Z, rstride=10, cstride=10, cmap='hot')
ax1.set_title('row step size 10, column step size 10')
ax2.plot_wireframe(Y, X, Z, rstride=20, cstride=20, cmap='hot')
ax2.set_title('row step size 20, column step size 20')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
# if using a Jupyter notebook, include:
%matplotlib inline
fig = plt.figure(figsize=(12, 4))
ax1 = fig.add_subplot(121, projection='3d')
ax2 = fig.add_subplot(122, projection='3d')
x = np.arange(0,20)
y = np.arange(0,20)
X,Y = np.meshgrid(x,y)
# Plot a basic wireframe
ax1.plot_surface(X, Y, Z, rstride=5, cstride=5, cmap='hot')
ax2.plot_surface(Y, X, Z, rstride=5, cstride=5, cmap='hot')
ax2.contourf(Y, X, Z, zdir='z', offset=np.min(Z), cmap=cm.ocean)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
# if using a Jupyter notebook, include:
%matplotlib inline
fig = plt.figure(figsize=(12, 4))
ax1 = fig.add_subplot(121, projection='3d')
ax2 = fig.add_subplot(122, projection='3d')
x = np.arange(0,20)
y = np.arange(0,20)
X,Y = np.meshgrid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I ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ X)
# )
|
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
|
mnp-club
|
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.compiler import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import matplotlib.pyplot as plotter
import scipy
import numpy as np
from IPython.display import display, Math, Latex
import qiskit.quantum_info as qi
%matplotlib inline
%pip install -I git+https://github.com/mnp-club/MnP_QC_Workshop.git
from mnp_qc_workshop_2020.unitary_circuit import *
U = get_unitary()
print(U.shape)
fig, (ax1, ax2) = plotter.subplots(nrows = 1, ncols = 2, figsize=(12,6))
ax1.imshow(np.real(U)) #plot real parts of each element
ax2.imshow(np.imag(U)) #plot imaginary parts of each element
fig, (ax3, ax4) = plotter.subplots(nrows = 1, ncols = 2, figsize=(12,6))
ax3.imshow(np.abs(U)) #plot the absolute values of each element
ax4.imshow(np.angle(U)) #plot the phase angles of each element
qc = QuantumCircuit(4)
qc.unitary(U, range(4))
matrix = qi.Operator(qc).data
print(matrix)
#
#
#Your code here
#
#
# qc = transpile(qc,basis_gates=['cx','u3'],optimization_level=3)
# qc.draw('mpl')
#Run this cell for getting your circuit checked
check_circuit(qc)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.drivers.second_quantization import GaussianForcesDriver
from qiskit_nature.problems.second_quantization import VibrationalStructureProblem
from qiskit_nature.settings import settings
settings.dict_aux_operators = True
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2)
# Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so:
second_q_ops = problem.second_q_ops()
hamiltonian = second_q_ops["VibrationalEnergy"]
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.second_q.drivers import GaussianForcesDriver
from qiskit_nature.second_q.problems import HarmonicBasis
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
basis = HarmonicBasis(num_modals=[2, 2, 3, 4])
# this is now done explicitly and already requires the basis
problem = driver.run(basis=basis)
problem.hamiltonian.truncation_order = 2
hamiltonian = problem.hamiltonian.second_q_op()
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.drivers.second_quantization import GaussianLogResult
from qiskit_nature.properties.second_quantization.vibrational.bases import HarmonicBasis
from qiskit_nature.settings import settings
settings.dict_aux_operators = True
log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log")
hamiltonian = log_result.get_vibrational_energy()
print(hamiltonian)
hamiltonian.basis = HarmonicBasis([2, 2, 3, 4])
op = hamiltonian.second_q_ops()["VibrationalEnergy"]
print("\n".join(str(op).splitlines()[:10] + ["..."]))
from qiskit_nature.second_q.drivers import GaussianLogResult
from qiskit_nature.second_q.formats import watson_to_problem
from qiskit_nature.second_q.problems import HarmonicBasis
log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log")
watson = log_result.get_watson_hamiltonian()
print(watson)
basis = HarmonicBasis(num_modals=[2, 2, 3, 4])
problem = watson_to_problem(watson, basis)
hamiltonian = problem.hamiltonian.second_q_op()
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.drivers.second_quantization import GaussianForcesDriver
from qiskit_nature.problems.second_quantization import VibrationalStructureProblem
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2)
# we trigger driver.run() implicitly like so:
second_q_ops = problem.second_q_ops()
hamiltonian_op = second_q_ops.pop("VibrationalEnergy")
aux_ops = second_q_ops
from qiskit_nature.second_q.drivers import GaussianForcesDriver
from qiskit_nature.second_q.problems import HarmonicBasis
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
basis = HarmonicBasis(num_modals=[2, 2, 3, 4])
problem = driver.run(basis=basis)
problem.hamiltonian.truncation_order = 2
hamiltonian_op, aux_ops = problem.second_q_ops()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### removed h gate ###
return qc
|
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/jacobwatkins1/rodeo-algorithm
|
jacobwatkins1
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Kraus, SuperOp
from qiskit.providers.aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
# Import from Qiskit Aer noise module
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise import QuantumError, ReadoutError
from qiskit.providers.aer.noise import pauli_error
from qiskit.providers.aer.noise import depolarizing_error
from qiskit.providers.aer.noise import thermal_relaxation_error
# Error probabilities
prob_1 = 0.01 # 1-qubit gate
prob_2 = 0.3 # 2-qubit gate
prob_b = 0.05 # 1-qubit gate for phase damping error.
# Depolarizing quantum errors
error_1 = noise.depolarizing_error(prob_1, 1)
error_2 = noise.depolarizing_error(prob_2, 2)
error_b = noise.phase_damping_error(prob_b)
# Add errors to noise model
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3'])
#noise_model.add_all_qubit_quantum_error(error_b, ['u1', 'u2', 'u3'])
noise_model.add_all_qubit_quantum_error(error_2, ['cx'])
# Get basis gates from noise model
basis_gates = noise_model.basis_gates
print(basis_gates)
# Make a circuit
circ = QuantumCircuit(3, 3)
circ.h(0)
circ.cx(0, 1)
circ.cx(1, 2)
circ.measure([0, 1, 2], [0, 1, 2])
# Perform a noise simulation
result = execute(circ, Aer.get_backend('qasm_simulator'),
basis_gates=basis_gates,
noise_model=noise_model).result()
counts = result.get_counts(0)
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 12345
from qiskit_machine_learning.datasets import ad_hoc_data
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=20,
test_size=5,
n=adhoc_dimension,
gap=0.3,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
import matplotlib.pyplot as plt
import numpy as np
def plot_features(ax, features, labels, class_label, marker, face, edge, label):
# A train plot
ax.scatter(
# x coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 0],
# y coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 1],
marker=marker,
facecolors=face,
edgecolors=edge,
label=label,
)
def plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total):
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
# A train plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "A train")
# B train plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B train")
# A test plot
plot_features(plt, test_features, test_labels, 0, "s", "b", "w", "A test")
# B test plot
plot_features(plt, test_features, test_labels, 1, "o", "r", "w", "B test")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset")
plt.show()
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
from qiskit.circuit.library import ZZFeatureMap
from qiskit.primitives import Sampler
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit_machine_learning.kernels import FidelityQuantumKernel
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
sampler = Sampler()
fidelity = ComputeUncompute(sampler=sampler)
adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map)
from sklearn.svm import SVC
adhoc_svc = SVC(kernel=adhoc_kernel.evaluate)
adhoc_svc.fit(train_features, train_labels)
adhoc_score_callable_function = adhoc_svc.score(test_features, test_labels)
print(f"Callable kernel classification test score: {adhoc_score_callable_function}")
adhoc_matrix_train = adhoc_kernel.evaluate(x_vec=train_features)
adhoc_matrix_test = adhoc_kernel.evaluate(x_vec=test_features, y_vec=train_features)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(
np.asmatrix(adhoc_matrix_train), interpolation="nearest", origin="upper", cmap="Blues"
)
axs[0].set_title("Ad hoc training kernel matrix")
axs[1].imshow(np.asmatrix(adhoc_matrix_test), interpolation="nearest", origin="upper", cmap="Reds")
axs[1].set_title("Ad hoc testing kernel matrix")
plt.show()
adhoc_svc = SVC(kernel="precomputed")
adhoc_svc.fit(adhoc_matrix_train, train_labels)
adhoc_score_precomputed_kernel = adhoc_svc.score(adhoc_matrix_test, test_labels)
print(f"Precomputed kernel classification test score: {adhoc_score_precomputed_kernel}")
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=adhoc_kernel)
qsvc.fit(train_features, train_labels)
qsvc_score = qsvc.score(test_features, test_labels)
print(f"QSVC classification test score: {qsvc_score}")
print(f"Classification Model | Accuracy Score")
print(f"---------------------------------------------------------")
print(f"SVC using kernel as a callable function | {adhoc_score_callable_function:10.2f}")
print(f"SVC using precomputed kernel matrix | {adhoc_score_precomputed_kernel:10.2f}")
print(f"QSVC | {qsvc_score:10.2f}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=0,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
# A label plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "B")
# B label plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for clustering")
plt.show()
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
adhoc_kernel = FidelityQuantumKernel(feature_map=adhoc_feature_map)
adhoc_matrix = adhoc_kernel.evaluate(x_vec=train_features)
plt.figure(figsize=(5, 5))
plt.imshow(np.asmatrix(adhoc_matrix), interpolation="nearest", origin="upper", cmap="Greens")
plt.title("Ad hoc clustering kernel matrix")
plt.show()
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score
adhoc_spectral = SpectralClustering(2, affinity="precomputed")
cluster_labels = adhoc_spectral.fit_predict(adhoc_matrix)
cluster_score = normalized_mutual_info_score(cluster_labels, train_labels)
print(f"Clustering score: {cluster_score}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=10,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement="linear")
qpca_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=feature_map)
matrix_train = qpca_kernel.evaluate(x_vec=train_features)
matrix_test = qpca_kernel.evaluate(x_vec=test_features, y_vec=test_features)
from sklearn.decomposition import KernelPCA
kernel_pca_rbf = KernelPCA(n_components=2, kernel="rbf")
kernel_pca_rbf.fit(train_features)
train_features_rbf = kernel_pca_rbf.transform(train_features)
test_features_rbf = kernel_pca_rbf.transform(test_features)
kernel_pca_q = KernelPCA(n_components=2, kernel="precomputed")
train_features_q = kernel_pca_q.fit_transform(matrix_train)
test_features_q = kernel_pca_q.fit_transform(matrix_test)
from sklearn.linear_model import LogisticRegression
logistic_regression = LogisticRegression()
logistic_regression.fit(train_features_q, train_labels)
logistic_score = logistic_regression.score(test_features_q, test_labels)
print(f"Logistic regression score: {logistic_score}")
fig, (q_ax, rbf_ax) = plt.subplots(1, 2, figsize=(10, 5))
plot_features(q_ax, train_features_q, train_labels, 0, "s", "w", "b", "A train")
plot_features(q_ax, train_features_q, train_labels, 1, "o", "w", "r", "B train")
plot_features(q_ax, test_features_q, test_labels, 0, "s", "b", "w", "A test")
plot_features(q_ax, test_features_q, test_labels, 1, "o", "r", "w", "A test")
q_ax.set_ylabel("Principal component #1")
q_ax.set_xlabel("Principal component #0")
q_ax.set_title("Projection of training and test data\n using KPCA with Quantum Kernel")
# Plotting the linear separation
h = 0.01 # step size in the mesh
# create a mesh to plot in
x_min, x_max = train_features_q[:, 0].min() - 1, train_features_q[:, 0].max() + 1
y_min, y_max = train_features_q[:, 1].min() - 1, train_features_q[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
predictions = logistic_regression.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
predictions = predictions.reshape(xx.shape)
q_ax.contourf(xx, yy, predictions, cmap=plt.cm.RdBu, alpha=0.2)
plot_features(rbf_ax, train_features_rbf, train_labels, 0, "s", "w", "b", "A train")
plot_features(rbf_ax, train_features_rbf, train_labels, 1, "o", "w", "r", "B train")
plot_features(rbf_ax, test_features_rbf, test_labels, 0, "s", "b", "w", "A test")
plot_features(rbf_ax, test_features_rbf, test_labels, 1, "o", "r", "w", "A test")
rbf_ax.set_ylabel("Principal component #1")
rbf_ax.set_xlabel("Principal component #0")
rbf_ax.set_title("Projection of training data\n using KernelPCA")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-docstring
import os
import configparser as cp
from uuid import uuid4
from unittest import mock
from qiskit import exceptions
from qiskit.test import QiskitTestCase
from qiskit import user_config
class TestUserConfig(QiskitTestCase):
def setUp(self):
super().setUp()
self.file_path = "test_%s.conf" % uuid4()
def test_empty_file_read(self):
config = user_config.UserConfig(self.file_path)
config.read_config_file()
self.assertEqual({}, config.settings)
def test_invalid_optimization_level(self):
test_config = """
[default]
transpile_optimization_level = 76
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file)
def test_invalid_circuit_drawer(self):
test_config = """
[default]
circuit_drawer = MSPaint
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file)
def test_circuit_drawer_valid(self):
test_config = """
[default]
circuit_drawer = latex
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
config.read_config_file()
self.assertEqual({"circuit_drawer": "latex"}, config.settings)
def test_invalid_circuit_reverse_bits(self):
test_config = """
[default]
circuit_reverse_bits = Neither
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file)
def test_circuit_reverse_bits_valid(self):
test_config = """
[default]
circuit_reverse_bits = false
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
config.read_config_file()
self.assertEqual({"circuit_reverse_bits": False}, config.settings)
def test_optimization_level_valid(self):
test_config = """
[default]
transpile_optimization_level = 1
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
config.read_config_file()
self.assertEqual({"transpile_optimization_level": 1}, config.settings)
def test_invalid_num_processes(self):
test_config = """
[default]
num_processes = -256
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file)
def test_valid_num_processes(self):
test_config = """
[default]
num_processes = 31
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
config.read_config_file()
self.assertEqual({"num_processes": 31}, config.settings)
def test_valid_parallel(self):
test_config = """
[default]
parallel = False
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
config.read_config_file()
self.assertEqual({"parallel_enabled": False}, config.settings)
def test_all_options_valid(self):
test_config = """
[default]
circuit_drawer = latex
circuit_mpl_style = default
circuit_mpl_style_path = ~:~/.qiskit
circuit_reverse_bits = false
transpile_optimization_level = 3
suppress_packaging_warnings = true
parallel = false
num_processes = 15
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
config.read_config_file()
self.assertEqual(
{
"circuit_drawer": "latex",
"circuit_mpl_style": "default",
"circuit_mpl_style_path": ["~", "~/.qiskit"],
"circuit_reverse_bits": False,
"transpile_optimization_level": 3,
"num_processes": 15,
"parallel_enabled": False,
},
config.settings,
)
def test_set_config_all_options_valid(self):
self.addCleanup(os.remove, self.file_path)
user_config.set_config("circuit_drawer", "latex", file_path=self.file_path)
user_config.set_config("circuit_mpl_style", "default", file_path=self.file_path)
user_config.set_config("circuit_mpl_style_path", "~:~/.qiskit", file_path=self.file_path)
user_config.set_config("circuit_reverse_bits", "false", file_path=self.file_path)
user_config.set_config("transpile_optimization_level", "3", file_path=self.file_path)
user_config.set_config("parallel", "false", file_path=self.file_path)
user_config.set_config("num_processes", "15", file_path=self.file_path)
config_settings = None
with mock.patch.dict(os.environ, {"QISKIT_SETTINGS": self.file_path}, clear=True):
config_settings = user_config.get_config()
self.assertEqual(
{
"circuit_drawer": "latex",
"circuit_mpl_style": "default",
"circuit_mpl_style_path": ["~", "~/.qiskit"],
"circuit_reverse_bits": False,
"transpile_optimization_level": 3,
"num_processes": 15,
"parallel_enabled": False,
},
config_settings,
)
def test_set_config_multiple_sections(self):
self.addCleanup(os.remove, self.file_path)
user_config.set_config("circuit_drawer", "latex", file_path=self.file_path)
user_config.set_config("circuit_mpl_style", "default", file_path=self.file_path)
user_config.set_config("transpile_optimization_level", "3", file_path=self.file_path)
user_config.set_config("circuit_drawer", "latex", section="test", file_path=self.file_path)
user_config.set_config("parallel", "false", section="test", file_path=self.file_path)
user_config.set_config("num_processes", "15", section="test", file_path=self.file_path)
config = cp.ConfigParser()
config.read(self.file_path)
self.assertEqual(config.sections(), ["default", "test"])
self.assertEqual(
{
"circuit_drawer": "latex",
"circuit_mpl_style": "default",
"transpile_optimization_level": "3",
},
dict(config.items("default")),
)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms.optimizers import SLSQP
ansatz = TwoLocal(3, rotation_blocks=["ry", "rz"], entanglement_blocks="cz", reps=1)
optimizer = SLSQP()
ansatz.decompose().draw('mpl')
from qiskit.primitives import Sampler, Estimator
from qiskit.algorithms.state_fidelities import ComputeUncompute
estimator = Estimator()
sampler = Sampler()
fidelity = ComputeUncompute(sampler)
k = 3
betas = [33, 33, 33]
counts = []
values = []
steps = []
def callback(eval_count, params, value, meta, step):
counts.append(eval_count)
values.append(value)
steps.append(step)
from qiskit.algorithms.eigensolvers import VQD
vqd = VQD(estimator, fidelity, ansatz, optimizer, k=k, betas=betas, callback=callback)
result = vqd.compute_eigenvalues(operator = H2_op)
vqd_values = result.optimal_values
print(vqd_values)
import numpy as np
import pylab
pylab.rcParams["figure.figsize"] = (12, 8)
steps = np.asarray(steps)
counts = np.asarray(counts)
values = np.asarray(values)
for i in range(1,4):
_counts = counts[np.where(steps == i)]
_values = values[np.where(steps == i)]
pylab.plot(_counts, _values, label=f"State {i-1}")
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Energy convergence for each computed state")
pylab.legend(loc="upper right");
from qiskit.algorithms.eigensolvers import NumPyEigensolver
from qiskit.opflow import PauliSumOp
exact_solver = NumPyEigensolver(k=3)
exact_result = exact_solver.compute_eigenvalues(PauliSumOp(H2_op))
ref_values = exact_result.eigenvalues
print(f"Reference values: {ref_values}")
print(f"VQD values: {vqd_values}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 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=cyclic-import
"""
=========
Schedules
=========
.. currentmodule:: qiskit.pulse
Schedules are Pulse programs. They describe instruction sequences for the control hardware.
The Schedule is one of the most fundamental objects to this pulse-level programming module.
A ``Schedule`` is a representation of a *program* in Pulse. Each schedule tracks the time of each
instruction occuring in parallel over multiple signal *channels*.
.. autosummary::
:toctree: ../stubs/
Schedule
ScheduleBlock
"""
import abc
import copy
import functools
import itertools
import multiprocessing as mp
import re
import sys
import warnings
from typing import List, Tuple, Iterable, Union, Dict, Callable, Set, Optional, Any
import numpy as np
import rustworkx as rx
from qiskit.circuit.parameter import Parameter
from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType
from qiskit.pulse.channels import Channel
from qiskit.pulse.exceptions import PulseError, UnassignedReferenceError
from qiskit.pulse.instructions import Instruction, Reference
from qiskit.pulse.utils import instruction_duration_validation
from qiskit.pulse.reference_manager import ReferenceManager
from qiskit.utils.multiprocessing import is_main_process
Interval = Tuple[int, int]
"""An interval type is a tuple of a start time (inclusive) and an end time (exclusive)."""
TimeSlots = Dict[Channel, List[Interval]]
"""List of timeslots occupied by instructions for each channel."""
class Schedule:
"""A quantum program *schedule* with exact time constraints for its instructions, operating
over all input signal *channels* and supporting special syntaxes for building.
Pulse program representation for the original Qiskit Pulse model [1].
Instructions are not allowed to overlap in time
on the same channel. This overlap constraint is immediately
evaluated when a new instruction is added to the ``Schedule`` object.
It is necessary to specify the absolute start time and duration
for each instruction so as to deterministically fix its execution time.
The ``Schedule`` program supports some syntax sugar for easier programming.
- Appending an instruction to the end of a channel
.. code-block:: python
sched = Schedule()
sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0))
- Appending an instruction shifted in time by a given amount
.. code-block:: python
sched = Schedule()
sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) << 30
- Merge two schedules
.. code-block:: python
sched1 = Schedule()
sched1 += Play(Gaussian(160, 0.1, 40), DriveChannel(0))
sched2 = Schedule()
sched2 += Play(Gaussian(160, 0.1, 40), DriveChannel(1))
sched2 = sched1 | sched2
A :obj:`.PulseError` is immediately raised when the overlap constraint is violated.
In the schedule representation, we cannot parametrize the duration of instructions.
Thus we need to create a new schedule object for each duration.
To parametrize an instruction's duration, the :class:`~qiskit.pulse.ScheduleBlock`
representation may be used instead.
References:
[1]: https://arxiv.org/abs/2004.06755
"""
# Prefix to use for auto naming.
prefix = "sched"
# Counter to count instance number.
instances_counter = itertools.count()
def __init__(
self,
*schedules: Union["ScheduleComponent", Tuple[int, "ScheduleComponent"]],
name: Optional[str] = None,
metadata: Optional[dict] = None,
):
"""Create an empty schedule.
Args:
*schedules: Child Schedules of this parent Schedule. May either be passed as
the list of schedules, or a list of ``(start_time, schedule)`` pairs.
name: Name of this schedule. Defaults to an autogenerated string if not provided.
metadata: Arbitrary key value metadata to associate with the schedule. This gets
stored as free-form data in a dict in the
:attr:`~qiskit.pulse.Schedule.metadata` attribute. It will not be directly
used in the schedule.
Raises:
TypeError: if metadata is not a dict.
"""
from qiskit.pulse.parameter_manager import ParameterManager
if name is None:
name = self.prefix + str(next(self.instances_counter))
if sys.platform != "win32" and not is_main_process():
name += f"-{mp.current_process().pid}"
self._name = name
self._parameter_manager = ParameterManager()
if not isinstance(metadata, dict) and metadata is not None:
raise TypeError("Only a dictionary or None is accepted for schedule metadata")
self._metadata = metadata or {}
self._duration = 0
# These attributes are populated by ``_mutable_insert``
self._timeslots = {}
self._children = []
for sched_pair in schedules:
try:
time, sched = sched_pair
except TypeError:
# recreate as sequence starting at 0.
time, sched = 0, sched_pair
self._mutable_insert(time, sched)
@classmethod
def initialize_from(cls, other_program: Any, name: Optional[str] = None) -> "Schedule":
"""Create new schedule object with metadata of another schedule object.
Args:
other_program: Qiskit program that provides metadata to new object.
name: Name of new schedule. Name of ``schedule`` is used by default.
Returns:
New schedule object with name and metadata.
Raises:
PulseError: When `other_program` does not provide necessary information.
"""
try:
name = name or other_program.name
if other_program.metadata:
metadata = other_program.metadata.copy()
else:
metadata = None
return cls(name=name, metadata=metadata)
except AttributeError as ex:
raise PulseError(
f"{cls.__name__} cannot be initialized from the program data "
f"{other_program.__class__.__name__}."
) from ex
@property
def name(self) -> str:
"""Name of this Schedule"""
return self._name
@property
def metadata(self) -> Dict[str, Any]:
"""The user provided metadata associated with the schedule.
User provided ``dict`` of metadata for the schedule.
The metadata contents do not affect the semantics of the program
but are used to influence the execution of the schedule. It is expected
to be passed between all transforms of the schedule and that providers
will associate any schedule metadata with the results it returns from the
execution of that schedule.
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Update the schedule metadata"""
if not isinstance(metadata, dict) and metadata is not None:
raise TypeError("Only a dictionary or None is accepted for schedule metadata")
self._metadata = metadata or {}
@property
def timeslots(self) -> TimeSlots:
"""Time keeping attribute."""
return self._timeslots
@property
def duration(self) -> int:
"""Duration of this schedule."""
return self._duration
@property
def start_time(self) -> int:
"""Starting time of this schedule."""
return self.ch_start_time(*self.channels)
@property
def stop_time(self) -> int:
"""Stopping time of this schedule."""
return self.duration
@property
def channels(self) -> Tuple[Channel]:
"""Returns channels that this schedule uses."""
return tuple(self._timeslots.keys())
@property
def children(self) -> Tuple[Tuple[int, "ScheduleComponent"], ...]:
"""Return the child schedule components of this ``Schedule`` in the
order they were added to the schedule.
Notes:
Nested schedules are returned as-is. If you want to collect only instructions,
use py:meth:`~Schedule.instructions` instead.
Returns:
A tuple, where each element is a two-tuple containing the initial
scheduled time of each ``NamedValue`` and the component
itself.
"""
return tuple(self._children)
@property
def instructions(self) -> Tuple[Tuple[int, Instruction]]:
"""Get the time-ordered instructions from self."""
def key(time_inst_pair):
inst = time_inst_pair[1]
return time_inst_pair[0], inst.duration, sorted(chan.name for chan in inst.channels)
return tuple(sorted(self._instructions(), key=key))
@property
def parameters(self) -> Set:
"""Parameters which determine the schedule behavior."""
return self._parameter_manager.parameters
def ch_duration(self, *channels: Channel) -> int:
"""Return the time of the end of the last instruction over the supplied channels.
Args:
*channels: Channels within ``self`` to include.
"""
return self.ch_stop_time(*channels)
def ch_start_time(self, *channels: Channel) -> int:
"""Return the time of the start of the first instruction over the supplied channels.
Args:
*channels: Channels within ``self`` to include.
"""
try:
chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots)
return min(intervals[0][0] for intervals in chan_intervals)
except ValueError:
# If there are no instructions over channels
return 0
def ch_stop_time(self, *channels: Channel) -> int:
"""Return maximum start time over supplied channels.
Args:
*channels: Channels within ``self`` to include.
"""
try:
chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots)
return max(intervals[-1][1] for intervals in chan_intervals)
except ValueError:
# If there are no instructions over channels
return 0
def _instructions(self, time: int = 0):
"""Iterable for flattening Schedule tree.
Args:
time: Shifted time due to parent.
Yields:
Iterable[Tuple[int, Instruction]]: Tuple containing the time each
:class:`~qiskit.pulse.Instruction`
starts at and the flattened :class:`~qiskit.pulse.Instruction` s.
"""
for insert_time, child_sched in self.children:
yield from child_sched._instructions(time + insert_time)
def shift(self, time: int, name: Optional[str] = None, inplace: bool = False) -> "Schedule":
"""Return a schedule shifted forward by ``time``.
Args:
time: Time to shift by.
name: Name of the new schedule. Defaults to the name of self.
inplace: Perform operation inplace on this schedule. Otherwise
return a new ``Schedule``.
"""
if inplace:
return self._mutable_shift(time)
return self._immutable_shift(time, name=name)
def _immutable_shift(self, time: int, name: Optional[str] = None) -> "Schedule":
"""Return a new schedule shifted forward by `time`.
Args:
time: Time to shift by
name: Name of the new schedule if call was mutable. Defaults to name of self
"""
shift_sched = Schedule.initialize_from(self, name)
shift_sched.insert(time, self, inplace=True)
return shift_sched
def _mutable_shift(self, time: int) -> "Schedule":
"""Return this schedule shifted forward by `time`.
Args:
time: Time to shift by
Raises:
PulseError: if ``time`` is not an integer.
"""
if not isinstance(time, int):
raise PulseError("Schedule start time must be an integer.")
timeslots = {}
for chan, ch_timeslots in self._timeslots.items():
timeslots[chan] = [(ts[0] + time, ts[1] + time) for ts in ch_timeslots]
_check_nonnegative_timeslot(timeslots)
self._duration = self._duration + time
self._timeslots = timeslots
self._children = [(orig_time + time, child) for orig_time, child in self.children]
return self
def insert(
self,
start_time: int,
schedule: "ScheduleComponent",
name: Optional[str] = None,
inplace: bool = False,
) -> "Schedule":
"""Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``.
Args:
start_time: Time to insert the schedule.
schedule: Schedule to insert.
name: Name of the new schedule. Defaults to the name of self.
inplace: Perform operation inplace on this schedule. Otherwise
return a new ``Schedule``.
"""
if inplace:
return self._mutable_insert(start_time, schedule)
return self._immutable_insert(start_time, schedule, name=name)
def _mutable_insert(self, start_time: int, schedule: "ScheduleComponent") -> "Schedule":
"""Mutably insert `schedule` into `self` at `start_time`.
Args:
start_time: Time to insert the second schedule.
schedule: Schedule to mutably insert.
"""
self._add_timeslots(start_time, schedule)
self._children.append((start_time, schedule))
self._parameter_manager.update_parameter_table(schedule)
return self
def _immutable_insert(
self,
start_time: int,
schedule: "ScheduleComponent",
name: Optional[str] = None,
) -> "Schedule":
"""Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``.
Args:
start_time: Time to insert the schedule.
schedule: Schedule to insert.
name: Name of the new ``Schedule``. Defaults to name of ``self``.
"""
new_sched = Schedule.initialize_from(self, name)
new_sched._mutable_insert(0, self)
new_sched._mutable_insert(start_time, schedule)
return new_sched
def append(
self, schedule: "ScheduleComponent", name: Optional[str] = None, inplace: bool = False
) -> "Schedule":
r"""Return a new schedule with ``schedule`` inserted at the maximum time over
all channels shared between ``self`` and ``schedule``.
.. math::
t = \textrm{max}(\texttt{x.stop_time} |\texttt{x} \in
\texttt{self.channels} \cap \texttt{schedule.channels})
Args:
schedule: Schedule to be appended.
name: Name of the new ``Schedule``. Defaults to name of ``self``.
inplace: Perform operation inplace on this schedule. Otherwise
return a new ``Schedule``.
"""
common_channels = set(self.channels) & set(schedule.channels)
time = self.ch_stop_time(*common_channels)
return self.insert(time, schedule, name=name, inplace=inplace)
def filter(
self,
*filter_funcs: Callable,
channels: Optional[Iterable[Channel]] = None,
instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None,
time_ranges: Optional[Iterable[Tuple[int, int]]] = None,
intervals: Optional[Iterable[Interval]] = None,
check_subroutine: bool = True,
) -> "Schedule":
"""Return a new ``Schedule`` with only the instructions from this ``Schedule`` which pass
though the provided filters; i.e. an instruction will be retained iff every function in
``filter_funcs`` returns ``True``, the instruction occurs on a channel type contained in
``channels``, the instruction type is contained in ``instruction_types``, and the period
over which the instruction operates is *fully* contained in one specified in
``time_ranges`` or ``intervals``.
If no arguments are provided, ``self`` is returned.
Args:
filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction])
tuple and return a bool.
channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``.
instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``.
time_ranges: For example, ``[(0, 5), (6, 10)]``.
intervals: For example, ``[(0, 5), (6, 10)]``.
check_subroutine: Set `True` to individually filter instructions inside of a subroutine
defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction.
"""
from qiskit.pulse.filters import composite_filter, filter_instructions
filters = composite_filter(channels, instruction_types, time_ranges, intervals)
filters.extend(filter_funcs)
return filter_instructions(
self, filters=filters, negate=False, recurse_subroutines=check_subroutine
)
def exclude(
self,
*filter_funcs: Callable,
channels: Optional[Iterable[Channel]] = None,
instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None,
time_ranges: Optional[Iterable[Tuple[int, int]]] = None,
intervals: Optional[Iterable[Interval]] = None,
check_subroutine: bool = True,
) -> "Schedule":
"""Return a ``Schedule`` with only the instructions from this Schedule *failing*
at least one of the provided filters.
This method is the complement of py:meth:`~self.filter`, so that::
self.filter(args) | self.exclude(args) == self
Args:
filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction])
tuple and return a bool.
channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``.
instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``.
time_ranges: For example, ``[(0, 5), (6, 10)]``.
intervals: For example, ``[(0, 5), (6, 10)]``.
check_subroutine: Set `True` to individually filter instructions inside of a subroutine
defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction.
"""
from qiskit.pulse.filters import composite_filter, filter_instructions
filters = composite_filter(channels, instruction_types, time_ranges, intervals)
filters.extend(filter_funcs)
return filter_instructions(
self, filters=filters, negate=True, recurse_subroutines=check_subroutine
)
def _add_timeslots(self, time: int, schedule: "ScheduleComponent") -> None:
"""Update all time tracking within this schedule based on the given schedule.
Args:
time: The time to insert the schedule into self.
schedule: The schedule to insert into self.
Raises:
PulseError: If timeslots overlap or an invalid start time is provided.
"""
if not np.issubdtype(type(time), np.integer):
raise PulseError("Schedule start time must be an integer.")
other_timeslots = _get_timeslots(schedule)
self._duration = max(self._duration, time + schedule.duration)
for channel in schedule.channels:
if channel not in self._timeslots:
if time == 0:
self._timeslots[channel] = copy.copy(other_timeslots[channel])
else:
self._timeslots[channel] = [
(i[0] + time, i[1] + time) for i in other_timeslots[channel]
]
continue
for idx, interval in enumerate(other_timeslots[channel]):
if interval[0] + time >= self._timeslots[channel][-1][1]:
# Can append the remaining intervals
self._timeslots[channel].extend(
[(i[0] + time, i[1] + time) for i in other_timeslots[channel][idx:]]
)
break
try:
interval = (interval[0] + time, interval[1] + time)
index = _find_insertion_index(self._timeslots[channel], interval)
self._timeslots[channel].insert(index, interval)
except PulseError as ex:
raise PulseError(
"Schedule(name='{new}') cannot be inserted into Schedule(name='{old}') at "
"time {time} because its instruction on channel {ch} scheduled from time "
"{t0} to {tf} overlaps with an existing instruction."
"".format(
new=schedule.name or "",
old=self.name or "",
time=time,
ch=channel,
t0=interval[0],
tf=interval[1],
)
) from ex
_check_nonnegative_timeslot(self._timeslots)
def _remove_timeslots(self, time: int, schedule: "ScheduleComponent"):
"""Delete the timeslots if present for the respective schedule component.
Args:
time: The time to remove the timeslots for the ``schedule`` component.
schedule: The schedule to insert into self.
Raises:
PulseError: If timeslots overlap or an invalid start time is provided.
"""
if not isinstance(time, int):
raise PulseError("Schedule start time must be an integer.")
for channel in schedule.channels:
if channel not in self._timeslots:
raise PulseError(f"The channel {channel} is not present in the schedule")
channel_timeslots = self._timeslots[channel]
other_timeslots = _get_timeslots(schedule)
for interval in other_timeslots[channel]:
if channel_timeslots:
interval = (interval[0] + time, interval[1] + time)
index = _interval_index(channel_timeslots, interval)
if channel_timeslots[index] == interval:
channel_timeslots.pop(index)
continue
raise PulseError(
"Cannot find interval ({t0}, {tf}) to remove from "
"channel {ch} in Schedule(name='{name}').".format(
ch=channel, t0=interval[0], tf=interval[1], name=schedule.name
)
)
if not channel_timeslots:
self._timeslots.pop(channel)
def _replace_timeslots(self, time: int, old: "ScheduleComponent", new: "ScheduleComponent"):
"""Replace the timeslots of ``old`` if present with the timeslots of ``new``.
Args:
time: The time to remove the timeslots for the ``schedule`` component.
old: Instruction to replace.
new: Instruction to replace with.
"""
self._remove_timeslots(time, old)
self._add_timeslots(time, new)
def _renew_timeslots(self):
"""Regenerate timeslots based on current instructions."""
self._timeslots.clear()
for t0, inst in self.instructions:
self._add_timeslots(t0, inst)
def replace(
self,
old: "ScheduleComponent",
new: "ScheduleComponent",
inplace: bool = False,
) -> "Schedule":
"""Return a ``Schedule`` with the ``old`` instruction replaced with a ``new``
instruction.
The replacement matching is based on an instruction equality check.
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
sched = pulse.Schedule()
old = pulse.Play(pulse.Constant(100, 1.0), d0)
new = pulse.Play(pulse.Constant(100, 0.1), d0)
sched += old
sched = sched.replace(old, new)
assert sched == pulse.Schedule(new)
Only matches at the top-level of the schedule tree. If you wish to
perform this replacement over all instructions in the schedule tree.
Flatten the schedule prior to running::
.. code-block::
sched = pulse.Schedule()
sched += pulse.Schedule(old)
sched = sched.flatten()
sched = sched.replace(old, new)
assert sched == pulse.Schedule(new)
Args:
old: Instruction to replace.
new: Instruction to replace with.
inplace: Replace instruction by mutably modifying this ``Schedule``.
Returns:
The modified schedule with ``old`` replaced by ``new``.
Raises:
PulseError: If the ``Schedule`` after replacements will has a timing overlap.
"""
from qiskit.pulse.parameter_manager import ParameterManager
new_children = []
new_parameters = ParameterManager()
for time, child in self.children:
if child == old:
new_children.append((time, new))
new_parameters.update_parameter_table(new)
else:
new_children.append((time, child))
new_parameters.update_parameter_table(child)
if inplace:
self._children = new_children
self._parameter_manager = new_parameters
self._renew_timeslots()
return self
else:
try:
new_sched = Schedule.initialize_from(self)
for time, inst in new_children:
new_sched.insert(time, inst, inplace=True)
return new_sched
except PulseError as err:
raise PulseError(
f"Replacement of {old} with {new} results in overlapping instructions."
) from err
def is_parameterized(self) -> bool:
"""Return True iff the instruction is parameterized."""
return self._parameter_manager.is_parameterized()
def assign_parameters(
self, value_dict: Dict[ParameterExpression, ParameterValueType], inplace: bool = True
) -> "Schedule":
"""Assign the parameters in this schedule according to the input.
Args:
value_dict: A mapping from Parameters to either numeric values or another
Parameter expression.
inplace: Set ``True`` to override this instance with new parameter.
Returns:
Schedule with updated parameters.
"""
if not inplace:
new_schedule = copy.deepcopy(self)
return new_schedule.assign_parameters(value_dict, inplace=True)
return self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict)
def get_parameters(self, parameter_name: str) -> List[Parameter]:
"""Get parameter object bound to this schedule by string name.
Because different ``Parameter`` objects can have the same name,
this method returns a list of ``Parameter`` s for the provided name.
Args:
parameter_name: Name of parameter.
Returns:
Parameter objects that have corresponding name.
"""
return self._parameter_manager.get_parameters(parameter_name)
def __len__(self) -> int:
"""Return number of instructions in the schedule."""
return len(self.instructions)
def __add__(self, other: "ScheduleComponent") -> "Schedule":
"""Return a new schedule with ``other`` inserted within ``self`` at ``start_time``."""
return self.append(other)
def __or__(self, other: "ScheduleComponent") -> "Schedule":
"""Return a new schedule which is the union of `self` and `other`."""
return self.insert(0, other)
def __lshift__(self, time: int) -> "Schedule":
"""Return a new schedule which is shifted forward by ``time``."""
return self.shift(time)
def __eq__(self, other: "ScheduleComponent") -> bool:
"""Test if two Schedule are equal.
Equality is checked by verifying there is an equal instruction at every time
in ``other`` for every instruction in this ``Schedule``.
.. warning::
This does not check for logical equivalency. Ie.,
```python
>>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0))
== Delay(20, DriveChannel(0))
False
```
"""
# 0. type check, we consider Instruction is a subtype of schedule
if not isinstance(other, (type(self), Instruction)):
return False
# 1. channel check
if set(self.channels) != set(other.channels):
return False
# 2. size check
if len(self.instructions) != len(other.instructions):
return False
# 3. instruction check
return all(
self_inst == other_inst
for self_inst, other_inst in zip(self.instructions, other.instructions)
)
def __repr__(self) -> str:
name = format(self._name) if self._name else ""
instructions = ", ".join([repr(instr) for instr in self.instructions[:50]])
if len(self.instructions) > 25:
instructions += ", ..."
return f'{self.__class__.__name__}({instructions}, name="{name}")'
def _require_schedule_conversion(function: Callable) -> Callable:
"""A method decorator to convert schedule block to pulse schedule.
This conversation is performed for backward compatibility only if all durations are assigned.
"""
@functools.wraps(function)
def wrapper(self, *args, **kwargs):
from qiskit.pulse.transforms import block_to_schedule
return function(block_to_schedule(self), *args, **kwargs)
return wrapper
class ScheduleBlock:
"""Time-ordered sequence of instructions with alignment context.
:class:`.ScheduleBlock` supports lazy scheduling of context instructions,
i.e. their timeslots is always generated at runtime.
This indicates we can parametrize instruction durations as well as
other parameters. In contrast to :class:`.Schedule` being somewhat static,
:class:`.ScheduleBlock` is a dynamic representation of a pulse program.
.. rubric:: Pulse Builder
The Qiskit pulse builder is a domain specific language that is developed on top of
the schedule block. Use of the builder syntax will improve the workflow of
pulse programming. See :ref:`pulse_builder` for a user guide.
.. rubric:: Alignment contexts
A schedule block is always relatively scheduled.
Instead of taking individual instructions with absolute execution time ``t0``,
the schedule block defines a context of scheduling and instructions
under the same context are scheduled in the same manner (alignment).
Several contexts are available in :ref:`pulse_alignments`.
A schedule block is instantiated with one of these alignment contexts.
The default context is :class:`AlignLeft`, for which all instructions are left-justified,
in other words, meaning they use as-soon-as-possible scheduling.
If you need an absolute-time interval in between instructions, you can explicitly
insert :class:`~qiskit.pulse.instructions.Delay` instructions.
.. rubric:: Nested blocks
A schedule block can contain other nested blocks with different alignment contexts.
This enables advanced scheduling, where a subset of instructions is
locally scheduled in a different manner.
Note that a :class:`.Schedule` instance cannot be directly added to a schedule block.
To add a :class:`.Schedule` instance, wrap it in a :class:`.Call` instruction.
This is implicitly performed when a schedule is added through the :ref:`pulse_builder`.
.. rubric:: Unsupported operations
Because the schedule block representation lacks timeslots, it cannot
perform particular :class:`.Schedule` operations such as :meth:`insert` or :meth:`shift` that
require instruction start time ``t0``.
In addition, :meth:`exclude` and :meth:`filter` methods are not supported
because these operations may identify the target instruction with ``t0``.
Except for these operations, :class:`.ScheduleBlock` provides full compatibility
with :class:`.Schedule`.
.. rubric:: Subroutine
The timeslots-free representation offers much greater flexibility for writing pulse programs.
Because :class:`.ScheduleBlock` only cares about the ordering of the child blocks
we can add an undefined pulse sequence as a subroutine of the main program.
If your program contains the same sequence multiple times, this representation may
reduce the memory footprint required by the program construction.
Such a subroutine is realized by the special compiler directive
:class:`~qiskit.pulse.instructions.Reference` that is defined by
a unique set of reference key strings to the subroutine.
The (executable) subroutine is separately stored in the main program.
Appended reference directives are resolved when the main program is executed.
Subroutines must be assigned through :meth:`assign_references` before execution.
.. rubric:: Program Scoping
When you call a subroutine from another subroutine, or append a schedule block
to another schedule block, the management of references and parameters
can be a hard task. Schedule block offers a convenient feature to help with this
by automatically scoping the parameters and subroutines.
.. code-block::
from qiskit import pulse
from qiskit.circuit.parameter import Parameter
amp1 = Parameter("amp")
with pulse.build() as sched1:
pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0))
print(sched1.scoped_parameters())
.. parsed-literal::
(Parameter(root::amp),)
The :meth:`~ScheduleBlock.scoped_parameters` method returns all :class:`~.Parameter`
objects defined in the schedule block. The parameter name is updated to reflect
its scope information, i.e. where it is defined.
The outer scope is called "root". Since the "amp" parameter is directly used
in the current builder context, it is prefixed with "root".
Note that the :class:`Parameter` object returned by :meth:`~ScheduleBlock.scoped_parameters`
preserves the hidden `UUID`_ key, and thus the scoped name doesn't break references
to the original :class:`Parameter`.
You may want to call this program from another program.
In this example, the program is called with the reference key "grand_child".
You can call a subroutine without specifying a substantial program
(like ``sched1`` above which we will assign later).
.. code-block::
amp2 = Parameter("amp")
with pulse.build() as sched2:
with pulse.align_right():
pulse.reference("grand_child")
pulse.play(pulse.Constant(200, amp2), pulse.DriveChannel(0))
print(sched2.scoped_parameters())
.. parsed-literal::
(Parameter(root::amp),)
This only returns "root::amp" because the "grand_child" reference is unknown.
Now you assign the actual pulse program to this reference.
.. code-block::
sched2.assign_references({("grand_child", ): sched1})
print(sched2.scoped_parameters())
.. parsed-literal::
(Parameter(root::amp), Parameter(root::grand_child::amp))
Now you get two parameters "root::amp" and "root::grand_child::amp".
The second parameter name indicates it is defined within the referred program "grand_child".
The program calling the "grand_child" has a reference program description
which is accessed through :attr:`ScheduleBlock.references`.
.. code-block::
print(sched2.references)
.. parsed-literal::
ReferenceManager:
- ('grand_child',): ScheduleBlock(Play(Constant(duration=100, amp=amp,...
Finally, you may want to call this program from another program.
Here we try a different approach to define subroutine. Namely, we call
a subroutine from the root program with the actual program ``sched2``.
.. code-block::
amp3 = Parameter("amp")
with pulse.build() as main:
pulse.play(pulse.Constant(300, amp3), pulse.DriveChannel(0))
pulse.call(sched2, name="child")
print(main.scoped_parameters())
.. parsed-literal::
(Parameter(root::amp), Parameter(root::child::amp), Parameter(root::child::grand_child::amp))
This implicitly creates a reference named "child" within
the root program and assigns ``sched2`` to it.
You get three parameters "root::amp", "root::child::amp", and "root::child::grand_child::amp".
As you can see, each parameter name reflects the layer of calls from the root program.
If you know the scope of a parameter, you can directly get the parameter object
using :meth:`ScheduleBlock.search_parameters` as follows.
.. code-block::
main.search_parameters("root::child::grand_child::amp")
You can use a regular expression to specify the scope.
The following returns the parameters defined within the scope of "ground_child"
regardless of its parent scope. This is sometimes convenient if you
want to extract parameters from a deeply nested program.
.. code-block::
main.search_parameters("\\S::grand_child::amp")
Note that the root program is only aware of its direct references.
.. code-block::
print(main.references)
.. parsed-literal::
ReferenceManager:
- ('child',): ScheduleBlock(ScheduleBlock(ScheduleBlock(Play(Con...
As you can see the main program cannot directly assign a subroutine to the "grand_child" because
this subroutine is not called within the root program, i.e. it is indirectly called by "child".
However, the returned :class:`.ReferenceManager` is a dict-like object, and you can still
reach to "grand_child" via the "child" program with the following chained dict access.
.. code-block::
main.references[("child", )].references[("grand_child", )]
Note that :attr:`ScheduleBlock.parameters` and :meth:`ScheduleBlock.scoped_parameters()`
still collect all parameters also from the subroutine once it's assigned.
.. _UUID: https://docs.python.org/3/library/uuid.html#module-uuid
"""
__slots__ = (
"_parent",
"_name",
"_reference_manager",
"_parameter_manager",
"_alignment_context",
"_blocks",
"_metadata",
)
# Prefix to use for auto naming.
prefix = "block"
# Counter to count instance number.
instances_counter = itertools.count()
def __init__(
self, name: Optional[str] = None, metadata: Optional[dict] = None, alignment_context=None
):
"""Create an empty schedule block.
Args:
name: Name of this schedule. Defaults to an autogenerated string if not provided.
metadata: Arbitrary key value metadata to associate with the schedule. This gets
stored as free-form data in a dict in the
:attr:`~qiskit.pulse.ScheduleBlock.metadata` attribute. It will not be directly
used in the schedule.
alignment_context (AlignmentKind): ``AlignmentKind`` instance that manages
scheduling of instructions in this block.
Raises:
TypeError: if metadata is not a dict.
"""
from qiskit.pulse.parameter_manager import ParameterManager
from qiskit.pulse.transforms import AlignLeft
if name is None:
name = self.prefix + str(next(self.instances_counter))
if sys.platform != "win32" and not is_main_process():
name += f"-{mp.current_process().pid}"
# This points to the parent schedule object in the current scope.
# Note that schedule block can be nested without referencing, e.g. .append(child_block),
# and parent=None indicates the root program of the current scope.
# The nested schedule block objects should not have _reference_manager and
# should refer to the one of the root program.
# This also means referenced program should be assigned to the root program, not to child.
self._parent = None
self._name = name
self._parameter_manager = ParameterManager()
self._reference_manager = ReferenceManager()
self._alignment_context = alignment_context or AlignLeft()
self._blocks = []
# get parameters from context
self._parameter_manager.update_parameter_table(self._alignment_context)
if not isinstance(metadata, dict) and metadata is not None:
raise TypeError("Only a dictionary or None is accepted for schedule metadata")
self._metadata = metadata or {}
@classmethod
def initialize_from(cls, other_program: Any, name: Optional[str] = None) -> "ScheduleBlock":
"""Create new schedule object with metadata of another schedule object.
Args:
other_program: Qiskit program that provides metadata to new object.
name: Name of new schedule. Name of ``block`` is used by default.
Returns:
New block object with name and metadata.
Raises:
PulseError: When ``other_program`` does not provide necessary information.
"""
try:
name = name or other_program.name
if other_program.metadata:
metadata = other_program.metadata.copy()
else:
metadata = None
try:
alignment_context = other_program.alignment_context
except AttributeError:
alignment_context = None
return cls(name=name, metadata=metadata, alignment_context=alignment_context)
except AttributeError as ex:
raise PulseError(
f"{cls.__name__} cannot be initialized from the program data "
f"{other_program.__class__.__name__}."
) from ex
@property
def name(self) -> str:
"""Return name of this schedule"""
return self._name
@property
def metadata(self) -> Dict[str, Any]:
"""The user provided metadata associated with the schedule.
User provided ``dict`` of metadata for the schedule.
The metadata contents do not affect the semantics of the program
but are used to influence the execution of the schedule. It is expected
to be passed between all transforms of the schedule and that providers
will associate any schedule metadata with the results it returns from the
execution of that schedule.
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Update the schedule metadata"""
if not isinstance(metadata, dict) and metadata is not None:
raise TypeError("Only a dictionary or None is accepted for schedule metadata")
self._metadata = metadata or {}
@property
def alignment_context(self):
"""Return alignment instance that allocates block component to generate schedule."""
return self._alignment_context
def is_schedulable(self) -> bool:
"""Return ``True`` if all durations are assigned."""
# check context assignment
for context_param in self._alignment_context._context_params:
if isinstance(context_param, ParameterExpression):
return False
# check duration assignment
for elm in self.blocks:
if isinstance(elm, ScheduleBlock):
if not elm.is_schedulable():
return False
else:
try:
if not isinstance(elm.duration, int):
return False
except UnassignedReferenceError:
return False
return True
@property
@_require_schedule_conversion
def duration(self) -> int:
"""Duration of this schedule block."""
return self.duration
@property
def channels(self) -> Tuple[Channel]:
"""Returns channels that this schedule block uses."""
chans = set()
for elm in self.blocks:
if isinstance(elm, Reference):
raise UnassignedReferenceError(
f"This schedule contains unassigned reference {elm.ref_keys} "
"and channels are ambiguous. Please assign the subroutine first."
)
chans = chans | set(elm.channels)
return tuple(chans)
@property
@_require_schedule_conversion
def instructions(self) -> Tuple[Tuple[int, Instruction]]:
"""Get the time-ordered instructions from self."""
return self.instructions
@property
def blocks(self) -> Tuple["BlockComponent", ...]:
"""Get the block elements added to self.
.. note::
The sequence of elements is returned in order of addition. Because the first element is
schedule first, e.g. FIFO, the returned sequence is roughly time-ordered.
However, in the parallel alignment context, especially in
the as-late-as-possible scheduling, or :class:`.AlignRight` context,
the actual timing of when the instructions are issued is unknown until
the :class:`.ScheduleBlock` is scheduled and converted into a :class:`.Schedule`.
"""
blocks = []
for elm in self._blocks:
if isinstance(elm, Reference):
elm = self.references.get(elm.ref_keys, None) or elm
blocks.append(elm)
return tuple(blocks)
@property
def parameters(self) -> Set[Parameter]:
"""Return unassigned parameters with raw names."""
# Need new object not to mutate parameter_manager.parameters
out_params = set()
out_params |= self._parameter_manager.parameters
for subroutine in self.references.values():
if subroutine is None:
continue
out_params |= subroutine.parameters
return out_params
def scoped_parameters(self) -> Tuple[Parameter]:
"""Return unassigned parameters with scoped names.
.. note::
If a parameter is defined within a nested scope,
it is prefixed with all parent-scope names with the delimiter string,
which is "::". If a reference key of the scope consists of
multiple key strings, it will be represented by a single string joined with ",".
For example, "root::xgate,q0::amp" for the parameter "amp" defined in the
reference specified by the key strings ("xgate", "q0").
"""
return tuple(
sorted(
_collect_scoped_parameters(self, current_scope="root").values(),
key=lambda p: p.name,
)
)
@property
def references(self) -> ReferenceManager:
"""Return a reference manager of the current scope."""
if self._parent is not None:
return self._parent.references
return self._reference_manager
@_require_schedule_conversion
def ch_duration(self, *channels: Channel) -> int:
"""Return the time of the end of the last instruction over the supplied channels.
Args:
*channels: Channels within ``self`` to include.
"""
return self.ch_duration(*channels)
def append(
self, block: "BlockComponent", name: Optional[str] = None, inplace: bool = True
) -> "ScheduleBlock":
"""Return a new schedule block with ``block`` appended to the context block.
The execution time is automatically assigned when the block is converted into schedule.
Args:
block: ScheduleBlock to be appended.
name: Name of the new ``Schedule``. Defaults to name of ``self``.
inplace: Perform operation inplace on this schedule. Otherwise,
return a new ``Schedule``.
Returns:
Schedule block with appended schedule.
Raises:
PulseError: When invalid schedule type is specified.
"""
if not isinstance(block, (ScheduleBlock, Instruction)):
raise PulseError(
f"Appended `schedule` {block.__class__.__name__} is invalid type. "
"Only `Instruction` and `ScheduleBlock` can be accepted."
)
if not inplace:
schedule = copy.deepcopy(self)
schedule._name = name or self.name
schedule.append(block, inplace=True)
return schedule
if isinstance(block, Reference) and block.ref_keys not in self.references:
self.references[block.ref_keys] = None
elif isinstance(block, ScheduleBlock):
block = copy.deepcopy(block)
# Expose subroutines to the current main scope.
# Note that this 'block' is not called.
# The block is just directly appended to the current scope.
if block.is_referenced():
if block._parent is not None:
# This is an edge case:
# If this is not a parent, block.references points to the parent's reference
# where subroutine not referred within the 'block' may exist.
# Move only references existing in the 'block'.
# See 'test.python.pulse.test_reference.TestReference.test_appending_child_block'
for ref in _get_references(block._blocks):
self.references[ref.ref_keys] = block.references[ref.ref_keys]
else:
# Avoid using dict.update and explicitly call __set_item__ for validation.
# Reference manager of appended block is cleared because of data reduction.
for ref_keys, ref in block._reference_manager.items():
self.references[ref_keys] = ref
block._reference_manager.clear()
# Now switch the parent because block is appended to self.
block._parent = self
self._blocks.append(block)
self._parameter_manager.update_parameter_table(block)
return self
def filter(
self,
*filter_funcs: List[Callable],
channels: Optional[Iterable[Channel]] = None,
instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None,
check_subroutine: bool = True,
):
"""Return a new ``ScheduleBlock`` with only the instructions from this ``ScheduleBlock``
which pass though the provided filters; i.e. an instruction will be retained if
every function in ``filter_funcs`` returns ``True``, the instruction occurs on
a channel type contained in ``channels``, and the instruction type is contained
in ``instruction_types``.
.. warning::
Because ``ScheduleBlock`` is not aware of the execution time of
the context instructions, filtering out some instructions may
change the execution time of the remaining instructions.
If no arguments are provided, ``self`` is returned.
Args:
filter_funcs: A list of Callables which take a ``Instruction`` and return a bool.
channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``.
instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``.
check_subroutine: Set `True` to individually filter instructions inside a subroutine
defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction.
Returns:
``ScheduleBlock`` consisting of instructions that matches with filtering condition.
"""
from qiskit.pulse.filters import composite_filter, filter_instructions
filters = composite_filter(channels, instruction_types)
filters.extend(filter_funcs)
return filter_instructions(
self, filters=filters, negate=False, recurse_subroutines=check_subroutine
)
def exclude(
self,
*filter_funcs: List[Callable],
channels: Optional[Iterable[Channel]] = None,
instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None,
check_subroutine: bool = True,
):
"""Return a new ``ScheduleBlock`` with only the instructions from this ``ScheduleBlock``
*failing* at least one of the provided filters.
This method is the complement of py:meth:`~self.filter`, so that::
self.filter(args) + self.exclude(args) == self in terms of instructions included.
.. warning::
Because ``ScheduleBlock`` is not aware of the execution time of
the context instructions, excluding some instructions may
change the execution time of the remaining instructions.
Args:
filter_funcs: A list of Callables which take a ``Instruction`` and return a bool.
channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``.
instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``.
check_subroutine: Set `True` to individually filter instructions inside of a subroutine
defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction.
Returns:
``ScheduleBlock`` consisting of instructions that do not match with
at least one of filtering conditions.
"""
from qiskit.pulse.filters import composite_filter, filter_instructions
filters = composite_filter(channels, instruction_types)
filters.extend(filter_funcs)
return filter_instructions(
self, filters=filters, negate=True, recurse_subroutines=check_subroutine
)
def replace(
self,
old: "BlockComponent",
new: "BlockComponent",
inplace: bool = True,
) -> "ScheduleBlock":
"""Return a ``ScheduleBlock`` with the ``old`` component replaced with a ``new``
component.
Args:
old: Schedule block component to replace.
new: Schedule block component to replace with.
inplace: Replace instruction by mutably modifying this ``ScheduleBlock``.
Returns:
The modified schedule block with ``old`` replaced by ``new``.
"""
if not inplace:
schedule = copy.deepcopy(self)
return schedule.replace(old, new, inplace=True)
if old not in self._blocks:
# Avoid unnecessary update of reference and parameter manager
return self
# Temporarily copies references
all_references = ReferenceManager()
if isinstance(new, ScheduleBlock):
new = copy.deepcopy(new)
all_references.update(new.references)
new._reference_manager.clear()
new._parent = self
for ref_key, subroutine in self.references.items():
if ref_key in all_references:
warnings.warn(
f"Reference {ref_key} conflicts with substituted program {new.name}. "
"Existing reference has been replaced with new reference.",
UserWarning,
)
continue
all_references[ref_key] = subroutine
# Regenerate parameter table by regenerating elements.
# Note that removal of parameters in old is not sufficient,
# because corresponding parameters might be also used in another block element.
self._parameter_manager.clear()
self._parameter_manager.update_parameter_table(self._alignment_context)
new_elms = []
for elm in self._blocks:
if elm == old:
elm = new
self._parameter_manager.update_parameter_table(elm)
new_elms.append(elm)
self._blocks = new_elms
# Regenerate reference table
# Note that reference is attached to the outer schedule if nested.
# Thus, this investigates all references within the scope.
self.references.clear()
root = self
while root._parent is not None:
root = root._parent
for ref in _get_references(root._blocks):
self.references[ref.ref_keys] = all_references[ref.ref_keys]
return self
def is_parameterized(self) -> bool:
"""Return True iff the instruction is parameterized."""
return any(self.parameters)
def is_referenced(self) -> bool:
"""Return True iff the current schedule block contains reference to subroutine."""
return len(self.references) > 0
def assign_parameters(
self,
value_dict: Dict[ParameterExpression, ParameterValueType],
inplace: bool = True,
) -> "ScheduleBlock":
"""Assign the parameters in this schedule according to the input.
Args:
value_dict: A mapping from Parameters to either numeric values or another
Parameter expression.
inplace: Set ``True`` to override this instance with new parameter.
Returns:
Schedule with updated parameters.
Raises:
PulseError: When the block is nested into another block.
"""
if not inplace:
new_schedule = copy.deepcopy(self)
return new_schedule.assign_parameters(value_dict, inplace=True)
# Update parameters in the current scope
self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict)
for subroutine in self._reference_manager.values():
# Also assigning parameters to the references associated with self.
# Note that references are always stored in the root program.
# So calling assign_parameters from nested block doesn't update references.
if subroutine is None:
continue
subroutine.assign_parameters(value_dict=value_dict, inplace=True)
return self
def assign_references(
self,
subroutine_dict: Dict[Union[str, Tuple[str, ...]], "ScheduleBlock"],
inplace: bool = True,
) -> "ScheduleBlock":
"""Assign schedules to references.
It is only capable of assigning a schedule block to immediate references
which are directly referred within the current scope.
Let's see following example:
.. code-block:: python
from qiskit import pulse
with pulse.build() as subroutine:
pulse.delay(10, pulse.DriveChannel(0))
with pulse.build() as sub_prog:
pulse.reference("A")
with pulse.build() as main_prog:
pulse.reference("B")
In above example, the ``main_prog`` can refer to the subroutine "root::B" and the
reference of "B" to program "A", i.e., "B::A", is not defined in the root namespace.
This prevents breaking the reference "root::B::A" by the assignment of "root::B".
For example, if a user could indirectly assign "root::B::A" from the root program,
one can later assign another program to "root::B" that doesn't contain "A" within it.
In this situation, a reference "root::B::A" would still live in
the reference manager of the root.
However, the subroutine "root::B::A" would no longer be used in the actual pulse program.
To assign subroutine "A" to ``nested_prog`` as a nested subprogram of ``main_prog``,
you must first assign "A" of the ``sub_prog``,
and then assign the ``sub_prog`` to the ``main_prog``.
.. code-block:: python
sub_prog.assign_references({("A", ): nested_prog}, inplace=True)
main_prog.assign_references({("B", ): sub_prog}, inplace=True)
Alternatively, you can also write
.. code-block:: python
main_prog.assign_references({("B", ): sub_prog}, inplace=True)
main_prog.references[("B", )].assign_references({"A": nested_prog}, inplace=True)
Here :attr:`.references` returns a dict-like object, and you can
mutably update the nested reference of the particular subroutine.
.. note::
Assigned programs are deep-copied to prevent an unexpected update.
Args:
subroutine_dict: A mapping from reference key to schedule block of the subroutine.
inplace: Set ``True`` to override this instance with new subroutine.
Returns:
Schedule block with assigned subroutine.
Raises:
PulseError: When reference key is not defined in the current scope.
"""
if not inplace:
new_schedule = copy.deepcopy(self)
return new_schedule.assign_references(subroutine_dict, inplace=True)
for key, subroutine in subroutine_dict.items():
if key not in self.references:
unassigned_keys = ", ".join(map(repr, self.references.unassigned()))
raise PulseError(
f"Reference instruction with {key} doesn't exist "
f"in the current scope: {unassigned_keys}"
)
self.references[key] = copy.deepcopy(subroutine)
return self
def get_parameters(self, parameter_name: str) -> List[Parameter]:
"""Get parameter object bound to this schedule by string name.
Note that we can define different parameter objects with the same name,
because these different objects are identified by their unique uuid.
For example,
.. code-block:: python
from qiskit import pulse, circuit
amp1 = circuit.Parameter("amp")
amp2 = circuit.Parameter("amp")
with pulse.build() as sub_prog:
pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(sub_prog, name="sub")
pulse.play(pulse.Constant(100, amp2), pulse.DriveChannel(0))
main_prog.get_parameters("amp")
This returns a list of two parameters ``amp1`` and ``amp2``.
Args:
parameter_name: Name of parameter.
Returns:
Parameter objects that have corresponding name.
"""
matched = [p for p in self.parameters if p.name == parameter_name]
return matched
def search_parameters(self, parameter_regex: str) -> List[Parameter]:
"""Search parameter with regular expression.
This method looks for the scope-aware parameters.
For example,
.. code-block:: python
from qiskit import pulse, circuit
amp1 = circuit.Parameter("amp")
amp2 = circuit.Parameter("amp")
with pulse.build() as sub_prog:
pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(sub_prog, name="sub")
pulse.play(pulse.Constant(100, amp2), pulse.DriveChannel(0))
main_prog.search_parameters("root::sub::amp")
This finds ``amp1`` with scoped name "root::sub::amp".
Args:
parameter_regex: Regular expression for scoped parameter name.
Returns:
Parameter objects that have corresponding name.
"""
pattern = re.compile(parameter_regex)
return sorted(
_collect_scoped_parameters(self, current_scope="root", filter_regex=pattern).values(),
key=lambda p: p.name,
)
def __len__(self) -> int:
"""Return number of instructions in the schedule."""
return len(self.blocks)
def __eq__(self, other: "ScheduleBlock") -> bool:
"""Test if two ScheduleBlocks are equal.
Equality is checked by verifying there is an equal instruction at every time
in ``other`` for every instruction in this ``ScheduleBlock``. This check is
performed by converting the instruction representation into directed acyclic graph,
in which execution order of every instruction is evaluated correctly across all channels.
Also ``self`` and ``other`` should have the same alignment context.
.. warning::
This does not check for logical equivalency. Ie.,
```python
>>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0))
== Delay(20, DriveChannel(0))
False
```
"""
# 0. type check
if not isinstance(other, type(self)):
return False
# 1. transformation check
if self.alignment_context != other.alignment_context:
return False
# 2. size check
if len(self) != len(other):
return False
# 3. instruction check with alignment
from qiskit.pulse.transforms.dag import block_to_dag as dag
if not rx.is_isomorphic_node_match(dag(self), dag(other), lambda x, y: x == y):
return False
return True
def __repr__(self) -> str:
name = format(self._name) if self._name else ""
blocks = ", ".join([repr(instr) for instr in self.blocks[:50]])
if len(self.blocks) > 25:
blocks += ", ..."
return '{}({}, name="{}", transform={})'.format(
self.__class__.__name__, blocks, name, repr(self.alignment_context)
)
def __add__(self, other: "BlockComponent") -> "ScheduleBlock":
"""Return a new schedule with ``other`` inserted within ``self`` at ``start_time``."""
return self.append(other)
def _common_method(*classes):
"""A function decorator to attach the function to specified classes as a method.
.. note:: For developer: A method attached through this decorator may hurt readability
of the codebase, because the method may not be detected by a code editor.
Thus, this decorator should be used to a limited extent, i.e. huge helper method.
By using this decorator wisely, we can reduce code maintenance overhead without
losing readability of the codebase.
"""
def decorator(method):
@functools.wraps(method)
def wrapper(*args, **kwargs):
return method(*args, **kwargs)
for cls in classes:
setattr(cls, method.__name__, wrapper)
return method
return decorator
@_common_method(Schedule, ScheduleBlock)
def draw(
self,
style: Optional[Dict[str, Any]] = None,
backend=None, # importing backend causes cyclic import
time_range: Optional[Tuple[int, int]] = None,
time_unit: str = "dt",
disable_channels: Optional[List[Channel]] = None,
show_snapshot: bool = True,
show_framechange: bool = True,
show_waveform_info: bool = True,
show_barrier: bool = True,
plotter: str = "mpl2d",
axis: Optional[Any] = None,
):
"""Plot the schedule.
Args:
style: Stylesheet options. This can be dictionary or preset stylesheet classes. See
:py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXStandard`,
:py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXSimple`, and
:py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXDebugging` for details of
preset stylesheets.
backend (Optional[BaseBackend]): Backend object to play the input pulse program.
If provided, the plotter may use to make the visualization hardware aware.
time_range: Set horizontal axis limit. Tuple `(tmin, tmax)`.
time_unit: The unit of specified time range either `dt` or `ns`.
The unit of `ns` is available only when `backend` object is provided.
disable_channels: A control property to show specific pulse channel.
Pulse channel instances provided as a list are not shown in the output image.
show_snapshot: Show snapshot instructions.
show_framechange: Show frame change instructions. The frame change represents
instructions that modulate phase or frequency of pulse channels.
show_waveform_info: Show additional information about waveforms such as their name.
show_barrier: Show barrier lines.
plotter: Name of plotter API to generate an output image.
One of following APIs should be specified::
mpl2d: Matplotlib API for 2D image generation.
Matplotlib API to generate 2D image. Charts are placed along y axis with
vertical offset. This API takes matplotlib.axes.Axes as ``axis`` input.
``axis`` and ``style`` kwargs may depend on the plotter.
axis: Arbitrary object passed to the plotter. If this object is provided,
the plotters use a given ``axis`` instead of internally initializing
a figure object. This object format depends on the plotter.
See plotter argument for details.
Returns:
Visualization output data.
The returned data type depends on the ``plotter``.
If matplotlib family is specified, this will be a ``matplotlib.pyplot.Figure`` data.
"""
# pylint: disable=cyclic-import
from qiskit.visualization import pulse_drawer
return pulse_drawer(
program=self,
style=style,
backend=backend,
time_range=time_range,
time_unit=time_unit,
disable_channels=disable_channels,
show_snapshot=show_snapshot,
show_framechange=show_framechange,
show_waveform_info=show_waveform_info,
show_barrier=show_barrier,
plotter=plotter,
axis=axis,
)
def _interval_index(intervals: List[Interval], interval: Interval) -> int:
"""Find the index of an interval.
Args:
intervals: A sorted list of non-overlapping Intervals.
interval: The interval for which the index into intervals will be found.
Returns:
The index of the interval.
Raises:
PulseError: If the interval does not exist.
"""
index = _locate_interval_index(intervals, interval)
found_interval = intervals[index]
if found_interval != interval:
raise PulseError(f"The interval: {interval} does not exist in intervals: {intervals}")
return index
def _locate_interval_index(intervals: List[Interval], interval: Interval, index: int = 0) -> int:
"""Using binary search on start times, find an interval.
Args:
intervals: A sorted list of non-overlapping Intervals.
interval: The interval for which the index into intervals will be found.
index: A running tally of the index, for recursion. The user should not pass a value.
Returns:
The index into intervals that new_interval would be inserted to maintain
a sorted list of intervals.
"""
if not intervals or len(intervals) == 1:
return index
mid_idx = len(intervals) // 2
mid = intervals[mid_idx]
if interval[1] <= mid[0] and (interval != mid):
return _locate_interval_index(intervals[:mid_idx], interval, index=index)
else:
return _locate_interval_index(intervals[mid_idx:], interval, index=index + mid_idx)
def _find_insertion_index(intervals: List[Interval], new_interval: Interval) -> int:
"""Using binary search on start times, return the index into `intervals` where the new interval
belongs, or raise an error if the new interval overlaps with any existing ones.
Args:
intervals: A sorted list of non-overlapping Intervals.
new_interval: The interval for which the index into intervals will be found.
Returns:
The index into intervals that new_interval should be inserted to maintain a sorted list
of intervals.
Raises:
PulseError: If new_interval overlaps with the given intervals.
"""
index = _locate_interval_index(intervals, new_interval)
if index < len(intervals):
if _overlaps(intervals[index], new_interval):
raise PulseError("New interval overlaps with existing.")
return index if new_interval[1] <= intervals[index][0] else index + 1
return index
def _overlaps(first: Interval, second: Interval) -> bool:
"""Return True iff first and second overlap.
Note: first.stop may equal second.start, since Interval stop times are exclusive.
"""
if first[0] == second[0] == second[1]:
# They fail to overlap if one of the intervals has duration 0
return False
if first[0] > second[0]:
first, second = second, first
return second[0] < first[1]
def _check_nonnegative_timeslot(timeslots: TimeSlots):
"""Test that a channel has no negative timeslots.
Raises:
PulseError: If a channel timeslot is negative.
"""
for chan, chan_timeslots in timeslots.items():
if chan_timeslots:
if chan_timeslots[0][0] < 0:
raise PulseError(f"An instruction on {chan} has a negative starting time.")
def _get_timeslots(schedule: "ScheduleComponent") -> TimeSlots:
"""Generate timeslots from given schedule component.
Args:
schedule: Input schedule component.
Raises:
PulseError: When invalid schedule type is specified.
"""
if isinstance(schedule, Instruction):
duration = schedule.duration
instruction_duration_validation(duration)
timeslots = {channel: [(0, duration)] for channel in schedule.channels}
elif isinstance(schedule, Schedule):
timeslots = schedule.timeslots
else:
raise PulseError(f"Invalid schedule type {type(schedule)} is specified.")
return timeslots
def _get_references(block_elms: List["BlockComponent"]) -> Set[Reference]:
"""Recursively get reference instructions in the current scope.
Args:
block_elms: List of schedule block elements to investigate.
Returns:
A set of unique reference instructions.
"""
references = set()
for elm in block_elms:
if isinstance(elm, ScheduleBlock):
references |= _get_references(elm._blocks)
elif isinstance(elm, Reference):
references.add(elm)
return references
def _collect_scoped_parameters(
schedule: ScheduleBlock,
current_scope: str,
filter_regex: Optional[re.Pattern] = None,
) -> Dict[Tuple[str, int], Parameter]:
"""A helper function to collect parameters from all references in scope-aware fashion.
Parameter object is renamed with attached scope information but its UUID is remained.
This means object is treated identically on the assignment logic.
This function returns a dictionary of all parameters existing in the target program
including its reference, which is keyed on the unique identifier consisting of
scoped parameter name and parameter object UUID.
This logic prevents parameter clash in the different scope.
For example, when two parameter objects with the same UUID exist in different references,
both of them appear in the output dictionary, even though they are technically the same object.
This feature is particularly convenient to search parameter object with associated scope.
Args:
schedule: Schedule to get parameters.
current_scope: Name of scope where schedule exist.
filter_regex: Optional. Compiled regex to sort parameter by name.
Returns:
A dictionary of scoped parameter objects.
"""
parameters_out = {}
for param in schedule._parameter_manager.parameters:
new_name = f"{current_scope}{Reference.scope_delimiter}{param.name}"
if filter_regex and not re.search(filter_regex, new_name):
continue
scoped_param = Parameter.__new__(Parameter, new_name, uuid=getattr(param, "_uuid"))
scoped_param.__init__(new_name)
unique_key = new_name, hash(param)
parameters_out[unique_key] = scoped_param
for sub_namespace, subroutine in schedule.references.items():
if subroutine is None:
continue
composite_key = Reference.key_delimiter.join(sub_namespace)
full_path = f"{current_scope}{Reference.scope_delimiter}{composite_key}"
sub_parameters = _collect_scoped_parameters(
subroutine, current_scope=full_path, filter_regex=filter_regex
)
parameters_out.update(sub_parameters)
return parameters_out
# These type aliases are defined at the bottom of the file, because as of 2022-01-18 they are
# imported into other parts of Terra. Previously, the aliases were at the top of the file and used
# forwards references within themselves. This was fine within the same file, but causes scoping
# issues when the aliases are imported into different scopes, in which the `ForwardRef` instances
# would no longer resolve. Instead, we only use forward references in the annotations of _this_
# file to reference the aliases, which are guaranteed to resolve in scope, so the aliases can all be
# concrete.
ScheduleComponent = Union[Schedule, Instruction]
"""An element that composes a pulse schedule."""
BlockComponent = Union[ScheduleBlock, Instruction]
"""An element that composes a pulse schedule block."""
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (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.
"""
Drawing objects for timeline drawer.
Drawing objects play two important roles:
- Allowing unittests of visualization module. Usually it is hard for image files to be tested.
- Removing program parser from each plotter interface. We can easily add new plotter.
This module is based on the structure of matplotlib as it is the primary plotter
of the timeline drawer. However this interface is agnostic to the actual plotter.
Design concept
~~~~~~~~~~~~~~
When we think about dynamically updating drawings, it will be most efficient to
update only the changed properties of drawings rather than regenerating entirely from scratch.
Thus the core :py:class:`~qiskit.visualization.timeline.core.DrawerCanvas` generates
all possible drawings in the beginning and then the canvas instance manages
visibility of each drawing according to the end-user request.
Data key
~~~~~~~~
In the abstract class ``ElementaryData`` common attributes to represent a drawing are
specified. In addition, drawings have the `data_key` property that returns an
unique hash of the object for comparison.
This key is generated from a data type, the location of the drawing in the canvas,
and associated qubit or classical bit objects.
See py:mod:`qiskit.visualization.timeline.types` for detail on the data type.
If a data key cannot distinguish two independent objects, you need to add a new data type.
The data key may be used in the plotter interface to identify the object.
Drawing objects
~~~~~~~~~~~~~~~
To support not only `matplotlib` but also multiple plotters, those drawings should be
universal and designed without strong dependency on modules in `matplotlib`.
This means drawings that represent primitive geometries are preferred.
It should be noted that there will be no unittest for each plotter API, which takes
drawings and outputs image data, we should avoid adding a complicated geometry
that has a context of the scheduled circuit program.
For example, a two qubit scheduled gate may be drawn by two rectangles that represent
time occupation of two quantum registers during the gate along with a line connecting
these rectangles to identify the pair. This shape can be represented with
two box-type objects with one line-type object instead of defining a new object dedicated
to the two qubit gate. As many plotters don't support an API that visualizes such
a linked-box shape, if we introduce such complex drawings and write a
custom wrapper function on top of the existing API,
it could be difficult to prevent bugs with the CI tools due to lack of
the effective unittest for image data.
Link between gates
~~~~~~~~~~~~~~~~~~
The ``GateLinkData`` is the special subclass of drawing that represents
a link between bits. Usually objects are associated to the specific bit,
but ``GateLinkData`` can be associated with multiple bits to illustrate relationship
between quantum or classical bits during a gate operation.
"""
from abc import ABC
from enum import Enum
from typing import Optional, Dict, Any, List, Union
import numpy as np
from qiskit import circuit
from qiskit.visualization.timeline import types
from qiskit.visualization.exceptions import VisualizationError
class ElementaryData(ABC):
"""Base class of the scheduled circuit visualization object.
Note that drawings are mutable.
"""
__hash__ = None
def __init__(
self,
data_type: Union[str, Enum],
xvals: Union[np.ndarray, List[types.Coordinate]],
yvals: Union[np.ndarray, List[types.Coordinate]],
bits: Optional[Union[types.Bits, List[types.Bits]]] = None,
meta: Optional[Dict[str, Any]] = None,
styles: Optional[Dict[str, Any]] = None,
):
"""Create new drawing.
Args:
data_type: String representation of this drawing.
xvals: Series of horizontal coordinate that the object is drawn.
yvals: Series of vertical coordinate that the object is drawn.
bits: Qubit or Clbit object bound to this drawing.
meta: Meta data dictionary of the object.
styles: Style keyword args of the object. This conforms to `matplotlib`.
"""
if bits and isinstance(bits, (circuit.Qubit, circuit.Clbit)):
bits = [bits]
if isinstance(data_type, Enum):
data_type = data_type.value
self.data_type = str(data_type)
self.xvals = xvals
self.yvals = yvals
self.bits = bits
self.meta = meta
self.styles = styles
@property
def data_key(self):
"""Return unique hash of this object."""
return str(
hash(
(
self.__class__.__name__,
self.data_type,
tuple(self.bits),
tuple(self.xvals),
tuple(self.yvals),
)
)
)
def __repr__(self):
return f"{self.__class__.__name__}(type={self.data_type}, key={self.data_key})"
def __eq__(self, other):
return isinstance(other, self.__class__) and self.data_key == other.data_key
class LineData(ElementaryData):
"""Drawing object that represents line shape."""
def __init__(
self,
data_type: Union[str, Enum],
xvals: Union[np.ndarray, List[types.Coordinate]],
yvals: Union[np.ndarray, List[types.Coordinate]],
bit: types.Bits,
meta: Dict[str, Any] = None,
styles: Dict[str, Any] = None,
):
"""Create new line.
Args:
data_type: String representation of this drawing.
xvals: Series of horizontal coordinate that the object is drawn.
yvals: Series of vertical coordinate that the object is drawn.
bit: Bit associated to this object.
meta: Meta data dictionary of the object.
styles: Style keyword args of the object. This conforms to `matplotlib`.
"""
super().__init__(
data_type=data_type, xvals=xvals, yvals=yvals, bits=bit, meta=meta, styles=styles
)
class BoxData(ElementaryData):
"""Drawing object that represents box shape."""
def __init__(
self,
data_type: Union[str, Enum],
xvals: Union[np.ndarray, List[types.Coordinate]],
yvals: Union[np.ndarray, List[types.Coordinate]],
bit: types.Bits,
meta: Dict[str, Any] = None,
styles: Dict[str, Any] = None,
):
"""Create new box.
Args:
data_type: String representation of this drawing.
xvals: Left and right coordinate that the object is drawn.
yvals: Top and bottom coordinate that the object is drawn.
bit: Bit associated to this object.
meta: Meta data dictionary of the object.
styles: Style keyword args of the object. This conforms to `matplotlib`.
Raises:
VisualizationError: When number of data points are not equals to 2.
"""
if len(xvals) != 2 or len(yvals) != 2:
raise VisualizationError("Length of data points are not equals to 2.")
super().__init__(
data_type=data_type, xvals=xvals, yvals=yvals, bits=bit, meta=meta, styles=styles
)
class TextData(ElementaryData):
"""Drawing object that represents a text on canvas."""
def __init__(
self,
data_type: Union[str, Enum],
xval: types.Coordinate,
yval: types.Coordinate,
bit: types.Bits,
text: str,
latex: Optional[str] = None,
meta: Dict[str, Any] = None,
styles: Dict[str, Any] = None,
):
"""Create new text.
Args:
data_type: String representation of this drawing.
xval: Horizontal coordinate that the object is drawn.
yval: Vertical coordinate that the object is drawn.
bit: Bit associated to this object.
text: A string to draw on the canvas.
latex: If set this string is used instead of `text`.
meta: Meta data dictionary of the object.
styles: Style keyword args of the object. This conforms to `matplotlib`.
"""
self.text = text
self.latex = latex
super().__init__(
data_type=data_type, xvals=[xval], yvals=[yval], bits=bit, meta=meta, styles=styles
)
class GateLinkData(ElementaryData):
"""A special drawing data type that represents bit link of multi-bit gates.
Note this object takes multiple bits and dedicates them to the bit link.
This may appear as a line on the canvas.
"""
def __init__(
self, xval: types.Coordinate, bits: List[types.Bits], styles: Dict[str, Any] = None
):
"""Create new bit link.
Args:
xval: Horizontal coordinate that the object is drawn.
bits: Bit associated to this object.
styles: Style keyword args of the object. This conforms to `matplotlib`.
"""
super().__init__(
data_type=types.LineType.GATE_LINK,
xvals=[xval],
yvals=[0],
bits=bits,
meta=None,
styles=styles,
)
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 2量子ビット回路を用意
qe = QuantumCircuit(2) # 今回は量子ビットのみ用意します。
# 回路を描画
qe.draw(output="mpl")
# 正解
qe.h(0) # ← 修正して回路を完成させてください。片方の量子ビットに重ね合わせを掛けます。
qe.draw(output='mpl')
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(qe, vector_sim )
counts = job.result().get_counts(qe) # 実行結果の詳細を取り出し
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
#正解
qe.cx(0,1) # ← cxゲートを使って回路を完成させてください。順番に注意してください。
qe.draw(output='mpl')
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(qe, vector_sim )
# result = job.result().get_statevector(qe, decimals=3)
# print(result)
counts = job.result().get_counts(qe) # 実行結果の詳細を取り出し
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
# 2量子ビット回路を用意
qe2 = QuantumCircuit(2,2) # 量子ビットと古典レジスターを用意します
# 量子回路を設計
qe2.h(0)
qe2.cx(0,1)
# 回路を測定
qe2.measure(0,0)
qe2.measure(1,1)
# 回路を描画
qe2.draw(output="mpl")
# QASMシミュレーターで実験
simulator = Aer.get_backend('qasm_simulator')
job = execute(qe2, backend=simulator, shots=1024)
result = job.result()
# 測定された回数を表示
counts = result.get_counts(qe2)
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
from qiskit import IBMQ
#IBMQ.save_account('MY_API_TOKEN')
# IBM Q アカウントをロードします。
provider = IBMQ.load_account()
from qiskit.providers.ibmq import least_busy
# 実行可能な量子コンピューターをリストします
large_enough_devices = IBMQ.get_provider().backends(filters=lambda x: x.configuration().n_qubits > 3 and not x.configuration().simulator)
print(large_enough_devices)
real_backend = least_busy(large_enough_devices) # その中から、最も空いている量子コンピューターを選出
print("The best backend is " + real_backend.name())
print('run on real device!')
real_result = execute(qe2,real_backend).result() # 計算を実行します
print(real_result.get_counts(qe2)) # 結果を表示
plot_histogram(real_result.get_counts(qe2)) # ヒストグラムを表示
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
# Checking the version of PYTHON; we only support 3 at the moment
import sys
if sys.version_info < (3,0):
raise Exception('Please use Python version 3 or greater.')
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import time
from pprint import pprint
# importing the QISKit
from qiskit import QuantumCircuit, QuantumProgram
#import Qconfig
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
Q_program = QuantumProgram()
#Q_program.set_api(Qconfig.APItoken, Qconfig.config['url'])
"Choice of the backend"
backend = 'local_qasm_simulator' #can be very slow when number of shoots increases
#backend = 'ibmqx_hpc_qasm_simulator'
print("Your choice for the backend is: ", backend)
# Define a F_gate
def F_gate(circ,q,i,j,n,k) :
theta = np.arccos(np.sqrt(1/(n-k+1)))
circ.ry(-theta,q[j])
circ.cz(q[i],q[j])
circ.ry(theta,q[j])
circ.barrier(q[i])
# Define the cxrv gate which uses reverse CNOT instead of CNOT
def cxrv(circ,q,i,j) :
circ.h(q[i])
circ.h(q[j])
circ.cx(q[j],q[i])
circ.h(q[i])
circ.h(q[j])
circ.barrier(q[i],q[j])
#"CIRCUITS"
q = Q_program.create_quantum_register("q", 16)
c = Q_program.create_classical_register("c", 16)
twin = Q_program.create_circuit("twin", [q], [c])
# First W state
twin.x(q[14])
F_gate(twin,q,14,3,3,1)
F_gate(twin,q,3,2,3,2)
twin.cx(q[3],q[14])
twin.cx(q[2],q[3])
#Second W state
twin.x(q[12])
F_gate(twin,q,12,5,3,1)
F_gate(twin,q,5,6,3,2)
cxrv(twin,q,5,12)
twin.cx(q[6],q[5])
#Coin tossing
twin.h(q[0])
twin.h(q[1])
switch1 = Q_program.create_circuit('switch1',[q],[c])
#Stick or switch
switch1.h(q[13])
for i in range (4) :
switch1.measure(q[i] , c[i]);
for i in range (5,7) :
switch1.measure(q[i] , c[i]);
for i in range (12,15) :
switch1.measure(q[i] , c[i]);
Q_program.add_circuit("AliceBob", twin+switch1)
Label = ["left", "central", "right"]
wstates = 0
while wstates != 1:
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print("Alice vs Bob", "backend=", backend, "starting time", time_exp)
result = Q_program.execute("AliceBob", backend=backend, shots=1, max_credits=5, wait=5, timeout=120)
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print("Alice vs Bob", "backend=", backend, " end time", time_exp)
cstr = str(result.get_counts("AliceBob"))
nb_of_cars = int(cstr[3]) + int(cstr[14]) + int(cstr[15])
nb_of_doors = int(cstr[12]) + int(cstr[11]) + int(cstr[5])
wstates = nb_of_cars * nb_of_doors
print(" ")
print('Alice: One car and two goats are now hidden behind these doors.')
print(' Which door do you choose?')
print(" ")
"Chosing the left door"
if int(cstr[5]) == 1:
Doorchosen = 1
"Chosing the center door"
if int(cstr[11]) == 1:
Doorchosen = 2
"Chosing the right door"
if int(cstr[12]) == 1:
Doorchosen = 3
time.sleep(2)
print('Bob: My choice is the',Label[Doorchosen-1], "door")
print(" ")
randomnb = int(cstr[16]) + int(cstr[17]) %2
if cstr[3] == "1": #car behind left door
Doorwinning = 1
if Doorchosen == 1:
Dooropen = 2 + randomnb
Doorswitch = 3 - randomnb
if Doorchosen == 2:
Dooropen = 3
Doorswitch = 1
if Doorchosen == 3:
Dooropen = 2
Doorswitch = 1
if cstr[14] == "1": #car behind central door
Doorwinning = 2
if Doorchosen == 2:
Dooropen = 1 + 2*randomnb
Doorswitch = 3 - 2*randomnb
if Doorchosen == 1:
Dooropen = 3
Doorswitch = 2
if Doorchosen == 3:
Dooropen = 1
Doorswitch = 2
if cstr[15] == "1": #car behind right door
Doorwinning = 3
if Doorchosen == 3:
Dooropen = randomnb + 1
Doorswitch = 2 - randomnb
if Doorchosen == 1:
Dooropen = 2
Doorswitch = 3
if Doorchosen == 2:
Dooropen = 1
Doorswitch = 3
time.sleep(2)
print('Alice: Now I open the', Label[Dooropen-1], 'door and you see a goat')
time.sleep(2)
print(' You get an opportunity to change your choice!')
time.sleep(2)
print(' Do you want to switch for the',Label[Doorswitch-1], "door?")
print(" ")
time.sleep(2)
switch_flag = int(cstr[4])
"BOB STICKS WITH HIS FIRST CHOICE!"
if switch_flag == 0:
Doorfinal = Doorchosen
print('Bob: I stick with my first choice, the',Label[Doorfinal-1], "door")
"BOB CHANGES HIS MIND!"
if switch_flag == 1:
Doorfinal = Doorswitch
print('Bob: I change my mind and choose the',Label[Doorfinal-1], "door")
"FINAL ANNOUNCE"
if Doorfinal == Doorwinning:
endmessage = 'won the car! Congratulations!'
else:
endmessage = 'won a goat! Sorry!'
time.sleep(2)
print()
print('Alice: You opened the',Label[Doorfinal-1],'door and', endmessage)
print("Game over")
#Toffoli gates
Toffoli = Q_program.create_circuit('Toffoli',[q],[c])
Toffoli.ccx(q[3], q[5], q[4])
Toffoli.swap(q[2],q[3])
Toffoli.swap(q[6],q[5])
Toffoli.ccx(q[3], q[5], q[4])
Toffoli.swap(q[3],q[14])
Toffoli.swap(q[12],q[5])
Toffoli.ccx(q[3], q[5], q[4])
# A general solution with 50% switching strategy
switch_fifty_percent = Q_program.create_circuit('switch_fifty_percent',[q],[c])
#switch flag
switch_fifty_percent.h(q[13])
switch_fifty_percent.cx(q[13],q[4])
switch_fifty_percent.measure(q[4] , c[4]);
switch_fifty_percent.measure(q[13] , c[13]);
Q_program.add_circuit("general_solution", twin+Toffoli+switch_fifty_percent)
circuits = ['general_solution']
shots = 1024
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print(backend, "shots", shots, "starting time", time_exp)
result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=30, timeout=600)
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print(backend, "shots", shots, "end time", time_exp)
plot_histogram(result.get_counts("general_solution"))
print(result.get_counts("general_solution"))
observable_stickwon = {'0000000000010000': 1, '0010000000010000': 0, '0010000000000000': 0, '0000000000000000': 0}
observable_switchwon = {'0000000000010000': 0, '0010000000010000': 1, '0010000000000000': 0, '0000000000000000': 0}
observable_stickall = {'0000000000010000': 1, '0010000000010000': 0, '0010000000000000': 0, '0000000000000000': 1}
observable_switchall = {'0000000000010000': 0, '0010000000010000': 1, '0010000000000000': 1, '0000000000000000': 0}
stickwon = result.average_data("general_solution",observable_stickwon)
switchwon = result.average_data("general_solution",observable_switchwon)
stickall = result.average_data("general_solution",observable_stickall)
switchall = result.average_data("general_solution",observable_switchall)
print("Proportion sticking: %6.2f " % stickall)
print("Proportion switching: %6.2f " % switchall)
stickwon_stickall = stickwon/stickall
switchwon_switchall = switchwon/switchall
print("Proportion winning when sticking: %6.2f " % stickwon_stickall)
print("Proportion winning when switching: %6.2f " % switchwon_switchall)
# Illustrating different strategies
xdat = []
ydat = []
observable = {'0000000000000000': 0, '0000000000010000': 1}
shots = 1024
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print(backend, "shots", shots, "starting time", time_exp)
for i in range(9) :
strategies = Q_program.create_circuit('strategies',[q],[c])
Prob = i/8
lambda_s = 2*np.arcsin(np.sqrt(Prob))
strategies.rx(lambda_s,q[13])
strategies.cx(q[13],q[4])
strategies.measure(q[4] , c[4]);
statploti = "statplot"+str(i)
Q_program.create_circuit("statploti",[q],[c])
Q_program.add_circuit("statploti",twin+Toffoli+strategies)
result = Q_program.execute("statploti", backend=backend, shots=shots, max_credits=5, wait=30, timeout=600)
loop_average=(result.average_data("statploti",observable))
print(statploti," Proportion switching: %6.3f" % Prob, " Proportion winning: %6.2f" % loop_average)
ydat.append(loop_average)
xdat.append(Prob)
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print(backend, "shots", shots, "end time", time_exp)
plt.plot(xdat, ydat, 'ro')
plt.grid()
plt.ylabel('Probability of Winning', fontsize=12)
plt.xlabel(r'Probability of Switching', fontsize=12)
plt.show()
print("Our Advice: \n")
y_aver = []
for j in range(0,7,3) :
y_aver.append((ydat[j] + ydat[j+1] +ydat[j+2])/3)
if y_aver[0] == max(y_aver) :
print(" Thou Shalt Not Switch")
elif y_aver[2] == max(y_aver) :
print(" Thou Shalt Not Stick")
else:
print(" Just follow the intuition of the moment")
%run "../version.ipynb"
|
https://github.com/brhn-4/CMSC457
|
brhn-4
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
def diffusion(qc,flip):
qc.h(flip)
qc.x(flip)
qc.h(flip[8])
qc.mct(flip[0:8], flip[8])
qc.h(flip[8])
qc.x(flip)
qc.h(flip)
def oracle(qc,flip,tile,oracle):
flip_tile(qc,flip,tile)
qc.x(tile[0:9])
qc.mct(tile[0:9],oracle[0])
qc.x(tile[0:9])
flip_tile(qc,flip,tile)
# Subroutine for oracle
# Calculate what the light state in `tile` will be after pressing each solution candidate in `flip`.
def flip_tile(qc,flip,tile):
#For tile 0,0
qc.cx(flip[0], tile[0])
qc.cx(flip[0], tile[1])
qc.cx(flip[0], tile[3])
#For tile 0,1
qc.cx(flip[1], tile[0])
qc.cx(flip[1], tile[1])
qc.cx(flip[1], tile[2])
qc.cx(flip[1], tile[4])
#For tile 0,2
qc.cx(flip[2], tile[1])
qc.cx(flip[2], tile[2])
qc.cx(flip[2], tile[5])
#For tile 1,0
qc.cx(flip[3], tile[0])
qc.cx(flip[3], tile[3])
qc.cx(flip[3], tile[4])
qc.cx(flip[3], tile[6])
#For tile 1,1
qc.cx(flip[4], tile[1])
qc.cx(flip[4], tile[3])
qc.cx(flip[4], tile[4])
qc.cx(flip[4], tile[5])
qc.cx(flip[4], tile[7])
#For tile 1,2
qc.cx(flip[5], tile[2])
qc.cx(flip[5], tile[4])
qc.cx(flip[5], tile[5])
qc.cx(flip[5], tile[8])
#For tile 2,0
qc.cx(flip[6], tile[3])
qc.cx(flip[6], tile[6])
qc.cx(flip[6], tile[7])
#For tile 2,1
qc.cx(flip[7], tile[4])
qc.cx(flip[7], tile[6])
qc.cx(flip[7], tile[7])
qc.cx(flip[7], tile[8])
#For tile 2,2
qc.cx(flip[8], tile[5])
qc.cx(flip[8], tile[7])
qc.cx(flip[8], tile[8])
def light_out_grover(lights, N):
tile = QuantumRegister(9)
flip = QuantumRegister(9)
oracle_output = QuantumRegister(1)
result = ClassicalRegister(9)
qc = QuantumCircuit(tile, flip, oracle_output, result)
# -----------------------------------------------------
# Do not modify the code of this function above
# Initialization
counter = 0
for i in lights:
if i==1:
qc.x(tile[counter])
counter+=1
else:
counter+=1
qc.h(flip[0:9])
qc.x(oracle_output[0])
qc.h(oracle_output[0])
# Grover Iteration
for i in range(N):
# Apply the oracle
oracle(qc,flip,tile,oracle_output)
# diffusion
diffusion(qc,flip)
pass
# Remember to do some uncomputation
qc.h(oracle_output[0])
qc.x(oracle_output[0])
# Do not modify the code below
# ------------------------------------------------------
# Measuremnt
qc.measure(flip,result)
# Make the Out put order the same as the input.
qc = qc.reverse_bits()
from qiskit import execute, Aer
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend=backend, shots=50, seed_simulator=12345)
result = job.result()
count = result.get_counts()
score_sorted = sorted(count.items(), key=lambda x:x[1], reverse=True)
final_score = score_sorted[0:40]
solution = final_score[0][0]
return solution
# For local test, your program should print 110010101 110010101
lights = [0, 1, 1, 1, 0, 0, 1, 1, 1]
print(light_out_grover(lights,17))
|
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
|
mnp-club
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import numpy as np
from fractions import Fraction as frac
import qiskit.quantum_info as qi
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
qc=QuantumCircuit(4)
#In this particular oracle, the last qubit is storing the value of the function
qc.cx(0,3)
qc.cx(1,3)
qc.cx(2,3)
#The last qubit is 1 if there are odd no. of 1s in the other 3 qubits
#and 0 otherwise
#Hence it is a balanced function
qc.draw('mpl')
qc1=QuantumCircuit(3)
qc1.x(2)
qc1.h(0)
qc1.h(1)
qc1.h(2)
qc1.barrier(range(3))
qc1.cx(0,2)
qc1.cx(1,2)
qc1.barrier(range(3))
qc1.h(0)
qc1.h(1)
meas = QuantumCircuit(3, 2)
meas.measure(range(2),range(2))
# The Qiskit circuit object supports composition using
# the addition operator.
circ = qc1+meas
circ.draw('mpl')
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(circ, backend_sim, shots=1000)
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
print(counts)
plot_histogram(counts)
qc2=QuantumCircuit(5)
qc2.x(4)
qc2.h(0)
qc2.h(1)
qc2.h(2)
qc2.h(3)
qc2.h(4)
qc2.barrier(range(5))
#The oracle:
qc2.x(0)
qc2.x(1)
qc2.x(3)
qc2.cx(0,4)
qc2.cx(1,4)
qc2.cx(2,4)
qc2.cx(3,4)
qc2.x(0)
qc2.x(1)
qc2.x(3)
#oracle ends here
qc2.barrier(range(5))
qc2.h(0)
qc2.h(1)
qc2.h(2)
qc2.h(3)
meas2 = QuantumCircuit(5, 4)
meas2.measure(range(4),range(4))
circ2 = qc2+meas2
circ2.draw('mpl')
#verification cell, reinitialising the circuit so that it's easier for you to copy-paste the oracle
qc2=QuantumCircuit(5)
#Add X gates HERE as required to change the input state
#Let's check for |1001>
qc2.x(0)
qc2.x(3)
qc2.barrier(range(5))
#Copy and paste your code for the oracle from the above cell here
qc2.x(0)
qc2.x(1)
qc2.x(3)
qc2.cx(0,4)
qc2.cx(1,4)
qc2.cx(2,4)
qc2.cx(3,4)
qc2.x(0)
qc2.x(1)
qc2.x(3)
qc2.barrier(range(5))
measv = QuantumCircuit(5, 1)
measv.measure(4,0)
circv = qc2+measv
circv.draw('mpl')
#DO NOT RUN THIS CELL WITHOUT EDITING THE ABOVE ONE AS DESIRED
#The following code will give you f(x) for the value of x you chose in the above cell
backend_sim2 = Aer.get_backend('qasm_simulator')
job_sim2 = execute(circv, backend_sim2, shots=1000)
result_sim2 = job_sim2.result()
counts2 = result_sim2.get_counts(circv)
print(counts2)
plot_histogram(counts2)
#Similarly you can check f(x) for different values of x
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### added y gate ###
qc.cx(0, 1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
### added h gate ###
qc.h(0)
return qc
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with a single qubit
# The default initial state of qubit will be |0> or [1,0]
qc = QuantumCircuit(1)
#Apply pauli x-gate on the qubit
qc.x(0)
#Apply the hadamard gate on the qubit
qc.h(0)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
# visualize the output as an animation
visualize_transition(qc)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the 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
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
qc2.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXSimple
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXSimple(), backend=FakeBoeblingen())
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
from qiskit import *
from math import pi
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit_textbook.tools import array_to_latex
from qiskit.visualization import plot_bloch_multivector, plot_histogram, plot_state_city,plot_state_qsphere
%matplotlib inline
qc1 = QuantumCircuit(2)
qc1.draw('mpl')
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
final_state = execute(qc1,backend).result().get_statevector()
job = execute(qc1,backend).result() # Do the simulation, returning the state vector
print(final_state)
array_to_latex(final_state, pretext="\\text{Statevector} = ")
plot_state_qsphere(job.get_statevector(qc1))
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.draw('mpl')
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
final_state = execute(qc1,backend).result().get_statevector()
job = execute(qc1,backend).result() # Do the simulation, returning the state vector
print(final_state)
array_to_latex(final_state, pretext="\\text{Statevector} = ")
plot_state_qsphere(job.get_statevector(qc1))
qc1 = QuantumCircuit(2)
qc1.x(1)
qc1.draw('mpl')
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
final_state = execute(qc1,backend).result().get_statevector()
job = execute(qc1,backend).result() # Do the simulation, returning the state vector
print(final_state)
array_to_latex(final_state, pretext="\\text{Statevector = }")
plot_state_qsphere(job.get_statevector(qc1))
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.x(1)
qc1.draw('mpl')
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
final_state = execute(qc1,backend).result().get_statevector()
job = execute(qc1,backend).result() # Do the simulation, returning the state vector
print(final_state)
array_to_latex(final_state, pretext="\\text{Statevector} = ")
plot_state_qsphere(job.get_statevector(qc1))
sv = Statevector.from_label('00')
# Bell State |Ψ+>
qcb = QuantumCircuit(2)
qcb.h(0)
qcb.cx(0, 1)
qcb.draw('mpl')
new_sv = sv.evolve(qcb)
print(new_sv)
plot_state_qsphere(new_sv.data)
qc = QuantumCircuit(2)
# Apply H-gate to the first:
qc.h(0)
# Apply a CNOT:
qc.cx(0,1)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,backend).result().get_statevector()
job = execute(qc,backend).result() # Do the simulation, returning the state vector
print(np.round(final_state,10))
array_to_latex(final_state, pretext="\\text{Statevector} = ")
plot_state_qsphere(job.get_statevector(qc))
sv = Statevector.from_label('01')
# Bell State |Ψ+>
qcx = QuantumCircuit(2)
qcx.h(0)
qcx.cx(0, 1)
qcx.draw('mpl')
new_sv = sv.evolve(qcx)
print(new_sv)
plot_state_qsphere(new_sv.data)
qc = QuantumCircuit(2)
# Apply H-gate to the first:
qc.x(0)
qc.h(0)
# Apply a CNOT:
qc.cx(0,1)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,backend).result().get_statevector()
job = execute(qc,backend).result() # Do the simulation, returning the state vector
print(np.round(final_state,10))
array_to_latex(final_state, pretext="\\text{Statevector} = ")
plot_state_qsphere(job.get_statevector(qc))
sv = Statevector.from_label('10')
# Bell State |Ψ+>
qcx = QuantumCircuit(2)
qcx.h(0)
qcx.cx(0, 1)
qcx.draw('mpl')
new_sv = sv.evolve(qcx)
print(new_sv)
plot_state_qsphere(new_sv.data)
qc = QuantumCircuit(2)
# Apply H-gate to the first:
qc.x(1)
qc.h(0)
# Apply a CNOT:
qc.cx(0,1)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,backend).result().get_statevector()
job = execute(qc,backend).result() # Do the simulation, returning the state vector
print(np.round(final_state,10))
array_to_latex(final_state, pretext="\\text{Statevector} = ")
plot_state_qsphere(job.get_statevector(qc))
sv = Statevector.from_label('11')
# Bell State |Ψ+>
qcx = QuantumCircuit(2)
qcx.h(0)
qcx.cx(0, 1)
qcx.draw('mpl')
new_sv = sv.evolve(qcx)
print(new_sv)
plot_state_qsphere(new_sv.data)
qc = QuantumCircuit(2)
# Apply H-gate to the first:
qc.x(0)
qc.x(1)
qc.h(0)
# Apply a CNOT:
qc.cx(0,1)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,backend).result().get_statevector()
job = execute(qc,backend).result() # Do the simulation, returning the state vector
print(np.round(final_state,10))
array_to_latex(final_state, pretext="\\text{Statevector} = ")
plot_state_qsphere(job.get_statevector(qc))
|
https://github.com/HuangJunye/Qiskit-for-GameDev
|
HuangJunye
|
ILUA_LOG_LEVEL=debug
a =2
q_command
-- our API object
q_command = {}
q_command.tools_placed = false
q_command.game_running_time = 0
q_command.block_pos = {}
q_command.circuit_specs = {} -- dir_str, pos, num_wires, num_columns, is_on_grid
q_command.circuit_specs.pos = {} -- x, y, z
function q_command:create_qasm_for_node(circuit_node_pos, wire_num,
include_measurement_blocks, c_if_table, tomo_meas_basis)
local qasm_str = ""
local circuit_node_block = circuit_blocks:get_circuit_block(circuit_node_pos)
local q_block = q_command:get_q_command_block(circuit_node_pos)
if circuit_node_block then
local node_type = circuit_node_block.get_node_type()
if node_type == CircuitNodeTypes.EMPTY or
node_type == CircuitNodeTypes.TRACE or
node_type == CircuitNodeTypes.CTRL then
-- Throw away a c_if if present
c_if_table[wire_num] = ""
-- Return immediately with zero length qasm_str
return qasm_str
else
if c_if_table[wire_num] and c_if_table[wire_num] ~= "" then
qasm_str = qasm_str .. c_if_table[wire_num] .. " "
c_if_table[wire_num] = ""
end
end
local ctrl_a = circuit_node_block.get_ctrl_a()
local ctrl_b = circuit_node_block.get_ctrl_b()
local swap = circuit_node_block.get_swap()
local radians = circuit_node_block.get_radians()
-- For convenience and brevity, create a zero-based, string, wire number
--local wire_num_idx = tostring(wire_num - 1 +
-- circuit_node_block.get_circuit_specs_wire_num_offset())
--local ctrl_a_idx = tostring(ctrl_a - 1 +
-- circuit_node_block.get_circuit_specs_wire_num_offset())
--local ctrl_b_idx = tostring(ctrl_b - 1 +
-- circuit_node_block.get_circuit_specs_wire_num_offset())
-- TODO: Replace above with below?
local wire_num_idx = tostring(wire_num - 1)
local ctrl_a_idx = tostring(ctrl_a - 1)
local ctrl_b_idx = tostring(ctrl_b - 1)
local swap_idx = tostring(swap - 1)
if node_type == CircuitNodeTypes.IDEN then
-- Identity gate
qasm_str = qasm_str .. 'id q[' .. wire_num_idx .. '];'
elseif node_type == CircuitNodeTypes.X then
local threshold = 0.0001
if math.abs(radians - math.pi) <= threshold then
if ctrl_a ~= -1 then
if ctrl_b ~= -1 then
-- Toffoli gate
qasm_str = qasm_str .. 'ccx q[' .. ctrl_a_idx .. '],'
qasm_str = qasm_str .. 'q[' .. ctrl_b_idx .. '],'
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
else
-- Controlled X gate
qasm_str = qasm_str .. 'cx q[' .. ctrl_a_idx .. '],'
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
end
else
-- Pauli-X gate
qasm_str = qasm_str .. 'x q[' .. wire_num_idx .. '];'
end
else
-- Rotation around X axis
qasm_str = qasm_str .. 'rx(' .. tostring(radians) .. ') '
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
end
elseif node_type == CircuitNodeTypes.Y then
local threshold = 0.0001
if math.abs(radians - math.pi) <= threshold then
if ctrl_a ~= -1 then
-- Controlled Y gate
qasm_str = qasm_str .. 'cy q[' .. ctrl_a_idx .. '],'
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
else
-- Pauli-Y gate
qasm_str = qasm_str .. 'y q[' .. wire_num_idx .. '];'
end
else
-- Rotation around Y axis
qasm_str = qasm_str .. 'ry(' .. tostring(radians) .. ') '
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
end
elseif node_type == CircuitNodeTypes.Z then
local threshold = 0.0001
if math.abs(radians - math.pi) <= threshold then
if ctrl_a ~= -1 then
-- Controlled Z gate
qasm_str = qasm_str .. 'cz q[' .. ctrl_a_idx .. '],'
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
else
-- Pauli-Z gate
qasm_str = qasm_str .. 'z q[' .. wire_num_idx .. '];'
end
else
if circuit_node_block.get_ctrl_a() ~= -1 then
-- Controlled rotation around the Z axis
qasm_str = qasm_str .. 'crz(' .. tostring(radians) .. ') '
qasm_str = qasm_str .. 'q[' .. ctrl_a_idx .. '],'
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
else
-- Rotation around Z axis
qasm_str = qasm_str .. 'rz(' .. tostring(radians) .. ') '
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
end
end
elseif node_type == CircuitNodeTypes.S then
-- S gate
qasm_str = qasm_str .. 's q[' .. wire_num_idx .. '];'
elseif node_type == CircuitNodeTypes.SDG then
-- S dagger gate
qasm_str = qasm_str .. 'sdg q[' .. wire_num_idx .. '];'
elseif node_type == CircuitNodeTypes.T then
-- T gate
qasm_str = qasm_str .. 't q[' .. wire_num_idx .. '];'
elseif node_type == CircuitNodeTypes.TDG then
-- T dagger gate
qasm_str = qasm_str .. 'tdg q[' .. wire_num_idx .. '];'
elseif node_type == CircuitNodeTypes.H then
if ctrl_a ~= -1 then
-- Controlled Hadamard
qasm_str = qasm_str .. 'ch q[' .. ctrl_a_idx .. '],'
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
else
-- Hadamard gate
qasm_str = qasm_str .. 'h q[' .. wire_num_idx .. '];'
end
elseif node_type == CircuitNodeTypes.BARRIER then
-- barrier
qasm_str = qasm_str .. 'barrier q[' .. wire_num_idx .. '];'
elseif node_type == CircuitNodeTypes.MEASURE_Z then
if include_measurement_blocks then
-- Measurement block
--qasm_str = qasm_str .. 'measure q[' .. wire_num_idx .. '] -> c[' .. wire_num_idx .. '];'
qasm_str = qasm_str .. 'measure q[' .. wire_num_idx .. '] -> c' .. wire_num_idx .. '[0];'
end
elseif node_type == CircuitNodeTypes.QUBIT_BASIS then
qasm_str = qasm_str .. 'reset q[' .. wire_num_idx .. '];'
if circuit_node_block.get_node_name():sub(-2) == "_1" then
qasm_str = qasm_str .. 'x q[' .. wire_num_idx .. '];'
end
elseif node_type == CircuitNodeTypes.CONNECTOR_M then
-- Connector to wire extension, so traverse
local wire_extension_block_pos = circuit_node_block.get_wire_extension_block_pos()
if wire_extension_block_pos.x ~= 0 then
local wire_extension_block = circuit_blocks:get_circuit_block(wire_extension_block_pos)
local wire_extension_dir_str = wire_extension_block.get_circuit_dir_str()
local wire_extension_circuit_pos = wire_extension_block.get_circuit_pos()
if wire_extension_circuit_pos.x ~= 0 then
local wire_extension_circuit = circuit_blocks:get_circuit_block(wire_extension_circuit_pos)
local extension_wire_num = wire_extension_circuit.get_circuit_specs_wire_num_offset() + 1
local extension_num_columns = wire_extension_circuit.get_circuit_num_columns()
for column_num = 1, extension_num_columns do
-- Assume dir_str is "+Z"
local circ_node_pos = {x = wire_extension_circuit_pos.x + column_num - 1,
y = wire_extension_circuit_pos.y,
z = wire_extension_circuit_pos.z}
if wire_extension_dir_str == "+X" then
circ_node_pos = {x = wire_extension_circuit_pos.x,
y = wire_extension_circuit_pos.y,
z = wire_extension_circuit_pos.z - column_num + 1}
elseif wire_extension_dir_str == "-X" then
circ_node_pos = {x = wire_extension_circuit_pos.x,
y = wire_extension_circuit_pos.y,
z = wire_extension_circuit_pos.z + column_num - 1}
elseif wire_extension_dir_str == "-Z" then
circ_node_pos = {x = wire_extension_circuit_pos.x - column_num + 1,
y = wire_extension_circuit_pos.y,
z = wire_extension_circuit_pos.z}
end
qasm_str = qasm_str ..
q_command:create_qasm_for_node(circ_node_pos,
extension_wire_num, include_measurement_blocks,
c_if_table, tomo_meas_basis)
end
end
end
elseif node_type == CircuitNodeTypes.SWAP and swap ~= -1 then
if ctrl_a ~= -1 then
-- Controlled Swap
qasm_str = qasm_str .. 'cswap q[' .. ctrl_a_idx .. '],'
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '],'
qasm_str = qasm_str .. 'q[' .. swap_idx .. '];'
else
-- Swap gate
qasm_str = qasm_str .. 'swap q[' .. wire_num_idx .. '],'
qasm_str = qasm_str .. 'q[' .. swap_idx .. '];'
end
elseif node_type == CircuitNodeTypes.C_IF then
local node_name = circuit_node_block.get_node_name()
local register_idx_str = node_name:sub(35, 35)
local eq_val_str = node_name:sub(39, 39)
c_if_table[wire_num] = "if(c" .. register_idx_str .. "==" ..
eq_val_str .. ")"
elseif node_type == CircuitNodeTypes.BLOCH_SPHERE or
node_type == CircuitNodeTypes.COLOR_QUBIT then
if include_measurement_blocks then
if tomo_meas_basis == 1 then
-- Measure in the X basis (by first rotating -pi/2 radians on Y axis)
qasm_str = qasm_str .. 'ry(' .. tostring(-math.pi / 2) .. ') '
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
elseif tomo_meas_basis == 2 then
-- Measure in the Y basis (by first rotating pi/2 radians on X axis)
qasm_str = qasm_str .. 'rx(' .. tostring(math.pi / 2) .. ') '
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
elseif tomo_meas_basis == 3 then
-- Measure in the Z basis (no rotation necessary)
end
qasm_str = qasm_str .. 'measure q[' .. wire_num_idx .. '] -> c' .. wire_num_idx .. '[0];'
end
end
else
print("Unknown gate!")
end
if LOG_DEBUG then
minetest.debug("End of create_qasm_for_node(), qasm_str:\n" .. qasm_str)
end
return qasm_str
end
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Instruction collection.
"""
from __future__ import annotations
from typing import Callable
from qiskit.circuit.exceptions import CircuitError
from .classicalregister import Clbit, ClassicalRegister
from .operation import Operation
from .quantumcircuitdata import CircuitInstruction
class InstructionSet:
"""Instruction collection, and their contexts."""
__slots__ = ("_instructions", "_requester")
def __init__( # pylint: disable=bad-docstring-quotes
self,
*,
resource_requester: Callable[..., ClassicalRegister | Clbit] | None = None,
):
"""New collection of instructions.
The context (``qargs`` and ``cargs`` that each instruction is attached to) is also stored
separately for each instruction.
Args:
resource_requester: A callable that takes in the classical resource used in the
condition, verifies that it is present in the attached circuit, resolves any indices
into concrete :obj:`.Clbit` instances, and returns the concrete resource. If this
is not given, specifying a condition with an index is forbidden, and all concrete
:obj:`.Clbit` and :obj:`.ClassicalRegister` resources will be assumed to be valid.
.. note::
The callback ``resource_requester`` is called once for each call to
:meth:`.c_if`, and assumes that a call implies that the resource will now be
used. It may throw an error if the resource is not valid for usage.
"""
self._instructions: list[CircuitInstruction] = []
self._requester = resource_requester
def __len__(self):
"""Return number of instructions in set"""
return len(self._instructions)
def __getitem__(self, i):
"""Return instruction at index"""
return self._instructions[i]
def add(self, instruction, qargs=None, cargs=None):
"""Add an instruction and its context (where it is attached)."""
if not isinstance(instruction, CircuitInstruction):
if not isinstance(instruction, Operation):
raise CircuitError("attempt to add non-Operation to InstructionSet")
if qargs is None or cargs is None:
raise CircuitError("missing qargs or cargs in old-style InstructionSet.add")
instruction = CircuitInstruction(instruction, tuple(qargs), tuple(cargs))
self._instructions.append(instruction)
def inverse(self):
"""Invert all instructions."""
for i, instruction in enumerate(self._instructions):
self._instructions[i] = instruction.replace(operation=instruction.operation.inverse())
return self
def c_if(self, classical: Clbit | ClassicalRegister | int, val: int) -> "InstructionSet":
"""Set a classical equality condition on all the instructions in this set between the
:obj:`.ClassicalRegister` or :obj:`.Clbit` ``classical`` and value ``val``.
.. note::
This is a setter method, not an additive one. Calling this multiple times will silently
override any previously set condition on any of the contained instructions; it does not
stack.
Args:
classical: the classical resource the equality condition should be on. If this is given
as an integer, it will be resolved into a :obj:`.Clbit` using the same conventions
as the circuit these instructions are attached to.
val: the value the classical resource should be equal to.
Returns:
This same instance of :obj:`.InstructionSet`, but now mutated to have the given equality
condition.
Raises:
CircuitError: if the passed classical resource is invalid, or otherwise not resolvable
to a concrete resource that these instructions are permitted to access.
Example:
.. plot::
:include-source:
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')
"""
if self._requester is None and not isinstance(classical, (Clbit, ClassicalRegister)):
raise CircuitError(
"Cannot pass an index as a condition variable without specifying a requester"
" when creating this InstructionSet."
)
if self._requester is not None:
classical = self._requester(classical)
for instruction in self._instructions:
instruction.operation.c_if(classical, val)
return self
# Legacy support for properties. Added in Terra 0.21 to support the internal switch in
# `QuantumCircuit.data` from the 3-tuple to `CircuitInstruction`.
@property
def instructions(self):
"""Legacy getter for the instruction components of an instruction set. This does not
support mutation."""
return [instruction.operation for instruction in self._instructions]
@property
def qargs(self):
"""Legacy getter for the qargs components of an instruction set. This does not support
mutation."""
return [list(instruction.qubits) for instruction in self._instructions]
@property
def cargs(self):
"""Legacy getter for the cargs components of an instruction set. This does not support
mutation."""
return [list(instruction.clbits) for instruction in self._instructions]
|
https://github.com/lancecarter03/QiskitLearning
|
lancecarter03
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers.aer import QasmSimulator
from qiskit.visualization import plot_histogram
circuit = QuantumCircuit(2,2)
circuit.h(0)
circuit.cx(0,1)
circuit.measure([0,1],[0,1])
circuit.draw()
|
https://github.com/rodolfocarobene/SPVQE
|
rodolfocarobene
|
import numpy as np
from qiskit.circuit.library import TwoLocal
from qiskit_nature.drivers import UnitsType
from qiskit_nature.drivers.second_quantization.electronic_structure_driver import MethodType
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import ParityMapper
from qiskit_nature.circuit.library import HartreeFock
from qiskit_nature.drivers.second_quantization import PySCFDriver
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
# ansatz
def get_ansatz_test():
converter = QubitConverter(mapper=ParityMapper(), two_qubit_reduction=True)
init_st = HartreeFock(4, (1,1), converter)
ansatz = TwoLocal(num_qubits=4,
rotation_blocks='ry',
entanglement_blocks='cx',
entanglement=[(0,1),(1,2),(1,3)],
reps=2,
name='TwoLocal',
initial_state=init_st)
return ansatz
# hamiltonian
def get_hamiltonian_test(dist):
converter = QubitConverter(mapper=ParityMapper(), two_qubit_reduction=True)
alt = np.sqrt(dist**2 - (dist/2)**2)
geom = f'H .0 .0 .0; H .0 .0 {dist}; H .0 {alt} {dist/2}'
driver = PySCFDriver(atom=geom,
unit=UnitsType.ANGSTROM,
basis='sto6g',
spin=0,
charge=1,
method=MethodType.RHF)
problem = ElectronicStructureProblem(driver)
hamiltonian = problem.second_q_ops()[0]
circuit_hamiltonian = converter.convert(hamiltonian, 2)
return circuit_hamiltonian
# DISTANZA 0.5
# NUMERO 1
vqe_pars_05_a = [-0.11550176, 0.12474728, 2.59668356, 3.8576121,
0.08466277, -0.08561239, 0.33366492, -0.09046052,
-0.01809542, 0.03835604, -0.19827222, 0.61663081]
spvqe_pars_05_a = [-0.14645914, 0.24085774, 2.4493363, 4.39635615,
0.0412351, -0.037009016, 0.13252825, -0.08387666,
-0.06751748, -0.1701828, -0.44594079, 1.11174508]
# NUMERO 2
vqe_pars_05_b = [0.05880473, -0.49585711, 1.38931493, 1.22058033,
0.04743988, -0.35168815, 1.23629905, 1.31486832,
-0.04791204, -0.12251855, -0.42800105, -0.54385726]
spvqe_pars_05_b = [-0.0524159, -0.35065509, 1.50978572, 1.44223811,
0.10572807, -0.3610393, 1.09925545, 1.16282622,
0.0417312, -0.03228112, -0.52763223, -0.54086796]
# NUMERO 3
vqe_pars_05_c = [-0.13742697, 0.06666297, 1.00157735, 1.26190522,
0.11471872, 0.04703104, 1.76370044, 1.61734347,
0.12522114, 0.01627249, -0.5024544, -0.2438825 ]
spvqe_pars_05_c = [-0.00932172, -0.26494813, 1.39315548, 1.32781559,
0.08164483, -0.23497221, 1.17428293, 1.23188309,
-0.00308427, -0.00491096, -0.60690943, -0.58952378]
# NUMERO 4
vqe_pars_05_d = [0.16870004, -0.43813479, 1.29677422, 1.25914724,
-0.04299792, -0.35431175,1.29298694, 1.26077492,
-0.15053771, -0.19731699, -0.51811108, -0.6556562]
spvqe_pars_05_d = [5.02394671, 9.41745152, 1.68675252, 7.85071438,
3.19550059, 9.42166769, 5.09519325, 2.59998515,
1.88735871, 3.1531819, 5.93912936, 2.11561298]
vqes_05 = [vqe_pars_05_a, vqe_pars_05_b, vqe_pars_05_c, vqe_pars_05_d]
spvqes_05 = [spvqe_pars_05_a, spvqe_pars_05_b, spvqe_pars_05_c, spvqe_pars_05_d]
# DISTANZA 1.0
# NUMERO 1
vqe_pars_10_a = [6.16740344, 3.20411669, 5.67528188 ,3.67933879,
2.95053784, 6.2426416, 5.32863549, 6.09733424,
3.16169489, 0.10689151, 5.8707268, 2.40834679]
spvqe_pars_10_a = [ 5.52205337, 6.33947666, 4.99314629, 1.56646707,
6.42004486, 9.34654435, 1.64389086, 1.53953422,
0.73439052, 9.42814649, -0.27327807, 9.44921354]
# NUMERO 2
vqe_pars_10_b = [-0.3512596, -0.0434752, 1.0358355, 1.46491864 ,
0.20682505, -0.00289901, 1.43619352, 1.23273737,
0.29697954 ,-0.07741656, -0.64436651, -0.4226421 ]
spvqe_pars_10_b = [-0.46588444 , 0.03577865 , 1.12642329, 1.60349416,
0.16878282, 0.03519882, 1.58751012, 1.25972376,
0.41562211, 0.01466055, -0.38381825, -0.28252069]
# NUMERO 3
vqe_pars_10_c = [ 0.62969728, 0.11563254, 1.90128434, 1.46585069,
0.18945206, 0.26035458, 0.80622198, 0.43826824,
-0.67497233 , 0.1055656 , -0.53464882, -1.27380774]
spvqe_pars_10_c = [ 0.5916648 , 1.06775659 , 1.57289366 , 1.56449836,
0.74571656, 1.14593536, 1.64660689, 1.73306393,
-0.25437019, -0.0159303 , 0.05439476, 0.16162612]
# NUMERO 4
vqe_pars_10_d = [ 0.99493485, 0.46749555, 1.66718638, 1.57712555,
0.76606805, 0.69293642, 1.88378101, 1.78376671,
-0.8351959, -0.06788017, 0.33365866, 0.21094284]
spvqe_pars_10_d = [ 1.27976371, -0.48962493, -1.35773093, 1.44466152,
2.0692902, -1.85807479, -0.80085892 , 0.50904985,
2.18264396, 0.25188056, 0.82224704, -1.06459749]
vqes_10 = [vqe_pars_10_a, vqe_pars_10_b, vqe_pars_10_c, vqe_pars_10_d]
spvqes_10 = [spvqe_pars_10_a, spvqe_pars_10_b, spvqe_pars_10_c, spvqe_pars_10_d]
# DISTANZA 1.5 (19_04_10_47.log)
# NUMERO 1
vqe_pars_15_a = [0.09991746, 0.62611588, 1.89744194, 4.32594859,
-0.07035062, -0.31686141, 0.54348101, 4.58529642,
0.05761779, -0.09718047, -0.71666062, 3.03730765]
spvqe_pars_15_a = [0.21380667, 0.2427542, 2.65108444, 8.19294383,
-0.25609082, 0.09342074, 0.35346509, 3.82999585,
-0.06775606, 0.17041844, -0.20121347, 2.58884638]
# NUMERO 2
vqe_pars_15_b = [-0.21548311, 0.20120314, 2.30422198, 4.48161905,
0.13964768, -0.19722156, 0.09335863, 0.23036292,
-0.38731748, -0.07424302, -1.00785697, 0.98497606]
spvqe_pars_15_b = [0.61714577, 2.47534277, 3.17142515, 4.70746919,
1.35411788, -1.58468248, 1.60239857, -0.02513338,
-0.97090705, -1.55142321, -0.79341562, 1.60062894]
# NUMERO 3
vqe_pars_15_c = [0.97968128, 1.57688493, 1.1570894, 1.60995628,
1.34060246, 1.39458515, 1.92058373, 0.14457375,
0.15368186, 0.51329187, 0.19821282, 0.04170353]
spvqe_pars_15_c = [ 0.48976517, -0.08104914, 0.72184541, -1.75849263,
0.25320102, 0.03368859, 2.59738978, -0.78635837,
0.28449398, -0.04249177, 0.2943293, 0.62921035]
# NUMERO 4
vqe_pars_15_d = [ 0.84450869, 1.25491968, -0.44514397, 2.38703763,
0.94495797, 0.15694397, 2.98751578, -0.692738 ,
-0.11166693, 0.72361479, -0.50367291, 0.49284549]
spvqe_pars_15_d = [ 3.90221684e-01, -4.15178472e-02, -2.99633796e-01 ,-1.58264586e+00,
2.13748167e-01, -5.61087214e-04, 3.11964764e+00, -7.96008889e-01,
-1.51861563e-01, -5.91138869e-02, -2.71376710e-01, 7.52653356e-01]
vqes_15 = [vqe_pars_15_a, vqe_pars_15_b, vqe_pars_15_c, vqe_pars_15_d]
spvqes_15 = [spvqe_pars_15_a, spvqe_pars_15_b, spvqe_pars_15_c, spvqe_pars_15_d]
# DISTANZA 2.0
# NUMERO 1
vqe_pars_20_a = [0.23225322, 4.20509329, 1.82170197, 4.27582049,
0.05729869, 0.15604462, 0.06000301, -0.13579914,
0.08299985, -1.07408837, -1.21879918, 1.24899782]
spvqe_pars_20_a = [1.43809554, 7.81734322, 3.17165507, 4.75015336,
2.33703869, -0.38781625, 0.44597784, -0.12498502,
-0.12032009, -1.55407031, -0.10911732, 1.61769171]
# NUMERO 2
vqe_pars_20_b = [6.65022149e-03, -9.50528847e-02, 1.60330579e+00, 7.19883316e+00,
-1.57724593e-02, -1.29639965e+00, -2.27676219e-02, 3.24072370e+00,
-7.34213970e-02, -1.27990560e+00, -1.48335812e+00, 1.75404689e+00]
spvqe_pars_20_b = [0.79587883, 0.32760775, 3.35288526, 7.85590383,
-0.0390306, -0.69694168, -1.4426973, 3.36124759,
-0.01221064, 0.74481681, -1.12900567, 1.70637381]
# NUMERO 3
vqe_pars_20_c = [-0.08454793, 5.11004342, 1.83282241, 4.5149173,
0.09799665, -0.57644001, -0.15790267, -0.14204233,
0.08811245, -1.19742568, -1.15342555, 1.45476172]
spvqe_pars_20_c = [0.11532082, 8.09680516, 2.37427009, 4.68877452,
1.42678813, -0.14232414, 0.17262165, -0.04088128,
-1.4429427, -1.6389454, -1.21152173, 1.53310367]
# NUMERO 4
vqe_pars_20_d = [-0.10993742, 1.08577653, -0.05778733, 1.43690763,
0.8346593, -0.64097313, -0.55031438, -0.02333615,
0.35142381, 1.30165111, 0.38822238, 1.1910818 ]
spvqe_pars_20_d = [-0.35471067, 1.3383629, 0.01617288, 1.44855139,
0.44430146, 1.60495214, 1.48593211, 0.08656238,
-0.34956568, 1.54163135, -0.18345526, -1.55837365]
vqes_20 = [vqe_pars_20_a, vqe_pars_20_b, vqe_pars_20_c, vqe_pars_20_d]
spvqes_20 = [spvqe_pars_20_a, spvqe_pars_20_b, spvqe_pars_20_c, spvqe_pars_20_d]
# DISTANZA 2.5
# NUMERO 1
vqe_pars_25_a = [-0.30538821, 4.60997242, 7.66433589, 4.17372787,
0.10927006, -0.51266663, 0.23441709, -0.334758,
-0.22351772, -0.53313997, -1.533864, 1.46004641]
spvqe_pars_25_a = [-1.24650601, 5.78497934, 9.18265278, 4.73156897,
-0.08129257, -0.41884356, -0.65460038, -0.08477229,
-0.97708064, 0.75940663, -1.0149008, 1.42565896]
# NUMERO 2
vqe_pars_25_b = [-0.57303308, 4.98891235, 1.94492016 , 4.53017413,
0.62503729, -0.61011673, -0.20483872, -0.11683771,
0.10371051, -1.2520706, -0.91139273, 1.4457862 ]
spvqe_pars_25_b = [-6.40316565e-01, 8.15161506e+00, 3.06074748e+00, 4.67190248e+00,
6.19902164e-01, -1.27453265e+00, 1.29407199e+00, -6.22156917e-03,
-7.40268451e-01, -1.58162040e+00, -3.93077842e-01, 1.55191480e+00]
# NUMERO 3
vqe_pars_25_c = [ 2.71938179e-02, 5.12982224e-01, 1.17797400e+00, -9.06135220e-02,
7.21795803e-04, -3.56296414e-01, 1.32625535e+00, 6.68248236e-03,
8.74291139e-02, -1.45434574e-01, -6.86335893e-01, -1.34254368e-01]
spvqe_pars_25_c = [ 0.99843238, 0.44052177, -0.1961437, -1.02581547,
-0.77302264, -0.7235378, -0.82344231, 0.26436617,
1.26044456, -0.31363713, -1.2597413, 1.28040742]
# NUMERO 4
vqe_pars_25_d = [ 0.18502226, 0.81530577, 0.73862034, 1.64122226,
0.21070779, 0.89669377, 1.56170187, -0.22372298,
0.18602616 , 0.63184611, -0.52464817, 1.38476156]
spvqe_pars_25_d = [ 1.53050786, 0.19805966, 0.09745304, -1.13801992,
0.4664388, 0.42438396, 1.14798148, 0.63809267,
2.067302, 0.01598754, 1.04750262, 1.75522881]
vqes_25 = [vqe_pars_25_a, vqe_pars_25_b, vqe_pars_25_c, vqe_pars_25_d]
spvqes_25 = [spvqe_pars_25_a, spvqe_pars_25_b, spvqe_pars_25_c, spvqe_pars_25_d]
vqe = [vqes_05, vqes_10, vqes_15, vqes_20, vqes_25]
spvqe = [spvqes_05, spvqes_10, spvqes_15, spvqes_20, spvqes_25]
from mitiq import zne
from functools import partial
from qiskit import Aer, IBMQ
from qiskit.utils import QuantumInstance
from qiskit.providers.aer.noise import NoiseModel
from qiskit.utils.mitigation import CompleteMeasFitter
from qiskit.opflow import CircuitStateFn, StateFn, PauliExpectation, CircuitSampler
#provider = IBMQ.load_account()
dist = 2.5
qubit_op = get_hamiltonian_test(dist)
my_ansatz = get_ansatz_test().assign_parameters(spvqe_pars_25_d).decompose()
def get_expectation(ansatz):
tot = 0
for pauli in qubit_op:
psi = CircuitStateFn( ansatz )
measurable_expression = StateFn( pauli, is_measurement = True ).compose( psi )
expectation = PauliExpectation().convert( measurable_expression )
sampler_qasm = CircuitSampler( quantuminstance ).convert( expectation )
expect_sampling_qasm = sampler_qasm.eval().real
tot += expect_sampling_qasm
return tot
shots = 10000
backend = Aer.get_backend('qasm_simulator' )
noise_model = NoiseModel.from_backend(provider.get_backend('ibmq_quito'))
measurement_error_mitigation_cls=CompleteMeasFitter
optimization_level = 0
quantuminstance = QuantumInstance(backend,
shots=shots,
noise_model=noise_model,
optimization_level=optimization_level,
measurement_error_mitigation_cls=measurement_error_mitigation_cls)
scale_factors = [1.0, 2.0, 3.0, 3.5]
mitigated = zne.execute_with_zne(my_ansatz, get_expectation,
factory=zne.inference.RichardsonFactory(scale_factors=scale_factors),
num_to_average=3,
scale_noise=partial(zne.scaling.fold_gates_from_left))
not_mitigated = get_expectation(my_ansatz)
quantuminstance = QuantumInstance(Aer.get_backend('statevector_simulator'))
exact = get_expectation(my_ansatz)
print(mitigated, not_mitigated, exact)
|
https://github.com/Qiskit/feedback
|
Qiskit
|
import qiskit
qiskit.__version__
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.compiler import transpile
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
qc = QuantumCircuit(qreg, creg)
qc.h([0, 1])
qc.h([0, 1])
qc.h([0, 1])
qc.measure([0, 1], [0, 1])
with qc.switch(creg) as case:
with case(0): # if the register is '00'
qc.z(0)
with case(1, 2): # if the register is '01' or '10'
qc.cx(0, 1)
with case(case.DEFAULT): # the default case
qc.h(0)
qc.draw("mpl")
from qiskit.compiler import transpile
from qiskit.providers.fake_provider import FakeBelemV2
from qiskit.circuit import SwitchCaseOp, IfElseOp, WhileLoopOp
backend = FakeBelemV2()
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
transpile(qc, backend, optimization_level=2, seed_transpiler=671_44).draw('mpl')
transpile(qc, backend, optimization_level=3, seed_transpiler=671_44).draw('mpl')
from qiskit.circuit.classical import expr
qr = QuantumRegister(4)
cr1 = ClassicalRegister(2)
cr2 = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr1, cr2)
qc.h(0)
qc.cx(0, 1)
qc.h(2)
qc.cx(2, 3)
qc.measure([0, 1, 2, 3], [0, 1, 2, 3])
# If the two registers are equal to each other.
with qc.if_test(expr.equal(cr1, cr2)):
qc.x(0)
# While either of two bits are set.
with qc.while_loop(expr.logic_or(cr1[0], cr1[1])):
qc.reset(0)
qc.reset(1)
qc.measure([0, 1], cr1)
qc.draw('mpl')
from qiskit.qasm3 import dumps
print(dumps(transpile(qc, backend, optimization_level=3)))
from qiskit.algorithms import VQE
import itertools
from math import pi
from qiskit.circuit.library import EfficientSU2
from qiskit.providers.fake_provider import FakeSherbrooke
backend = FakeSherbrooke()
circuit = EfficientSU2(127, entanglement='linear', reps=50)
print(f"Number of circuit parameters: {len(circuit.parameters)}")
value_cycle = itertools.cycle([0, pi / 4, pi / 2, 3*pi / 4, pi, 2* pi])
%timeit -n 1 circuit.assign_parameters([x[1] for x in zip(range(len(circuit.parameters)), value_cycle)], inplace=False)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
# TODO: This example should use a real mock backend.
backend = FakeOpenPulse3Q()
d2 = pulse.DriveChannel(2)
with pulse.build(backend) as bell_prep:
pulse.u2(0, math.pi, 0)
pulse.cx(0, 1)
with pulse.build(backend) as decoupled_bell_prep_and_measure:
# We call our bell state preparation schedule constructed above.
with pulse.align_right():
pulse.call(bell_prep)
pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2)
pulse.barrier(0, 1, 2)
registers = pulse.measure_all()
decoupled_bell_prep_and_measure.draw()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Providers that support BackendV1 interface"""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeProvider
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit_algorithms import VQE, Grover, AmplificationProblem
from qiskit.opflow import X, Z, I
from qiskit_algorithms.optimizers import SPSA
from qiskit.circuit.library import TwoLocal, EfficientSU2
from qiskit.utils.mitigation import CompleteMeasFitter
class TestBackendV1(QiskitAlgorithmsTestCase):
"""test BackendV1 interface"""
def setUp(self):
super().setUp()
self._provider = FakeProvider()
self._qasm = self._provider.get_backend("fake_qasm_simulator")
self.seed = 50
def test_vqe_qasm(self):
"""Test the VQE on QASM simulator."""
optimizer = SPSA(maxiter=300, last_avg=5)
wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
with self.assertWarns(DeprecationWarning):
h2_op = (
-1.052373245772859 * (I ^ I)
+ 0.39793742484318045 * (I ^ Z)
- 0.39793742484318045 * (Z ^ I)
- 0.01128010425623538 * (Z ^ Z)
+ 0.18093119978423156 * (X ^ X)
)
qasm_simulator = QuantumInstance(
self._qasm, shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed
)
with self.assertWarns(DeprecationWarning):
vqe = VQE(
ansatz=wavefunction,
optimizer=optimizer,
max_evals_grouped=1,
quantum_instance=qasm_simulator,
)
result = vqe.compute_minimum_eigenvalue(operator=h2_op)
self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05)
def test_run_circuit_oracle(self):
"""Test execution with a quantum circuit oracle"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=["11"])
with self.assertWarns(DeprecationWarning):
qi = QuantumInstance(
self._provider.get_backend("fake_vigo"), seed_simulator=12, seed_transpiler=32
)
with self.assertWarns(DeprecationWarning):
grover = Grover(quantum_instance=qi)
result = grover.amplify(problem)
self.assertIn(result.top_measurement, ["11"])
def test_run_circuit_oracle_single_experiment_backend(self):
"""Test execution with a quantum circuit oracle"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=["11"])
backend = self._provider.get_backend("fake_vigo")
backend._configuration.max_experiments = 1
with self.assertWarns(DeprecationWarning):
qi = QuantumInstance(backend, seed_simulator=12, seed_transpiler=32)
with self.assertWarns(DeprecationWarning):
grover = Grover(quantum_instance=qi)
result = grover.amplify(problem)
self.assertIn(result.top_measurement, ["11"])
def test_measurement_error_mitigation_with_vqe(self):
"""measurement error mitigation test with vqe"""
try:
from qiskit.providers.aer import noise
except ImportError as ex:
self.skipTest(f"Package doesn't appear to be installed. Error: '{str(ex)}'")
return
algorithm_globals.random_seed = 0
# build noise model
noise_model = noise.NoiseModel()
read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]])
noise_model.add_all_qubit_readout_error(read_err)
backend = self._qasm
with self.assertWarns(DeprecationWarning):
quantum_instance = QuantumInstance(
backend=backend,
seed_simulator=167,
seed_transpiler=167,
noise_model=noise_model,
measurement_error_mitigation_cls=CompleteMeasFitter,
)
h2_hamiltonian = (
-1.052373245772859 * (I ^ I)
+ 0.39793742484318045 * (I ^ Z)
- 0.39793742484318045 * (Z ^ I)
- 0.01128010425623538 * (Z ^ Z)
+ 0.18093119978423156 * (X ^ X)
)
optimizer = SPSA(maxiter=200)
ansatz = EfficientSU2(2, reps=1)
with self.assertWarns(DeprecationWarning):
vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance)
result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian)
self.assertGreater(quantum_instance.time_taken, 0.0)
quantum_instance.reset_execution_results()
self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05)
if __name__ == "__main__":
unittest.main()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (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.
"""Tests for visualization tools."""
import unittest
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit
from qiskit.visualization.circuit import _utils
from qiskit.visualization import array_to_latex
from qiskit.test import QiskitTestCase
from qiskit.utils import optionals
class TestVisualizationUtils(QiskitTestCase):
"""Tests for circuit drawer utilities."""
def setUp(self):
super().setUp()
self.qr1 = QuantumRegister(2, "qr1")
self.qr2 = QuantumRegister(2, "qr2")
self.cr1 = ClassicalRegister(2, "cr1")
self.cr2 = ClassicalRegister(2, "cr2")
self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2)
self.circuit.cx(self.qr2[0], self.qr2[1])
self.circuit.measure(self.qr2[0], self.cr2[0])
self.circuit.cx(self.qr2[1], self.qr2[0])
self.circuit.measure(self.qr2[1], self.cr2[1])
self.circuit.cx(self.qr1[0], self.qr1[1])
self.circuit.measure(self.qr1[0], self.cr1[0])
self.circuit.cx(self.qr1[1], self.qr1[0])
self.circuit.measure(self.qr1[1], self.cr1[1])
def test_get_layered_instructions(self):
"""_get_layered_instructions without reverse_bits"""
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(self.circuit)
exp = [
[("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())],
[("measure", (self.qr2[0],), (self.cr2[0],))],
[("measure", (self.qr1[0],), (self.cr1[0],))],
[("cx", (self.qr2[1], self.qr2[0]), ()), ("cx", (self.qr1[1], self.qr1[0]), ())],
[("measure", (self.qr2[1],), (self.cr2[1],))],
[("measure", (self.qr1[1],), (self.cr1[1],))],
]
self.assertEqual([self.qr1[0], self.qr1[1], self.qr2[0], self.qr2[1]], qregs)
self.assertEqual([self.cr1[0], self.cr1[1], self.cr2[0], self.cr2[1]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_reverse_bits(self):
"""_get_layered_instructions with reverse_bits=True"""
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(
self.circuit, reverse_bits=True
)
exp = [
[("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())],
[("measure", (self.qr2[0],), (self.cr2[0],))],
[("measure", (self.qr1[0],), (self.cr1[0],)), ("cx", (self.qr2[1], self.qr2[0]), ())],
[("cx", (self.qr1[1], self.qr1[0]), ())],
[("measure", (self.qr2[1],), (self.cr2[1],))],
[("measure", (self.qr1[1],), (self.cr1[1],))],
]
self.assertEqual([self.qr2[1], self.qr2[0], self.qr1[1], self.qr1[0]], qregs)
self.assertEqual([self.cr2[1], self.cr2[0], self.cr1[1], self.cr1[0]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_remove_idle_wires(self):
"""_get_layered_instructions with idle_wires=False"""
qr1 = QuantumRegister(3, "qr1")
qr2 = QuantumRegister(3, "qr2")
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.cx(qr2[0], qr2[1])
circuit.measure(qr2[0], cr2[0])
circuit.cx(qr2[1], qr2[0])
circuit.measure(qr2[1], cr2[1])
circuit.cx(qr1[0], qr1[1])
circuit.measure(qr1[0], cr1[0])
circuit.cx(qr1[1], qr1[0])
circuit.measure(qr1[1], cr1[1])
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(circuit, idle_wires=False)
exp = [
[("cx", (qr2[0], qr2[1]), ()), ("cx", (qr1[0], qr1[1]), ())],
[("measure", (qr2[0],), (cr2[0],))],
[("measure", (qr1[0],), (cr1[0],))],
[("cx", (qr2[1], qr2[0]), ()), ("cx", (qr1[1], qr1[0]), ())],
[("measure", (qr2[1],), (cr2[1],))],
[("measure", (qr1[1],), (cr1[1],))],
]
self.assertEqual([qr1[0], qr1[1], qr2[0], qr2[1]], qregs)
self.assertEqual([cr1[0], cr1[1], cr2[0], cr2[1]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_left_justification_simple(self):
"""Test _get_layered_instructions left justification simple since #2802
q_0: |0>───────■──
┌───┐ │
q_1: |0>┤ H ├──┼──
├───┤ │
q_2: |0>┤ H ├──┼──
└───┘┌─┴─┐
q_3: |0>─────┤ X ├
└───┘
"""
qc = QuantumCircuit(4)
qc.h(1)
qc.h(2)
qc.cx(0, 3)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left")
l_exp = [
[
("h", (Qubit(QuantumRegister(4, "q"), 1),), ()),
("h", (Qubit(QuantumRegister(4, "q"), 2),), ()),
],
[("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())],
]
self.assertEqual(
l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_right_justification_simple(self):
"""Test _get_layered_instructions right justification simple since #2802
q_0: |0>──■───────
│ ┌───┐
q_1: |0>──┼──┤ H ├
│ ├───┤
q_2: |0>──┼──┤ H ├
┌─┴─┐└───┘
q_3: |0>┤ X ├─────
└───┘
"""
qc = QuantumCircuit(4)
qc.h(1)
qc.h(2)
qc.cx(0, 3)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right")
r_exp = [
[("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())],
[
("h", (Qubit(QuantumRegister(4, "q"), 1),), ()),
("h", (Qubit(QuantumRegister(4, "q"), 2),), ()),
],
]
self.assertEqual(
r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_left_justification_less_simple(self):
"""Test _get_layered_instructions left justification
less simple example since #2802
┌────────────┐┌───┐┌────────────┐ ┌─┐┌────────────┐┌───┐┌────────────┐
q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├──────────────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
├────────────┤└─┬─┘├────────────┤┌────────────┐└╥┘└────────────┘└─┬─┘├────────────┤
q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├
└────────────┘ └────────────┘└────────────┘ ║ └────────────┘
q_2: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
q_3: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
q_4: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════
"""
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
creg c1[1];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1];
measure q[0] -> c1[0];
u2(0,3.14159265358979) q[0];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
"""
qc = QuantumCircuit.from_qasm_str(qasm)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left")
l_exp = [
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("u2", (Qubit(QuantumRegister(5, "q"), 1),), ())],
[
(
"measure",
(Qubit(QuantumRegister(5, "q"), 0),),
(Clbit(ClassicalRegister(1, "c1"), 0),),
)
],
[("u2", (Qubit(QuantumRegister(5, "q"), 0),), ())],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
]
self.assertEqual(
l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_right_justification_less_simple(self):
"""Test _get_layered_instructions right justification
less simple example since #2802
┌────────────┐┌───┐┌────────────┐┌─┐┌────────────┐┌───┐┌────────────┐
q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
├────────────┤└─┬─┘├────────────┤└╥┘├────────────┤└─┬─┘├────────────┤
q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├─╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├
└────────────┘ └────────────┘ ║ └────────────┘ └────────────┘
q_2: |0>──────────────────────────────────╫──────────────────────────────────
║
q_3: |0>──────────────────────────────────╫──────────────────────────────────
║
q_4: |0>──────────────────────────────────╫──────────────────────────────────
║
c1_0: 0 ══════════════════════════════════╩══════════════════════════════════
"""
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
creg c1[1];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1];
measure q[0] -> c1[0];
u2(0,3.14159265358979) q[0];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
"""
qc = QuantumCircuit.from_qasm_str(qasm)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right")
r_exp = [
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[
(
"measure",
(Qubit(QuantumRegister(5, "q"), 0),),
(Clbit(ClassicalRegister(1, "c1"), 0),),
)
],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
]
self.assertEqual(
r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_op_with_cargs(self):
"""Test _get_layered_instructions op with cargs right of measure
┌───┐┌─┐
q_0: |0>┤ H ├┤M├─────────────
└───┘└╥┘┌───────────┐
q_1: |0>──────╫─┤0 ├
║ │ add_circ │
c_0: 0 ══════╩═╡0 ╞
└───────────┘
c_1: 0 ═════════════════════
"""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.measure(0, 0)
qc_2 = QuantumCircuit(1, 1, name="add_circ")
qc_2.h(0).c_if(qc_2.cregs[0], 1)
qc_2.measure(0, 0)
qc.append(qc_2, [1], [0])
(_, _, layered_ops) = _utils._get_layered_instructions(qc)
expected = [
[("h", (Qubit(QuantumRegister(2, "q"), 0),), ())],
[
(
"measure",
(Qubit(QuantumRegister(2, "q"), 0),),
(Clbit(ClassicalRegister(2, "c"), 0),),
)
],
[
(
"add_circ",
(Qubit(QuantumRegister(2, "q"), 1),),
(Clbit(ClassicalRegister(2, "c"), 0),),
)
],
]
self.assertEqual(
expected, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_nomathmode(self):
"""Test generate latex label default."""
self.assertEqual("abc", _utils.generate_latex_label("abc"))
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_nomathmode_utf8char(self):
"""Test generate latex label utf8 characters."""
self.assertEqual(
"{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_mathmode_utf8char(self):
"""Test generate latex label mathtext with utf8."""
self.assertEqual(
"abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("$abc_$∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_mathmode_underscore_outside(self):
"""Test generate latex label with underscore outside mathmode."""
self.assertEqual(
"abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("$abc$_∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_escaped_dollar_signs(self):
"""Test generate latex label with escaped dollarsign."""
self.assertEqual("${\\ensuremath{\\forall}}$", _utils.generate_latex_label(r"\$∀\$"))
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_escaped_dollar_sign_in_mathmode(self):
"""Test generate latex label with escaped dollar sign in mathmode."""
self.assertEqual(
"a$bc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label(r"$a$bc$_∭X∀Y"),
)
def test_array_to_latex(self):
"""Test array_to_latex produces correct latex string"""
matrix = [
[np.sqrt(1 / 2), 1 / 16, 1 / np.sqrt(8) + 3j, -0.5 + 0.5j],
[1 / 3 - 1 / 3j, np.sqrt(1 / 2) * 1j, 34.3210, -9 / 2],
]
matrix = np.array(matrix)
exp_str = (
"\\begin{bmatrix}\\frac{\\sqrt{2}}{2}&\\frac{1}{16}&"
"\\frac{\\sqrt{2}}{4}+3i&-\\frac{1}{2}+\\frac{i}{2}\\\\"
"\\frac{1}{3}+\\frac{i}{3}&\\frac{\\sqrt{2}i}{2}&34.321&-"
"\\frac{9}{2}\\\\\\end{bmatrix}"
)
result = array_to_latex(matrix, source=True).replace(" ", "").replace("\n", "")
self.assertEqual(exp_str, result)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/Innanov/Qiskit-Global-Summer-School-2022
|
Innanov
|
import networkx as nx
import numpy as np
import plotly.graph_objects as go
import matplotlib as mpl
import pandas as pd
from IPython.display import clear_output
from plotly.subplots import make_subplots
from matplotlib import pyplot as plt
from qiskit import Aer
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_city
from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM
from time import time
from copy import copy
from typing import List
from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs
mpl.rcParams['figure.dpi'] = 300
from qiskit.circuit import Parameter, ParameterVector
#Parameters are initialized with a simple string identifier
parameter_0 = Parameter('θ[0]')
parameter_1 = Parameter('θ[1]')
circuit = QuantumCircuit(1)
#We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates
circuit.ry(theta = parameter_0, qubit = 0)
circuit.rx(theta = parameter_1, qubit = 0)
circuit.draw('mpl')
parameter = Parameter('θ')
circuit = QuantumCircuit(1)
circuit.ry(theta = parameter, qubit = 0)
circuit.rx(theta = parameter, qubit = 0)
circuit.draw('mpl')
#Set the number of layers and qubits
n=3
num_layers = 2
#ParameterVectors are initialized with a string identifier and an integer specifying the vector length
parameters = ParameterVector('θ', n*(num_layers+1))
circuit = QuantumCircuit(n, n)
for layer in range(num_layers):
#Appending the parameterized Ry gates using parameters from the vector constructed above
for i in range(n):
circuit.ry(parameters[n*layer+i], i)
circuit.barrier()
#Appending the entangling CNOT gates
for i in range(n):
for j in range(i):
circuit.cx(j,i)
circuit.barrier()
#Appending one additional layer of parameterized Ry gates
for i in range(n):
circuit.ry(parameters[n*num_layers+i], i)
circuit.barrier()
circuit.draw('mpl')
print(circuit.parameters)
#Create parameter dictionary with random values to bind
param_dict = {parameter: np.random.random() for parameter in parameters}
print(param_dict)
#Assign parameters using the assign_parameters method
bound_circuit = circuit.assign_parameters(parameters = param_dict)
bound_circuit.draw('mpl')
new_parameters = ParameterVector('Ψ',9)
new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)])
new_circuit.draw('mpl')
#Run the circuit with assigned parameters on Aer's statevector simulator
simulator = Aer.get_backend('statevector_simulator')
result = simulator.run(bound_circuit).result()
statevector = result.get_statevector(bound_circuit)
plot_state_city(statevector)
#The following line produces an error when run because 'circuit' still contains non-assigned parameters
#result = simulator.run(circuit).result()
for key in graphs.keys():
print(key)
graph = nx.Graph()
#Add nodes and edges
graph.add_nodes_from(np.arange(0,6,1))
edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)]
graph.add_weighted_edges_from(edges)
graphs['custom'] = graph
#Display widget
display_maxcut_widget(graphs['custom'])
def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float:
"""
Computes the maxcut cost function value for a given graph and cut represented by some bitstring
Args:
graph: The graph to compute cut values for
bitstring: A list of integer values '0' or '1' specifying a cut of the graph
Returns:
The value of the cut
"""
#Get the weight matrix of the graph
weight_matrix = nx.adjacency_matrix(graph).toarray()
size = weight_matrix.shape[0]
value = 0.
#INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE
for i in range(size):
for j in range(size):
value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j])
return value
def plot_maxcut_histogram(graph: nx.Graph) -> None:
"""
Plots a bar diagram with the values for all possible cuts of a given graph.
Args:
graph: The graph to compute cut values for
"""
num_vars = graph.number_of_nodes()
#Create list of bitstrings and corresponding cut values
bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)]
values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings]
#Sort both lists by largest cut value
values, bitstrings = zip(*sorted(zip(values, bitstrings)))
#Plot bar diagram
bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value')))
fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600))
fig.show()
plot_maxcut_histogram(graph = graphs['custom'])
from qc_grader import grade_lab2_ex1
bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE
# Note that the grading function is expecting a list of integers '0' and '1'
grade_lab2_ex1(bitstring)
from qiskit_optimization import QuadraticProgram
quadratic_program = QuadraticProgram('sample_problem')
print(quadratic_program.export_as_lp_string())
quadratic_program.binary_var(name = 'x_0')
quadratic_program.integer_var(name = 'x_1')
quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8)
quadratic = [[0,1,2],[3,4,5],[0,1,2]]
linear = [10,20,30]
quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5)
print(quadratic_program.export_as_lp_string())
def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram:
"""Constructs a quadratic program from a given graph for a MaxCut problem instance.
Args:
graph: Underlying graph of the problem.
Returns:
QuadraticProgram
"""
#Get weight matrix of graph
weight_matrix = nx.adjacency_matrix(graph)
shape = weight_matrix.shape
size = shape[0]
#Build qubo matrix Q from weight matrix W
qubo_matrix = np.zeros((size, size))
qubo_vector = np.zeros(size)
for i in range(size):
for j in range(size):
qubo_matrix[i, j] -= weight_matrix[i, j]
for i in range(size):
for j in range(size):
qubo_vector[i] += weight_matrix[i,j]
#INSERT YOUR CODE HERE
quadratic_program=QuadraticProgram('sample_problem')
for i in range(size):
quadratic_program.binary_var(name='x_{}'.format(i))
quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector)
return quadratic_program
quadratic_program = quadratic_program_from_graph(graphs['custom'])
print(quadratic_program.export_as_lp_string())
from qc_grader import grade_lab2_ex2
# Note that the grading function is expecting a quadratic program
grade_lab2_ex2(quadratic_program)
def qaoa_circuit(qubo: QuadraticProgram, p: int = 1):
"""
Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers.
Args:
qubo: The quadratic program instance
p: The number of layers in the QAOA circuit
Returns:
The parameterized QAOA circuit
"""
size = len(qubo.variables)
qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True)
qubo_linearity = qubo.objective.linear.to_array()
#Prepare the quantum and classical registers
qaoa_circuit = QuantumCircuit(size,size)
#Apply the initial layer of Hadamard gates to all qubits
qaoa_circuit.h(range(size))
#Create the parameters to be used in the circuit
gammas = ParameterVector('gamma', p)
betas = ParameterVector('beta', p)
#Outer loop to create each layer
for i in range(p):
#Apply R_Z rotational gates from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
qubo_matrix_sum_of_col = 0
for k in range(size):
qubo_matrix_sum_of_col+= qubo_matrix[j][k]
qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j)
#Apply R_ZZ rotational gates for entangled qubit rotations from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
for k in range(size):
if j!=k:
qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k)
# Apply single qubit X - rotations with angle 2*beta_i to all qubits
#INSERT YOUR CODE HERE
for j in range(size):
qaoa_circuit.rx(2*betas[i],j)
return qaoa_circuit
quadratic_program = quadratic_program_from_graph(graphs['custom'])
custom_circuit = qaoa_circuit(qubo = quadratic_program)
test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters))
from qc_grader import grade_lab2_ex3
# Note that the grading function is expecting a quantum circuit
grade_lab2_ex3(test)
from qiskit.algorithms import QAOA
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = Aer.get_backend('statevector_simulator')
qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1])
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
quadratic_program = quadratic_program_from_graph(graphs['custom'])
result = eigen_optimizer.solve(quadratic_program)
print(result)
def plot_samples(samples):
"""
Plots a bar diagram for the samples of a quantum algorithm
Args:
samples
"""
#Sort samples by probability
samples = sorted(samples, key = lambda x: x.probability)
#Get list of probabilities, function values and bitstrings
probabilities = [sample.probability for sample in samples]
values = [sample.fval for sample in samples]
bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples]
#Plot bar diagram
sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value')))
fig = go.Figure(
data=sample_plot,
layout = dict(
xaxis=dict(
type = 'category'
)
)
)
fig.show()
plot_samples(result.samples)
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name])
trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]}
offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum()
def callback(eval_count, params, mean, std_dev):
trajectory['beta_0'].append(params[1])
trajectory['gamma_0'].append(params[0])
trajectory['energy'].append(-mean + offset)
optimizers = {
'cobyla': COBYLA(),
'slsqp': SLSQP(),
'adam': ADAM()
}
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
result = eigen_optimizer.solve(quadratic_program)
fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples)
fig.show()
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graphs[graph_name])
#Create callback to record total number of evaluations
max_evals = 0
def callback(eval_count, params, mean, std_dev):
global max_evals
max_evals = eval_count
#Create empty lists to track values
energies = []
runtimes = []
num_evals=[]
#Run QAOA for different values of p
for p in range(1,10):
print(f'Evaluating for p = {p}...')
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
start = time()
result = eigen_optimizer.solve(quadratic_program)
runtimes.append(time()-start)
num_evals.append(max_evals)
#Calculate energy of final state from samples
avg_value = 0.
for sample in result.samples:
avg_value += sample.probability*sample.fval
energies.append(avg_value)
#Create and display plots
energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma'))
runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma'))
num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma'))
fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations'])
fig.update_layout(width=1800,height=600, showlegend=False)
fig.add_trace(energy_plot, row=1, col=1)
fig.add_trace(runtime_plot, row=1, col=2)
fig.add_trace(num_evals_plot, row=1, col=3)
clear_output()
fig.show()
def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None):
num_shots = 1000
seed = 42
simulator = Aer.get_backend('qasm_simulator')
simulator.set_options(seed_simulator = 42)
#Generate circuit
circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1)
circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes()))
#Create dictionary with precomputed cut values for all bitstrings
cut_values = {}
size = graph.number_of_nodes()
for i in range(2**size):
bitstr = '{:b}'.format(i).rjust(size, '0')[::-1]
x = [int(bit) for bit in bitstr]
cut_values[bitstr] = maxcut_cost_fn(graph, x)
#Perform grid search over all parameters
data_points = []
max_energy = None
for beta in np.linspace(0,np.pi, 50):
for gamma in np.linspace(0, 4*np.pi, 50):
bound_circuit = circuit.assign_parameters([beta, gamma])
result = simulator.run(bound_circuit, shots = num_shots).result()
statevector = result.get_counts(bound_circuit)
energy = 0
measured_cuts = []
for bitstring, count in statevector.items():
measured_cuts = measured_cuts + [cut_values[bitstring]]*count
if cvar is None:
#Calculate the mean of all cut values
energy = sum(measured_cuts)/num_shots
else:
#raise NotImplementedError()
#INSERT YOUR CODE HERE
measured_cuts = sorted(measured_cuts, reverse = True)
for w in range(int(cvar*num_shots)):
energy += measured_cuts[w]/int((cvar*num_shots))
#Update optimal parameters
if max_energy is None or energy > max_energy:
max_energy = energy
optimum = {'beta': beta, 'gamma': gamma, 'energy': energy}
#Update data
data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy})
#Create and display surface plot from data_points
df = pd.DataFrame(data_points)
df = df.pivot(index='beta', columns='gamma', values='energy')
matrix = df.to_numpy()
beta_values = df.index.tolist()
gamma_values = df.columns.tolist()
surface_plot = go.Surface(
x=gamma_values,
y=beta_values,
z=matrix,
coloraxis = 'coloraxis'
)
fig = go.Figure(data = surface_plot)
fig.show()
#Return optimum
return optimum
graph = graphs['custom']
optimal_parameters = plot_qaoa_energy_landscape(graph = graph)
print('Optimal parameters:')
print(optimal_parameters)
optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2)
print(optimal_parameters)
from qc_grader import grade_lab2_ex4
# Note that the grading function is expecting a python dictionary
# with the entries 'beta', 'gamma' and 'energy'
grade_lab2_ex4(optimal_parameters)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
for idx in range(5):
qc.h(idx)
qc.cx(idx, idx+5)
qc.cx(1, 7)
qc.x(8)
qc.cx(1, 9)
qc.x(7)
qc.cx(1, 11)
qc.swap(6, 11)
qc.swap(6, 9)
qc.swap(6, 10)
qc.x(6)
qc.draw('mpl')
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
import math
import os
from copy import deepcopy
import pytest
import qiskit
from qeqiskit.backend import QiskitBackend
from qeqiskit.conversions import export_to_qiskit
from qiskit.providers.exceptions import QiskitBackendNotFoundError
from zquantum.core.circuits import CNOT, Circuit, X
from zquantum.core.interfaces.backend_test import QuantumBackendTests
from zquantum.core.measurement import Measurements
@pytest.fixture(
params=[
{
"device_name": "ibmq_qasm_simulator",
"api_token": os.getenv("ZAPATA_IBMQ_API_TOKEN"),
"retry_delay_seconds": 1,
},
]
)
def backend(request):
return QiskitBackend(**request.param)
@pytest.fixture(
params=[
{
"device_name": "ibmq_qasm_simulator",
"api_token": os.getenv("ZAPATA_IBMQ_API_TOKEN"),
"readout_correction": True,
"n_samples_for_readout_calibration": 1,
"retry_delay_seconds": 1,
},
{
"device_name": "ibmq_qasm_simulator",
"api_token": os.getenv("ZAPATA_IBMQ_API_TOKEN"),
"readout_correction": True,
"n_samples_for_readout_calibration": 1,
"retry_delay_seconds": 1,
"noise_inversion_method": "pseudo_inverse",
},
],
)
def backend_with_readout_correction(request):
return QiskitBackend(**request.param)
class TestQiskitBackend(QuantumBackendTests):
def x_cnot_circuit(self):
return Circuit([X(0), CNOT(1, 2)])
def x_circuit(self):
return Circuit([X(0)])
def test_transform_circuitset_to_ibmq_experiments(self, backend):
circuit = self.x_cnot_circuit()
circuitset = (circuit,) * 2
n_samples = [backend.max_shots + 1] * 2
(
experiments,
n_samples_for_experiments,
multiplicities,
) = backend.transform_circuitset_to_ibmq_experiments(circuitset, n_samples)
assert multiplicities == [2, 2]
assert n_samples_for_experiments == [
backend.max_shots,
1,
backend.max_shots,
1,
]
assert len(set([circuit.name for circuit in experiments])) == 4
def test_batch_experiments(self, backend):
circuit = self.x_cnot_circuit()
n_circuits = backend.batch_size + 1
experiments = (export_to_qiskit(circuit),) * n_circuits
n_samples_for_ibmq_circuits = (10,) * n_circuits
batches, n_samples_for_batches = backend.batch_experiments(
experiments, n_samples_for_ibmq_circuits
)
assert len(batches) == 2
assert len(batches[0]) == backend.batch_size
assert len(batches[1]) == 1
assert n_samples_for_batches == [10, 10]
def test_aggregate_measurements(self, backend):
multiplicities = [3, 1]
circuit = export_to_qiskit(self.x_cnot_circuit())
circuit.barrier(range(3))
circuit.add_register(qiskit.ClassicalRegister(3))
circuit.measure(range(3), range(3))
batches = [
[circuit.copy("circuit1"), circuit.copy("circuit2")],
[circuit.copy("circuit3"), circuit.copy("circuit4")],
]
jobs = [
backend.execute_with_retries(
batch,
10,
)
for batch in batches
]
measurements_set = backend.aggregate_measurements(
jobs,
batches,
multiplicities,
)
assert (
measurements_set[0].bitstrings
== [
(1, 0, 0),
]
* 30
)
assert (
measurements_set[1].bitstrings
== [
(1, 0, 0),
]
* 10
)
assert len(measurements_set) == 2
def test_run_circuitset_and_measure(self, backend):
# Given
num_circuits = 10
circuit = self.x_circuit()
n_samples = 100
# When
measurements_set = backend.run_circuitset_and_measure(
[circuit] * num_circuits, [n_samples] * num_circuits
)
# Then
assert len(measurements_set) == num_circuits
for measurements in measurements_set:
assert len(measurements.bitstrings) == n_samples
counts = measurements.get_counts()
assert max(counts, key=counts.get) == "1"
def test_execute_with_retries(self, backend):
# This test has a race condition where the IBMQ server might finish
# executing the first job before the last one is submitted. The test
# will still pass in the case, but will not actually perform a retry.
# We can address in the future by using a mock provider.
# Given
circuit = export_to_qiskit(self.x_circuit())
n_samples = 10
num_jobs = backend.device.job_limit().maximum_jobs + 1
# When
jobs = [
backend.execute_with_retries([circuit], n_samples) for _ in range(num_jobs)
]
# Then
# The correct number of jobs were submitted
assert len(jobs) == num_jobs
# Each job has a unique ID
assert len(set([job.job_id() for job in jobs])) == num_jobs
def test_execute_with_retries_timeout(self, backend):
# This test has a race condition where the IBMQ server might finish
# executing the first job before the last one is submitted, causing the
# test to fail. We can address this in the future using a mock provider.
# Given
circuit = export_to_qiskit(self.x_cnot_circuit())
n_samples = 10
backend.retry_timeout_seconds = 0
# need large number here as + 1 was not enough
num_jobs = backend.device.job_limit().maximum_jobs + int(10e20)
# Then
with pytest.raises(RuntimeError):
# When
for _ in range(num_jobs):
backend.execute_with_retries([circuit], n_samples)
@pytest.mark.skip(reason="test will always succeed.")
def test_run_circuitset_and_measure_readout_correction_retries(
self, backend_with_readout_correction
):
# This test has a race condition where the IBMQ server might finish
# executing the first job before the last one is submitted. The test
# will still pass in the case, but will not actually perform a retry.
# We can address in the future by using a mock provider.
# Given
circuit = self.x_cnot_circuit()
n_samples = 10
num_circuits = (
backend_with_readout_correction.batch_size
* backend_with_readout_correction.device.job_limit().maximum_jobs
+ 1
)
# When
measurements_set = backend_with_readout_correction.run_circuitset_and_measure(
[circuit] * num_circuits, [n_samples] * num_circuits
)
# Then
assert len(measurements_set) == num_circuits
def test_run_circuitset_and_measure_split_circuits_and_jobs(self, backend):
# Given
num_circuits = 2 # Minimum number of circuits to require batching
circuit = self.x_cnot_circuit()
n_samples = backend.max_shots + 1
backend.batch_size = 2
# Verify that we are actually going to need multiple batches
assert (
num_circuits * math.ceil(n_samples / backend.max_shots) > backend.batch_size
)
# When
measurements_set = backend.run_circuitset_and_measure(
[circuit] * num_circuits, [n_samples] * num_circuits
)
# Then
assert len(measurements_set) == num_circuits
for measurements in measurements_set:
assert len(measurements.bitstrings) == n_samples or len(
measurements.bitstrings
) == backend.max_shots * math.ceil(n_samples / backend.max_shots)
# Then (since SPAM error could result in unexpected bitstrings, we make sure
# the most common bitstring is the one we expect)
counts = measurements.get_counts()
assert max(counts, key=counts.get) == "100"
def test_readout_correction_works_run_circuit_and_measure(
self, backend_with_readout_correction
):
# Given
circuit = self.x_cnot_circuit()
# When
backend_with_readout_correction.run_circuit_and_measure(circuit, n_samples=1)
# Then
assert backend_with_readout_correction.readout_correction
assert backend_with_readout_correction.readout_correction_filters is not None
def test_readout_correction_for_distributed_circuit(
self, backend_with_readout_correction
):
# Given
num_circuits = 10
circuit = self.x_circuit() + X(5)
n_samples = 100
# When
measurements_set = backend_with_readout_correction.run_circuitset_and_measure(
[circuit] * num_circuits, [n_samples] * num_circuits
)
# Then
assert backend_with_readout_correction.readout_correction
assert (
backend_with_readout_correction.readout_correction_filters.get(str([0, 5]))
is not None
)
assert len(measurements_set) == num_circuits
for measurements in measurements_set:
assert len(measurements.bitstrings) == n_samples
counts = measurements.get_counts()
assert max(counts, key=counts.get) == "11"
@pytest.mark.parametrize(
"counts, active_qubits",
[
({"100000000000000000001": 10}, [0, 20]),
({"100000000000000000100": 10}, [0, 18, 20]),
({"001000000000000000001": 10}, [2, 20]),
],
)
def test_subset_readout_correction(
self, counts, active_qubits, backend_with_readout_correction
):
# Given
copied_counts = deepcopy(counts)
# When
mitigated_counts = backend_with_readout_correction._apply_readout_correction(
copied_counts, active_qubits
)
# Then
assert backend_with_readout_correction.readout_correction
assert backend_with_readout_correction.readout_correction_filters.get(
str(active_qubits)
)
assert copied_counts == pytest.approx(mitigated_counts, 10e-5)
def test_subset_readout_correction_with_unspecified_active_qubits(
self, backend_with_readout_correction
):
# Given
counts = {"11": 10}
# When
mitigated_counts = backend_with_readout_correction._apply_readout_correction(
counts
)
# Then
assert backend_with_readout_correction.readout_correction
assert backend_with_readout_correction.readout_correction_filters.get(
str([0, 1])
)
assert counts == pytest.approx(mitigated_counts, 10e-5)
def test_must_define_n_samples_for_readout_calibration_for_readout_correction(
self, backend_with_readout_correction
):
# Given
counts, active_qubits = ({"11": 10}, None)
backend_with_readout_correction.n_samples_for_readout_calibration = None
# When/Then
with pytest.raises(TypeError):
backend_with_readout_correction._apply_readout_correction(
counts, active_qubits
)
def test_subset_readout_correction_for_multiple_subsets(
self, backend_with_readout_correction
):
# Given
counts_1, active_qubits_1 = ({"100000000000000000001": 10}, [0, 20])
counts_2, active_qubits_2 = ({"001000000000000000001": 10}, [2, 20])
# When
mitigated_counts_1 = backend_with_readout_correction._apply_readout_correction(
counts_1, active_qubits_1
)
mitigated_counts_2 = backend_with_readout_correction._apply_readout_correction(
counts_2, active_qubits_2
)
# Then
assert backend_with_readout_correction.readout_correction
assert backend_with_readout_correction.readout_correction_filters.get(
str(active_qubits_1)
)
assert backend_with_readout_correction.readout_correction_filters.get(
str(active_qubits_2)
)
assert counts_1 == pytest.approx(mitigated_counts_1, 10e-5)
assert counts_2 == pytest.approx(mitigated_counts_2, 10e-5)
def test_device_that_does_not_exist(self):
# Given/When/Then
with pytest.raises(QiskitBackendNotFoundError):
QiskitBackend("DEVICE DOES NOT EXIST")
def test_run_circuitset_and_measure_n_samples(self, backend):
# We override the base test because the qiskit integration may return
# more samples than requested due to the fact that each circuit in a
# batch must have the same number of measurements.
# Given
backend.number_of_circuits_run = 0
backend.number_of_jobs_run = 0
first_circuit = Circuit(
[
X(0),
X(0),
X(1),
X(1),
X(2),
]
)
second_circuit = Circuit(
[
X(0),
X(1),
X(2),
]
)
n_samples = [2, 3]
# When
measurements_set = backend.run_circuitset_and_measure(
[first_circuit, second_circuit], n_samples
)
counts = measurements_set[0].get_counts()
assert max(counts, key=counts.get) == "001"
counts = measurements_set[1].get_counts()
assert max(counts, key=counts.get) == "111"
assert len(measurements_set[0].bitstrings) >= n_samples[0]
assert len(measurements_set[1].bitstrings) >= n_samples[1]
assert backend.number_of_circuits_run == 2
@pytest.mark.parametrize("n_samples", [1, 2, 10])
def test_run_circuit_and_measure_correct_num_measurements_attribute(
self, backend, n_samples
):
# Overriding to reduce number of samples required
# Given
backend.number_of_circuits_run = 0
backend.number_of_jobs_run = 0
circuit = self.x_cnot_circuit()
# When
measurements = backend.run_circuit_and_measure(circuit, n_samples)
# Then
assert isinstance(measurements, Measurements)
assert len(measurements.bitstrings) == n_samples
assert backend.number_of_circuits_run == 1
assert backend.number_of_jobs_run == 1
def test_run_circuit_and_measure_correct_indexing(self, backend):
# Overriding to reduce number of samples required
# Given
backend.number_of_circuits_run = 0
backend.number_of_jobs_run = 0
circuit = self.x_cnot_circuit()
n_samples = 2 # qiskit only runs simulators, so we can use low n_samples
measurements = backend.run_circuit_and_measure(circuit, n_samples)
counts = measurements.get_counts()
assert max(counts, key=counts.get) == "100"
assert backend.number_of_circuits_run == 1
assert backend.number_of_jobs_run == 1
|
https://github.com/ncitron/qiskit-hack
|
ncitron
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram as ph
%matplotlib inline
# Battleship Grid
## 0 1 2 3 4 5 6 7 8 9
#A - - - - - X X - - -
#B - - X - - - - X X X
#C - - X - - - - - - -
#D - - X - - X - - - -
#E - - - - - X - - - -
#F - - - - - X - - - -
#G - - - - - X - - - -
#H - - - - - - - - - -
#I - - - - - - - - - -
#J - - - - - X X X X X
#Acceptable solutions:
sol = [
'0000101',
'0000110',
'0001100',
'0010001',
'0010010',
'0010011',
'0010110',
'0100000',
'0101010',
'0101101',
'0110111',
'1000001',
'1001011',
'1101100',
'1101101',
'1101110',
'1101111'
]
tot = len(sol)
n = 7
s = []
for i in range(n-1):
s.append(i)
# 17 - 2 # 16 - 2 # 15 - 2 # 14 - 2 # 13 - 2
# 12 - 2 # 11 - 2 # 10 - 2 # 9 - 2
# 8 - 3 # 7 - 3 # 6 - 3 # 5 - 3
# 4 - 4 # 3 - 5 # 2 - 6 # 1 - 8
if tot > 8:
rep = 2
elif tot > 4:
rep = 3
elif tot == 4:
rep = 4
elif tot == 3:
rep = 5
elif tot == 2:
rep = 6
else:
rep = 8
def build_oracle(circuit, solutions):
for i in range(tot):
temp = solutions[i]
for j, yesno in enumerate(reversed(temp)):
if yesno == '0':
circuit.x(j)
circuit.h(n-1)
circuit.mct(s, n-1)
circuit.h(n-1)
for k, noyes in enumerate(reversed(temp)):
if noyes == '0':
circuit.x(k)
def amplify(circuit):
circuit.h(range(n))
circuit.x(range(n))
circuit.h(n-1)
circuit.mct(s, n-1)
circuit.h(n-1)
circuit.x(range(n))
circuit.h(range(n))
qc = QuantumCircuit(n)
qc.h(range(n))
for i in range(rep):
qc.barrier()
build_oracle(qc, sol)
qc.barrier()
amplify(qc)
qc.measure_all()
bknd = Aer.get_backend('qasm_simulator')
ph(execute(qc,backend=bknd,shots=1000000).result().get_counts())
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 1).result()
counts = result.get_counts()
print(counts)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
"""A test for visualizing device coupling maps"""
import unittest
from io import BytesIO
from ddt import ddt, data
from qiskit.providers.fake_provider import (
FakeProvider,
FakeKolkata,
FakeWashington,
FakeKolkataV2,
FakeWashingtonV2,
)
from qiskit.visualization import (
plot_gate_map,
plot_coupling_map,
plot_circuit_layout,
plot_error_map,
)
from qiskit.utils import optionals
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler.layout import Layout, TranspileLayout
from .visualization import path_to_diagram_reference, QiskitVisualizationTestCase
if optionals.HAS_MATPLOTLIB:
import matplotlib.pyplot as plt
if optionals.HAS_PIL:
from PIL import Image
@ddt
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "matplotlib not available.")
@unittest.skipUnless(optionals.HAS_PIL, "PIL not available")
@unittest.skipUnless(optionals.HAS_SEABORN, "seaborn not available")
class TestGateMap(QiskitVisualizationTestCase):
"""visual tests for plot_gate_map"""
backends = list(
filter(
lambda x: not x.configuration().simulator
and x.configuration().num_qubits in range(5, 21),
FakeProvider().backends(),
)
)
@data(*backends)
def test_plot_gate_map(self, backend):
"""tests plotting of gate map of a device (20 qubit, 16 qubit, 14 qubit and 5 qubit)"""
n = backend.configuration().n_qubits
img_ref = path_to_diagram_reference(str(n) + "bit_quantum_computer.png")
fig = plot_gate_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
@data(*backends)
def test_plot_circuit_layout(self, backend):
"""tests plot_circuit_layout for each device"""
layout_length = int(backend._configuration.n_qubits / 2)
qr = QuantumRegister(layout_length, "qr")
circuit = QuantumCircuit(qr)
circuit._layout = TranspileLayout(
Layout({qr[i]: i * 2 for i in range(layout_length)}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
circuit._layout.initial_layout.add_register(qr)
n = backend.configuration().n_qubits
img_ref = path_to_diagram_reference(str(n) + "_plot_circuit_layout.png")
fig = plot_circuit_layout(circuit, backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.1)
plt.close(fig)
def test_plot_gate_map_no_backend(self):
"""tests plotting of gate map without a device"""
n_qubits = 8
coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]]
qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]]
img_ref = path_to_diagram_reference(str(n_qubits) + "qubits.png")
fig = plot_coupling_map(
num_qubits=n_qubits, qubit_coordinates=qubit_coordinates, coupling_map=coupling_map
)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
def test_plot_error_map_backend_v1(self):
"""Test plotting error map with fake backend v1."""
backend = FakeKolkata()
img_ref = path_to_diagram_reference("kolkata_error.png")
fig = plot_error_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
def test_plot_error_map_backend_v2(self):
"""Test plotting error map with fake backend v2."""
backend = FakeKolkataV2()
img_ref = path_to_diagram_reference("kolkata_v2_error.png")
fig = plot_error_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
def test_plot_error_map_over_100_qubit(self):
"""Test plotting error map with large fake backend."""
backend = FakeWashington()
img_ref = path_to_diagram_reference("washington_error.png")
fig = plot_error_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
def test_plot_error_map_over_100_qubit_backend_v2(self):
"""Test plotting error map with large fake backendv2."""
backend = FakeWashingtonV2()
img_ref = path_to_diagram_reference("washington_v2_error.png")
fig = plot_error_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (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.
"""Tests LogicNetwork.Tweedledum2Qiskit converter."""
import unittest
from qiskit.utils.optionals import HAS_TWEEDLEDUM
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import XGate
if HAS_TWEEDLEDUM:
# pylint: disable=import-error
from qiskit.circuit.classicalfunction.utils import tweedledum2qiskit
from tweedledum.ir import Circuit
from tweedledum.operators import X
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
class TestTweedledum2Qiskit(QiskitTestCase):
"""Tests qiskit.transpiler.classicalfunction.utils.tweedledum2qiskit function."""
def test_x(self):
"""Single uncontrolled X"""
tweedledum_circuit = Circuit()
tweedledum_circuit.apply_operator(X(), [tweedledum_circuit.create_qubit()])
circuit = tweedledum2qiskit(tweedledum_circuit)
expected = QuantumCircuit(1)
expected.x(0)
self.assertEqual(circuit, expected)
def test_cx_0_1(self):
"""CX(0, 1)"""
tweedledum_circuit = Circuit()
qubits = []
qubits.append(tweedledum_circuit.create_qubit())
qubits.append(tweedledum_circuit.create_qubit())
tweedledum_circuit.apply_operator(X(), [qubits[0], qubits[1]])
circuit = tweedledum2qiskit(tweedledum_circuit)
expected = QuantumCircuit(2)
expected.append(XGate().control(1, ctrl_state="1"), [0, 1])
self.assertEqual(circuit, expected)
def test_cx_1_0(self):
"""CX(1, 0)"""
tweedledum_circuit = Circuit()
qubits = []
qubits.append(tweedledum_circuit.create_qubit())
qubits.append(tweedledum_circuit.create_qubit())
tweedledum_circuit.apply_operator(X(), [qubits[1], qubits[0]])
circuit = tweedledum2qiskit(tweedledum_circuit)
expected = QuantumCircuit(2)
expected.append(XGate().control(1, ctrl_state="1"), [1, 0])
self.assertEqual(expected, circuit)
def test_cx_qreg(self):
"""CX(0, 1) with qregs parameter"""
tweedledum_circuit = Circuit()
qubits = []
qubits.append(tweedledum_circuit.create_qubit())
qubits.append(tweedledum_circuit.create_qubit())
tweedledum_circuit.apply_operator(X(), [qubits[1], qubits[0]])
qr = QuantumRegister(2, "qr")
circuit = tweedledum2qiskit(tweedledum_circuit, qregs=[qr])
expected = QuantumCircuit(qr)
expected.append(XGate().control(1, ctrl_state="1"), [qr[1], qr[0]])
self.assertEqual(expected, circuit)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
from qiskit import *
# In[2]:
qr = QuantumRegister(3, 'q')
cr = ClassicalRegister(2, 'zx_meas')
qc = QuantumCircuit(qr,cr)
qc.reset(range(3))
qc.barrier()
qc.h(1)
qc.cx([1,0],[2,1])
qc.h(0)
qc.barrier()
qc.measure([0,1], [0,1])
qc.barrier()
qc.z(2).c_if(cr, 1)
qc.x(2).c_if(cr, 2)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 12345
from qiskit_machine_learning.datasets import ad_hoc_data
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=20,
test_size=5,
n=adhoc_dimension,
gap=0.3,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
import matplotlib.pyplot as plt
import numpy as np
def plot_features(ax, features, labels, class_label, marker, face, edge, label):
# A train plot
ax.scatter(
# x coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 0],
# y coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 1],
marker=marker,
facecolors=face,
edgecolors=edge,
label=label,
)
def plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total):
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
# A train plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "A train")
# B train plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B train")
# A test plot
plot_features(plt, test_features, test_labels, 0, "s", "b", "w", "A test")
# B test plot
plot_features(plt, test_features, test_labels, 1, "o", "r", "w", "B test")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset")
plt.show()
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
from qiskit.circuit.library import ZZFeatureMap
from qiskit.primitives import Sampler
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit_machine_learning.kernels import FidelityQuantumKernel
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
sampler = Sampler()
fidelity = ComputeUncompute(sampler=sampler)
adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map)
from sklearn.svm import SVC
adhoc_svc = SVC(kernel=adhoc_kernel.evaluate)
adhoc_svc.fit(train_features, train_labels)
adhoc_score_callable_function = adhoc_svc.score(test_features, test_labels)
print(f"Callable kernel classification test score: {adhoc_score_callable_function}")
adhoc_matrix_train = adhoc_kernel.evaluate(x_vec=train_features)
adhoc_matrix_test = adhoc_kernel.evaluate(x_vec=test_features, y_vec=train_features)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(
np.asmatrix(adhoc_matrix_train), interpolation="nearest", origin="upper", cmap="Blues"
)
axs[0].set_title("Ad hoc training kernel matrix")
axs[1].imshow(np.asmatrix(adhoc_matrix_test), interpolation="nearest", origin="upper", cmap="Reds")
axs[1].set_title("Ad hoc testing kernel matrix")
plt.show()
adhoc_svc = SVC(kernel="precomputed")
adhoc_svc.fit(adhoc_matrix_train, train_labels)
adhoc_score_precomputed_kernel = adhoc_svc.score(adhoc_matrix_test, test_labels)
print(f"Precomputed kernel classification test score: {adhoc_score_precomputed_kernel}")
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=adhoc_kernel)
qsvc.fit(train_features, train_labels)
qsvc_score = qsvc.score(test_features, test_labels)
print(f"QSVC classification test score: {qsvc_score}")
print(f"Classification Model | Accuracy Score")
print(f"---------------------------------------------------------")
print(f"SVC using kernel as a callable function | {adhoc_score_callable_function:10.2f}")
print(f"SVC using precomputed kernel matrix | {adhoc_score_precomputed_kernel:10.2f}")
print(f"QSVC | {qsvc_score:10.2f}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=0,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
# A label plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "B")
# B label plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for clustering")
plt.show()
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
adhoc_kernel = FidelityQuantumKernel(feature_map=adhoc_feature_map)
adhoc_matrix = adhoc_kernel.evaluate(x_vec=train_features)
plt.figure(figsize=(5, 5))
plt.imshow(np.asmatrix(adhoc_matrix), interpolation="nearest", origin="upper", cmap="Greens")
plt.title("Ad hoc clustering kernel matrix")
plt.show()
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score
adhoc_spectral = SpectralClustering(2, affinity="precomputed")
cluster_labels = adhoc_spectral.fit_predict(adhoc_matrix)
cluster_score = normalized_mutual_info_score(cluster_labels, train_labels)
print(f"Clustering score: {cluster_score}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=10,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement="linear")
qpca_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=feature_map)
matrix_train = qpca_kernel.evaluate(x_vec=train_features)
matrix_test = qpca_kernel.evaluate(x_vec=test_features, y_vec=test_features)
from sklearn.decomposition import KernelPCA
kernel_pca_rbf = KernelPCA(n_components=2, kernel="rbf")
kernel_pca_rbf.fit(train_features)
train_features_rbf = kernel_pca_rbf.transform(train_features)
test_features_rbf = kernel_pca_rbf.transform(test_features)
kernel_pca_q = KernelPCA(n_components=2, kernel="precomputed")
train_features_q = kernel_pca_q.fit_transform(matrix_train)
test_features_q = kernel_pca_q.fit_transform(matrix_test)
from sklearn.linear_model import LogisticRegression
logistic_regression = LogisticRegression()
logistic_regression.fit(train_features_q, train_labels)
logistic_score = logistic_regression.score(test_features_q, test_labels)
print(f"Logistic regression score: {logistic_score}")
fig, (q_ax, rbf_ax) = plt.subplots(1, 2, figsize=(10, 5))
plot_features(q_ax, train_features_q, train_labels, 0, "s", "w", "b", "A train")
plot_features(q_ax, train_features_q, train_labels, 1, "o", "w", "r", "B train")
plot_features(q_ax, test_features_q, test_labels, 0, "s", "b", "w", "A test")
plot_features(q_ax, test_features_q, test_labels, 1, "o", "r", "w", "A test")
q_ax.set_ylabel("Principal component #1")
q_ax.set_xlabel("Principal component #0")
q_ax.set_title("Projection of training and test data\n using KPCA with Quantum Kernel")
# Plotting the linear separation
h = 0.01 # step size in the mesh
# create a mesh to plot in
x_min, x_max = train_features_q[:, 0].min() - 1, train_features_q[:, 0].max() + 1
y_min, y_max = train_features_q[:, 1].min() - 1, train_features_q[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
predictions = logistic_regression.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
predictions = predictions.reshape(xx.shape)
q_ax.contourf(xx, yy, predictions, cmap=plt.cm.RdBu, alpha=0.2)
plot_features(rbf_ax, train_features_rbf, train_labels, 0, "s", "w", "b", "A train")
plot_features(rbf_ax, train_features_rbf, train_labels, 1, "o", "w", "r", "B train")
plot_features(rbf_ax, test_features_rbf, test_labels, 0, "s", "b", "w", "A test")
plot_features(rbf_ax, test_features_rbf, test_labels, 1, "o", "r", "w", "A test")
rbf_ax.set_ylabel("Principal component #1")
rbf_ax.set_xlabel("Principal component #0")
rbf_ax.set_title("Projection of training data\n using KernelPCA")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/arnavdas88/QuGlassyIsing
|
arnavdas88
|
!pip install qiskit
J = 4.0
B_x = 0.5
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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^ I ^ I ^ I ^ I ^ I ^ 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_CountsAF2.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/rubenandrebarreiro/summer-school-on-quantum-computing-software-for-near-term-quantum-devices-2020
|
rubenandrebarreiro
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
def ising_gate(circuit,qrj,qrl,Jt):
circuit.cx(qrj,qrl)
circuit.u1(-2*Jt,qrl)
circuit.cx(qrj,qrl)
def fieldx_gate(circuit,qrj,Bt):
# We use rotation around x
circuit.rx(-2*Bt,qrj)
def fieldz_gate(circuit,qrj,Bt):
circuit.rz(-2*Bt,qrj)
def initialize_qa(circuit,qr):
circuit.h(qr)
qr = QuantumRegister(2)
cr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
initialize_qa(circuit,qr)
ising_gate(circuit,qr[0],qr[1],1)
fieldx_gate(circuit,qr,1)
circuit.draw(output='mpl')
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
from qiskit import QuantumCircuit, QuantumRegister
import numpy as np
# load a dummy circuit
# generate network of random cnots
n, M = 2, 4
N = n**2
register = QuantumRegister(N)
qc = QuantumCircuit(register)
for _ in range(M):
qc.cx(*np.random.choice(N, 2, replace=False))
qc.name = "random cx circuit"
qc.decompose().draw("mpl")
from qiskit.transpiler.coupling import CouplingMap
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
coupling = CouplingMap.from_line(3)
qc.decompose().draw("mpl")
from virtual_swap.pass_managers import BruteCNS
brute = BruteCNS(coupling)
transp = brute.run(qc)
transp.draw("mpl")
from qiskit.transpiler.passes import OptimizeSwapBeforeMeasure, Unroller
from qiskit.converters import dag_to_circuit
from qiskit.transpiler import PassManager
clean = PassManager()
clean.append(OptimizeSwapBeforeMeasure())
clean.append(Unroller(["u", "cx", "iswap", "swap"]))
property_set = brute.pm.property_set # Reference for brevity
dags, costs, perms = (
property_set["all_dags"],
property_set["all_costs"],
property_set["all_perms"],
)
for dag, cost, perm in zip(dags, costs, perms):
print(cost)
perm_str = ", ".join(
[f"{node.name}[{node.qargs[0].index},{node.qargs[1].index}]" for node in perm]
)
print("Permutation:", perm_str)
circuit = dag_to_circuit(dag)
print(clean.run(circuit).draw(fold=-1))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/AislingHeanue/Quantum-Computing-Circuits
|
AislingHeanue
|
import matplotlib.pyplot as plt
import numpy as np
from fractions import Fraction
from qiskit import QuantumCircuit, Aer, execute, transpile, assemble, QuantumRegister, ClassicalRegister
from qiskit.visualization import plot_histogram
from qiskit.circuit.library import DraperQFTAdder as draper
# functions
# Draper QFT adder, in gate form
# https://arxiv.org/pdf/quant-ph/0008033.pdf
def add(qc, a, b, n):
drapergate = draper(n,kind = "half").decompose().decompose().to_gate()
qc.append(drapergate,list(a[:]) + list(b[:]))
#a,b -> a,b+a or a,b-a
def makeAdder(nbits,adding = True):
qc = QuantumCircuit(2*nbits+1) #a is size N, b is N + 1
add(qc, range(nbits), range(nbits,2*nbits+1),nbits)
addergate = qc.to_gate()
addergate.name = "adder"
iaddergate = addergate.inverse()
iaddergate.name = "inverse adder"
if adding:
return addergate
else:
return iaddergate
def binary(num,length):
b = bin(num)[2:]
return "0"*(length-len(b))+str(b)
def x(number,length,controls = 0): #this changes a decimal number to a series of x gates, not to be confused with qc.x
circ = QuantumCircuit(length)
for i,num in enumerate(binary(number,length)):
if num == "1":
circ.x(length - 1 - i)
xgate = circ.to_gate()
xgate.name = str(number)
if controls != 0:
cxgate = xgate.control(controls)
return cxgate #num bitts will be controls + length
else:
return xgate
def makeAdderMod(a,b,t1,t2,n,nbits,N,control = False): #a,b,n quantum registers, output a,a+bmodN, N. t and aux both start and end zero
qc = QuantumCircuit(a, b, t1, t2, n)
qc.append(makeAdder(nbits,True),range(2*nbits+1))
qc.swap(a,n)
qc.append(makeAdder(nbits, False),range(2*nbits+1))
qc.x(t1)
qc.cx(t1,t2)
qc.x(t1)
#set top register to zero by bitwise adding N
qc.append(x(N,nbits,1),t2[:] + a[:])
qc.append(makeAdder(nbits,True),range(2*nbits+1)) #adds nothing if b is already positive
#turn it back into N
qc.append(x(N,nbits,1),t2[:] + a[:])
qc.swap(a,n)
qc.append(makeAdder(nbits, False),range(2*nbits+1))
qc.cx(t1,t2) #t2 reset to zero
qc.append(makeAdder(nbits, True),range(2*nbits+1))
addmod = qc.to_gate()
addmod.name = "a + b mod "+str(N)
if control:
caddmod = addmod.control(1)
return caddmod
else:
return addmod
def makecmult(c, xreg, tempa, y, t1, t2, n, numa, nbits, N,inv = False):
qc = QuantumCircuit(c,xreg,tempa,y,t1,t2,n)
for p in range(nbits):
qc.append(x((2**p*numa)%N,nbits,2),c[:] + xreg[p:p+1] + tempa[:])
qc.append(makeAdderMod(tempa,y,t1,t2,n,nbits,N),tempa[:] + y[:] + t1[:] + t2[:] + n[:])
qc.append(x((2**p*numa)%N,nbits,2),c[:] + xreg[p:p+1] + tempa[:])
qc.x(c)
for q in range(nbits):
qc.ccx(c,xreg[q],y[q])
qc.x(c)
cmult = qc.to_gate()
iqc = qc.inverse()
icmult = iqc.to_gate()
cmult.name = "times "+str(numa)+" mod "+str(N)
icmult.name = "inverse of (times "+str(numa)+" mod "+str(N)+")"
return icmult if inv else cmult
def fakecmult(c, xreg, tempa, y, t1, t2, n, numa, nbits, N,inv = False):
qc = QuantumCircuit(c,xreg,tempa,y,t1,t2,n)
cmult = qc.to_gate()
iqc = qc.inverse()
icmult = iqc.to_gate()
cmult.name = "times "+str(numa)+" mod "+str(N)
icmult.name = "divided by "+str(modinv(numa,N))+" mod "+str(N)
return icmult if inv else cmult
def makea2pmod(out1, tempa, out2, t1, t2, n, numa,p,nbits,N):
c = QuantumRegister(1)
qc = QuantumCircuit(c, out1, tempa, out2, t1, t2, n)
#print(l,(numa**(2**l))%N) #it's the iversion that's wrong
qc.append(makecmult(c, out1, tempa, out2, t1, t2, n, (numa**(2**p))%N, nbits, N),list(range(0,4*nbits+3)))
qc.swap(out1,out2)
qc.append(makecmult(c, out1, tempa, out2, t1, t2, n, modinv((numa**(2**p))%N,N), nbits, N, True),list(range(0,4*nbits+3)))
#qc = qc.to_gate()
qc.name = str(numa)+"^"+str(2**p)+" mod "+str(N)
return qc
def makeAXmod(xreg, out1, tempa, out2, t1, t2, n,numa,mbits,nbits,N,control = False):
qc = QuantumCircuit(xreg, out1, tempa, out2, t1, t2, n)
#x starts and finishes as NOT ZERO
c = QuantumRegister(1)
for l in range(mbits):
#print(l,(numa**(2**l))%N) #it's the iversion that's wrong
qc.append(makecmult(c, out1, tempa, out2, t1, t2, n, (numa**(2**l))%N, nbits, N),[l] + list(range(mbits,mbits+(4*nbits+2))))
qc.swap(out1,out2)
qc.append(makecmult(c, out1, tempa, out2, t1, t2, n, modinv((numa**(2**l))%N,N), nbits, N, True),[l] + list(range(mbits,mbits+(4*nbits+2))))
#qc.append(x(numx,mbits),xreg[:]) #reset x to zero
if control:
qc = qc.control(1)
AXmod = qc#.to_gate()
AXmod.name = str(numa)+"^x mod "+str(N)
return AXmod
#Euclidean gcd method source: Wikibooks
#https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
#source: Qiskit textbook
def QFT(n):
circuit = QuantumCircuit(n)
for bit in range(n//2):
circuit.swap(bit,n-bit-1)
for j in range(n):
for m in range(j):
circuit.cp(np.pi/(2**(j-m)), m, j)
circuit.h(j)
circuit.name = "QFT"
return circuit
def makeSum(inverse = False):
qc = QuantumCircuit(3)
qc.cx(1,2)
qc.cx(0,2)
return qc.inverse() if inverse else qc
def carry(inverse = False):
qc = QuantumCircuit(4)
qc.ccx(1,2,3)
qc.cx(1,2)
qc.ccx(0,2,3)
return qc.inverse() if inverse else qc
def sim(qc): #prints simulated results of 2 classical registers
backend_sim = Aer.get_backend('aer_simulator')
job_sim = execute(qc, backend_sim,shots = 100)
result_sim = job_sim.result()
results = str(list(result_sim.get_counts().keys())[0]).split(" ") #result of add is b+a a
resultsint = [int(res,2) for res in results]
print(resultsint[1],resultsint[0])
# test code to make sure the adder gate works
A = 5
B = 7
ca,cb = ClassicalRegister(4),ClassicalRegister(5)
q = QuantumRegister(9)
qc = QuantumCircuit(q,ca,cb)
qc.append(x(A,4),range(4))
qc.append(x(B,4),range(4,8))
qc.append(makeAdder(4,True),range(9))
qc.barrier()
qc.measure(range(4),ca)
qc.measure(range(4,9),cb)
sim(qc)
print(A,A+B)
qc.draw(output="text",plot_barriers=False,fold = -1)
#modular addition
N = 33
numa = 15
numb = 12 #works as long as a+b < 2N
nbits = 6
a = QuantumRegister(nbits,"a")
b = QuantumRegister(nbits,"b")
t1 = QuantumRegister(1,"temp1")
n = QuantumRegister(nbits,"n")
t2 = QuantumRegister(1,"temp2")
ca = ClassicalRegister(nbits,"ca")
cb = ClassicalRegister(nbits,"cb")
qc = QuantumCircuit(a, b, t1, t2, n, ca, cb)
#initialise qubits
qc.append(x(numa,nbits),a[:])
qc.append(x(numb,nbits),b)
qc.append(x(N,nbits),n)
#draw the circuit
qc.append(makeAdder(nbits,True),range(2*nbits+1))
qc.swap(a,n)
qc.append(makeAdder(nbits, False),range(2*nbits+1))
qc.x(t1)
qc.cx(t1,t2)
qc.x(t1)
#set top register to zero by bitwise adding N
qc.append(x(N,nbits,1),t2[:] + a[:])
qc.append(makeAdder(nbits,True),range(2*nbits+1))
#turn it back into N
qc.append(x(N,nbits,1),t2[:] + a[:])
qc.swap(a,n)
qc.append(makeAdder(nbits, False),range(2*nbits+1))
qc.cx(t1,t2) #t2 reset to zero
qc.append(makeAdder(nbits, True),range(2*nbits+1))
qc.measure(a,ca)
qc.measure(b,cb)
sim(qc)
print(numa,(numa+numb)%N) #check against correct value
qc.draw(output = "latex",fold = -1,plot_barriers = False)
#result is a, a+b mod N
#controlled mult
N = 15
numx = 6
numa = 5
nbits = 4 #goal = c,x,0 -> c,x,ax mod N
on = True
c = QuantumRegister(1,"c") #control for next step
xreg = QuantumRegister(nbits,"x") #output 1
tempa = QuantumRegister(nbits,"a") #temp from adder (nbits)
y = QuantumRegister(nbits,"b") #output 2
t1 = QuantumRegister(1,"temp1") #temp from adder (1)
t2 = QuantumRegister(1,"temp2") #temp from adder (1)
n = QuantumRegister(nbits,"n") #N (nbits)
cx = ClassicalRegister(nbits,"cx") #answer
cy = ClassicalRegister(nbits,"cy") #answer
qc = QuantumCircuit(c, xreg, tempa, y, t1, t2, n, cx, cy)
#initialise qubits
qc.append(x(numx,nbits),xreg)
qc.append(x(N,nbits),n)
if on:
qc.append(x(1,1),c)
for p in range(nbits):
qc.append(x((2**p*numa)%N,nbits,2),c[:] + xreg[p:p+1] + tempa[:])
qc.append(makeAdderMod(tempa,y,t1,t2,n,nbits,N),tempa[:] + y[:] + t1[:] + t2[:] + n[:])
qc.append(x((2**p*numa)%N,nbits,2),c[:] + xreg[p:p+1] + tempa[:])
qc.x(c)
for q in range(nbits):
qc.ccx(c,xreg[q],y[q])
qc.x(c)
qc.barrier()
qc.measure(xreg,cx)
qc.measure(y,cy)
sim(qc)
print(numx,(numa*numx)%N)
qc.draw(output= "latex",fold = -1,plot_barriers=False)
N = 15
numa = 2
nbits = 4
p = 1 #power of 2
#result = a^2^p mod n
#xreg = QuantumRegister(mbits,"x") #control, max x is 2^nbits for now but we can define mbits instead
c = QuantumRegister(1,"c")
out1 = QuantumRegister(nbits,"x") #output 1
tempa = QuantumRegister(nbits,"a") #temp from adder (nbits)
out2 = QuantumRegister(nbits,"b") #temp from cmult
t1 = QuantumRegister(1,"temp1") #temp from adder (1)
t2 = QuantumRegister(1,"temp2") #temp from adder (1)
n = QuantumRegister(nbits,"n") #N (nbits)
cx = ClassicalRegister(nbits,"cx") #answer (same size as xreg)
cy = ClassicalRegister(nbits,"cy") #answer
qc = QuantumCircuit(c, out1, tempa, out2, t1, t2, n, cx, cy)
qc.x(c)
qc.append(x(1,nbits),out1)
qc.append(x(N,nbits),n)
qc.append(makecmult(c, out1, tempa, out2, t1, t2, n, (numa**(2**p))%N, nbits, N),list(range(0,4*nbits+3)))
qc.swap(out1,out2)
qc.append(makecmult(c, out1, tempa, out2, t1, t2, n, modinv((numa**(2**p))%N,N), nbits, N, True),list(range(0,4*nbits+3)))
qc.barrier()
qc.measure(out1,cx)
qc.measure(out2,cy)
sim(qc)
print((numa**(2**p)) % N,0)
qc.draw(output= "latex",fold = -1,plot_barriers=False)
N = 15
numa = 2
nbits = 4
mbits = nbits
period = QuantumRegister(mbits,"period")
out1 = QuantumRegister(nbits,"x") #output 1
tempa = QuantumRegister(nbits,"a") #temp from adder (nbits)
out2 = QuantumRegister(nbits,"b") #temp from cmult
t1 = QuantumRegister(1,"temp1") #temp from adder (1)
t2 = QuantumRegister(1,"temp2") #temp from adder (1)
n = QuantumRegister(nbits,"n") #N (nbits)
cx = ClassicalRegister(mbits,"cx") #answer (same size as xreg)
qc = QuantumCircuit(period, out1, tempa, out2, t1, t2, n, cx)
#qc.append(x(14,mbits),period[:])
qc.h(period[:])
qc.append(x(1,nbits),out1[:])
qc.append(x(N,nbits),n[:])
for p in range(mbits):
qc.append(makea2pmod(out1, tempa, out2, t1, t2, n, numa,p,nbits,N),[p] + list(range(mbits,mbits+4*nbits+2)))
qc.append(QFT(nbits),range(nbits))
qc.measure(period,cx)
qc.draw(fold=-1,output = "latex")
aersim = Aer.get_backend('aer_simulator')
tqc = transpile(qc,aersim)
results = aersim.run(tqc,shots=5000).result()
plot_histogram(results.get_counts())
checkedlist = []
factorfound = False
for output in results.get_counts():
if results.get_counts()[output] > 30: #filtering any measurements from random noise
phase = int(output,base=2)/(2**nbits)
r = Fraction(phase).limit_denominator(int(N/2)).denominator
if r not in checkedlist:
checkedlist.append(r)
if r > 1 and r % 2 == 0:
if int(numa**(r/2)) <= 2**62: #gcd requires numbers below 2^64
p1 = np.gcd(int(numa**(r/2)-1),N)
p2 = np.gcd(int(numa**(r/2)+1),N)
plist = [p1,p2] if p1 <= p2 else [p2,p1]
if p1 * p2 == N and p1 != 1 and p2 != 1:
print( f"{plist[0]:<2d}* {plist[1]:<3d} = {N:<3d}, r = {r:<3d}, a = {numa:<3d}, nbits = {nbits:<2d}")
factorfound = True
if not factorfound:
print(f"{N} is prime or cannot be found with a = {numa}")
#Altenative gate construction for x = 2 and N = 2^n - 1
power2 = 4
N = 2**power2 - 1
def powermodp2(power,power2): #multiply by 2^p (mod 2^n-1)
U = QuantumCircuit(power2)
for i in range(power):
for j in range(power2-1):
U.swap(j,j+1)
U = U.to_gate()
U.name = f"2^{power} mod {N}"
c_U = U.control()
return c_U
nbits = power2 - 1 #edit this line to change the size of the input regiter (eg: nbits = power2 + 1)
xreg = QuantumRegister(nbits,"input")
y = QuantumRegister(power2,"y")
cx = ClassicalRegister(nbits)
qc = QuantumCircuit(xreg,y,cx)
qc.h(xreg[:])
qc.x(nbits + power2 - 1)
for k in range(nbits):
qc.append(powermodp2(2**k,power2),[k] + y[:])
qc.append(QFT(nbits),range(nbits))
qc.measure(range(nbits),range(nbits))
qc.draw(fold=-1,output="latex")
aersim = Aer.get_backend('aer_simulator') #set memory=True to see measurements
tqc = transpile(qc,aersim)
results = aersim.run(tqc,shots=10000).result()
nbits = 3
d = results.get_counts()
oldkeys = list(d.keys())
xblue = [1,3,5,7]
xred = [0,2,4,6]
for key in xblue+xred:
d[str(key)] = 0
for key in oldkeys:
d[str(int(key,2))] = d[key]
del d[key]
yred = [d[str(xi)]/10000 for xi in xred]
yblue = [d[str(xi)]/10000 for xi in xblue]
plt.xlim(-0.9,7.9)
plt.bar(xred,yred,color=(1,0,0))
plt.bar(xblue,yblue,color=(0.4,0.6,1))
plt.ylabel("Probability")
plt.xlabel("x")
newd = {"0x0": 2919, "0x1": 2298, "0x2": 2249, "0x3": 1850, "0x4": 3353, "0x5": 2431, "0x6": 2704, "0x7": 2196}
nbits = 3
oldkeys = list(newd.keys())
xblue = [1,3,5,7]
xred = [0,2,4,6]
for key in xblue+xred:
newd[str(key)] = 0
for key in oldkeys:
newd[str(key[2:])] = newd[key]
del newd[key]
print(newd)
yred = [newd[str(xi)]/20000 for xi in xred]
yblue = [newd[str(xi)]/20000 for xi in xblue]
plt.xlim(-1,7.9)
plt.bar(xred,yred,color=(1,0,0))
plt.bar(xblue,yblue,color=(0.4,0.6,1))
plt.ylabel("Probability")
plt.xlabel("x")
print(yred[1]+yred[3])
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
from qiskit_aqua import Operator, run_algorithm
from qiskit_aqua.translators.ising import stableset
from qiskit_aqua.input import EnergyInput
from qiskit_aqua.algorithms.classical.cplex.cplex_ising import CPLEX_Ising
from qiskit import Aer
w = stableset.parse_gset_format('sample.maxcut')
qubitOp, offset = stableset.get_stableset_qubitops(w)
algo_input = EnergyInput(qubitOp)
if True:
np.random.seed(8123179)
w = stableset.random_graph(5, edge_prob=0.5)
qubitOp, offset = stableset.get_stableset_qubitops(w)
algo_input.qubit_op = qubitOp
print(w)
to_be_tested_algos = ['ExactEigensolver', 'CPLEX.Ising', 'VQE']
print(to_be_tested_algos)
algorithm_cfg = {
'name': 'ExactEigensolver',
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg
}
result = run_algorithm(params,algo_input)
x = stableset.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('stable set objective:', result['energy'] + offset)
print('solution:', stableset.get_graph_solution(x))
print('solution objective and feasibility:', stableset.stableset_value(x, w))
cplex_installed = True
try:
CPLEX_Ising.check_pluggable_valid()
except Exception as e:
cplex_installed = False
if cplex_installed:
algorithm_cfg = {
'name': 'CPLEX.Ising',
'display': 0
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg
}
result = run_algorithm(params, algo_input)
x_dict = result['x_sol']
print('energy:', result['energy'])
print('time:', result['eval_time'])
print('stable set objective:', result['energy'] + offset)
x = np.array([x_dict[i] for i in sorted(x_dict.keys())])
print('solution:', stableset.get_graph_solution(x))
print('solution objective and feasibility:', stableset.stableset_value(x, w))
algorithm_cfg = {
'name': 'VQE',
'operator_mode': 'matrix'
}
optimizer_cfg = {
'name': 'L_BFGS_B',
'maxfun': 2000
}
var_form_cfg = {
'name': 'RYRZ',
'depth': 3,
'entanglement': 'linear'
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg,
'optimizer': optimizer_cfg,
'variational_form': var_form_cfg
}
backend = Aer.get_backend('statevector_simulator')
result = run_algorithm(params, algo_input, backend=backend)
x = stableset.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('time:', result['eval_time'])
print('stable set objective:', result['energy'] + offset)
print('solution:', stableset.get_graph_solution(x))
print('solution objective and feasibility:', stableset.stableset_value(x, w))
|
https://github.com/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="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs)
print("created zne_qcs (length:", len(zne_qcs), ")")
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[32].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)
# 1回目: 2022-04-12 17:27:43.880500
# 2回目: 2022-04-13 01:19:40.602655
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')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
#!/usr/bin/env python3
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Utility to check that slow imports are not used in the default path."""
import subprocess
import sys
# This is not unused: importing it sets up sys.modules
import qiskit # pylint: disable=unused-import
def _main():
optional_imports = [
"networkx",
"sympy",
"pydot",
"pygments",
"ipywidgets",
"scipy.stats",
"matplotlib",
"qiskit.providers.aer",
"qiskit.providers.ibmq",
"qiskit.ignis",
"qiskit.aqua",
"docplex",
]
modules_imported = []
for mod in optional_imports:
if mod in sys.modules:
modules_imported.append(mod)
if not modules_imported:
sys.exit(0)
res = subprocess.run(
[sys.executable, "-X", "importtime", "-c", "import qiskit"],
capture_output=True,
encoding="utf8",
check=True,
)
import_tree = [
x.split("|")[-1]
for x in res.stderr.split("\n")
if "RuntimeWarning" not in x or "warnings.warn" not in x
]
indent = -1
matched_module = None
for module in import_tree:
line_indent = len(module) - len(module.lstrip())
module_name = module.strip()
if module_name in modules_imported:
if indent > 0:
continue
indent = line_indent
matched_module = module_name
if indent > 0:
if line_indent < indent:
print(f"ERROR: {matched_module} is imported via {module_name}")
indent = -1
matched_module = None
sys.exit(len(modules_imported))
if __name__ == "__main__":
_main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
dc = pulse.DriveChannel
d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4)
with pulse.build(name='pulse_programming_in') as pulse_prog:
pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3)
pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4)
pulse_prog.draw()
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/asgunzi/QiskitCompReal
|
asgunzi
|
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 19 12:24:57 2020
@author: asgunzi
"""
from qiskit import *
from qiskit.visualization import plot_histogram
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
#Cria um circuito quântico, composto de um qubit e um bit
circuit = QuantumCircuit(qr,cr)
circuit.h(0)
circuit.cx(0,1)
circuit.measure(qr,cr)
print(circuit)
#Vamos rodar num simulador de computador quântico. Qasm vem de “quantum assembly simulator”.
simulator = Aer.get_backend('qasm_simulator')
results = execute(circuit,simulator).result().get_counts()
plot_histogram(results)
# # #Vamos rodar num computador real
IBMQ.load_account() #È necessário ter uma conta no Qiskit da IBM
provider = IBMQ.get_provider(hub = 'ibm-q')
device = provider.get_backend('ibmqx2')
#Ou ibmq_16_melbourne, ibmqx2
job = execute(circuit,backend = device,shots = 1024)
print(job.job_id())
from qiskit.tools.monitor import job_monitor
job_monitor(job)
device_result = job.result()
plot_histogram(device_result.get_counts(circuit))
|
https://github.com/dv-gorasiya/quantum-machine-learning
|
dv-gorasiya
|
from datasets import *
from qiskit import BasicAer
from qiskit.aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name
from qiskit.aqua.input import ClassificationInput
from qiskit.aqua import run_algorithm, QuantumInstance
from qiskit.aqua.algorithms import QSVM
from qiskit.aqua.components.feature_maps import SecondOrderExpansion
# setup aqua logging
import logging
from qiskit.aqua import set_qiskit_aqua_logging
set_qiskit_aqua_logging(logging.DEBUG)
from qiskit import IBMQ
IBMQ.save_account('2670c486a8792dff6c5327a9729c669ffe3fe33b5970cb3b5c1fd8662121db289092e7eb6d2525215d9d0e17808cf25599b7da660807e30e2c3409e302bfb2f5', 'https://api.quantum-computing.ibm.com/api/Hubs/ibm-q/Groups/open/Projects/main')
IBMQ.load_accounts(overwrite=True)
feature_dim=5 # we support feature_dim 2 or 3
sample_Total, training_input, test_input, class_labels = ad_hoc_data(
training_size=20,
test_size=10,
n=feature_dim,
gap=0.3,
PLOT_DATA=True
)
extra_test_data = sample_ad_hoc_data(sample_Total, 10, n=feature_dim)
datapoints, class_to_label = split_dataset_to_data_and_labels(extra_test_data)
print(class_to_label)
seed = 10598
feature_map = SecondOrderExpansion(feature_dimension=feature_dim, depth=2, entanglement='linear')
qsvm = QSVM(feature_map, training_input, test_input, datapoints[0])
#backend = BasicAer.get_backend('qasm_simulator')
backend = IBMQ.get_backend('ibmq_16_melbourne')
quantum_instance = QuantumInstance(backend, shots=1024, seed=seed, seed_transpiler=seed)
result = qsvm.run(quantum_instance)
"""declarative approach
params = {
'problem': {'name': 'classification', 'random_seed': 10598},
'algorithm': {
'name': 'QSVM'
},
'backend': {'provider': 'qiskit.BasicAer', 'name': 'qasm_simulator', 'shots': 1024},
'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entanglement': 'linear'}
}
algo_input = ClassificationInput(training_input, test_input, datapoints[0])
result = run_algorithm(params, algo_input)
"""
print("testing success ratio: {}".format(result['testing_accuracy']))
print("preduction of datapoints:")
print("ground truth: {}".format(map_label_to_class_name(datapoints[1], qsvm.label_to_class)))
print("prediction: {}".format(result['predicted_classes']))
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
sample_Total, training_input, test_input, class_labels = Breast_cancer(
training_size=20,
test_size=10,
n=2,
PLOT_DATA=True
)
seed = 10598
feature_map = SecondOrderExpansion(feature_dimension=feature_dim, depth=2, entanglement='linear')
qsvm = QSVM(feature_map, training_input, test_input)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024, seed=seed, seed_transpiler=seed)
result = qsvm.run(quantum_instance)
"""declarative approach, re-use the params above
algo_input = ClassificationInput(training_input, test_input)
result = run_algorithm(params, algo_input)
"""
print("testing success ratio: ", result['testing_accuracy'])
result
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
sample_Total.shape
|
https://github.com/soultanis/Quantum-SAT-Solver
|
soultanis
|
"""
Solves SAT instance by reading from stdin using Qiskit framework from IBM.
For text recognition as input you have to set the path to your lib.
"""
import pylab
import numpy as np
from sys import stdin
import argparse
from argparse import ArgumentParser
from argparse import FileType
from PIL import Image
import pytesseract
from qiskit.providers.ibmq import least_busy
from qiskit import LegacySimulators, execute, IBMQ, Aer
from qiskit.tools.visualization import plot_histogram
from qiskit_aqua import QuantumInstance
from qiskit_aqua import run_algorithm
from qiskit_aqua.algorithms import Grover
from qiskit_aqua.components.oracles import SAT
# from qiskit_aqua.components.oracles import LogicalExpressionOracle
def grover_solution(m, n, hr, i):
# normal parser
if m and n is not None:
satProblem = 'examples\\3sat' + m + '-' + n + '.cnf'
with open(satProblem, 'r') as f:
sat_cnf = f.read()
print(sat_cnf)
# hand recognition parser: still needs to be implemented
elif hr:
# tesseract parser
pass
else:
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
i_read = pytesseract.image_to_string(Image.open(i.name), lang='eng')
print(i_read)
sat_oracle = SAT(sat_cnf)
algorithm = Grover(sat_oracle)
backend = Aer.get_backend('qasm_simulator')
algorithm = Grover(sat_oracle)
result = algorithm.run(backend)
print(result['result'])
plot_histogram(result['measurements'])
def main():
args = parse_args()
grover_solution(args.variable, args.equation,
args.hand_recognition, args.file_input)
def parse_args():
parser = ArgumentParser(
description='Quantum SAT solver with Grovers algorithm')
parser.add_argument('-m',
'--variable',
help='the number of variable for the SAT-Problem from examples')
parser.add_argument('-n',
'--equation',
help='the number of equation for the SAT-Problem from examples')
parser.add_argument('-hr',
'--hand_recognition',
action='store_true',
help='set to true, if your file is handwritten (still needs to be implemented)')
parser.add_argument('-i',
'--file_input',
type=FileType('r'),
help='read from given file instead of stdin',)
return parser.parse_args()
if __name__ == "__main__":
main()
'''
print('Type the number of m variables and on the next line the number of n equations for the SAT-Problem:')
m = input()
n = input()
print('You set the SAT-Problem with ' + m +
' variables and ' + n + ' equations.')
(m, n)
parser.add_argument('-i',
'--input',
help='read from given file instead of stdin',
type=FileType('r'),
default=stdin)
parser.add_argument('-o',
'--output',
help='write to given file instead of default stdout',
type=FileType('w'),
default=stdout)
'''
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import IBMQ
from qiskit import BasicAer as Aer
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import execute
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle
import copy
from ipywidgets import widgets
from IPython.display import display, clear_output
try:
IBMQ.load_accounts()
except:
pass
class run_game():
# Implements a puzzle, which is defined by the given inputs.
def __init__(self,initialize, success_condition, allowed_gates, vi, qubit_names, eps=0.1, backend=Aer.get_backend('qasm_simulator'), shots=1024,mode='circle',verbose=False):
"""
initialize
List of gates applied to the initial 00 state to get the starting state of the puzzle.
Supported single qubit gates (applied to qubit '0' or '1') are 'x', 'y', 'z', 'h', 'ry(pi/4)'.
Supported two qubit gates are 'cz' and 'cx'. Specify only the target qubit.
success_condition
Values for pauli observables that must be obtained for the puzzle to declare success.
allowed_gates
For each qubit, specify which operations are allowed in this puzzle. 'both' should be used only for operations that don't need a qubit to be specified ('cz' and 'unbloch').
Gates are expressed as a dict with an int as value. If this is non-zero, it specifies the number of times the gate is must be used (no more or less) for the puzzle to be successfully solved. If the value is zero, the player can use the gate any number of times.
vi
Some visualization information as a three element list. These specify:
* which qubits are hidden (empty list if both shown).
* whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles).
* whether the correlation circles (the four in the middle) are shown.
qubit_names
The two qubits are always called '0' and '1' from the programming side. But for the player, we can display different names.
eps=0.1
How close the expectation values need to be to the targets for success to be declared.
backend=Aer.get_backend('qasm_simulator')
Backend to be used by Qiskit to calculate expectation values (defaults to local simulator).
shots=1024
Number of shots used to to calculate expectation values.
mode='circle'
Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line').
verbose=False
"""
def get_total_gate_list():
# Get a text block describing allowed gates.
total_gate_list = ""
for qubit in allowed_gates:
gate_list = ""
for gate in allowed_gates[qubit]:
if required_gates[qubit][gate] > 0 :
gate_list += ' ' + gate+" (use "+str(required_gates[qubit][gate])+" time"+"s"*(required_gates[qubit][gate]>1)+")"
elif allowed_gates[qubit][gate]==0:
gate_list += ' '+gate + ' '
if gate_list!="":
if qubit=="both" :
gate_list = "\nAllowed symmetric operations:" + gate_list
else :
gate_list = "\nAllowed operations for " + qubit_names[qubit] + ":\n" + " "*10 + gate_list
total_gate_list += gate_list +"\n"
return total_gate_list
def get_success(required_gates):
# Determine whether the success conditions are satisfied, both for expectation values, and the number of gates to be used.
success = True
grid.get_rho()
if verbose:
print(grid.rho)
for pauli in success_condition:
success = success and (abs(success_condition[pauli] - grid.rho[pauli])<eps)
for qubit in required_gates:
for gate in required_gates[qubit]:
success = success and (required_gates[qubit][gate]==0)
return success
def get_command(gate,qubit):
# For a given gate and qubit, return the string describing the corresoinding Qiskit string.
if qubit=='both':
qubit = '1'
qubit_name = qubit_names[qubit]
for name in qubit_names.values():
if name!=qubit_name:
other_name = name
# then make the command (both for the grid, and for printing to screen)
if gate in ['x','y','z','h']:
real_command = 'grid.qc.'+gate+'(grid.qr['+qubit+'])'
clean_command = 'qc.'+gate+'('+qubit_name+')'
elif gate in ['ry(pi/4)','ry(-pi/4)']:
real_command = 'grid.qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,grid.qr['+qubit+'])'
clean_command = 'qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,'+qubit_name+')'
elif gate in ['cz','cx','swap']:
real_command = 'grid.qc.'+gate+'(grid.qr['+'0'*(qubit=='1')+'1'*(qubit=='0')+'],grid.qr['+qubit+'])'
clean_command = 'qc.'+gate+'('+other_name+','+qubit_name+')'
return [real_command,clean_command]
clear_output()
bloch = [None]
# set up initial state and figure
grid = pauli_grid(backend=backend,shots=shots,mode=mode)
for gate in initialize:
eval( get_command(gate[0],gate[1])[0] )
required_gates = copy.deepcopy(allowed_gates)
# determine which qubits to show in figure
if allowed_gates['0']=={} : # if no gates are allowed for qubit 0, we know to only show qubit 1
shown_qubit = 1
elif allowed_gates['1']=={} : # and vice versa
shown_qubit = 0
else :
shown_qubit = 2
# show figure
grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list())
description = {'gate':['Choose gate'],'qubit':['Choose '+'qu'*vi[1]+'bit'],'action':['Make it happen!']}
all_allowed_gates_raw = []
for q in ['0','1','both']:
all_allowed_gates_raw += list(allowed_gates[q])
all_allowed_gates_raw = list(set(all_allowed_gates_raw))
all_allowed_gates = []
for g in ['bloch','unbloch']:
if g in all_allowed_gates_raw:
all_allowed_gates.append( g )
for g in ['x','y','z','h','cz','cx']:
if g in all_allowed_gates_raw:
all_allowed_gates.append( g )
for g in all_allowed_gates_raw:
if g not in all_allowed_gates:
all_allowed_gates.append( g )
gate = widgets.ToggleButtons(options=description['gate']+all_allowed_gates)
qubit = widgets.ToggleButtons(options=[''])
action = widgets.ToggleButtons(options=[''])
boxes = widgets.VBox([gate,qubit,action])
display(boxes)
if vi[1]:
print('\nYour quantum program so far\n')
self.program = []
def given_gate(a):
# Action to be taken when gate is chosen. This sets up the system to choose a qubit.
if gate.value:
if gate.value in allowed_gates['both']:
qubit.options = description['qubit'] + ["not required"]
qubit.value = "not required"
else:
allowed_qubits = []
for q in ['0','1']:
if (gate.value in allowed_gates[q]) or (gate.value in allowed_gates['both']):
allowed_qubits.append(q)
allowed_qubit_names = []
for q in allowed_qubits:
allowed_qubit_names += [qubit_names[q]]
qubit.options = description['qubit'] + allowed_qubit_names
def given_qubit(b):
# Action to be taken when qubit is chosen. This sets up the system to choose an action.
if qubit.value not in ['',description['qubit'][0],'Success!']:
action.options = description['action']+['Apply operation']
def given_action(c):
# Action to be taken when user confirms their choice of gate and qubit.
# This applied the command, updates the visualization and checks whether the puzzle is solved.
if action.value not in ['',description['action'][0]]:
# apply operation
if action.value=='Apply operation':
if qubit.value not in ['',description['qubit'][0],'Success!']:
# translate bit gates to qubit gates
if gate.value=='NOT':
q_gate = 'x'
elif gate.value=='CNOT':
q_gate = 'cx'
else:
q_gate = gate.value
if qubit.value=="not required":
q = qubit_names['1']
else:
q = qubit.value
q01 = '0'*(qubit.value==qubit_names['0']) + '1'*(qubit.value==qubit_names['1']) + 'both'*(qubit.value=="not required")
if q_gate in ['bloch','unbloch']:
if q_gate=='bloch':
bloch[0] = q01
else:
bloch[0] = None
else:
command = get_command(q_gate,q01)
eval(command[0])
if vi[1]:
print(command[1])
self.program.append( command[1] )
if required_gates[q01][gate.value]>0:
required_gates[q01][gate.value] -= 1
grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list())
success = get_success(required_gates)
if success:
gate.options = ['Success!']
qubit.options = ['Success!']
action.options = ['Success!']
plt.close(grid.fig)
else:
gate.value = description['gate'][0]
qubit.options = ['']
action.options = ['']
gate.observe(given_gate)
qubit.observe(given_qubit)
action.observe(given_action)
class pauli_grid():
# Allows a quantum circuit to be created, modified and implemented, and visualizes the output in the style of 'Hello Quantum'.
def __init__(self,backend=Aer.get_backend('qasm_simulator'),shots=1024,mode='circle'):
"""
backend=Aer.get_backend('qasm_simulator')
Backend to be used by Qiskit to calculate expectation values (defaults to local simulator).
shots=1024
Number of shots used to to calculate expectation values.
mode='circle'
Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line').
"""
self.backend = backend
self.shots = shots
self.box = {'ZI':(-1, 2),'XI':(-2, 3),'IZ':( 1, 2),'IX':( 2, 3),'ZZ':( 0, 3),'ZX':( 1, 4),'XZ':(-1, 4),'XX':( 0, 5)}
self.rho = {}
for pauli in self.box:
self.rho[pauli] = 0.0
for pauli in ['ZI','IZ','ZZ']:
self.rho[pauli] = 1.0
self.qr = QuantumRegister(2)
self.cr = ClassicalRegister(2)
self.qc = QuantumCircuit(self.qr, self.cr)
self.mode = mode
# colors are background, qubit circles and correlation circles, respectively
if self.mode=='line':
self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)]
else:
self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)]
self.fig = plt.figure(figsize=(5,5),facecolor=self.colors[0])
self.ax = self.fig.add_subplot(111)
plt.axis('off')
self.bottom = self.ax.text(-3,1,"",size=9,va='top',color='w')
self.lines = {}
for pauli in self.box:
w = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(1.0,1.0,1.0), lw=0 )
b = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(0.0,0.0,0.0), lw=0 )
c = {}
c['w'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(0,0,0), zorder=10) )
c['b'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(1,1,1), zorder=10) )
self.lines[pauli] = {'w':w,'b':b,'c':c}
def get_rho(self):
# Runs the circuit specified by self.qc and determines the expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'.
bases = ['ZZ','ZX','XZ','XX']
results = {}
for basis in bases:
temp_qc = copy.deepcopy(self.qc)
for j in range(2):
if basis[j]=='X':
temp_qc.h(self.qr[j])
temp_qc.barrier(self.qr)
temp_qc.measure(self.qr,self.cr)
job = execute(temp_qc, backend=self.backend, shots=self.shots)
results[basis] = job.result().get_counts()
for string in results[basis]:
results[basis][string] = results[basis][string]/self.shots
prob = {}
# prob of expectation value -1 for single qubit observables
for j in range(2):
for p in ['X','Z']:
pauli = {}
for pp in 'IXZ':
pauli[pp] = (j==1)*pp + p + (j==0)*pp
prob[pauli['I']] = 0
for basis in [pauli['X'],pauli['Z']]:
for string in results[basis]:
if string[(j+1)%2]=='1':
prob[pauli['I']] += results[basis][string]/2
# prob of expectation value -1 for two qubit observables
for basis in ['ZZ','ZX','XZ','XX']:
prob[basis] = 0
for string in results[basis]:
if string[0]!=string[1]:
prob[basis] += results[basis][string]
for pauli in prob:
self.rho[pauli] = 1-2*prob[pauli]
def update_grid(self,rho=None,labels=False,bloch=None,hidden=[],qubit=True,corr=True,message=""):
"""
rho = None
Dictionary of expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. If supplied, this will be visualized instead of the results of running self.qc.
labels = None
Dictionary of strings for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ' that are printed in the corresponding boxes.
bloch = None
If a qubit name is supplied, and if mode='line', Bloch circles are displayed for this qubit
hidden = []
Which qubits have their circles hidden (empty list if both shown).
qubit = True
Whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles).
corr = True
Whether the correlation circles (the four in the middle) are shown.
message
A string of text that is displayed below the grid.
"""
def see_if_unhidden(pauli):
# For a given Pauli, see whether its circle should be shown.
unhidden = True
# first: does it act non-trivially on a qubit in `hidden`
for j in hidden:
unhidden = unhidden and (pauli[j]=='I')
# second: does it contain something other than 'I' or 'Z' when only bits are shown
if qubit==False:
for j in range(2):
unhidden = unhidden and (pauli[j] in ['I','Z'])
# third: is it a correlation pauli when these are not allowed
if corr==False:
unhidden = unhidden and ((pauli[0]=='I') or (pauli[1]=='I'))
return unhidden
def add_line(line,pauli_pos,pauli):
"""
For mode='line', add in the line.
line = the type of line to be drawn (X, Z or the other one)
pauli = the box where the line is to be drawn
expect = the expectation value that determines its length
"""
unhidden = see_if_unhidden(pauli)
coord = None
p = (1-self.rho[pauli])/2 # prob of 1 output
# in the following, white lines goes from a to b, and black from b to c
if unhidden:
if line=='Z':
a = ( self.box[pauli_pos][0], self.box[pauli_pos][1]+l/2 )
c = ( self.box[pauli_pos][0], self.box[pauli_pos][1]-l/2 )
b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] )
lw = 8
coord = (b[1] - (a[1]+c[1])/2)*1.2 + (a[1]+c[1])/2
elif line=='X':
a = ( self.box[pauli_pos][0]+l/2, self.box[pauli_pos][1] )
c = ( self.box[pauli_pos][0]-l/2, self.box[pauli_pos][1] )
b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] )
lw = 9
coord = (b[0] - (a[0]+c[0])/2)*1.1 + (a[0]+c[0])/2
else:
a = ( self.box[pauli_pos][0]+l/(2*np.sqrt(2)), self.box[pauli_pos][1]+l/(2*np.sqrt(2)) )
c = ( self.box[pauli_pos][0]-l/(2*np.sqrt(2)), self.box[pauli_pos][1]-l/(2*np.sqrt(2)) )
b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] )
lw = 9
self.lines[pauli]['w'].pop(0).remove()
self.lines[pauli]['b'].pop(0).remove()
self.lines[pauli]['w'] = plt.plot( [a[0],b[0]], [a[1],b[1]], color=(1.0,1.0,1.0), lw=lw )
self.lines[pauli]['b'] = plt.plot( [b[0],c[0]], [b[1],c[1]], color=(0.0,0.0,0.0), lw=lw )
return coord
l = 0.9 # line length
r = 0.6 # circle radius
L = 0.98*np.sqrt(2) # box height and width
if rho==None:
self.get_rho()
# draw boxes
for pauli in self.box:
if 'I' in pauli:
color = self.colors[1]
else:
color = self.colors[2]
self.ax.add_patch( Rectangle( (self.box[pauli][0],self.box[pauli][1]-1), L, L, angle=45, color=color) )
# draw circles
for pauli in self.box:
unhidden = see_if_unhidden(pauli)
if unhidden:
if self.mode=='line':
self.ax.add_patch( Circle(self.box[pauli], r, color=(0.5,0.5,0.5)) )
else:
prob = (1-self.rho[pauli])/2
self.ax.add_patch( Circle(self.box[pauli], r, color=(prob,prob,prob)) )
# update bars if required
if self.mode=='line':
if bloch in ['0','1']:
for other in 'IXZ':
px = other*(bloch=='1') + 'X' + other*(bloch=='0')
pz = other*(bloch=='1') + 'Z' + other*(bloch=='0')
z_coord = add_line('Z',pz,pz)
x_coord = add_line('X',pz,px)
for j in self.lines[pz]['c']:
self.lines[pz]['c'][j].center = (x_coord,z_coord)
self.lines[pz]['c'][j].radius = (j=='w')*0.05 + (j=='b')*0.04
px = 'I'*(bloch=='0') + 'X' + 'I'*(bloch=='1')
pz = 'I'*(bloch=='0') + 'Z' + 'I'*(bloch=='1')
add_line('Z',pz,pz)
add_line('X',px,px)
else:
for pauli in self.box:
for j in self.lines[pauli]['c']:
self.lines[pauli]['c'][j].radius = 0.0
if pauli in ['ZI','IZ','ZZ']:
add_line('Z',pauli,pauli)
if pauli in ['XI','IX','XX']:
add_line('X',pauli,pauli)
if pauli in ['XZ','ZX']:
add_line('ZX',pauli,pauli)
self.bottom.set_text(message)
if labels:
for pauli in box:
plt.text(self.box[pauli][0]-0.05,self.box[pauli][1]-0.85, pauli)
self.ax.set_xlim([-3,3])
self.ax.set_ylim([0,6])
self.fig.canvas.draw()
|
https://github.com/arnavdas88/QuGlassyIsing
|
arnavdas88
|
!pip install qiskit==0.26.2 #==0.13.0
from qiskit.providers.aer import QasmSimulator
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import EfficientSU2
# opflow is Qiskit's module for creating operators like yours
from qiskit.opflow import Z, X, I # Pauli Z, X matrices and identity
h = 0.25 # or whatever value you have for h
H = - h * ((X ^ I) + (I ^ X))
# you can swap this for a real quantum device and keep the rest of the code the same!
backend = QasmSimulator()
# COBYLA usually works well for small problems like this one
optimizer = COBYLA(maxiter=200)
# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library
ansatz = EfficientSU2(2, reps=1)
# set the algorithm
vqe = VQE(ansatz, optimizer, quantum_instance=backend)
# run it with the Hamiltonian we defined above
result = vqe.compute_minimum_eigenvalue(H)
# print the result (it contains lot's of information)
print(result)
|
https://github.com/Juan-Varela11/BNL_2020_Summer_Internship
|
Juan-Varela11
|
# Import general libraries (needed for functions)
import numpy as np
import time
# Import Qiskit classes
import qiskit
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer
from qiskit.providers.aer import noise
from qiskit.tools.visualization import plot_histogram
# Import measurement calibration functions
from qiskit.ignis.mitigation.measurement import (complete_meas_cal, tensored_meas_cal,
CompleteMeasFitter, TensoredMeasFitter)
from qiskit import IBMQ
IBMQ.load_account()
# Generate the calibration circuits
qr = qiskit.QuantumRegister(5)
qubit_list = [2,3,4]
meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal')
state_labels
provider = IBMQ.get_provider(hub='ibm-q-internal',group='dev-qiskit')
backend = provider.get_backend('ibmq_johannesburg')
backend_config = backend.configuration()
assert backend_config.open_pulse, "Backend doesn't support OpenPulse"
backend_defaults = backend.defaults()
dt = backend_config.dt
print(f"Sampling time: {dt} ns") # The configuration returns dt in seconds
# Execute the calibration circuits without noise
job = qiskit.execute(meas_calibs, backend=backend, shots=1000)
cal_results = job.result()
# The calibration matrix without noise is the identity matrix
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
# Generate a noise model for the 5 qubits
noise_model = noise.NoiseModel()
for qi in range(5):
read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],[0.25,0.75]])
noise_model.add_readout_error(read_err, [qi])
# Execute the calibration circuits
backend = qiskit.Aer.get_backend('qasm_simulator')
job = qiskit.execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model)
cal_results = job.result()
# Calculate the calibration matrix with the noise model
meas_fitter = CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list, circlabel='mcal')
print(meas_fitter.cal_matrix)
# Plot the calibration matrix
meas_fitter.plot_calibration()
# What is the measurement fidelity?
print("Average Measurement Fidelity: %f" % meas_fitter.readout_fidelity())
# What is the measurement fidelity of Q0?
print("Average Measurement Fidelity of Q0: %f" % meas_fitter.readout_fidelity(
label_list = [['000','001','010','011'],['100','101','110','111']]))
# Make a 3Q GHZ state
cr = ClassicalRegister(3)
ghz = QuantumCircuit(qr, cr)
ghz.h(qr[2])
ghz.cx(qr[2], qr[3])
ghz.cx(qr[3], qr[4])
ghz.measure(qr[2],cr[0])
ghz.measure(qr[3],cr[1])
ghz.measure(qr[4],cr[2])
job = qiskit.execute([ghz], backend=backend, shots=5000, noise_model=noise_model)
results = job.result()
# Results without mitigation
raw_counts = results.get_counts()
# Get the filter object
meas_filter = meas_fitter.filter
# Results with mitigation
mitigated_results = meas_filter.apply(results)
mitigated_counts = mitigated_results.get_counts(0)
from qiskit.tools.visualization import *
plot_histogram([raw_counts, mitigated_counts], legend=['raw', 'mitigated'])
# Make a 2Q Bell state between Q2 and Q4
cr = ClassicalRegister(2)
bell = QuantumCircuit(qr, cr)
bell.h(qr[2])
bell.cx(qr[2], qr[4])
bell.measure(qr[2],cr[0])
bell.measure(qr[4],cr[1])
job = qiskit.execute([bell], backend=backend, shots=5000, noise_model=noise_model)
results = job.result()
#build a fitter from the subset
meas_fitter_sub = meas_fitter.subset_fitter(qubit_sublist=[2,4])
#The calibration matrix is now in the space Q2/Q4
meas_fitter_sub.cal_matrix
# Results without mitigation
raw_counts = results.get_counts()
# Get the filter object
meas_filter_sub = meas_fitter_sub.filter
# Results with mitigation
mitigated_results = meas_filter_sub.apply(results)
mitigated_counts = mitigated_results.get_counts(0)
from qiskit.tools.visualization import *
plot_histogram([raw_counts, mitigated_counts], legend=['raw', 'mitigated'])
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc.draw(output='mpl')
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for Chi quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators.channel import Chi
from .channel_test_case import ChannelTestCase
class TestChi(ChannelTestCase):
"""Tests for Chi channel representation."""
def test_init(self):
"""Test initialization"""
mat4 = np.eye(4) / 2.0
chan = Chi(mat4)
assert_allclose(chan.data, mat4)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
mat16 = np.eye(16) / 4
chan = Chi(mat16)
assert_allclose(chan.data, mat16)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan.num_qubits, 2)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Chi, mat16, input_dims=2, output_dims=4)
# Non multi-qubit dimensions should raise exception
self.assertRaises(QiskitError, Chi, np.eye(6) / 2, input_dims=3, output_dims=2)
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Chi(circuit)
target = Chi(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Chi, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(4, 4, real=True)
self.assertEqual(Chi(mat), Chi(mat))
def test_copy(self):
"""Test copy method"""
mat = np.eye(4)
with self.subTest("Deep copy"):
orig = Chi(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Chi(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Chi(self.depol_chi(0.25)).is_cptp())
# Non-CPTP should return false
self.assertFalse(Chi(1.25 * self.chiI - 0.25 * self.depol_chi(1)).is_cptp())
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Chi(np.eye(4)).compose, Chi(np.eye(16)))
self.assertRaises(QiskitError, Chi(np.eye(4)).compose, 2)
def test_compose(self):
"""Test compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Chi(self.chiX)
chan2 = Chi(self.chiY)
chan = chan1.compose(chan2)
target = rho.evolve(Chi(self.chiZ))
output = rho.evolve(chan)
self.assertEqual(output, target)
# 50% depolarizing channel
chan1 = Chi(self.depol_chi(0.5))
chan = chan1.compose(chan1)
target = rho.evolve(Chi(self.depol_chi(0.75)))
output = rho.evolve(chan)
self.assertEqual(output, target)
# Compose random
chi1 = self.rand_matrix(4, 4, real=True)
chi2 = self.rand_matrix(4, 4, real=True)
chan1 = Chi(chi1, input_dims=2, output_dims=2)
chan2 = Chi(chi2, input_dims=2, output_dims=2)
target = rho.evolve(chan1).evolve(chan2)
chan = chan1.compose(chan2)
output = rho.evolve(chan)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(output, target)
chan = chan1 & chan2
output = rho.evolve(chan)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(output, target)
def test_dot(self):
"""Test dot method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Chi(self.chiX)
chan2 = Chi(self.chiY)
target = rho.evolve(Chi(self.chiZ))
output = rho.evolve(chan2.dot(chan1))
self.assertEqual(output, target)
# Compose random
chi1 = self.rand_matrix(4, 4, real=True)
chi2 = self.rand_matrix(4, 4, real=True)
chan1 = Chi(chi1, input_dims=2, output_dims=2)
chan2 = Chi(chi2, input_dims=2, output_dims=2)
target = rho.evolve(chan1).evolve(chan2)
chan = chan2.dot(chan1)
output = rho.evolve(chan)
self.assertEqual(output, target)
chan = chan2 @ chan1
output = rho.evolve(chan)
self.assertEqual(output, target)
def test_compose_front(self):
"""Test front compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Chi(self.chiX)
chan2 = Chi(self.chiY)
chan = chan2.compose(chan1, front=True)
target = rho.evolve(Chi(self.chiZ))
output = rho.evolve(chan)
self.assertEqual(output, target)
# Compose random
chi1 = self.rand_matrix(4, 4, real=True)
chi2 = self.rand_matrix(4, 4, real=True)
chan1 = Chi(chi1, input_dims=2, output_dims=2)
chan2 = Chi(chi2, input_dims=2, output_dims=2)
target = rho.evolve(chan1).evolve(chan2)
chan = chan2.compose(chan1, front=True)
output = rho.evolve(chan)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(output, target)
def test_expand(self):
"""Test expand method."""
# Pauli channels
paulis = [self.chiI, self.chiX, self.chiY, self.chiZ]
targs = 4 * np.eye(16) # diagonals of Pauli channel Chi mats
for i, chi1 in enumerate(paulis):
for j, chi2 in enumerate(paulis):
chan1 = Chi(chi1)
chan2 = Chi(chi2)
chan = chan1.expand(chan2)
# Target for diagonal Pauli channel
targ = Chi(np.diag(targs[i + 4 * j]))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan, targ)
# Completely depolarizing
rho = DensityMatrix(np.diag([1, 0, 0, 0]))
chan_dep = Chi(self.depol_chi(1))
chan = chan_dep.expand(chan_dep)
target = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
output = rho.evolve(chan)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(output, target)
def test_tensor(self):
"""Test tensor method."""
# Pauli channels
paulis = [self.chiI, self.chiX, self.chiY, self.chiZ]
targs = 4 * np.eye(16) # diagonals of Pauli channel Chi mats
for i, chi1 in enumerate(paulis):
for j, chi2 in enumerate(paulis):
chan1 = Chi(chi1)
chan2 = Chi(chi2)
chan = chan2.tensor(chan1)
# Target for diagonal Pauli channel
targ = Chi(np.diag(targs[i + 4 * j]))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan, targ)
# Test overload
chan = chan2 ^ chan1
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan, targ)
# Completely depolarizing
rho = DensityMatrix(np.diag([1, 0, 0, 0]))
chan_dep = Chi(self.depol_chi(1))
chan = chan_dep.tensor(chan_dep)
target = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
output = rho.evolve(chan)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(output, target)
# Test operator overload
chan = chan_dep ^ chan_dep
output = rho.evolve(chan)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(output, target)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
p_id = 0.9
depol = Chi(self.depol_chi(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = depol.power(3)
targ3 = Chi(self.depol_chi(1 - p_id3))
self.assertEqual(chan3, targ3)
def test_add(self):
"""Test add method."""
mat1 = 0.5 * self.chiI
mat2 = 0.5 * self.depol_chi(1)
chan1 = Chi(mat1)
chan2 = Chi(mat2)
targ = Chi(mat1 + mat2)
self.assertEqual(chan1._add(chan2), targ)
self.assertEqual(chan1 + chan2, targ)
targ = Chi(mat1 - mat2)
self.assertEqual(chan1 - chan2, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = Chi(mat)
op0 = Chi(mat0)
op1 = Chi(mat1)
op01 = op1.tensor(op0)
eye = Chi(self.chiI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = Chi(mat)
op0 = Chi(mat0)
op1 = Chi(mat1)
op01 = op1.tensor(op0)
eye = Chi(self.chiI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_add_except(self):
"""Test add method raises exceptions."""
chan1 = Chi(self.chiI)
chan2 = Chi(np.eye(16))
self.assertRaises(QiskitError, chan1._add, chan2)
self.assertRaises(QiskitError, chan1._add, 5)
def test_multiply(self):
"""Test multiply method."""
chan = Chi(self.chiI)
val = 0.5
targ = Chi(val * self.chiI)
self.assertEqual(chan._multiply(val), targ)
self.assertEqual(val * chan, targ)
targ = Chi(self.chiI * val)
self.assertEqual(chan * val, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Chi(self.chiI)
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
chan = Chi(self.chiI)
targ = Chi(-self.chiI)
self.assertEqual(-chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/SimoneGasperini/qiskit-symb
|
SimoneGasperini
|
"""Symbolic quantum base module"""
import numpy
import sympy
from sympy import Symbol, lambdify
from sympy.matrices import Matrix, matrix2numpy
from qiskit import QuantumCircuit
from qiskit.providers.basic_provider.basic_provider_tools import einsum_matmul_index
class QuantumBase:
"""Abstract symbolic quantum base class"""
def __init__(self, data, params):
"""todo"""
# pylint: disable=no-member
if isinstance(data, QuantumCircuit):
params = list(data.parameters)
data = self._get_data_from_circuit(circuit=data)
self._data = data
self._params = params
@staticmethod
def _get_circ_unitary(circ):
"""todo"""
# pylint: disable=import-outside-toplevel
# pylint: disable=protected-access
from ..utils import transpile_circuit, flatten_circuit
from ..circuit import Gate
circ = transpile_circuit(flatten_circuit(circ))
layers = circ.draw(output='text').nodes
dim = 2 ** circ.num_qubits
newshape = (2, 2) * circ.num_qubits
unitary = numpy.reshape(numpy.eye(dim), newshape=newshape)
for layer in layers:
for instruction in layer[::-1]:
gate_tensor = Gate.get(instruction)._get_tensor()
gate_indices = [qarg._index for qarg in instruction.qargs]
indexing = einsum_matmul_index(
gate_indices=gate_indices, number_of_qubits=circ.num_qubits)
unitary = numpy.einsum(indexing, gate_tensor, unitary,
dtype=object, casting='no', optimize='optimal')
gph = sympy.exp(sympy.I * circ.global_phase)
return gph * Matrix(numpy.reshape(unitary, newshape=(dim, dim)))
@classmethod
def from_label(cls, label):
"""todo"""
# pylint: disable=no-member
data = cls._get_data_from_label(label)
return cls(data=data, params=[])
@classmethod
def from_circuit(cls, circuit):
"""todo"""
# pylint: disable=no-member
data = cls._get_data_from_circuit(circuit)
params = list(circuit.parameters)
return cls(data=data, params=params)
def to_sympy(self):
"""todo"""
return self._data
def to_numpy(self):
"""todo"""
return matrix2numpy(self._data, dtype=complex)
def to_lambda(self):
"""todo"""
sympy_matrix = self._data
name2symb = {symb.name: symb for symb in sympy_matrix.free_symbols}
args = [name2symb[par.name] if par.name in name2symb else Symbol('_')
for par in self._params]
return lambdify(args=args, expr=sympy_matrix, modules='numpy', dummify=True, cse=True)
def subs(self, params_dict):
"""todo"""
par2val = {}
for par, val in params_dict.items():
if hasattr(par, '__len__'):
par2val.update(dict(zip(par, val)))
else:
par2val[par] = val
sympy_matrix = self._data
name2symb = {symb.name: symb for symb in sympy_matrix.free_symbols}
symb2val = {name2symb[par.name]: val for par, val in par2val.items()
if par.name in name2symb}
data = sympy_matrix.subs(symb2val)
params = [par for par in self._params if par not in par2val]
return self.__class__(data=data, params=params)
def transpose(self):
"""todo"""
return self.__class__(data=self._data.T, params=self._params)
def conjugate(self):
"""todo"""
return self.__class__(data=self._data.conjugate(), params=self._params)
def dagger(self):
"""todo"""
return self.__class__(data=self._data.T.conjugate(), params=self._params)
|
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/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-docstring
"""BasicAerJob creation and test suite."""
import uuid
from contextlib import contextmanager
from os import path
import unittest
from unittest.mock import patch
from qiskit.test import QiskitTestCase
from qiskit.test.mock import new_fake_qobj, FakeRueschlikon
class TestSimulatorsJob(QiskitTestCase):
"""Test how backends create BasicAerJob objects and the BasicAerJob class."""
def test_multiple_execution(self):
# Notice that it is Python responsibility to test the executors
# can run several tasks at the same time. It is our responsibility to
# use the executor correctly. That is what this test checks.
taskcount = 10
target_tasks = [lambda: None for _ in range(taskcount)]
job_id = str(uuid.uuid4())
backend = FakeRueschlikon()
with mocked_executor() as (SimulatorJob, executor):
for index in range(taskcount):
job = SimulatorJob(backend, job_id, target_tasks[index], new_fake_qobj())
job.submit()
self.assertEqual(executor.submit.call_count, taskcount)
for index in range(taskcount):
_, callargs, _ = executor.submit.mock_calls[index]
submitted_task = callargs[0]
target_task = target_tasks[index]
self.assertEqual(submitted_task, target_task)
def test_cancel(self):
# Again, cancelling jobs is beyond our responsibility. In this test
# we only check if we delegate on the proper method of the underlaying
# future object.
job_id = str(uuid.uuid4())
backend = FakeRueschlikon()
with mocked_executor() as (BasicAerJob, executor):
job = BasicAerJob(backend, job_id, lambda: None, new_fake_qobj())
job.submit()
job.cancel()
self.assertCalledOnce(executor.submit)
mocked_future = executor.submit.return_value
self.assertCalledOnce(mocked_future.cancel)
def assertCalledOnce(self, mocked_callable):
"""Assert a mocked callable has been called once."""
call_count = mocked_callable.call_count
self.assertEqual(
call_count, 1,
'Callable object has been called more than once ({})'.format(
call_count))
@contextmanager
def mocked_executor():
"""Context that patches the derived executor classes to return the same
executor object. Also patches the future object returned by executor's
submit()."""
import importlib
import concurrent.futures as futures
import qiskit.providers.basicaer.basicaerjob as basicaerjob
executor = unittest.mock.MagicMock(spec=futures.Executor)
executor.submit.return_value = unittest.mock.MagicMock(spec=futures.Future)
mock_options = {'return_value': executor, 'autospec': True}
with patch.object(futures, 'ProcessPoolExecutor', **mock_options),\
patch.object(futures, 'ThreadPoolExecutor', **mock_options):
importlib.reload(basicaerjob)
yield basicaerjob.BasicAerJob, executor
@contextmanager
def mocked_simulator_binaries():
"""Context to force binary-based simulators to think the simulators exist.
"""
with patch.object(path, 'exists', return_value=True, autospec=True),\
patch.object(path, 'getsize', return_value=1000, autospec=True):
yield
if __name__ == '__main__':
unittest.main(verbosity=2)
|
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.
"""Module to describe fermionic states in occupation number basis"""
from typing import List, Union
import warnings
import numpy as np
from qiskit import QuantumCircuit
from qiskit_cold_atom.exceptions import QiskitColdAtomError
class FermionicState:
"""Fermionic states in an occupation number representation."""
def __init__(self, occupations: Union[List[int], List[List[int]]]):
"""Create a :class:`FermionicState` from the given occupations.
Args:
occupations: List of occupation numbers. When List[int] is given, the occupations
correspond to the number of indistinguishable fermionic particles in each mode,
e.g. [0, 1, 1, 0] implies that sites one and two are occupied by a fermion.
When List[List[int]] is given, the occupations describe the number of particles in
fermionic modes with different (distinguishable) species of fermions. Each
inner list gives the occupations of one fermionic species.
Raises:
QiskitColdAtomError:
- If the inner lists do not have the same length
- If the occupations are not 0 or 1
"""
if isinstance(occupations[0], (int, np.integer)):
occupations = [occupations]
self._sites = len(occupations[0])
self._occupations = occupations
self._num_species = len(occupations)
self._occupations_flat = []
for occs in self.occupations:
self._occupations_flat += occs
for occs in self.occupations[0:]:
if len(occs) != self._sites:
raise QiskitColdAtomError(
f"All occupations of different fermionic species must have "
f"same length, received {self.occupations[0]} and {occs}."
)
for n in occs:
if n not in (0, 1):
raise QiskitColdAtomError(f"Fermionic occupations must be 0 or 1, got {n}.")
@property
def occupations(self) -> List[List[int]]:
"""Return the occupation number of each fermionic mode."""
return self._occupations
@property
def occupations_flat(self) -> List[int]:
"""Return the occupations of each fermionic mode in a flat list."""
return self._occupations_flat
@property
def sites(self) -> int:
"""Return the number of fermionic sites."""
return self._sites
@property
def num_species(self) -> int:
"""Return the number of species of fermions, e.g. 2 for spin up/down systems."""
return self._num_species
def __str__(self):
output = ""
for i in range(self.num_species):
output += "|" + str(self.occupations[i])[1:-1] + ">"
return output
@classmethod
def from_total_occupations(cls, occupations: List[int], num_species: int) -> "FermionicState":
"""
Create a fermionic state from a single (flat) list of total occupations.
Args:
occupations: a list of occupations of all fermionic modes, e.g. [0, 1, 1, 0, 1, 0].
num_species: number of fermionic species. If > 1, the total occupation list is cast
into a nested list where each inner list describes one fermionic species. In the
above example, for num_species = 2, this becomes
FermionicState([[0, 1, 1], [0, 1, 0]]).
Returns:
A fermionic state initialized with the given input.
Raises:
QiskitColdAtomError: If the length of occupations is not a multiple of num_species.
"""
if len(occupations) % num_species != 0:
raise QiskitColdAtomError(
"The state must have a number of occupations that is a multiple of the"
"number of fermionic species."
)
sites = int(len(occupations) / num_species)
return cls(np.reshape(occupations, (num_species, sites)).tolist())
@classmethod
def initial_state(cls, circuit: QuantumCircuit, num_species: int = 1) -> "FermionicState":
"""
Create a fermionic state from a quantum circuit that uses the `LoadFermion` instruction.
This instruction must be the first instructions of the circuit and no further LoadFermion
instruction can be applied, even after other instructions such as gates have been applied.
Args:
circuit: a quantum circuit with LoadFermions instructions that initialize fermionic
particles.
num_species: number of different fermionic species, e.g. 1 for a single
type of spinless fermions (default), 2 for spin-1/2 fermions etc.
Returns:
A FermionicState initialized from the given circuit.
Raises:
QiskitColdAtomError:
- If the number of wires in the circuit is not a multiple of num_species,
- If LoadFermions instructions come after other instructions.
"""
if num_species > 1:
if circuit.num_qubits % num_species != 0:
raise QiskitColdAtomError(
"The circuit must have a number of wires that is a multiple of the"
"number of fermionic species."
)
occupations = [0] * circuit.num_qubits
gates_applied = [False] * circuit.num_qubits
if not circuit.data[0][0].name == "load":
warnings.warn(
"No particles have been initialized, the circuit will return a trivial result."
)
# check that there are no more 'LoadFermions' instructions
for instruction in circuit.data:
qargs = [circuit.qubits.index(qubit) for qubit in instruction[1]]
if instruction[0].name == "load":
for idx in qargs:
if gates_applied[idx]:
raise QiskitColdAtomError(
f"State preparation instruction in circuit after gates on wire {idx}"
)
occupations[idx] = 1
else:
for idx in qargs:
gates_applied[idx] = True
return cls.from_total_occupations(occupations, num_species)
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumCircuit, Aer
from qiskit.visualization import array_to_latex
sim = Aer.get_backend("aer_simulator")
qc = QuantumCircuit(2)
qc.cx(0, 1)
display(qc.draw("mpl"))
qc.save_unitary()
unitary = sim.run(qc).result().get_unitary()
display(array_to_latex(unitary, prefix="\\text{CNOT (LSB as Target) = }"))
|
https://github.com/abhilash1910/EuroPython-21-QuantumDeepLearning
|
abhilash1910
|
!pip install pennylane
%load_ext tensorboard
import pennylane as qml
from pennylane import numpy as np
from pennylane.templates import RandomLayers
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import os
from datetime import datetime
%tensorboard --logdir logs/scalars/
tensorboard_callback = keras.callbacks.TensorBoard(
log_dir= "logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S"),
histogram_freq=0,
write_graph=True,
write_grads=True
)
n_epochs = 30 # Number of optimization epochs
n_layers = 1 # Number of random layers
n_train = 50 # Size of the train dataset
n_test = 30 # Size of the test dataset
SAVE_PATH = "quanvolution/" # Data saving folder
PREPROCESS = True # If False, skip quantum processing and load data from SAVE_PATH
np.random.seed(0) # Seed for NumPy random number generator
tf.random.set_seed(0) # Seed for TensorFlow random number generator
mnist_dataset = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist_dataset.load_data()
# Reduce dataset size
train_images = train_images[:n_train]
train_labels = train_labels[:n_train]
test_images = test_images[:n_test]
test_labels = test_labels[:n_test]
# Normalize pixel values within 0 and 1
train_images = train_images / 255
test_images = test_images / 255
# Add extra dimension for convolution channels
train_images = np.array(train_images[..., tf.newaxis], requires_grad=False)
test_images = np.array(test_images[..., tf.newaxis], requires_grad=False)
dev = qml.device("default.qubit", wires=4)
# Random circuit parameters
rand_params = np.random.uniform(high=2 * np.pi, size=(n_layers, 4))
@qml.qnode(dev)
def circuit(phi):
# Encoding of 4 classical input values
for j in range(4):
qml.RY(np.pi * phi[j], wires=j)
# Random quantum circuit
RandomLayers(rand_params, wires=list(range(4)))
# Measurement producing 4 classical output values
return [qml.expval(qml.PauliZ(j)) for j in range(4)]
def quanv(image):
"""Convolves the input image with many applications of the same quantum circuit."""
out = np.zeros((14, 14, 4))
# Loop over the coordinates of the top-left pixel of 2X2 squares
for j in range(0, 28, 2):
for k in range(0, 28, 2):
# Process a squared 2x2 region of the image with a quantum circuit
q_results = circuit(
[
image[j, k, 0],
image[j, k + 1, 0],
image[j + 1, k, 0],
image[j + 1, k + 1, 0]
]
)
# Assign expectation values to different channels of the output pixel (j/2, k/2)
for c in range(4):
out[j // 2, k // 2, c] = q_results[c]
return out
if PREPROCESS == True:
q_train_images = []
print("Quantum pre-processing of train images:")
for idx, img in enumerate(train_images):
print("{}/{} ".format(idx + 1, n_train), end="\r")
q_train_images.append(quanv(img))
q_train_images = np.asarray(q_train_images)
q_test_images = []
print("\nQuantum pre-processing of test images:")
for idx, img in enumerate(test_images):
print("{}/{} ".format(idx + 1, n_test), end="\r")
q_test_images.append(quanv(img))
q_test_images = np.asarray(q_test_images)
# Save pre-processed images
if (os.path.exists(SAVE_PATH))==False:
os.makedirs(SAVE_PATH)
np.save(SAVE_PATH + "q_train_images.npy", q_train_images)
np.save(SAVE_PATH + "q_test_images.npy", q_test_images)
# Load pre-processed images
q_train_images = np.load(SAVE_PATH + "q_train_images.npy")
q_test_images = np.load(SAVE_PATH + "q_test_images.npy")
n_samples = 4
n_channels = 4
def plotter():
fig, axes = plt.subplots(1 + n_channels, n_samples, figsize=(10, 10))
for k in range(n_samples):
axes[0, 0].set_ylabel("Input")
if k != 0:
axes[0, k].yaxis.set_visible(False)
axes[0, k].imshow(train_images[k, :, :, 0], cmap="gray")
# Plot all output channels
for c in range(n_channels):
axes[c + 1, 0].set_ylabel("Output [ch. {}]".format(c))
if k != 0:
axes[c, k].yaxis.set_visible(False)
axes[c + 1, k].imshow(q_train_images[k, :, :, c], cmap="gray")
plt.tight_layout()
plt.show()
plotter()
def Model():
"""Initializes and returns a custom Keras model
which is ready to be trained."""
model = keras.models.Sequential([
keras.layers.Conv2D(32,(3,3),activation='relu'),
keras.layers.Flatten(),
keras.layers.Dense(12),
keras.layers.Dense(10, activation="softmax")
])
model.compile(
optimizer='adam',
loss="sparse_categorical_crossentropy",
metrics=["accuracy"],
)
return model
q_model = Model()
q_history = q_model.fit(
q_train_images,
train_labels,
validation_data=(q_test_images, test_labels),
batch_size=4,
epochs=n_epochs,
verbose=2,callbacks=[tensorboard_callback]
)
c_model = Model()
c_history = c_model.fit(
train_images,
train_labels,
validation_data=(test_images, test_labels),
batch_size=4,
epochs=n_epochs,
verbose=2,callbacks=[tensorboard_callback]
)
print(q_model.summary())
print(c_model.summary())
def plot_model(model,filename):
tf.keras.utils.plot_model(model, to_file=filename, show_shapes=False, show_dtype=False,show_layer_names=True, rankdir='TB', expand_nested=False, dpi=96)
plot_model(q_model,'QConv.png')
plot_model(c_model,'CConv.png')
|
https://github.com/arnavdas88/QuGlassyIsing
|
arnavdas88
|
!pip install qiskit
J = 4.0
B_x = 1.5
B_z = 1.5
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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^ 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_CountsDIS3.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/Sidx369/Qiskit-Developer-Exam-C1000-112-Prep
|
Sidx369
|
import qiskit
qiskit.__version__
qiskit.__qiskit_version__
import qiskit.tools.jupyter
%qiskit_version_table
from qiskit import QuantumCircuit
qc = QuantumCircuit(2,2) # (qbit, classicalbit)
qc.measure_all()
qc.draw()
qc.draw('mpl')
qc.draw('latex')
qc = QuantumCircuit(3,2) # (qbit, classicalbit)
qc.measure([0,1], [0,1])
qc.draw('mpl')
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.measure([0, 1], [0, 1])
qc.draw('mpl')
from qiskit.visualization import plot_histogram
sim = Aer.get_backend('statevector_simulator')
job = execute(qc, sim, shots=1024)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
from qiskit.visualization import plot_state_qsphere
from qiskit.quantum_info import Statevector
qc=QuantumCircuit(1)
qc.x(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_qsphere(state)
from qiskit.visualization import array_to_latex
sim = Aer.get_backend('unitary_simulator')
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
#array_to_latex(result.get_statevector(qc)) # for statevector_simulator
qc=QuantumCircuit(1)
qc.y(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_qsphere(state)
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
qc=QuantumCircuit(1)
qc.x(0)
qc.y(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_qsphere(state)
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
qc=QuantumCircuit(1)
qc.z(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_qsphere(state)
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
qc=QuantumCircuit(1)
qc.x(0)
qc.z(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_qsphere(state)
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
qc=QuantumCircuit(1)
qc.h(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_qsphere(state)
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
qc=QuantumCircuit(1)
qc.s(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_qsphere(state)
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
qc=QuantumCircuit(1)
qc.x(0)
qc.s(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_qsphere(state)
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
qc=QuantumCircuit(1)
qc.sdg(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_qsphere(state)
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
qc=QuantumCircuit(1)
qc.x(0)
qc.s(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_qsphere(state)
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
qc=QuantumCircuit(1)
qc.t(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_qsphere(state)
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
qc=QuantumCircuit(1)
qc.x(0)
qc.t(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_qsphere(state)
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
qc=QuantumCircuit(1)
qc.tdg(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_qsphere(state)
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
qc=QuantumCircuit(1)
qc.x(0)
qc.tdg(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_qsphere(state)
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
from math import pi
qc=QuantumCircuit(1)
qc.p(pi,0)
qc.draw(output="mpl")
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
qc=QuantumCircuit(1)
qc.p(pi/2,0)
qc.draw(output="mpl")
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
qc=QuantumCircuit(1)
qc.p(pi/4,0)
qc.draw(output="mpl")
job = execute(qc, sim)
result = job.result()
array_to_latex(result.get_unitary(qc, decimals=3))
|
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/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_pairs = ['00','01','10','11']
for pair in all_pairs:
# create a quantum curcuit with two qubits: Asja's and Balvis' qubits.
# both are initially set to |0>.
qreg = QuantumRegister(2) # quantum register with 2 qubits
creg = ClassicalRegister(2) # classical register with 2 bits
mycircuit = QuantumCircuit(qreg,creg) # quantum circuit with quantum and classical registers
# apply h-gate (Hadamard) to the first qubit.
mycircuit.h(qreg[0])
# apply cx-gate (CNOT) with parameters first-qubit and second-qubit.
mycircuit.cx(qreg[0],qreg[1])
# they are separated now.
# if a is 1, then apply z-gate to the first qubit.
if pair[0]=='1':
mycircuit.z(qreg[0])
# if b is 1, then apply x-gate (NOT) to the first qubit.
if pair[1]=='1':
mycircuit.x(qreg[0])
# Asja sends her qubit to Balvis.
# apply cx-gate (CNOT) with parameters first-qubit and second-qubit.
mycircuit.cx(qreg[0],qreg[1])
# apply h-gate (Hadamard) to the first qubit.
mycircuit.h(qreg[0])
# measure both qubits
mycircuit.measure(qreg,creg)
# compare the results with pair (a,b)
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit)
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print("(a,b) is",pair,": ",reverse_outcome,"is observed",counts[outcome],"times")
# draw the circuit
mycircuit.draw(output='mpl',reverse_bits=True)
# reexecute me if you DO NOT see the circuit diagram
|
https://github.com/JavaFXpert/qiskit4devs-workshop-notebooks
|
JavaFXpert
|
#!pip install qiskit
# Do the usual setup, but without classical registers or measurement
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, execute
qr = QuantumRegister(1)
circ = QuantumCircuit(qr)
# Place an Ry gate with a −3π/4 rotation
circ.ry(-3/4 * np.pi, qr[0])
# Draw the circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circ, backend_sv_sim)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector
quantum_state
# Plot the state vector on a Bloch sphere
from qiskit.tools.visualization import plot_bloch_multivector
plot_bloch_multivector(quantum_state)
# Do the usual setup, but without classical registers or measurement
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, execute
qr = QuantumRegister(1)
circ = QuantumCircuit(qr)
# Place gates that will achieve the desired state
# Draw the circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circ, backend_sv_sim)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector
quantum_state
# Plot the state vector on a Bloch sphere
from qiskit.tools.visualization import plot_bloch_multivector
plot_bloch_multivector(quantum_state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can choose different colors for the real and imaginary parts of the density matrix.
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = DensityMatrix(qc)
plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
|
https://github.com/luis6156/Shor-s-Quantum-Algorithm
|
luis6156
|
from qiskit import QuantumCircuit, Aer, execute, IBMQ
from qiskit.utils import QuantumInstance
import numpy as np
from qiskit.algorithms import Shor
IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here
provider = IBMQ.get_provider(hub='ibm-q')
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1000)
my_shor = Shor(quantum_instance)
result_dict = my_shor.factor(15)
print(result_dict)
|
https://github.com/AnuvabSen1/Quantum-Computing-Algorithms-Implemented-on-IBM-s-QSAM-Qiskit
|
AnuvabSen1
|
import numpy as np
import math
import gmpy2
from gmpy2 import powmod,mpz,isqrt,invert
from qiskit.aqua.algorithms import Shor
from qiskit.aqua import QuantumInstance
from qiskit import Aer,execute,QuantumCircuit
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.ibmq import least_busy
from qiskit import IBMQ, execute
def generate_keys():
# prime number of 3 digits i.e 7 bits
random1 = np.random.randint(3,40)
random2 = np.random.randint(3,40)
p = int(gmpy2.next_prime(random1))
q = int(gmpy2.next_prime(random2))
n = p*q
while (n<100 or n>127):
random1 = np.random.randint(3,40)
random2 = np.random.randint(3,40)
p = int(gmpy2.next_prime(random1))
q = int(gmpy2.next_prime(random2))
n = p*q
phi = (p-1)*(q-1)
e = 2
while True:
if gmpy2.gcd(phi,e) != 1:
e = e + 1
else :
break
d = gmpy2.invert(e,phi)
return n,e,d
def encrypt(plain_text_blocks,public_keys):
cipher_text_blocks = []
n,e = public_keys
for plain_text in plain_text_blocks:
cipher_text = (gmpy2.powmod(plain_text,e,n))
cipher_text_blocks.append(cipher_text)
return cipher_text_blocks
def decrypt(cipher_text_blocks,secret_key,public_keys):
n,e = public_keys
d = secret_key
decypted_plain_text_blocks = []
for cipher_text in cipher_text_blocks:
plain_text = (gmpy2.powmod(cipher_text,d,n))
decypted_plain_text_blocks.append(plain_text)
return decypted_plain_text_blocks
def get_factors(public_keys):
n,e = public_keys
# backend = Aer.get_backend('qasm_simulator')
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_qasm_simulator')
quantum_instance = QuantumInstance(backend,shots=2500)
find_factors = Shor(n,a=2,quantum_instance=quantum_instance)
factors = Shor.run(find_factors)
p = ((factors['factors'])[0])[0]
q = ((factors['factors'])[0])[1]
print('Factors of',n,'are :',p,q)
return p,q
# taken in 'Hello World!!!' returns ['Hello World!','!!']
def get_blocks(PT,block_size):
blocks = []
i = 0
while i<len(PT):
temp_str=''
if i+block_size-1 < len(PT):
temp_str=temp_str+PT[i:i+block_size]
else :
temp_str=temp_str+PT[i::]
blocks.append(temp_str)
i=i+block_size
return blocks
# covert plain_text block from characters to the numbers
def format_plain_text(PT):
plain_text_blocks = []
for block in PT:
plain_text = 0
for i in range(len(block)):
# for 'd'
if ord(block[i]) == 100:
plain_text = plain_text*100 + 28
# between (101,127)
elif ord(block[i])>100:
plain_text = plain_text*100 + (ord(block[i])-100)
else :
plain_text = plain_text*100 + (ord(block[i]))
plain_text_blocks.append(plain_text)
return plain_text_blocks
# convert numeric decypted_plain_text_blocks into a single plain text of characters
def format_decrypted_plain_text(decypted_plain_text_blocks):
plain_text_blocks = []
for dc_pt in decypted_plain_text_blocks:
plain_text = ''
temp = dc_pt
# for 'd' temp = 28
while temp > 0:
if temp%100 == 28:
plain_text = plain_text + 'd'
elif (temp%100) in range(0,27):
plain_text = plain_text + chr((temp%100)+100)
else :
plain_text = plain_text + chr((temp%100))
temp = temp//100
plain_text = plain_text[::-1]
plain_text_blocks.append(plain_text)
final_plain_text = ''
for plain_text_block in plain_text_blocks:
final_plain_text = final_plain_text + plain_text_block
return final_plain_text
n,e,d = generate_keys()
public_keys = (n,e)
secret_key = d
print("\nPublic Key :")
print('n :',n)
print('e :',e)
print("Secret Key :\nd :",d)
PT = input("\nEnter Plain Text to encrypt : ")
original_plain_text = PT
block_size = 1
PT = get_blocks(PT,block_size)
print('\nPlain Text after converting to blocks',PT)
plain_text_blocks = format_plain_text(PT)
print('\nPlain text blocks after formatting to numbers:',plain_text_blocks)
cipher_text_blocks = encrypt(plain_text_blocks,public_keys)
print("\nCipher Text Blocks After RSA encryption :",cipher_text_blocks)
p,q = get_factors(public_keys)
phi = (p-1)*(q-1)
broken_d = gmpy2.invert(e,phi)
compromised_PT = decrypt(cipher_text_blocks,broken_d,public_keys)
compromised_PT = format_decrypted_plain_text(compromised_PT)
compromised_PT = '!!!Your message has been attacked!!! ' + compromised_PT
compromised_PT = get_blocks(compromised_PT,block_size)
compromised_PT = format_plain_text(compromised_PT)
compromised_CT = encrypt(compromised_PT,public_keys)
cipher_text_blocks = compromised_CT
decypted_plain_text_blocks = decrypt(cipher_text_blocks,secret_key,public_keys)
print("\nPlain Text blocks after decryption of Cipher Text blocks :",decypted_plain_text_blocks)
plain_text_after_decryption = format_decrypted_plain_text(decypted_plain_text_blocks)
print("\nAfter decryption Plain Text :",plain_text_after_decryption)
if (original_plain_text == plain_text_after_decryption):
print("\nHurrayyy!!!\n\nDecrypted plain_text is same as original plain_text! :) ")
else :
print('RSA was attacked!!! :(')
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import pylab
from qiskit_chemistry import QiskitChemistry
# Input dictionary to configure Qiskit Chemistry for the chemistry problem.
qiskit_chemistry_dict = {
'driver': {'name': 'PYSCF'},
'PYSCF': {'atom': '', 'basis': 'sto3g'},
'operator': {'name': 'hamiltonian', 'qubit_mapping': 'parity', 'two_qubit_reduction': True},
'algorithm': {'name': 'ExactEigensolver', 'k': 4},
}
molecule = 'H .0 .0 -{0}; H .0 .0 {0}'
start = 0.5 # Start distance
by = 0.5 # How much to increase distance by
steps = 20 # Number of steps to increase by
energies = np.empty([4, steps+1])
distances = np.empty(steps+1)
print('Processing step __', end='')
for i in range(steps+1):
print('\b\b{:2d}'.format(i), end='', flush=True)
d = start + i*by/steps
qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2)
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict)
energies[:, i] = result['energies']
distances[i] = d
print(' --- complete')
print('Distances: ', distances)
print('Energies:', energies)
pylab.rcParams['figure.figsize'] = (12, 8)
for j in range(energies.shape[0]):
label = 'Ground state' if j ==0 else 'Excited state {}'.format(j)
pylab.plot(distances, energies[j], label=label)
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.title('H2 Ground and Excited States')
pylab.legend(loc='upper right')
pylab.show()
pylab.rcParams['figure.figsize'] = (6, 4)
prop_cycle = pylab.rcParams['axes.prop_cycle']
colors = prop_cycle.by_key()['color']
for j in range(energies.shape[0]):
label = 'Ground state' if j ==0 else 'Excited state {}'.format(j)
pylab.plot(distances, energies[j], color=colors[j], label=label)
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.title('H2 {}'.format(label))
pylab.legend(loc='upper right')
pylab.show()
|
https://github.com/omarcostahamido/Qu-Beats
|
omarcostahamido
|
from qiskit import *
import numpy as np
from mido import Message, MidiFile, MidiTrack
from mido import *
import mido
from qiskit.tools.visualization import plot_histogram
def add_circuit(qc):
qc.h(0)
qc.cx(0,1)
return qc
def Teleportation(qc):
qc.z(0); qc.h(0)
qc.h(1)
qc.cx(1,2); qc.cx(0,1)
qc.measure(1,1)
qc.cx(1,2); qc.h(0)
qc.measure(0,0)
qc.cz(0,2)
qc.h(2); qc.z(2)
qc.measure(2,2)
return qc
def grover(qc):
qc.h(0)
qc.h(1)
qc.x(0)
qc.x(1)
qc.cz(0,1)
qc.x(0)
qc.x(1)
qc.h(0)
qc.h(1)
qc.cz(0,1)
qc.h(0)
qc.h(1)
return qc
def Bertstein_Vazirani(qc):
qc.h(0); qc.h(1); qc.h(2); qc.h(3)
qc.z(0); qc.z(1); qc.z(2); qc.z(3)
qc.h(0); qc.h(1); qc.h(2); qc.h(3)
qc.measure([0,1,2,3], [0,1,2,3])
return qc
Beat_array = []
Beat1 = [0,1,0,0,1,0,1,0,1,0]; Beat_array.append(Beat1)
Beat2 = [1,1,0,1,1,0,1,1,1,1]; Beat_array.append(Beat2)
Beat3 = [0,0,0,1,1,1,1,0,0,1]; Beat_array.append(Beat3)
Beat4 = [1,0,0,0,1,1,0,0,0,1]; Beat_array.append(Beat4)
## The 4 starting Beats being converted to MIDI
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
current_time = 0
for bt in Beat_array[0]:
if bt == 1:
track.append(Message('note_on', note=32, time=100))#current_time))
else:
track.append(Message('note_off', note=32,time=100))#current_time))
#current_time = current_time + 32
mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat1.mid')
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
for bt in Beat_array[1]:
if bt == 1:
track.append(Message('note_on', note=35, time=100))#current_time))
else:
track.append(Message('note_off', note=35, time=100))#current_time))
#current_time = current_time + 32
mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat2.mid')
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
for bt in Beat_array[2]:
if bt == 1:
track.append(Message('note_on', note=38, time=100))#current_time))
else:
track.append(Message('note_off', note=38, time=100))#current_time))
#current_time = current_time + 32
mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat3.mid')
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
for bt in Beat_array[3]:
if bt == 1:
track.append(Message('note_on', note=40, time=100))#current_time))
else:
track.append(Message('note_off', note=40, time=100))#current_time))
#current_time = current_time + 32
mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat4.mid')
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
#qc = QuantumCircuit(qr, cr)
circuits = []
for i, val in enumerate(Beat1):
qc = QuantumCircuit(qr, cr)
if val == 1:
qc.x(0)
if Beat2[i] == 1:
qc.x(1)
add_circuit(qc)
qc.measure([0,1], [0,1])
circuits.append(qc)
circuits[0].draw(output='mpl')
## Execuuting code
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuits, backend = simulator, shots=1).result()
cir_array = []
for c in circuits:
cir_array.append([k for k in result.get_counts(c).keys()][0])
new_track1 = []
new_track2 = []
for b in cir_array:
new_track1.append(int(b[0]))
new_track2.append(int(b[1]))
#print(cir_array);
print(new_track1), print(new_track2)
## New Midi Rhythms
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
current_time = 0
for bt in new_track1:
if bt == 1:
track.append(Message('note_on', note=32, time=100))#current_time))
else:
track.append(Message('note_off', note=32, time=100))#current_time))
#current_time = current_time + 32
mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/Bell_Circ.mid')
mid = MidiFile()
track2 = MidiTrack()
mid.tracks.append(track2)
current_time = 0
for bt in new_track2:
if bt == 1:
track2.append(Message('note_on', note=35, time=100))#current_time))
else:
track2.append(Message('note_off', note=35, time=100))#current_time))
#current_time = current_time + 32
mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/Bell_Circ2.mid')
###--------------- Rhythm #2 ------------------------------------------------------------------------------------------
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuits = []
for i, val in enumerate(Beat1):
qc = QuantumCircuit(qr, cr)
if val == 1:
qc.x(0)
if Beat2[i] == 1:
qc.x(1)
if Beat3[i] == 1:
qc.x(2)
qc.barrier()
Teleportation(qc)
circuits.append(qc)
circuits[0].draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuits, backend = simulator, shots=1).result()
plot_histogram(result.get_counts(qc))
print(len(result.results))
## Execuuting code
cir_array = []
for c in circuits:
cir_array.append([k for k in result.get_counts(c).keys()][0])
new_track1 = []
new_track2 = []
new_track3 = []
for b in cir_array:
new_track1.append(int(b[0]))
new_track2.append(int(b[1]))
new_track3.append(int(b[2]))
#print(cir_array);
print(new_track1), print(new_track2); print(new_track3)
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
circuits = []
for i, val in enumerate(Beat1):
qc = QuantumCircuit(qr, cr)
if val == 1:
qc.x(0)
if Beat2[i] == 1:
qc.x(1)
if Beat2[i] == 1:
qc.x(2)
if Beat2[i] == 1:
qc.x(3)
qc.barrier()
Bertstein_Vazirani(qc)
circuits.append(qc)
circuits[0].draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuits, backend = simulator, shots=1024).result()
plot_histogram(result.get_counts(circuits[4]))
## Execuuting code
cir_array = []
for c in circuits:
cir_array.append([k for k in result.get_counts(c).keys()][0])
new_track1 = []
new_track2 = []
new_track3 = []
for b in cir_array:
new_track1.append(int(b[0]))
new_track2.append(int(b[1]))
new_track3.append(int(b[2]))
#print(cir_array);
print(new_track1), print(new_track2); print(new_track3)
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
for bt in new_track1:
if bt == 1:
track.append(Message('note_on', note=32, time=100))#current_time))
else:
track.append(Message('note_off', note=32, time=100))#current_time))
#current_time = current_time + 32
mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/new_teleport1.mid')
mid = MidiFile()
track2 = MidiTrack()
mid.tracks.append(track2)
for bt in new_track2:
if bt == 1:
track2.append(Message('note_on', note=35, time=100))#current_time))
else:
track2.append(Message('note_off', note=35,time=100))#current_time))
#current_time = current_time + 32
mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/new_teleport2.mid')
mid = MidiFile()
track3 = MidiTrack()
mid.tracks.append(track3)
for bt in new_track3:
if bt == 1:
track3.append(Message('note_on', note=38, time=100))#current_time))
else:
track3.append(Message('note_off', note=38, time=100))#current_time))
#current_time = current_time + 32
mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/new_teleport3.mid')
## -----------------------------------------------------------------------
## The 4 starting Beats being converted to MIDI
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
current_time = 0
for bt in Beat_array[0]:
if bt == 1:
track.append(Message('note_on', time=100))#current_time))
else:
track.append(Message('note_off', time=100))#current_time))
#current_time = current_time + 32
mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat1.mid')
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
for bt in Beat_array[1]:
if bt == 1:
track.append(Message('note_on', time=100))#current_time))
else:
track.append(Message('note_off', time=100))#current_time))
#current_time = current_time + 32
mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat2.mid')
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
for bt in Beat_array[2]:
if bt == 1:
track.append(Message('note_on', time=100))#current_time))
else:
track.append(Message('note_off', time=100))#current_time))
#current_time = current_time + 32
mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat3.mid')
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
for bt in Beat_array[3]:
if bt == 1:
track.append(Message('note_on', time=100))#current_time))
else:
track.append(Message('note_off', time=100))#current_time))
#current_time = current_time + 32
mid.save('/Users/scottoshiro/Documents/Qiskit_Camp/pBeat4.mid')
|
https://github.com/chunfuchen/qiskit-chemistry
|
chunfuchen
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import unittest
from parameterized import parameterized
import numpy as np
import qiskit
from qiskit.transpiler import PassManager
from qiskit.aqua.utils import decimal_to_binary
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms.single_sample import QPE
from qiskit.aqua.algorithms.classical import ExactEigensolver
from qiskit.aqua.components.iqfts import Standard
from test.common import QiskitChemistryTestCase
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry import FermionicOperator, QiskitChemistryError
from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock
class TestEnd2EndWithQPE(QiskitChemistryTestCase):
"""QPE tests."""
@parameterized.expand([
[0.5],
[0.735],
[1],
])
def test_qpe(self, distance):
self.algorithm = 'QPE'
self.log.debug('Testing End-to-End with QPE on H2 with inter-atomic distance {}.'.format(distance))
try:
driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 {}'.format(distance),
unit=UnitsType.ANGSTROM,
charge=0,
spin=0,
basis='sto3g')
except QiskitChemistryError:
self.skipTest('PYSCF driver does not appear to be installed')
self.molecule = driver.run()
qubit_mapping = 'parity'
fer_op = FermionicOperator(
h1=self.molecule.one_body_integrals, h2=self.molecule.two_body_integrals)
self.qubit_op = fer_op.mapping(map_type=qubit_mapping,
threshold=1e-10).two_qubit_reduced_operator(2)
exact_eigensolver = ExactEigensolver(self.qubit_op, k=1)
results = exact_eigensolver.run()
self.reference_energy = results['energy']
self.log.debug(
'The exact ground state energy is: {}'.format(results['energy']))
num_particles = self.molecule.num_alpha + self.molecule.num_beta
two_qubit_reduction = True
num_orbitals = self.qubit_op.num_qubits + \
(2 if two_qubit_reduction else 0)
num_time_slices = 50
n_ancillae = 9
state_in = HartreeFock(self.qubit_op.num_qubits, num_orbitals,
num_particles, qubit_mapping, two_qubit_reduction)
iqft = Standard(n_ancillae)
qpe = QPE(self.qubit_op, state_in, iqft, num_time_slices, n_ancillae,
expansion_mode='suzuki',
expansion_order=2, shallow_circuit_concat=True)
backend = qiskit.BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=100, pass_manager=PassManager())
result = qpe.run(quantum_instance)
self.log.debug('eigvals: {}'.format(result['eigvals']))
self.log.debug('top result str label: {}'.format(result['top_measurement_label']))
self.log.debug('top result in decimal: {}'.format(result['top_measurement_decimal']))
self.log.debug('stretch: {}'.format(result['stretch']))
self.log.debug('translation: {}'.format(result['translation']))
self.log.debug('final energy from QPE: {}'.format(result['energy']))
self.log.debug('reference energy: {}'.format(self.reference_energy))
self.log.debug('ref energy (transformed): {}'.format(
(self.reference_energy + result['translation']) * result['stretch']))
self.log.debug('ref binary str label: {}'.format(decimal_to_binary((self.reference_energy + result['translation']) * result['stretch'],
max_num_digits=n_ancillae + 3,
fractional_part_only=True)))
np.testing.assert_approx_equal(
result['energy'], self.reference_energy, significant=2)
if __name__ == '__main__':
unittest.main()
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
import qiskit
print("hello many worlds")
|
https://github.com/Qottmann/Quantum-anomaly-detection
|
Qottmann
|
import time
import datetime
import numpy as np
from matplotlib import pyplot as plt
import qiskit
from qiskit import *
from qiskit.opflow import X,Z,I
from qiskit.opflow.state_fns import StateFn, CircuitStateFn
from qiskit.providers.aer import StatevectorSimulator, AerSimulator
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA
from scipy import sparse
import scipy.sparse.linalg.eigen.arpack as arp
from modules.utils import *
gz = 0
anti = 1
gx = 1e-1
L = 5
num_trash = 2
name = f"qsim_params_VQE_Ising_L{L:.0f}_anti_{anti:.0f}_single-jobs"
filename = 'data/' + name
print(filename)
gx_vals = np.logspace(-2,2,logspace_size)
# more in-depth noise models https://qiskit.org/documentation/tutorials/simulators/2_device_noise_simulation.html
#backend = qiskit.Aer.get_backend('qasm_simulator') # apparently outdated (legacy)
IBMQ.load_account() # this then automatically loads your saved account
provider = IBMQ.get_provider(hub='ibm-q-research')
real_backend = provider.backends(simulator=False, operational=True)[6]
backend = qiskit.providers.aer.AerSimulator.from_backend(real_backend)
backend_sim = backend
ansatz = qiskit.circuit.library.EfficientSU2(L, reps=3)
ansatz = qiskit.transpile(ansatz, backend)
#optimizer = SLSQP(maxiter=1000)
#optimizer = COBYLA(maxiter=1000)
optimizer = SPSA(maxiter=1000)
vqe = VQE(ansatz, optimizer, quantum_instance=backend)
t0 = datetime.datetime.now()
H = QHIsing(L,anti,np.float32(gx),np.float32(gz))
result = vqe.compute_minimum_eigenvalue(H, aux_operators=[QMag(L,anti)]) #ED with Qiskit VQE
print(f"elapsed time {datetime.datetime.now()-t0}")
# ED
ED_state, E, ham = ising_groundstate(L, anti, np.float32(gx), np.float32(gz))
print(f"ED energy: {E} ;; VQE energy: {result.eigenvalue}")
print(f"ED mag: {ED_state.T.conj()@Mag(L,anti)@ED_state} ;; VQE mag: {result.aux_operator_eigenvalues}")
phis = [sort_params(result.optimal_parameters)] # needs to be called phis for later
vqe2 = VQE(qiskit.circuit.library.EfficientSU2(L, reps=3), optimizer, quantum_instance=StatevectorSimulator())
t0 = datetime.datetime.now()
result2 = vqe2.compute_minimum_eigenvalue(H, aux_operators=[QMag(L,anti)]) #ED with Qiskit VQE
print(f"elapsed time {datetime.datetime.now()-t0}")
phis.append(sort_params(result2.optimal_parameters))
state = init_vqe(phis[-1], L=L)
state
state = init_vqe(phis[-1], L=L)
state = qiskit.transpile(state, backend)
meas_outcome = ~StateFn(QMag(L,anti)) @ StateFn(state)
Qmag2 = meas_outcome.eval()
e_outcome = ~StateFn(H) @ StateFn(state)
Qen2 = e_outcome.eval()
print(f"ED energy: {E} ;; VQE energy: {result.eigenvalue} ;; VQE energy from simulated: {result2.eigenvalue} ;; VQE simualted but real execution: {Qen2}")
print(f"ED mag: {ED_state.T.conj()@Mag(L,anti)@ED_state} ;; VQE mag: {result.aux_operator_eigenvalues} ;; VQE magfrom simulated: {result2.aux_operator_eigenvalues} ;; VQE simualted but real execution: {Qmag2}")
##############################################################################
### II - Training ###########################################################
##############################################################################
thetas = np.random.uniform(0, 2*np.pi, 2*L+2) # initial parameters without feature encoding
# thetas = np.random.uniform(0, 2*np.pi, (2*L+2, 2)) # initial parameters with feature encoding
# linear entangler (as in scales linearly with trash qubits)
def get_entangler_map(L, num_trash, i_permut=1):
result = []
nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy
nums_compressed = nums.copy()[:L-num_trash]
nums_trash = nums.copy()[-num_trash:]
#print(nums, nums_compressed, nums_trash)
# combine all trash qubits with themselves
for trash_q in nums_trash[:-1]:
result.append((trash_q+1,trash_q))
# combine each of the trash qubits with every n-th
repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly
for i in range(L-num_trash):
result.append((repeated[i_permut + i], nums_compressed[i]))
return result
def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"):
entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)]
circ = qiskit.circuit.library.TwoLocal(L,
parametrized_gate,
entangling_gate,
entanglement,
reps=num_trash,
insert_barriers=insert_barriers,
skip_final_rotation_layer=True
).assign_parameters(thetas[:-num_trash])
if insert_barriers: circ.barrier()
for i in range(num_trash):
circ.ry(thetas[L-i-1], L-i-1)
#circ.ry(circuit.Parameter(f'θ{i}'), L-i-1)
return circ
def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True):
qreg = QuantumRegister(L, 'q')
creg = ClassicalRegister(num_trash, 'c')
circ = QuantumCircuit(qreg, creg)
circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=True)#.assign_parameters(thetas) # difference to bind?
if measurement:
for i in range(num_trash):
circ.measure(qreg[L-i-1], creg[i])
if init_state is not None:
if vqe:
circ = init_vqe(init_state,L=L) + circ
else:
circ.initialize(init_state, qreg)
return circ
def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=1000, backend=backend):
circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe)
circ = qiskit.transpile(circ, backend)
# Execute the circuit on the qasm simulator.
job_sim = execute(circ, backend_sim, shots=shots, seed_simulator=123, seed_transpiler=234) # fix seed to make it reproducible
return job_sim
phi = phis[0]
job = run_circuit(thetas, L, num_trash, phi)
counts = job.result().get_counts()
counts
def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0):
""" Optimizes circuit """
if vqe:
init_state = phis[p]
else:
J, gx, gz = p
init_state, _ = ising_groundstate(L, J, gx, gz)
if param_encoding: thetas = feature_encoding(thetas, x)
out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots).result().get_counts()
cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0)
return cost/shots
def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0):
""" Optimizes circuit """
cost = 0.
n_samples = len(ising_params)
for i, p in enumerate(ising_params):
if param_encoding:
cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i])
else:
cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding)
return cost/n_samples
def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None):
if thetas is None:
n_params = (2*L+2)*2 if param_encoding else (2*L+2)
thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding
print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)))
counts, values, accepted = [], [], []
def store_intermediate_result(eval_count, parameters, mean, std, ac):
# counts.append(eval_count)
values.append(mean)
accepted.append(ac)
# Initialize optimizer
if pick_optimizer == "cobyla":
optimizer = COBYLA(maxiter=max_iter, tol=0.0001)
if pick_optimizer == "adam" or pick_optimizer == "ADAM":
optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter)
# optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08)
if pick_optimizer == "spsa" or pick_optimizer == None:
optimizer = SPSA(maxiter=max_iter,
#blocking=True,
callback=store_intermediate_result,
#learning_rate=1e-1,
#perturbation=0.4
) # recommended from qiskit (first iteraction takes quite long)
# to reduce time figure out optimal learning rate and perturbation in advance
start_time = time.time()
ret = optimizer.optimize(
num_vars=len(thetas),
objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)),
initial_point=thetas
)
print("Time: {:.5f} sec".format(time.time()-start_time))
print(ret)
return ret[0], values, accepted
def run_inference(thetas, shots=1000, L=5):
cost = np.zeros((len(gx_vals)))
shots = 1000
for i,p in enumerate(list(zip(gxs, gzs))):
cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots)
return cost
# from the original vqe calculated state
thetas, loss, accepted = optimize([0], max_iter=100, L=5) #, pick_optimizer="adam")
plt.plot(loss)
# using the VQE parameters from simulation
thetas, loss, accepted = optimize([1], max_iter=100, L=5) #, pick_optimizer="adam")
plt.plot(loss)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.