repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from functools import reduce
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.quantum_info import Pauli
from qiskit.aqua import Operator
class QAOAVarForm:
"""Global X phases and parameterized problem hamiltonian."""
def __init__(self, cost_operator, p, initial_state=None, mixer_operator=None):
self._cost_operator = cost_operator
self._p = p
self._initial_state = initial_state
self.num_parameters = 2 * p
self.parameter_bounds = [(0, np.pi)] * p + [(0, 2 * np.pi)] * p
self.preferred_init_points = [0] * p * 2
# prepare the mixer operator
v = np.zeros(self._cost_operator.num_qubits)
ws = np.eye(self._cost_operator.num_qubits)
if mixer_operator is None:
self._mixer_operator = reduce(
lambda x, y: x + y,
[
Operator([[1, Pauli(v, ws[i, :])]])
for i in range(self._cost_operator.num_qubits)
]
)
else:
if not type(mixer_operator) == Operator:
raise TypeError('The mixer should be a qiskit.aqua.Operator '
+ 'object, found {} instead'.format(type(mixer_operator)))
self._mixer_operator = mixer_operator
def construct_circuit(self, angles):
if not len(angles) == self.num_parameters:
raise ValueError('Incorrect number of angles: expecting {}, but {} given.'.format(
self.num_parameters, len(angles)
))
circuit = QuantumCircuit()
if self._initial_state:
circuit += self._initial_state.construct_circuit('circuit')
if len(circuit.qregs) == 0:
q = QuantumRegister(self._cost_operator.num_qubits, name='q')
circuit.add_register(q)
elif len(circuit.qregs) == 1:
q = circuit.qregs[0]
else:
raise NotImplementedError
circuit.u2(0, np.pi, q)
for idx in range(self._p):
beta, gamma = angles[idx], angles[idx + self._p]
circuit += self._cost_operator.evolve(
evo_time=gamma, evo_mode='circuit', num_time_slices=1, quantum_registers=q
)
circuit += self._mixer_operator.evolve(
evo_time=beta, evo_mode='circuit', num_time_slices=1, quantum_registers=q
)
return circuit
@property
def setting(self):
ret = "Variational Form: {}\n".format(self.__class__.__name__)
params = ""
for key, value in self.__dict__.items():
if key != "_configuration" and key[0] == "_":
params += "-- {}: {}\n".format(key[1:], value)
ret += "{}".format(params)
return ret
|
https://github.com/CynthiaRios/quantum_orchestra
|
CynthiaRios
|
#pip install music21
#pip install RISE
from qiskit import QuantumCircuit, execute
from qiskit import Aer
from qiskit.visualization import plot_histogram
from qiskit import IBMQ
import qiskit.tools.jupyter
%qiskit_job_watcher
from IPython.display import Audio
import wave
import numpy as np
#start for the project
# import
from music21 import *
#minimum user input will just be for them to fill out the create quantum circuit function inthe backend
n = 1 #insert number of qubits
def CreateQuantumCircuit(n):
cct = QuantumCircuit(n,1)
cct.h(0)
return cct
cct = CreateQuantumCircuit(n)
cct.draw(output="mpl")
def Measurement(cct):
backend = Aer.get_backend('statevector_simulator')
sv = execute(cct, backend).result().get_statevector()
return sv
sv = Measurement(cct)
print(sv)
#from qiskit.visualization import plot_state_city
#plot_state_city(sv)
def MusicalTransformation():
note = 'a';
return note
tune_array = ['c','d'] #collect notes
#for i in range(n+1):
# note = MusicalTransformation()
# tune_array.append(note)
print(tune_array)
def PlayPianoTune(character, song):
if character == 'c':
sound_file = "./Audio/Piano/1-st.wav"
songs.append(sound_file)
if character == 'd':
sound_file = "./Audio/Piano/2-st.wav"
songs.append(sound_file)
if character == 'e':
sound_file = "./Audio/Piano/3-st.wav"
songs.append(sound_file)
if character == 'f':
sound_file = "./Audio/Piano/4-st.wav"
songs.append(sound_file)
if character == 'g':
sound_file = "./Audio/Piano/5-st.wav"
songs.append(sound_file)
def PlayGuitarTune(character, song):
if character == 'c':
sound_file = "./Audio/Guitar/1-ag.wav"
songs.append(sound_file)
if character == 'd':
sound_file = "./Audio/Guitar/2-ag.wav"
songs.append(sound_file)
if character == 'e':
sound_file = "./Audio/Guitar/3-ag.wav"
songs.append(sound_file)
if character == 'f':
sound_file = "./Audio/Guitar/4-ag.wav"
songs.append(sound_file)
if character == 'g':
sound_file = "./Audio/Guitar/5-ag.wav"
songs.append(sound_file)
def PlayBassTune(character, song):
if character == 'c':
sound_file = "./Audio/Bass/1.wav"
songs.append(sound_file)
if character == 'd':
sound_file = "./Audio/Bass/2.wav"
songs.append(sound_file)
if character == 'e':
sound_file = "./Audio/Bass/3.wav"
songs.append(sound_file)
if character == 'f':
sound_file = "./Audio/Bass/4.wav"
songs.append(sound_file)
if character == 'g':
sound_file = "./Audio/Bass/5.wav"
songs.append(sound_file)
def PlayTrumpetTune(character, song):
if character == 'c':
sound_file = "./Audio/Trumpet/1.wav"
songs.append(sound_file)
if character == 'd':
sound_file = "./Audio/Trumpet/2.wav"
songs.append(sound_file)
if character == 'e':
sound_file = "./Audio/Trumpet/3.wav"
songs.append(sound_file)
if character == 'f':
sound_file = "./Audio/Trumpet/4.wav"
songs.append(sound_file)
if character == 'g':
sound_file = "./Audio/Trumpet/5.wav"
songs.append(sound_file)
songs = []
for i in range(n+1):
character = tune_array[i-1]
PlayPianoTune(character, songs)
print(songs)
outfile = "pianosounds.wav"
data= []
for song in songs:
w = wave.open(song, 'rb')
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
output.writeframes(data[0][1])
output.writeframes(data[1][1])
output.close()
songs = []
for i in range(n+1):
character = tune_array[i-1]
PlayGuitarTune(character, songs)
print(songs)
outfile = "guitarsounds.wav"
data= []
for song in songs:
w = wave.open(song, 'rb')
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
output.writeframes(data[0][1])
output.writeframes(data[1][1])
output.close()
songs = []
for i in range(n+1):
character = tune_array[i-1]
PlayTrumpetTune(character, songs)
print(songs)
outfile = "trumpetsounds.wav"
data= []
for song in songs:
w = wave.open(song, 'rb')
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
output.writeframes(data[0][1])
output.writeframes(data[1][1])
output.close()
songs = []
for i in range(n+1):
character = tune_array[i-1]
PlayBassTune(character, songs)
print(songs)
outfile = "basssounds.wav"
data= []
for song in songs:
w = wave.open(song, 'rb')
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
output.writeframes(data[0][1])
output.writeframes(data[1][1])
output.close()
sound_file = "./pianosounds.wav"
Audio(sound_file, autoplay=True)
sound_file = "./guitarsounds.wav"
Audio(sound_file, autoplay=True)
sound_file = "./basssounds.wav"
Audio(sound_file, autoplay=True)
sound_file = "./trumpetsounds.wav"
Audio(sound_file, autoplay=True)
up1 = note.Unpitched()
up1.storedInstrument = instrument.BassDrum()
upUnknownInstrument = note.Unpitched()
up2 = note.Unpitched()
up2.storedInstrument = instrument.Cowbell()
s = stream.Stream()
s.append(up1)
s.append(upUnknownInstrument)
s.append(up2)
s2 = instrument.unbundleInstruments(s)
s3 = instrument.bundleInstruments(s2)
for test in s3:
print(test.storedInstrument)
instrument.ensembleNameBySize(4)
instrument.ensembleNameBySize(1)
instrument.ensembleNameBySize(83)
t1 = instrument.fromString('Clarinet 2 in A')
t1
t1.transposition
t2 = instrument.fromString('Clarinetto 3')
t2
t3 = instrument.fromString('flauto 2')
t3
t4 = instrument.fromString('I <3 music saxofono tenor go beavers')
t4
t5 = instrument.fromString('Bb Clarinet')
t5
t5.transposition
t6 = instrument.fromString('Clarinet in B-flat')
t5.__class__ == t6.__class__
t5.transposition == t6.transposition
t7 = instrument.fromString('B-flat Clarinet.')
t5.__class__ == t7.__class__ and t5.transposition == t7.transposition
t8 = instrument.fromString('Eb Clarinet')
t5.__class__ == t8.__class__
t8.transposition
t9 = instrument.fromString('Klarinette in B.')
t9
t9.transposition
instrument.instrumentFromMidiProgram(0)
instrument.instrumentFromMidiProgram(21)
p1 = converter.parse("tinynotation: 4/4 c4 d e f g a b c' c1")
p2 = converter.parse("tinynotation: 4/4 C#4 D# E# F# G# A# B# c# C#1")
p1.getElementsByClass('Measure')[0].insert(0.0, instrument.Piccolo())
p1.getElementsByClass('Measure')[0].insert(2.0, instrument.AltoSaxophone())
p1.getElementsByClass('Measure')[1].insert(3.0, instrument.Piccolo())
p2.getElementsByClass('Measure')[0].insert(0.0, instrument.Trombone())
p2.getElementsByClass('Measure')[0].insert(3.0, instrument.Piccolo()) # not likely...
p2.getElementsByClass('Measure')[1].insert(1.0, instrument.Trombone())
s = stream.Score()
s.insert(0, p1)
s.insert(0, p2)
s.show('musicxml') #this show on musicscore
s2 = instrument.partitionByInstrument(s)
len(s2.parts)
for p in s2.parts:
unused = p.makeRests(fillGaps=True, inPlace=True)
for p in s2.parts:
p.makeMeasures(inPlace=True)
p.makeTies(inPlace=True)
s2.show('musicxml')
up1 = note.Unpitched()
up1.storedInstrument = instrument.BassDrum()
up2 = note.Unpitched()
up2.storedInstrument = instrument.Cowbell()
s = stream.Stream()
s.append(up1)
s.append(up2)
s2 = instrument.unbundleInstruments(s)
s2.show('musicxml')
us = environment.UserSettings()
#C:\Program Files\MuseScore 3\bin\MuseScore3.exe
us['musicxmlPath'] = "C:\\Program Files\\MuseScore 3\\bin\\MuseScore3.exe"
us['musescoreDirectPNGPath'] = "C:\\Program Files\\MuseScore 3\\bin\\MuseScore3.exe"
print(us)
instrument1 = 60
instrument2 = 65
instrument3 = 70
instrument4 = 75
instrument1 = converter.parse("tinynotation: 4/4 c4 d e f g a b c' c1")
instrument2 = converter.parse("tinynotation: 4/4 C#4 D# E# F# G# A# B# c# C#1")
instrument3 = converter.parse("tinynotation: 4/4 e f g a b c d e f")
#instrument4 = converter.parse("tinynotation: 4/4 g a b c d e f g a")
note1 = note.Note("C4")
note2 = note.Note("F#4")
note3 = note.Note("F#4")
note4 = note.Note("F#4")
note5 = note.Note("F#4")
note6 = note.Note("F#4")
note7 = note.Note("F#4")
note8 = note.Note("F#4")
note9 = note.Note("F#4")
instrument4 = [note1, note2, note3, note4, note5, note6, note7, note8, note9]
print(instrument4)
stream2 = stream.Stream()
stream2.append(instrument4)
stream2.getElementsByClass('Measure')[0].insert(0.0, instrument.Tuba())
#This creates a stream of a single part
#Add an instrument to the part
instrument1.getElementsByClass('Measure')[0].insert(0.0, instrument.Trumpet())
instrument2.getElementsByClass('Measure')[0].insert(0.0, instrument.EnglishHorn())
instrument3.getElementsByClass('Measure')[0].insert(0.0, instrument.Trombone())
instrument4.getElementsByClass('Measure')[0].insert(0.0, instrument.Tuba())
s = stream.Score()
s.insert(0, instrument1)
s.insert(0, instrument2)
s.insert(0, instrument3)
s.insert(0, instrument4)
s.show()
s.show('midi')
s.show('musicxml') #this show on musicscore
stream1 = stream.Stream()
stream1.addGroupForElements('flute')
stream1.append(midiChordType1)
stream1.append(midiChordType2)
stream1.append(midiChordType3)
stream1.append(midiChordType4)
stream1.show('midi')
stream1.show('musicxml') #this show on musicscore
#c = converter.parse('musicxml')
stream1.show()
midiChordType1 = chord.Chord([instrument1, instrument2, instrument3, instrument4])
midiChordType2 = chord.Chord([55, 60, 65, 70])
midiChordType2.getElementsByClass('Measure')[0].insert(2.0, instrument.Bass())
midiChordType3 = chord.Chord([50, 55, 60, 70])
midiChordType3.getElementsByClass('Measure')[1].insert(3.0, instrument.Guitar())
midiChordType4 = chord.Chord([65, 70, 75, 80])
midiChordType4.getElementsByClass('Measure')[1].insert(3.0, instrument.Trombone())
note1 = note.Note("C4")
note2 = note.Note("F#4")
note3 = note.Note("B-2")
stream1 = stream.Stream()
stream1.append(note1)
stream1.append(note2)
stream1.append(note3)
stream1.show('midi')
note1 = midiChordType
midiChordType1 = chord.Chord([60, 65, 70, 75])
midiChordType2 = chord.Chord([55, 60, 65, 70])
midiChordType3 = chord.Chord([50, 55, 60, 70])
midiChordType4 = chord.Chord([65, 70, 75, 80])
stream1 = stream.Stream()
stream1.append(midiChordType1)
stream1.append(midiChordType2)
stream1.append(midiChordType3)
stream1.append(midiChordType4)
stream1.show('midi')
p1 = converter.parse("tinynotation: 4/4 c4 d e f g a b c' c1")
p2 = converter.parse("tinynotation: 4/4 C#4 D# E# F# G# A# B# c# C#1")
p1.show('midi')
p2.show('midi')
p1.getElementsByClass('Measure')[0].insert(0.0, instrument.Piccolo())
p1.getElementsByClass('Measure')[0].insert(2.0, instrument.AltoSaxophone())
p1.getElementsByClass('Measure')[1].insert(3.0, instrument.Piccolo())
p2.getElementsByClass('Measure')[0].insert(0.0, instrument.Trombone())
p2.getElementsByClass('Measure')[0].insert(3.0, instrument.Piccolo()) # not likely...
p2.getElementsByClass('Measure')[1].insert(1.0, instrument.Trombone())
s.show()
s = corpus.parse('bach/bwv65.2.xml')
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Check CNOT direction pass"""
import unittest
import ddt
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import CXGate, CZGate, ECRGate
from qiskit.transpiler.passes import CheckGateDirection
from qiskit.transpiler import CouplingMap, Target
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestCheckGateDirection(QiskitTestCase):
"""Tests the CheckGateDirection pass"""
def test_trivial_map(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_true_direction(self):
"""Mapped is easy to check
qr0:---.--[H]--.--
| |
qr1:--(+)------|--
|
qr2:----------(+)-
CouplingMap map: [1]<-[0]->[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_true_direction_in_same_layer(self):
"""Two CXs distance_qubits 1 to each other, in the same layer
qr0:--(+)--
|
qr1:---.---
qr2:--(+)--
|
qr3:---.---
CouplingMap map: [0]->[1]->[2]->[3]
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_wrongly_mapped(self):
"""Needs [0]-[1] in a [0]--[2]--[1]
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]->[2]->[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
coupling = CouplingMap([[0, 2], [2, 1]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_true_direction_undirected(self):
"""Mapped but with wrong direction
qr0:--(+)-[H]--.--
| |
qr1:---.-------|--
|
qr2:----------(+)-
CouplingMap map: [1]<-[0]->[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[2], qr[0])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_false_direction_in_same_layer_undirected(self):
"""Two CXs in the same layer, but one is wrongly directed
qr0:--(+)--
|
qr1:---.---
qr2:---.---
|
qr3:--(+)--
CouplingMap map: [0]->[1]->[2]->[3]
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[3], qr[2])
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_2q_barrier(self):
"""A 2q barrier should be ignored
qr0:--|--
|
qr1:--|--
CouplingMap map: None
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0], qr[1])
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_ecr_gate(self):
"""A directional ECR gate is detected.
ββββββββ
q_0: β€1 β
β ECR β
q_1: β€0 β
ββββββββ
CouplingMap map: [0, 1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.ecr(qr[1], qr[0])
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
@ddt.data(CXGate(), CZGate(), ECRGate())
def test_target_static(self, gate):
"""Test that static 2q gates are detected correctly both if available and not available."""
circuit = QuantumCircuit(2)
circuit.append(gate, [0, 1], [])
matching = Target(num_qubits=2)
matching.add_instruction(gate, {(0, 1): None})
pass_ = CheckGateDirection(None, target=matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
swapped = Target(num_qubits=2)
swapped.add_instruction(gate, {(1, 0): None})
pass_ = CheckGateDirection(None, target=swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_coupling_map_control_flow(self):
"""Test recursing into control-flow operations with a coupling map."""
matching = CouplingMap.from_line(5, bidirectional=True)
swapped = CouplingMap.from_line(5, bidirectional=False)
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
circuit.cx(1, 0)
pass_ = CheckGateDirection(matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cz(3, 2)
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.ecr(4, 3)
pass_ = CheckGateDirection(matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_target_control_flow(self):
"""Test recursing into control-flow operations with a coupling map."""
swapped = Target(num_qubits=5)
for gate in (CXGate(), CZGate(), ECRGate()):
swapped.add_instruction(gate, {qargs: None for qargs in zip(range(4), range(1, 5))})
matching = Target(num_qubits=5)
for gate in (CXGate(), CZGate(), ECRGate()):
matching.add_instruction(gate, {None: None})
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
circuit.cx(1, 0)
pass_ = CheckGateDirection(None, target=matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(None, target=swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cz(3, 2)
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.ecr(4, 3)
pass_ = CheckGateDirection(None, target=matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(None, target=swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/tula3and/random-question-generator
|
tula3and
|
from qiskit import *
# from qiskit import IBMQ
# IBMQ.save_account('<API Token>')
# provider = IBMQ.load_account()
# backend = IBMQ.get_provider(hub='ibm-q-kaist', group='internal', project='default').backends.ibmq_manhattan
backend = Aer.get_backend('qasm_simulator')
q = QuantumRegister(48)
c = ClassicalRegister(48)
circuit = QuantumCircuit(q,c)
circuit.h(q)
for i in range(47):
circuit.cx(q[i], q[47])
circuit.measure(q,c)
import string
table = string.ascii_uppercase + string.ascii_lowercase + string.digits
def hash8():
hash_result = ''
result = execute(circuit, backend, shots=1).result()
count = result.get_counts(circuit)
bits = max(count, key=lambda i: count[i])
start = 0
end = 6
while (end <= 48):
rand = int(bits[start:end], 2) % len(table)
start += 6
end += 6
hash_result += table[rand]
return hash_result
|
https://github.com/qiskit-community/qiskit-dell-runtime
|
qiskit-community
|
from dell_runtime import DellRuntimeProvider
from qiskit import QuantumCircuit
import logging
import requests
import time
RUNTIME_PROGRAM = """
# This code is part of qiskit-runtime.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
from qiskit.compiler import transpile, schedule
import time
def main(backend, user_messenger, **kwargs):
iterations = kwargs.pop("iterations", 5)
for it in range(iterations):
user_messenger.publish({"iteration": it })
time.sleep(5)
user_messenger.publish("All done!", final=True)
"""
RUNTIME_PROGRAM_METADATA = {
"max_execution_time": 600,
"description": "Qiskit test program"
}
PROGRAM_PREFIX = 'qiskit-test'
REMOTE_RUNTIME = 'http://localhost:8080'
def main():
print("Starting...")
logging.basicConfig(level=logging.DEBUG)
provider = DellRuntimeProvider()
# provider.remote(REMOTE_RUNTIME)
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
print(f"PROGRAM ID: {program_id}")
program_inputs = {
'iterations': 3,
}
job = provider.runtime.run(program_id, options=None, inputs=program_inputs)
time.sleep(2)
print(job.get_unread_messages())
results = job.result(timeout=25)
print(results)
if __name__ == "__main__":
main()
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import re
import unittest
from typing import List, Optional
import numpy as np
import qiskit
import qiskit.result
from ddt import ddt, data as test_data, unpack
import dsp_data
import dc_qiskit_stochastics.benchmark as benchmark
from dc_qiskit_stochastics.dsp_common import apply_initial, x_measurement, y_measurement
from dc_qiskit_stochastics.dsp_independent import index_independent_prep
logging.basicConfig(format=logging.BASIC_FORMAT, level='DEBUG')
LOG = logging.getLogger(__name__)
@ddt
class QiskitDspCircuitTests(unittest.TestCase):
@staticmethod
def report_progress(job_id: str, job_status: qiskit.providers.JobStatus, job: qiskit.providers.JobV1):
LOG.info(f'Processing {job_id} with status {job_status}...')
def assert_statevector(self, probabilities: np.ndarray, realizations: np.ndarray,
scaling: float, initial_value: float,job: qiskit.providers.JobV1,
measurement: Optional[str] = None):
LOG.info(f'Asserting {job.job_id()} with status {job.status()}...')
if job.status() == qiskit.providers.JobStatus.DONE:
result: qiskit.result.Result = job.result()
vector = result.get_statevector()
# Gather facts from the probabilities about the number k (realizations)
# and the number of qubits to encode a this number
k = len(probabilities[0, :])
index_register_size = int(np.ceil(np.log2(k)))
# The bits show the string length of bits to encode the Hilbert space of the state vector (dimension of it)
bits = int(np.log2(len(vector)))
# First assertion: the bits to encode the dimension of the state vector must be
# divisible by the index register size if the data bit is removed
self.assertTrue((bits - 1) % index_register_size == 0, msg='Bit length of state vector must be 1 data bit + l level index.')
# If the last assertion passed, the divisor os the number of levels, so it must be equal
levels = (bits - 1) / index_register_size
self.assertTrue(levels == len(probabilities), msg='Bit length of state vector must show the correct number of levels.')
# Save the resulting expected vector to compare later. We do this because we want to
# get the full information first, before we fail the test
expected_vector: List[complex] = []
phase_diff_list: List[float] = []
for index, value in enumerate(vector):
basis_state_bits = "{0:b}".format(index).zfill(bits) # [::-1]
data_state = int(basis_state_bits[-1], 2)
values: List[str] = re.findall(''.join(index_register_size*['.']), basis_state_bits[:-1])
values: List[int] = [int(v, 2) for v in values]
LOG.debug(f'Found the extraction indices to be {values}.')
all_probs = probabilities[np.arange(len(probabilities)), values]
LOG.debug(f'Found the extraction probabilities to be {all_probs}.')
all_reals = realizations[np.arange(len(realizations)), values]
LOG.debug(f'Found the extraction realizations to be {all_reals}.')
p = 1 / np.sqrt(2) * np.prod(np.sqrt(all_probs))
x = np.sum(all_reals)
if measurement is None:
expected_value: complex = p * np.exp(
1.0j * scaling * (initial_value + x) if data_state == 1 else 0.0
)
elif measurement == 'sigma_x':
expected_value: complex = p * np.exp(
(-1.0)**(1 - data_state) * 1.0j * scaling * (initial_value + x)
)
elif measurement == 'sigma_y':
expected_value: complex = p * np.exp(
(-1.0)**(1 - data_state) * 1.0j * (np.pi/2 + scaling * (initial_value + x))
)
else:
self.fail("If a measurement is given, it must either 'sigma_x' or 'sigma_y'.")
expected_vector.append(expected_value)
# As quantum mechanics is neglecting a global phase, we need to find the phase difference.
# If later we find that all phase differences are the same, we have a global phase
# and need to adjust for it.
phase_diff = np.angle(expected_value) - np.angle(value)
phase_diff_list.append(phase_diff if phase_diff > 10e-6 else phase_diff + 2 * np.pi)
LOG.info(f'Basis: {basis_state_bits} (data/indices: {data_state}/{values}), '
f'Expected: {np.abs(expected_value):.4f} * e^{np.angle(expected_value):.4f}, '
f'Actual: {np.abs(value):.4f} * e^{np.angle(value):.4f}')
# First we check by pairwise comparison, if we have phase differences all within a small
# delta, if so, we have found a global phase difference.
LOG.info(f"Phase differences: {phase_diff_list}")
[self.assertAlmostEqual(x, y, delta=10e-3, msg='Phase Differences have to negligible.')
for i, x in enumerate(phase_diff_list)
for j, y in enumerate(phase_diff_list) if i != j]
# Checking the equality of expect vs. actual values with the global phase taken into account.
LOG.info(f"Checking of state vector is as expected (modulo phase shift of): {phase_diff_list[0]}")
for expected, actual in zip(expected_vector, vector):
actual_phase_shifted = actual * np.exp(1.0j * phase_diff_list[0])
LOG.debug(f'Expected: {np.abs(expected):.4f} * e^{np.angle(expected):.4f}, '
f'Actual: {np.abs(actual_phase_shifted):.4f} * e^{np.angle(actual_phase_shifted):.4f}')
self.assertAlmostEqual(expected.real, actual_phase_shifted.real, delta=10e-3)
self.assertAlmostEqual(expected.imag, actual_phase_shifted.imag, delta=10e-3)
return expected_vector
else:
self.fail("The job is not done. Cannot assert correctness.")
@test_data(*dsp_data.testing_data)
@unpack
def test_create_circuit(self, scaling: float, initial_value: float, probabilities: np.ndarray,
realizations: np.ndarray, apply_func):
LOG.info(f"Data: scaling={scaling}, initial value={initial_value}, "
f"probabilities={list(probabilities)}, realizations={list(realizations)},"
f"applied function={apply_func.__name__}.")
qc = qiskit.QuantumCircuit(name='dsp_simulation')
LOG.info(f"Initializing with {initial_value} and scaling {scaling}.")
init_qc = apply_initial(initial_value, scaling)
qc.extend(init_qc)
for level, (p, r) in enumerate(zip(probabilities, realizations)):
LOG.info(f"Adding level {level}: {p} with {r} and scaling {scaling}.")
qc_index = index_independent_prep(level, p)
qc_level_l = apply_func(level, r, scaling)
qc.extend(qc_index)
qc.extend(qc_level_l)
LOG.info(f"Circuit:\n{qc.draw(output='text', fold=-1)}")
qc_compiled = qiskit.transpile(qc, optimization_level=3,basis_gates=['id', 'u1', 'u2', 'u3', 'cx'])
LOG.info(f"Circuit:\n{qc_compiled.draw(output='text', fold=-1)}")
backend: qiskit.providers.aer.StatevectorSimulator = qiskit.Aer.get_backend('statevector_simulator')
job: qiskit.providers.aer.AerJob = qiskit.execute(qc_compiled, backend)
job.wait_for_final_state(callback=QiskitDspCircuitTests.report_progress, wait=1)
self.assert_statevector(probabilities, realizations, scaling, initial_value, job)
@test_data(*dsp_data.testing_data)
@unpack
def test_calculate_x_measurement_cos(self, scaling: float, initial_value: float, probabilities: np.ndarray,
realizations: np.ndarray, apply_func):
LOG.info(f"Data: scaling={scaling}, initial value={initial_value}, "
f"probabilities={list(probabilities)}, realizations={list(realizations)},"
f"applied function={apply_func.__name__}.")
qc = qiskit.QuantumCircuit(name='dsp_simulation')
LOG.info(f"Initializing with {initial_value} and scaling {scaling}.")
init_qc = apply_initial(initial_value, scaling)
qc.extend(init_qc)
for level, (p, r) in enumerate(zip(probabilities, realizations)):
LOG.info(f"Adding level {level}: {p} with {r} and scaling {scaling}.")
qc_index = index_independent_prep(level, p)
qc_level_l = apply_func(level, r, scaling)
qc.extend(qc_index)
qc.extend(qc_level_l)
qc.extend(x_measurement())
LOG.info(f"Circuit:\n{qc.draw(output='text', fold=-1)}")
qc_compiled = qiskit.transpile(qc, optimization_level=3,basis_gates=['id', 'u1', 'u2', 'u3', 'cx'])
LOG.info(f"Circuit:\n{qc_compiled.draw(output='text', fold=-1)}")
backend: qiskit.providers.aer.StatevectorSimulator = qiskit.Aer.get_backend('qasm_simulator')
job: qiskit.providers.aer.AerJob = qiskit.execute(qc_compiled, backend, shots=2**16)
job.wait_for_final_state(callback=QiskitDspCircuitTests.report_progress, wait=1)
expected_cos = benchmark.brute_force_rw_ind(probabilities, realizations, initial_value, scaling, np.cos)
result: qiskit.result.Result = job.result()
counts = result.get_counts()
p: float = (counts.get('0', 0) - counts.get('1', 0)) / (counts.get('0', 0) + counts.get('1', 0))
LOG.info(f"Assertion: expected={expected_cos}, actual={p}, diff={np.abs(expected_cos - p)}")
self.assertAlmostEqual(expected_cos, p, delta=10e-3)
@test_data(*dsp_data.testing_data)
@unpack
def test_calculate_y_measurement_sin(self, scaling: float, initial_value: float, probabilities: np.ndarray,
realizations: np.ndarray, apply_func):
LOG.info(f"Data: scaling={scaling}, initial value={initial_value}, "
f"probabilities={list(probabilities)}, realizations={list(realizations)},"
f"applied function={apply_func.__name__}.")
qc = qiskit.QuantumCircuit(name='dsp_simulation')
LOG.info(f"Initializing with {initial_value} and scaling {scaling}.")
init_qc = apply_initial(initial_value, scaling)
qc.extend(init_qc)
for level, (p, r) in enumerate(zip(probabilities, realizations)):
LOG.info(f"Adding level {level}: {p} with {r} and scaling {scaling}.")
qc_index = index_independent_prep(level, p)
qc_level_l = apply_func(level, r, scaling)
qc.extend(qc_index)
qc.extend(qc_level_l)
qc.extend(y_measurement())
LOG.info(f"Circuit:\n{qc.draw(output='text', fold=-1)}")
qc_compiled = qiskit.transpile(qc, optimization_level=3,basis_gates=['id', 'u1', 'u2', 'u3', 'cx'])
LOG.info(f"Circuit:\n{qc_compiled.draw(output='text', fold=-1)}")
backend: qiskit.providers.aer.StatevectorSimulator = qiskit.Aer.get_backend('qasm_simulator')
job: qiskit.providers.aer.AerJob = qiskit.execute(qc_compiled, backend, shots=2**16)
job.wait_for_final_state(callback=QiskitDspCircuitTests.report_progress, wait=1)
expected_cos = benchmark.brute_force_rw_ind(probabilities, realizations, initial_value, scaling, np.sin)
result: qiskit.result.Result = job.result()
counts = result.get_counts()
p: float = (counts.get('0', 0) - counts.get('1', 0)) / (counts.get('0', 0) + counts.get('1', 0))
LOG.info(f"Assertion: expected={expected_cos}, actual={p}, diff={np.abs(expected_cos - p)}")
self.assertAlmostEqual(expected_cos, p, delta=10e-3)
|
https://github.com/bartubisgin/QSVTinQiskit-2021-Europe-Hackathon-Winning-Project-
|
bartubisgin
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
for _ in range(100):
depths.append(
transpile(
ghz,
backend,
layout_method='trivial' # Fixed layout mapped in circuit order
).depth()
)
plt.figure(figsize=(8, 6))
plt.hist(depths, align='left', color='#AC557C')
plt.xlabel('Depth', fontsize=14)
plt.ylabel('Counts', fontsize=14);
|
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
|
mnp-club
|
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
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
def qft_rotations(circuit, n):
"""Performs qft on the first n qubits in circuit (without swaps)"""
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cu1(np.pi/2**(n-qubit), qubit, n)
# At the end of our function, we call the same function again on
# the next qubits (we reduced n by one earlier in the function)
qft_rotations(circuit, n)
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
"""QFT on the first n qubits in circuit"""
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
# Let's see how it looks:
qc = QuantumCircuit(4,4)
qft(qc,4)
qc.draw(output = 'mpl')
def inverse_qft(circuit, n):
"""Does the inverse QFT on the first n qubits in circuit"""
# First we create a QFT circuit of the correct size:
qft_circ = qft(QuantumCircuit(n), n)
# Then we take the inverse of this circuit
invqft_circ = qft_circ.inverse()
# And add it to the first n qubits in our existing circuit
circuit.append(invqft_circ, circuit.qubits[:n])
return circuit.decompose() # .decompose() allows us to see the individual gates
qc = inverse_qft(qc,4)
qc.measure(range(4),range(4))
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 10000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc)
print(counts)
plot_histogram(counts)
# we should get the intial state '0000'
qc1 = QuantumCircuit(3,3)
qc1.x(0)
qc1.x(1)
qc1.x(2) # try for different initial values
for i in range(4):# choose the number of times you want to do qft)
qft(qc1,3)
qc1.measure(0,0)
qc1.measure(1,1)
qc1.measure(2,2)
def run_circuit(qc1):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc1, backend, shots = 10000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc1)
print(counts)
plot_histogram(counts)
qc2 = QuantumCircuit(2)
for i in range(2):
qft(qc2, 2)
matrix = qi.Operator(qc2).data
print(matrix)
def Modulo_increment(qc):
qft(qc,4)
for i in range(4):
qc.u1(np.pi/(2**(3-i)), i)
qft(qc, 4)
return qc
# checking for the case of '1000'
qc2 = QuantumCircuit(4,4)
qc2.x(3)
qc2 = Modulo_increment(qc2)
qc2.measure(range(4),range(4))
# qc2.draw('mpl')
def run_circuit(qc2):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc2, backend, shots = 10000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc2)
print(counts)
plot_histogram(counts)
# checking for the case of '1101'
qc3 = QuantumCircuit(4,4)
qc3.x(3)
qc3.x(2)
qc3.x(0)
qc3 = Modulo_increment(qc2)
qc3.measure(range(4),range(4))
def run_circuit(qc3):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc3, backend, shots = 10000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc3)
print(counts)
plot_histogram(counts)
# checking for the case of '1111'
qc4 = QuantumCircuit(4,4)
qc4.x(range(4))
qc4 = Modulo_increment(qc4)
qc4.measure(range(4),range(4))
def run_circuit(qc4):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc4, backend, shots = 10000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc4)
print(counts)
plot_histogram(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.
"""Test the Check CNOT direction pass"""
import unittest
import ddt
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import CXGate, CZGate, ECRGate
from qiskit.transpiler.passes import CheckGateDirection
from qiskit.transpiler import CouplingMap, Target
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestCheckGateDirection(QiskitTestCase):
"""Tests the CheckGateDirection pass"""
def test_trivial_map(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_true_direction(self):
"""Mapped is easy to check
qr0:---.--[H]--.--
| |
qr1:--(+)------|--
|
qr2:----------(+)-
CouplingMap map: [1]<-[0]->[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_true_direction_in_same_layer(self):
"""Two CXs distance_qubits 1 to each other, in the same layer
qr0:--(+)--
|
qr1:---.---
qr2:--(+)--
|
qr3:---.---
CouplingMap map: [0]->[1]->[2]->[3]
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_wrongly_mapped(self):
"""Needs [0]-[1] in a [0]--[2]--[1]
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]->[2]->[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
coupling = CouplingMap([[0, 2], [2, 1]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_true_direction_undirected(self):
"""Mapped but with wrong direction
qr0:--(+)-[H]--.--
| |
qr1:---.-------|--
|
qr2:----------(+)-
CouplingMap map: [1]<-[0]->[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[2], qr[0])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_false_direction_in_same_layer_undirected(self):
"""Two CXs in the same layer, but one is wrongly directed
qr0:--(+)--
|
qr1:---.---
qr2:---.---
|
qr3:--(+)--
CouplingMap map: [0]->[1]->[2]->[3]
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[3], qr[2])
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_2q_barrier(self):
"""A 2q barrier should be ignored
qr0:--|--
|
qr1:--|--
CouplingMap map: None
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0], qr[1])
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_ecr_gate(self):
"""A directional ECR gate is detected.
ββββββββ
q_0: β€1 β
β ECR β
q_1: β€0 β
ββββββββ
CouplingMap map: [0, 1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.ecr(qr[1], qr[0])
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
@ddt.data(CXGate(), CZGate(), ECRGate())
def test_target_static(self, gate):
"""Test that static 2q gates are detected correctly both if available and not available."""
circuit = QuantumCircuit(2)
circuit.append(gate, [0, 1], [])
matching = Target(num_qubits=2)
matching.add_instruction(gate, {(0, 1): None})
pass_ = CheckGateDirection(None, target=matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
swapped = Target(num_qubits=2)
swapped.add_instruction(gate, {(1, 0): None})
pass_ = CheckGateDirection(None, target=swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_coupling_map_control_flow(self):
"""Test recursing into control-flow operations with a coupling map."""
matching = CouplingMap.from_line(5, bidirectional=True)
swapped = CouplingMap.from_line(5, bidirectional=False)
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
circuit.cx(1, 0)
pass_ = CheckGateDirection(matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cz(3, 2)
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.ecr(4, 3)
pass_ = CheckGateDirection(matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_target_control_flow(self):
"""Test recursing into control-flow operations with a coupling map."""
swapped = Target(num_qubits=5)
for gate in (CXGate(), CZGate(), ECRGate()):
swapped.add_instruction(gate, {qargs: None for qargs in zip(range(4), range(1, 5))})
matching = Target(num_qubits=5)
for gate in (CXGate(), CZGate(), ECRGate()):
matching.add_instruction(gate, {None: None})
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
circuit.cx(1, 0)
pass_ = CheckGateDirection(None, target=matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(None, target=swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cz(3, 2)
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.ecr(4, 3)
pass_ = CheckGateDirection(None, target=matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(None, target=swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/Qottmann/Quantum-anomaly-detection
|
Qottmann
|
from matplotlib import pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec
path = "data/BH_phase-diagrams-and-loss/data_rike/"
x = np.load(path + "x.npy")
y = np.load(path + "y.npy")
es = np.load(path + "es.npy")
dd = np.load(path + "dd.npy")
cost0 = np.load(path + "cost_bh_L12_trash2_d48_v5_seed17.npy")
cost1 = np.load(path + "cost_bh_L12_trash4_d25_v47_seed16.npy")
cost2 = np.load(path + "cost_bh_L12_trash6_d10_v10_seed22.npy")
vs = np.logspace(-2,2,50)
ds = np.linspace(-0.95,0.95,50)
cbar = np.zeros((2,2), dtype="object")
fig,axs = plt.subplots(ncols=2, nrows=2,figsize=(10,6),sharex=True, sharey=True)
cmap = plt.get_cmap("plasma") #'viridis'
cbar_labelsize = 14
cbar = np.zeros((2,2), dtype="object")
ax = axs[0,0]
im = ax.pcolormesh(x,y,dd.T, cmap=cmap, shading="auto",rasterized=True) #,rasterized=True necessary for pdf export
ax.set_xscale("log")
cbar[0,0] = fig.colorbar(im, ax=ax)
cbar[0,0].ax.tick_params(labelsize=cbar_labelsize)
ax = axs[0,1]
im = ax.pcolormesh(x,y,es.T, cmap=cmap, shading="auto",rasterized=True)
ax.set_xscale("log")
cbar[0,1] = fig.colorbar(im, ax=ax)
cbar[0,1].ax.tick_params(labelsize=cbar_labelsize)
ax = axs[1,0]
im = ax.pcolormesh(x,y,cost2.T,vmin=0, cmap=cmap, shading="auto",rasterized=True)
ax.set_xscale("log")
cbar[1,0] = fig.colorbar(im, ax=ax)
cbar[1,0].ax.tick_params(labelsize=cbar_labelsize)
ax.plot(vs[10],ds[10],"x", color="magenta")
ax = axs[1,1]
im = ax.pcolormesh(x,y,cost1.T,vmin=0, cmap=cmap, shading="auto",rasterized=True)
ax.set_xscale("log")
cbar[1,1] = fig.colorbar(im, ax=ax)
cbar[1,1].ax.tick_params(labelsize=cbar_labelsize)
ax.plot(vs[47],ds[25],"x", color="magenta")
for ax in axs.flatten():
ax.tick_params(labelsize=14)
axs[1,0].set_xlabel(r"$V$",fontsize=18)
axs[1,1].set_xlabel(r"$V$",fontsize=18)
axs[0,0].set_ylabel(r"$\delta t$",fontsize=18)
axs[1,0].set_ylabel(r"$\delta t$",fontsize=18)
plt.tight_layout()
# has to happen after tight_layout()
axs[0,0].text(-0.25,0.9,"a", fontweight="bold", size=18, transform = axs[0,0].transAxes)
axs[1,0].text(-0.25,0.9,"c", fontweight="bold", size=18, transform = axs[1,0].transAxes)
axs[0,1].text(-0.1,0.9,"b", fontweight="bold", size=18, transform = axs[0,1].transAxes)
axs[1,1].text(-0.1,0.9,"d", fontweight="bold", size=18, transform = axs[1,1].transAxes)
cbar[0,0].ax.set_title("$\\langle n_i n_j \\rangle$")
axs[0,0].set_title("density-density correlations", fontsize=14)
cbar[0,1].ax.set_title("$\Delta \\lambda$")
axs[0,1].set_title("Entanglement spectrum degeneracy", fontsize=14)
cbar[1,0].ax.set_title("cost")
cbar[1,1].ax.set_title("cost")
plt.savefig("plots/BH_replot.pdf", bbox_inches='tight')
fig,aa = plt.subplots(figsize=(15,5.7),sharey="row",dpi=220)
ax00 = plt.subplot2grid(shape=(2,5), loc=(0, 0), rowspan=1, colspan=1, xticklabels=[])
ax10 = plt.subplot2grid(shape=(2,5), loc=(1, 0), rowspan=1, colspan=1, xticklabels=[])
ax01 = plt.subplot2grid(shape=(2,5), loc=(0, 1), rowspan=2, colspan=2, xticklabels=[], yticklabels=[])
ax02 = plt.subplot2grid(shape=(2,5), loc=(0, 3), rowspan=2, colspan=2, xticklabels=[], yticklabels=[])
cmap = plt.get_cmap("plasma") #'viridis'
cbar_labelsize = 10
cbar = np.zeros((2,2), dtype="object")
axs=np.array([[ax00,ax10],[ax01,ax02]])
print(axs[0,0])
ax = axs[0,0]
im = ax.pcolormesh(x,y,dd.T, cmap=cmap, shading="auto",rasterized=True) #,rasterized=True necessary for pdf export
#im.ax.tick_params(labelsize=cbar_labelsize)
ax.set_xscale("log")
cbar[0,0] = fig.colorbar(im, ax=ax)
cbar[0,0].ax.tick_params(labelsize=cbar_labelsize)
ax = axs[0,1]
im = ax.pcolormesh(x,y,es.T, cmap=cmap, shading="auto",rasterized=True)
ax.set_xscale("log")
cbar[0,1] = fig.colorbar(im, ax=ax)
cbar[0,1].ax.tick_params(labelsize=cbar_labelsize)
ax = axs[1,0]
im = ax.pcolormesh(x,y,cost2.T,vmin=0, cmap=cmap, shading="auto",rasterized=True)
ax.set_xscale("log")
cbar[1,0] = fig.colorbar(im, ax=ax)
cbar[1,0].ax.tick_params(labelsize=cbar_labelsize)
ax.plot(vs[10],ds[10],"X", color="magenta",markersize=15)
ax = axs[1,1]
im = ax.pcolormesh(x,y,cost1.T,vmin=0, cmap=cmap, shading="auto",rasterized=True)
ax.set_xscale("log")
cbar[1,1] = fig.colorbar(im, ax=ax)
cbar[1,1].ax.tick_params(labelsize=cbar_labelsize)
ax.plot(vs[47],ds[25],"X", color="magenta",markersize=15)
for ax in axs.flatten():
ax.tick_params(labelsize=10)
axs[1,0].set_xlabel(r"$V$",fontsize=12)
axs[0,1].set_ylabel(r"$\delta J$",fontsize=12)
axs[1,1].set_xlabel(r"$V$",fontsize=12)
axs[0,0].set_ylabel(r"$\delta J$",fontsize=12)
axs[1,0].set_ylabel(r"$\delta J$",fontsize=12)
#plt.tight_layout()
# has to happen after tight_layout()
axs[0,0].text(0.01,0.89,"a", fontweight="bold", size=18, transform = axs[0,0].transAxes, color="white")
axs[1,0].text(0.02,0.95,"c", fontweight="bold", size=18, transform = axs[1,0].transAxes)
axs[0,1].text(0.01,0.88,"b", fontweight="bold", size=18, transform = axs[0,1].transAxes)
axs[1,1].text(0.02,0.94,"d", fontweight="bold", size=18, transform = axs[1,1].transAxes)
axs[1,0].text(0.23,0.05,"MI", fontweight="bold", size=18, transform = axs[1,0].transAxes, color="white")
axs[1,0].text(0.23,0.8,"TMI", fontweight="bold", size=18, transform = axs[1,0].transAxes)
axs[1,0].text(0.77,0.5,"CDW", fontweight="bold", size=18, transform = axs[1,0].transAxes)
#cbar[0,0].ax.set_title("$\\langle n_i n_j \\rangle$")
cbar[0,0].ax.set_title("$O_{CDW}$")
axs[0,0].set_title("DMRG", fontsize=14)
cbar[0,1].ax.set_title("ES")
#axs[0,1].set_title("Entanglement spectrum degeneracy", fontsize=14)
cbar[1,0].ax.set_title("cost")
cbar[1,1].ax.set_title("cost")
plt.savefig("plots/BH_replot2.pdf", bbox_inches='tight')
fig, ax = plt.subplots(figsize=(6,4))
im = ax.pcolormesh(x,y,cost2.T,vmin=0, cmap=cmap, shading="auto",rasterized=True)
ax.set_xscale("log")
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=cbar_labelsize)
ax.set_title("Anomaly Syndrome", fontsize=14)
cbar.ax.set_title("cost")
ax.plot(vs[10],ds[10],"x", markersize=15, color="magenta")
ax.text(vs[10],ds[10]-0.25,"Training example", color="magenta")
ax.tick_params(labelsize=14)
#ax.set_xlabel(r"$V$",fontsize=18)
#ax.set_ylabel(r"$\delta t$",fontsize=18)
plt.tight_layout()
plt.savefig("plots/BH_ex_for_presentation.png", dpi=500, bbox_inches='tight')
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
from math import pi
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer, qx_color_scheme
# We recommend the following options for Jupter notebook
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
# Create a Quantum Register called "q" with 3 qubits
qr = QuantumRegister(3, 'q')
# Create a Classical Register called "c" with 3 bits
cr = ClassicalRegister(3, 'c')
# Create a Quantum Circuit called involving "qr" and "cr"
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0]).c_if(cr, 3)
circuit.z(qr[0])
circuit.u2(pi/2, 2*pi/3, qr[1])
circuit.cu1(pi, qr[0], qr[1])
# Barrier to seperator the input from the circuit
circuit.barrier(qr[0])
circuit.barrier(qr[1])
circuit.barrier(qr[2])
# Toffoli gate from qubit 0,1 to qubit 2
circuit.ccx(qr[0], qr[1], qr[2])
# CNOT (Controlled-NOT) gate from qubit 0 to qubit 1
circuit.cx(qr[0], qr[1])
circuit.swap(qr[0], qr[2])
# measure gate from qr to cr
circuit.measure(qr, cr)
QASM_source = circuit.qasm()
print(QASM_source)
drawer(circuit)
drawer(circuit, basis='u1,u2,u3,id,cx', scale=1.0)
my_style = {'plotbarrier': True}
drawer(circuit, style=my_style)
my_style = {'cregbundle': True}
drawer(circuit, style=my_style)
my_style = {'showindex': True}
drawer(circuit, style=my_style)
my_style = {'compress': True}
drawer(circuit, style=my_style)
my_style = {'fold': 6}
drawer(circuit, style=my_style)
my_style = {'usepiformat': True}
drawer(circuit, style=my_style)
qr = QuantumRegister(1, 'q')
circuit_xyz = QuantumCircuit(qr)
circuit_xyz.x(qr[0])
circuit_xyz.y(qr[0])
circuit_xyz.z(qr[0])
drawer(circuit_xyz)
my_style = {'displaytext': {'x': 'πΊ', 'y': '\Sigma', 'z': 'β'}}
drawer(circuit_xyz, style=my_style)
qr = QuantumRegister(2, 'q')
circuit_cucz = QuantumCircuit(qr)
circuit_cucz.cz(qr[0], qr[1])
circuit_cucz.cu1(pi, qr[0], qr[1])
drawer(circuit_cucz)
my_style = {'latexdrawerstyle': False}
drawer(circuit_cucz, style=my_style)
qr = QuantumRegister(3, 'q')
cr = ClassicalRegister(3, 'c')
circuit_all = QuantumCircuit(qr, cr)
circuit_all.x(qr[0])
circuit_all.y(qr[0])
circuit_all.z(qr[0])
circuit_all.barrier(qr[0])
circuit_all.barrier(qr[1])
circuit_all.barrier(qr[2])
circuit_all.h(qr[0])
circuit_all.s(qr[0])
circuit_all.sdg(qr[0])
circuit_all.t(qr[0])
circuit_all.tdg(qr[0])
circuit_all.iden(qr[0])
circuit_all.reset(qr[0])
circuit_all.rx(pi, qr[0])
circuit_all.ry(pi, qr[0])
circuit_all.rz(pi, qr[0])
circuit_all.u0(pi, qr[0])
circuit_all.u1(pi, qr[0])
circuit_all.u2(pi, pi, qr[0])
circuit_all.u3(pi, pi, pi, qr[0])
circuit_all.swap(qr[0], qr[1])
circuit_all.cx(qr[0], qr[1])
circuit_all.cy(qr[0], qr[1])
circuit_all.cz(qr[0], qr[1])
circuit_all.ch(qr[0], qr[1])
circuit_all.cu1(pi, qr[0], qr[1])
circuit_all.cu3(pi, pi, pi, qr[0], qr[1])
circuit_all.crz(pi, qr[0], qr[1])
circuit_all.ccx(qr[0], qr[1], qr[2])
circuit_all.cswap(qr[0], qr[1], qr[2])
circuit_all.measure(qr, cr)
drawer(circuit_all)
cmp_style = qx_color_scheme()
cmp_style
drawer(circuit_all, style=cmp_style)
cmp_style.update({
'usepiformat': True,
'showindex': True,
'cregbundle': True,
'compress': True,
'fold': 17
})
drawer(circuit_all, filename='circuit.pdf', style=cmp_style)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibm_nairobi')
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
qr = QuantumRegister(4); cr = ClassicalRegister(4); qc = QuantumCircuit(qr,cr)
qc.h([0,1])
qc.barrier()
qc.cx(0,2); qc.cx(0,3); qc.cx(1,2); qc.cx(1,3) # oraculo
qc.barrier()
qc.measure([2,3],[2,3])
qc.barrier()
qc.h([0,1]); qc.measure([0,1],[0,1])
qc.draw(output='mpl')
jobS = execute(qc, backend = simulator, shots = nshots)
jobE = execute(qc, backend = device, shots = nshots)
job_monitor(jobE)
plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)],
bar_labels = False, legend = ['sim', 'exp'])
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
#
# A quantum circuit is composed by quantum and classical bits in Qiskit.
#
# here are the objects that we use to create a quantum circuit in qiskit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
# we use a quantum register to keep our quantum bits.
q = QuantumRegister(1,"qreg") # in this example we will use a single quantum bit
# the second parameter is optional
# To retrieve an information from a quantum bit, it must be measured. (More details will appear.)
# The measurement result is stored classically.
# Therefore, we also use a classical regiser with classical bit(s)
c = ClassicalRegister(1,"creg") # in this example we will use a single classical bit
# the second parameter is optional
# now we can define our quantum circuit
# it is composed by a quantum and a classical registers
qc = QuantumCircuit(q,c)
# we apply operators on quantum bits
# operators are called as gates
# we apply NOT operator represented as "x" in qiskit
# operator is a part of the circuit, and we should specify the quantum bit as its parameter
qc.x(q[0]) # (quantum) bits are enumerated starting from 0
# NOT operator or x-gate is applied to the first qubit of the quantum register
# measurement is defined by associating a quantum bit to a classical bit
qc.measure(q[0],c[0])
# after the measurement, the observed value of the quantum bit is stored in the classical bit
# we run our codes until now, and then draw our circuit
print("The design of the circuit is done.")
# in Qiskit, the circuit object has a method called "draw"
# the default drawing method uses ASCII art
# let's draw our circuit now
qc.draw()
# re-execute this cell if you DO NOT see the circuit diagram
# we can draw the same circuit by using matplotlib
qc.draw(output='mpl')
# we use the method "execute" and the object "Aer" from qiskit library
from qiskit import execute, Aer
# we create a job object for execution of the circuit
# there are three parameters
# 1. mycircuit
# 2. backend on which it will be executed: we will use local simulator
# 3. how many times it will be executed, by default it is 1024
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1024)
# we can get the result of the outcome as follows
counts = job.result().get_counts(qc)
print(counts) # counts is a dictionary
# we can show the result by using histogram as follows
from qiskit.visualization import plot_histogram
plot_histogram(counts)
#print qasm code of our program
print(qc.qasm())
#
# A quantum circuit with four quantum and classical bits
#
# import all objects and methods at once
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# define quantum and classical registers and then quantum circuit
q2 = QuantumRegister(4,"qreg")
c2 = ClassicalRegister(4,"creg")
qc2 = QuantumCircuit(q2,c2)
# apply x-gate to the first quantum bit twice
qc2.x(q2[0])
qc2.x(q2[0])
# apply x-gate to the fourth quantum bit once
qc2.x(q2[3])
# apply x-gate to the third quantum bit three times
qc2.x(q2[2])
qc2.x(q2[2])
qc2.x(q2[2])
# apply x-gate to the second quantum bit four times
qc2.x(q2[1])
qc2.x(q2[1])
qc2.x(q2[1])
qc2.x(q2[1])
# define a barrier (for a better visualization)
qc2.barrier()
# if the sizes of quantum and classical registers are the same, we can define measurements with a single line of code
qc2.measure(q2,c2)
# then quantum bits and classical bits are associated with respect to their indices
# run the codes until now, and then draw our circuit
print("The design of the circuit is done.")
qc2.draw(output='mpl')
# re-execute this cell if the circuit diagram does not appear
# by seting parameter "reverse_bits" to "True", the order of quantum bits are reversed when drawing
qc2.draw(output='mpl',reverse_bits=True)
# re-execute this cell if the circuit diagram does not appear
job = execute(qc2,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(qc2)
print(counts)
from random import randrange
n = 20
r=randrange(n) # pick a number from the list {0,1,...,n-1}
print(r)
# test this method by using a loop
for i in range(10):
print(randrange(n))
#
# your solution is here
#
# we import all necessary methods and objects
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from random import randrange
# we use 8 qubits and 8 classical bits
q = QuantumRegister(8)
c = ClassicalRegister(8)
qc = QuantumCircuit(q,c)
# we store the index of each qubit to which x-gate is applied
picked_qubits=[]
for i in range(8):
if randrange(2) == 0: # Assume that 0 is Head and 1 is Tail
qc.x(q[i]) # apply x-gate
print("x-gate is applied to the qubit with index",i)
picked_qubits.append(i) # i is picked
# define a barrier
qc.barrier()
# measurement
qc.measure(q,c)
# draw the circuit
#mycircuit.draw(reverse_bits=True)
qc.draw(output='mpl',reverse_bits=True)
# execute the circuit and read the results
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=128)
counts = job.result().get_counts(qc)
print(counts)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
import sys
import os
current_dir = os.getcwd()
sys.path.append(current_dir)
from quantum_circuit import QuantumCircuit
# import qiskit.providers.fake_provider
from qiskit.transpiler import CouplingMap
import qiskit_ibm_runtime.fake_provider
from Backend.backend import Backend
class FakeBackend(Backend):
def __init__(self, backend_name : str) -> None:
self.backend = FakeBackend.get_ibm_fake_backend(backend_name=backend_name)
@staticmethod
def get_ibm_fake_backend_name_list() -> list[str]:
ibm_dir = dir(qiskit_ibm_runtime.fake_provider)
return [val for val in ibm_dir if '__' not in val and 'Fake' in val]
@staticmethod
def get_ibm_fake_backend(backend_name : str):
try:
return getattr(qiskit_ibm_runtime.fake_provider, backend_name)()
except: pass
fake_backend_name = FakeBackend.get_ibm_fake_backend_name_list()
for backend in fake_backend_name:
backend = FakeBackend.get_ibm_fake_backend(backend)
if backend is not None:
try:
if backend.name == backend_name:
return backend
except: pass
return None
@staticmethod
def get_ibm_fake_backend_names_with_limit(min_qubit : int = 1, max_qubit: int = float('inf')) -> list[str]:
limited_backend = []
fake_backend_name = FakeBackend.get_ibm_fake_backend_name_list()
for backend in fake_backend_name:
backend = FakeBackend.get_ibm_fake_backend(backend)
if backend is not None:
try:
num_qubit = backend.num_qubits
if num_qubit >= min_qubit and num_qubit <= max_qubit:
limited_backend.append(backend.name)
except: pass
return limited_backend
if __name__ == "__main__":
print(FakeBackend.get_ibm_fake_backend_name_list())
backend = FakeBackend('fake_auckland')
qc = QuantumCircuit(2)
qc.x(0)
qc.h(1)
qc.measure_all()
print(qc.draw())
job = backend.run(qc)
print(job.result())
qc_transpile = backend.traspile_qiskit(qc)[0]
print(qc_transpile.draw())
job = backend.run(qc_transpile)
print(job.result())
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.visualization import plot_error_map
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
plot_error_map(backend)
|
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.
"""
Ripple adder example based on Cuccaro et al., quant-ph/0410184.
"""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import BasicAer
from qiskit import execute
###############################################################
# Set the backend name and coupling map.
###############################################################
backend = BasicAer.get_backend("qasm_simulator")
coupling_map = [
[0, 1],
[0, 8],
[1, 2],
[1, 9],
[2, 3],
[2, 10],
[3, 4],
[3, 11],
[4, 5],
[4, 12],
[5, 6],
[5, 13],
[6, 7],
[6, 14],
[7, 15],
[8, 9],
[9, 10],
[10, 11],
[11, 12],
[12, 13],
[13, 14],
[14, 15],
]
###############################################################
# Make a quantum program for the n-bit ripple adder.
###############################################################
n = 2
a = QuantumRegister(n, "a")
b = QuantumRegister(n, "b")
cin = QuantumRegister(1, "cin")
cout = QuantumRegister(1, "cout")
ans = ClassicalRegister(n + 1, "ans")
qc = QuantumCircuit(a, b, cin, cout, ans, name="rippleadd")
def majority(p, a, b, c):
"""Majority gate."""
p.cx(c, b)
p.cx(c, a)
p.ccx(a, b, c)
def unmajority(p, a, b, c):
"""Unmajority gate."""
p.ccx(a, b, c)
p.cx(c, a)
p.cx(a, b)
# Build a temporary subcircuit that adds a to b,
# storing the result in b
adder_subcircuit = QuantumCircuit(cin, a, b, cout)
majority(adder_subcircuit, cin[0], b[0], a[0])
for j in range(n - 1):
majority(adder_subcircuit, a[j], b[j + 1], a[j + 1])
adder_subcircuit.cx(a[n - 1], cout[0])
for j in reversed(range(n - 1)):
unmajority(adder_subcircuit, a[j], b[j + 1], a[j + 1])
unmajority(adder_subcircuit, cin[0], b[0], a[0])
# Set the inputs to the adder
qc.x(a[0]) # Set input a = 0...0001
qc.x(b) # Set input b = 1...1111
# Apply the adder
qc &= adder_subcircuit
# Measure the output register in the computational basis
for j in range(n):
qc.measure(b[j], ans[j])
qc.measure(cout[0], ans[n])
###############################################################
# execute the program.
###############################################################
# First version: not mapped
job = execute(qc, backend=backend, coupling_map=None, shots=1024)
result = job.result()
print(result.get_counts(qc))
# Second version: mapped to 2x8 array coupling graph
job = execute(qc, backend=backend, coupling_map=coupling_map, shots=1024)
result = job.result()
print(result.get_counts(qc))
# Both versions should give the same distribution
|
https://github.com/jaykomarraju/Quantum-Optimization-for-Solar-Farm
|
jaykomarraju
|
import numpy as np
import networkx as nx
from qiskit import Aer
from qiskit.algorithms import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.algorithms import MinimumEigenOptimizer
num_time_slots = 24
# Define the QUBO problem
qubo = QuadraticProgram()
# Add binary variables for charging (c) and discharging (d) states
for t in range(num_time_slots):
qubo.binary_var(f'c_{t}')
qubo.binary_var(f'd_{t}')
# Define the objective function
# (In practice, you need to calculate Jij and hi based on the solar farm data)
Jij = np.random.rand(num_time_slots, num_time_slots) * 0.5
hi_c = -1 + np.random.rand(num_time_slots)
hi_d = 1 - np.random.rand(num_time_slots)
# Set linear and quadratic terms of the objective function
linear_terms = {}
quadratic_terms = {}
for t in range(num_time_slots):
linear_terms[f'c_{t}'] = hi_c[t]
linear_terms[f'd_{t}'] = hi_d[t]
for s in range(num_time_slots):
if t != s:
quadratic_terms[(f'c_{t}', f'c_{s}')] = Jij[t, s]
quadratic_terms[(f'd_{t}', f'd_{s}')] = Jij[t, s]
qubo.minimize(linear=linear_terms, quadratic=quadratic_terms)
# Set up the quantum instance
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=42, seed_transpiler=42, shots=10000)
# Set up the QAOA algorithm and optimizer
optimizer = COBYLA(maxiter=500)
qaoa = QAOA(optimizer=optimizer, reps=5, quantum_instance=quantum_instance)
# Set up the minimum eigen optimizer
min_eig_optimizer = MinimumEigenOptimizer(qaoa)
# Solve the problem
result = min_eig_optimizer.solve(qubo)
print("QAOA result:", result)
# Solve the problem using a classical solver (NumPyMinimumEigensolver)
exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
exact_result = exact_solver.solve(qubo)
print("Classical result:", exact_result)
|
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
|
VedDharkar
|
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 import *
# Loading your IBM Q account(s)
#provider = IBMQ.load_account()
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.draw('mpl')
sim = Aer.get_backend('statevector_simulator')
qobj = assemble(qc)
final_state = sim.run(qobj).result().get_statevector()
final_state
#BLOCH SPHERE
"""
THERE ARE 2 TYPES OF BLOCH SPHERE:-
1. plot_bloch_multivector
2.plot_bloch_vector
"""
plot_bloch_multivector(final_state, "Entanglement")
#FOR BLOCH_MULTIVECTOR YOU NEED A STATE
#FOR BLOCH_VECTOR YOU NEED COORDINATE POINTS
coords = [1, 1, 1]
plot_bloch_vector(coords, coord_type='cartesian')
#THERE IS ANOTHER COORD_TYPE THAT IS "SPHERICAL"
coords1 = [1, np.pi, np.pi]
plot_bloch_vector(coords1, coord_type='spherical')
|
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.
"""
Special data types.
"""
from enum import Enum
from typing import NamedTuple, List, Union, NewType, Tuple, Dict
from qiskit import circuit
ScheduledGate = NamedTuple(
"ScheduledGate",
[
("t0", int),
("operand", circuit.Gate),
("duration", int),
("bits", List[Union[circuit.Qubit, circuit.Clbit]]),
("bit_position", int),
],
)
ScheduledGate.__doc__ = "A gate instruction with embedded time."
ScheduledGate.t0.__doc__ = "Time when the instruction is issued."
ScheduledGate.operand.__doc__ = "Gate object associated with the gate."
ScheduledGate.duration.__doc__ = "Time duration of the instruction."
ScheduledGate.bits.__doc__ = "List of bit associated with the gate."
ScheduledGate.bit_position.__doc__ = "Position of bit associated with this drawing source."
GateLink = NamedTuple(
"GateLink", [("t0", int), ("opname", str), ("bits", List[Union[circuit.Qubit, circuit.Clbit]])]
)
GateLink.__doc__ = "Dedicated object to represent a relationship between instructions."
GateLink.t0.__doc__ = "A position where the link is placed."
GateLink.opname.__doc__ = "Name of gate associated with this link."
GateLink.bits.__doc__ = "List of bit associated with the instruction."
Barrier = NamedTuple(
"Barrier",
[("t0", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int)],
)
Barrier.__doc__ = "Dedicated object to represent a barrier instruction."
Barrier.t0.__doc__ = "A position where the barrier is placed."
Barrier.bits.__doc__ = "List of bit associated with the instruction."
Barrier.bit_position.__doc__ = "Position of bit associated with this drawing source."
HorizontalAxis = NamedTuple(
"HorizontalAxis", [("window", Tuple[int, int]), ("axis_map", Dict[int, int]), ("label", str)]
)
HorizontalAxis.__doc__ = "Data to represent configuration of horizontal axis."
HorizontalAxis.window.__doc__ = "Left and right edge of graph."
HorizontalAxis.axis_map.__doc__ = "Mapping of apparent coordinate system and actual location."
HorizontalAxis.label.__doc__ = "Label of horizontal axis."
class BoxType(str, Enum):
"""Box type.
SCHED_GATE: Box that represents occupation time by gate.
DELAY: Box associated with delay.
TIMELINE: Box that represents time slot of a bit.
"""
SCHED_GATE = "Box.ScheduledGate"
DELAY = "Box.Delay"
TIMELINE = "Box.Timeline"
class LineType(str, Enum):
"""Line type.
BARRIER: Line that represents barrier instruction.
GATE_LINK: Line that represents a link among gates.
"""
BARRIER = "Line.Barrier"
GATE_LINK = "Line.GateLink"
class SymbolType(str, Enum):
"""Symbol type.
FRAME: Symbol that represents zero time frame change (Rz) instruction.
"""
FRAME = "Symbol.Frame"
class LabelType(str, Enum):
"""Label type.
GATE_NAME: Label that represents name of gate.
DELAY: Label associated with delay.
GATE_PARAM: Label that represents parameter of gate.
BIT_NAME: Label that represents name of bit.
"""
GATE_NAME = "Label.Gate.Name"
DELAY = "Label.Delay"
GATE_PARAM = "Label.Gate.Param"
BIT_NAME = "Label.Bit.Name"
class AbstractCoordinate(Enum):
"""Abstract coordinate that the exact value depends on the user preference.
RIGHT: The horizontal coordinate at t0 shifted by the left margin.
LEFT: The horizontal coordinate at tf shifted by the right margin.
TOP: The vertical coordinate at the top of the canvas.
BOTTOM: The vertical coordinate at the bottom of the canvas.
"""
RIGHT = "RIGHT"
LEFT = "LEFT"
TOP = "TOP"
BOTTOM = "BOTTOM"
class Plotter(str, Enum):
"""Name of timeline plotter APIs.
MPL: Matplotlib plotter interface. Show timeline in 2D canvas.
"""
MPL = "mpl"
# convenient type to represent union of drawing data
DataTypes = NewType("DataType", Union[BoxType, LabelType, LineType, SymbolType])
# convenient type to represent union of values to represent a coordinate
Coordinate = NewType("Coordinate", Union[float, AbstractCoordinate])
# Valid bit objects
Bits = NewType("Bits", Union[circuit.Qubit, circuit.Clbit])
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# 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.
"""Test the variational quantum eigensolver algorithm."""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from functools import partial
import numpy as np
from scipy.optimize import minimize as scipy_minimize
from ddt import data, ddt
from qiskit import QuantumCircuit
from qiskit_algorithms import AlgorithmError
from qiskit_algorithms.gradients import ParamShiftEstimatorGradient
from qiskit_algorithms.minimum_eigensolvers import VQE
from qiskit_algorithms.optimizers import (
CG,
COBYLA,
GradientDescent,
L_BFGS_B,
OptimizerResult,
P_BFGS,
QNSPSA,
SLSQP,
SPSA,
TNC,
)
from qiskit_algorithms.state_fidelities import ComputeUncompute
from qiskit.circuit.library import RealAmplitudes, TwoLocal
from qiskit.opflow import PauliSumOp, TwoQubitReduction
from qiskit.quantum_info import SparsePauliOp, Operator, Pauli
from qiskit.primitives import Estimator, Sampler
from qiskit.utils import algorithm_globals
# pylint: disable=invalid-name
def _mock_optimizer(fun, x0, jac=None, bounds=None, inputs=None) -> OptimizerResult:
"""A mock of a callable that can be used as minimizer in the VQE."""
result = OptimizerResult()
result.x = np.zeros_like(x0)
result.fun = fun(result.x)
result.nit = 0
if inputs is not None:
inputs.update({"fun": fun, "x0": x0, "jac": jac, "bounds": bounds})
return result
@ddt
class TestVQE(QiskitAlgorithmsTestCase):
"""Test VQE"""
def setUp(self):
super().setUp()
self.seed = 50
algorithm_globals.random_seed = self.seed
self.h2_op = SparsePauliOp(
["II", "IZ", "ZI", "ZZ", "XX"],
coeffs=[
-1.052373245772859,
0.39793742484318045,
-0.39793742484318045,
-0.01128010425623538,
0.18093119978423156,
],
)
self.h2_energy = -1.85727503
self.ryrz_wavefunction = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz")
self.ry_wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
@data(L_BFGS_B(), COBYLA())
def test_basic_aer_statevector(self, estimator):
"""Test VQE using reference Estimator."""
vqe = VQE(Estimator(), self.ryrz_wavefunction, estimator)
result = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
with self.subTest(msg="test eigenvalue"):
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5)
with self.subTest(msg="test optimal_value"):
self.assertAlmostEqual(result.optimal_value, self.h2_energy)
with self.subTest(msg="test dimension of optimal point"):
self.assertEqual(len(result.optimal_point), 16)
with self.subTest(msg="assert cost_function_evals is set"):
self.assertIsNotNone(result.cost_function_evals)
with self.subTest(msg="assert optimizer_time is set"):
self.assertIsNotNone(result.optimizer_time)
with self.subTest(msg="assert optimizer_result is set"):
self.assertIsNotNone(result.optimizer_result)
with self.subTest(msg="assert optimizer_result."):
self.assertAlmostEqual(result.optimizer_result.fun, self.h2_energy, places=5)
with self.subTest(msg="assert return ansatz is set"):
estimator = Estimator()
job = estimator.run(result.optimal_circuit, self.h2_op, result.optimal_point)
np.testing.assert_array_almost_equal(job.result().values, result.eigenvalue, 6)
def test_invalid_initial_point(self):
"""Test the proper error is raised when the initial point has the wrong size."""
ansatz = self.ryrz_wavefunction
initial_point = np.array([1])
vqe = VQE(
Estimator(),
ansatz,
SLSQP(),
initial_point=initial_point,
)
with self.assertRaises(ValueError):
_ = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
def test_ansatz_resize(self):
"""Test the ansatz is properly resized if it's a blueprint circuit."""
ansatz = RealAmplitudes(1, reps=1)
vqe = VQE(Estimator(), ansatz, SLSQP())
result = vqe.compute_minimum_eigenvalue(self.h2_op)
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5)
def test_invalid_ansatz_size(self):
"""Test an error is raised if the ansatz has the wrong number of qubits."""
ansatz = QuantumCircuit(1)
ansatz.compose(RealAmplitudes(1, reps=2))
vqe = VQE(Estimator(), ansatz, SLSQP())
with self.assertRaises(AlgorithmError):
_ = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
def test_missing_ansatz_params(self):
"""Test specifying an ansatz with no parameters raises an error."""
ansatz = QuantumCircuit(self.h2_op.num_qubits)
vqe = VQE(Estimator(), ansatz, SLSQP())
with self.assertRaises(AlgorithmError):
vqe.compute_minimum_eigenvalue(operator=self.h2_op)
def test_max_evals_grouped(self):
"""Test with SLSQP with max_evals_grouped."""
optimizer = SLSQP(maxiter=50, max_evals_grouped=5)
vqe = VQE(
Estimator(),
self.ryrz_wavefunction,
optimizer,
)
result = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5)
@data(
CG(),
L_BFGS_B(),
P_BFGS(),
SLSQP(),
TNC(),
)
def test_with_gradient(self, optimizer):
"""Test VQE using gradient primitive."""
estimator = Estimator()
vqe = VQE(
estimator,
self.ry_wavefunction,
optimizer,
gradient=ParamShiftEstimatorGradient(estimator),
)
result = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5)
def test_gradient_passed(self):
"""Test the gradient is properly passed into the optimizer."""
inputs = {}
estimator = Estimator()
vqe = VQE(
estimator,
RealAmplitudes(),
partial(_mock_optimizer, inputs=inputs),
gradient=ParamShiftEstimatorGradient(estimator),
)
_ = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
self.assertIsNotNone(inputs["jac"])
def test_gradient_run(self):
"""Test using the gradient to calculate the minimum."""
estimator = Estimator()
vqe = VQE(
estimator,
RealAmplitudes(),
GradientDescent(maxiter=200, learning_rate=0.1),
gradient=ParamShiftEstimatorGradient(estimator),
)
result = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5)
def test_with_two_qubit_reduction(self):
"""Test the VQE using TwoQubitReduction."""
with self.assertWarns(DeprecationWarning):
qubit_op = PauliSumOp.from_list(
[
("IIII", -0.8105479805373266),
("IIIZ", 0.17218393261915552),
("IIZZ", -0.22575349222402472),
("IZZI", 0.1721839326191556),
("ZZII", -0.22575349222402466),
("IIZI", 0.1209126326177663),
("IZZZ", 0.16892753870087912),
("IXZX", -0.045232799946057854),
("ZXIX", 0.045232799946057854),
("IXIX", 0.045232799946057854),
("ZXZX", -0.045232799946057854),
("ZZIZ", 0.16614543256382414),
("IZIZ", 0.16614543256382414),
("ZZZZ", 0.17464343068300453),
("ZIZI", 0.1209126326177663),
]
)
tapered_qubit_op = TwoQubitReduction(num_particles=2).convert(qubit_op)
vqe = VQE(
Estimator(),
self.ry_wavefunction,
SPSA(maxiter=300, last_avg=5),
)
result = vqe.compute_minimum_eigenvalue(tapered_qubit_op)
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=2)
def test_callback(self):
"""Test the callback on VQE."""
history = {"eval_count": [], "parameters": [], "mean": [], "metadata": []}
def store_intermediate_result(eval_count, parameters, mean, metadata):
history["eval_count"].append(eval_count)
history["parameters"].append(parameters)
history["mean"].append(mean)
history["metadata"].append(metadata)
optimizer = COBYLA(maxiter=3)
wavefunction = self.ry_wavefunction
estimator = Estimator()
vqe = VQE(
estimator,
wavefunction,
optimizer,
callback=store_intermediate_result,
)
vqe.compute_minimum_eigenvalue(operator=self.h2_op)
self.assertTrue(all(isinstance(count, int) for count in history["eval_count"]))
self.assertTrue(all(isinstance(mean, float) for mean in history["mean"]))
self.assertTrue(all(isinstance(metadata, dict) for metadata in history["metadata"]))
for params in history["parameters"]:
self.assertTrue(all(isinstance(param, float) for param in params))
def test_reuse(self):
"""Test re-using a VQE algorithm instance."""
ansatz = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz")
vqe = VQE(Estimator(), ansatz, SLSQP(maxiter=300))
with self.subTest(msg="assert VQE works once all info is available"):
result = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5)
operator = Operator(np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]))
with self.subTest(msg="assert vqe works on re-use."):
result = vqe.compute_minimum_eigenvalue(operator=operator)
self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5)
def test_vqe_optimizer_reuse(self):
"""Test running same VQE twice to re-use optimizer, then switch optimizer"""
vqe = VQE(
Estimator(),
self.ryrz_wavefunction,
SLSQP(),
)
def run_check():
result = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5)
run_check()
with self.subTest("Optimizer re-use."):
run_check()
with self.subTest("Optimizer replace."):
vqe.optimizer = L_BFGS_B()
run_check()
def test_default_batch_evaluation_on_spsa(self):
"""Test the default batching works."""
ansatz = TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz")
wrapped_estimator = Estimator()
inner_estimator = Estimator()
callcount = {"estimator": 0}
def wrapped_estimator_run(*args, **kwargs):
kwargs["callcount"]["estimator"] += 1
return inner_estimator.run(*args, **kwargs)
wrapped_estimator.run = partial(wrapped_estimator_run, callcount=callcount)
spsa = SPSA(maxiter=5)
vqe = VQE(wrapped_estimator, ansatz, spsa)
_ = vqe.compute_minimum_eigenvalue(Pauli("ZZ"))
# 1 calibration + 5 loss + 1 return loss
expected_estimator_runs = 1 + 5 + 1
with self.subTest(msg="check callcount"):
self.assertEqual(callcount["estimator"], expected_estimator_runs)
with self.subTest(msg="check reset to original max evals grouped"):
self.assertIsNone(spsa._max_evals_grouped)
def test_batch_evaluate_with_qnspsa(self):
"""Test batch evaluating with QNSPSA works."""
ansatz = TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz")
wrapped_sampler = Sampler()
inner_sampler = Sampler()
wrapped_estimator = Estimator()
inner_estimator = Estimator()
callcount = {"sampler": 0, "estimator": 0}
def wrapped_estimator_run(*args, **kwargs):
kwargs["callcount"]["estimator"] += 1
return inner_estimator.run(*args, **kwargs)
def wrapped_sampler_run(*args, **kwargs):
kwargs["callcount"]["sampler"] += 1
return inner_sampler.run(*args, **kwargs)
wrapped_estimator.run = partial(wrapped_estimator_run, callcount=callcount)
wrapped_sampler.run = partial(wrapped_sampler_run, callcount=callcount)
fidelity = ComputeUncompute(wrapped_sampler)
def fidelity_callable(left, right):
batchsize = np.asarray(left).shape[0]
job = fidelity.run(batchsize * [ansatz], batchsize * [ansatz], left, right)
return job.result().fidelities
qnspsa = QNSPSA(fidelity_callable, maxiter=5)
qnspsa.set_max_evals_grouped(100)
vqe = VQE(
wrapped_estimator,
ansatz,
qnspsa,
)
_ = vqe.compute_minimum_eigenvalue(Pauli("ZZ"))
# 5 (fidelity)
expected_sampler_runs = 5
# 1 calibration + 1 stddev estimation + 1 initial blocking
# + 5 (1 loss + 1 blocking) + 1 return loss
expected_estimator_runs = 1 + 1 + 1 + 5 * 2 + 1
self.assertEqual(callcount["sampler"], expected_sampler_runs)
self.assertEqual(callcount["estimator"], expected_estimator_runs)
def test_optimizer_scipy_callable(self):
"""Test passing a SciPy optimizer directly as callable."""
vqe = VQE(
Estimator(),
self.ryrz_wavefunction,
partial(scipy_minimize, method="L-BFGS-B", options={"maxiter": 10}),
)
result = vqe.compute_minimum_eigenvalue(self.h2_op)
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=2)
def test_optimizer_callable(self):
"""Test passing a optimizer directly as callable."""
ansatz = RealAmplitudes(1, reps=1)
vqe = VQE(Estimator(), ansatz, _mock_optimizer)
result = vqe.compute_minimum_eigenvalue(SparsePauliOp("Z"))
self.assertTrue(np.all(result.optimal_point == np.zeros(ansatz.num_parameters)))
def test_aux_operators_list(self):
"""Test list-based aux_operators."""
vqe = VQE(Estimator(), self.ry_wavefunction, SLSQP(maxiter=300))
with self.subTest("Test with an empty list."):
result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=[])
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6)
self.assertIsInstance(result.aux_operators_evaluated, list)
self.assertEqual(len(result.aux_operators_evaluated), 0)
with self.subTest("Test with two auxiliary operators."):
with self.assertWarns(DeprecationWarning):
aux_op1 = PauliSumOp.from_list([("II", 2.0)])
aux_op2 = PauliSumOp.from_list(
[("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]
)
aux_ops = [aux_op1, aux_op2]
result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops)
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5)
self.assertEqual(len(result.aux_operators_evaluated), 2)
# expectation values
self.assertAlmostEqual(result.aux_operators_evaluated[0][0], 2.0, places=6)
self.assertAlmostEqual(result.aux_operators_evaluated[1][0], 0.0, places=6)
# metadata
self.assertIsInstance(result.aux_operators_evaluated[0][1], dict)
self.assertIsInstance(result.aux_operators_evaluated[1][1], dict)
with self.subTest("Test with additional zero operator."):
extra_ops = [*aux_ops, 0]
result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops)
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5)
self.assertEqual(len(result.aux_operators_evaluated), 3)
# expectation values
self.assertAlmostEqual(result.aux_operators_evaluated[0][0], 2.0, places=6)
self.assertAlmostEqual(result.aux_operators_evaluated[1][0], 0.0, places=6)
self.assertAlmostEqual(result.aux_operators_evaluated[2][0], 0.0)
# metadata
self.assertIsInstance(result.aux_operators_evaluated[0][1], dict)
self.assertIsInstance(result.aux_operators_evaluated[1][1], dict)
self.assertIsInstance(result.aux_operators_evaluated[2][1], dict)
def test_aux_operators_dict(self):
"""Test dictionary compatibility of aux_operators"""
vqe = VQE(Estimator(), self.ry_wavefunction, SLSQP(maxiter=300))
with self.subTest("Test with an empty dictionary."):
result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators={})
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6)
self.assertIsInstance(result.aux_operators_evaluated, dict)
self.assertEqual(len(result.aux_operators_evaluated), 0)
with self.subTest("Test with two auxiliary operators."):
with self.assertWarns(DeprecationWarning):
aux_op1 = PauliSumOp.from_list([("II", 2.0)])
aux_op2 = PauliSumOp.from_list(
[("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]
)
aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2}
result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops)
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6)
self.assertEqual(len(result.aux_operators_evaluated), 2)
# expectation values
self.assertAlmostEqual(result.aux_operators_evaluated["aux_op1"][0], 2.0, places=5)
self.assertAlmostEqual(result.aux_operators_evaluated["aux_op2"][0], 0.0, places=5)
# metadata
self.assertIsInstance(result.aux_operators_evaluated["aux_op1"][1], dict)
self.assertIsInstance(result.aux_operators_evaluated["aux_op2"][1], dict)
with self.subTest("Test with additional zero operator."):
extra_ops = {**aux_ops, "zero_operator": 0}
result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops)
self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6)
self.assertEqual(len(result.aux_operators_evaluated), 3)
# expectation values
self.assertAlmostEqual(result.aux_operators_evaluated["aux_op1"][0], 2.0, places=5)
self.assertAlmostEqual(result.aux_operators_evaluated["aux_op2"][0], 0.0, places=5)
self.assertAlmostEqual(result.aux_operators_evaluated["zero_operator"][0], 0.0)
# metadata
self.assertIsInstance(result.aux_operators_evaluated["aux_op1"][1], dict)
self.assertIsInstance(result.aux_operators_evaluated["aux_op2"][1], dict)
self.assertIsInstance(result.aux_operators_evaluated["zero_operator"][1], dict)
if __name__ == "__main__":
unittest.main()
|
https://github.com/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
from qiskit import QuantumCircuit
from qiskit import execute, Aer
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display
from qiskit.tools.monitor import job_monitor
from qiskit.extensions import UnitaryGate
from qiskit.circuit import Gate
class IQPE:
"""Implements the iterative QPE algorithm upto n bit precision specified by user
Attributes:
precision : int([1,...]): precision of the phase estimation ( also equal to number of qubits in scratch register)
unitary(np.ndarray or QuantumCircuit or UnitaryGate): unitary operator for which QPE is being applied.
unknown(bool) : a boolean variable used to specify whether exponentiation of unitary needs to be done or not
(True : no exponentiation done)
powers(dict): contains the powers of the unitary matrix
key : exponent, value : U^(exponent)
controls(dict): contains equivalent controlled U gates to be applied
key : iteration number, value : controlled U gate
Methods :
get_powers(unitary,n) : generates powers of U from U^1 -> U^(2^(n-1)) and stores power in dict
get_controls() : generates the U^(2^j) control gates for faster simulation of the QPE algorithm
"""
def __init__(self, precision, unitary, unknown=False): # write docs
"""
Args :
precision(int) : The precision upto which the phase needs to be estimated.
Interpreted as 2^(-precision).
eg. precision = 4 means the phase is going to be precise
upto 2^(-4).
unitary(np.ndarray or UnitaryGate or QuantumCircuit):
The unitary for which we want to determine the phase. Currently
this class supports 2 x 2 matrices or single qubit gates.
Shall be extended for higher order matrices.
unknown(bool) : Whether exponentiation is to be done or not
Raises :
TypeError : if precision or unitary are not of a valid type
ValueError : if precision is not valid
Exception : if unitary is of larger size than 2 x 2
Examples :
from iter_QPE import IQPE
# passing as ndarray
theta = 1/5
U1 = np.ndarray([[1,0],
[0, np.exp(2*np.pi*1j*(theta))]])
qpe1 = IQPE(precision = 4, unitary = U1,unknown = True)
# passing as QuantumCircuit
U2 = QuantumCircuit(1)
U2.rz(np.pi/7,0)
qpe2 = IQPE(precision = 5,unitary = U2,unknown = True)
"""
# handle precision
if type(precision) != int:
raise TypeError("Precision needs to be an integer")
elif precision < 0 or precision == 0:
raise ValueError("Precision needs to be atleast 1")
self.precision = precision
# handle unitary
if (
not isinstance(unitary, np.ndarray)
and not isinstance(unitary, QuantumCircuit)
and not isinstance(unitary, UnitaryGate)
and not isinstance(unitary, Gate)
):
raise TypeError(
"A numpy array, Quantum Circuit or Gate needs to be passed as the unitary matrix"
)
if unknown == False:
# means matrix rep needed
if not isinstance(unitary, np.ndarray) and not isinstance(
unitary, UnitaryGate
):
raise TypeError(
"""Unitary needs to be of type ndarray or Unitary Gate if optimization
needs to be done"""
)
if isinstance(unitary, UnitaryGate):
U = unitary.to_matrix()
else:
U = unitary # already an array
else:
# if it is numpy type array
if isinstance(unitary, np.ndarray):
U = UnitaryGate(data=unitary)
else:
U = unitary
# here we can directly use the .control method in our circuit.
# the unitary is an ndarray if unknown is False and
# the unitary is not ndarray is unknown is true
self.unitary = U
self.unknown = unknown
self.powers = {}
# optimization can only be performed when we know the
# matrix representation
if unknown == False:
self.controls = self.get_controls()
def get_powers(self, unitary, n):
"""This function returns the matrix U^(n) and saves
other smaller powers
Arguments:
unitary(np.ndarray):
The Unitary matrix which needs to be exponentitated
n(int): integer specifying the exponent
Raises:
ValueError : when n is < 0
Returns:
a dictionary containing the relevant powers of the matrix U"""
if n < 0:
raise ValueError("Power should be atleast 0")
if n == 1:
self.powers[1] = unitary
return unitary
if n % 2 == 1:
if n - 1 not in self.powers:
self.powers[n - 1] = self.get_powers(unitary, n - 1)
self.powers[n] = unitary @ self.powers[n - 1]
return self.powers[n]
else:
if n / 2 not in self.powers:
self.powers[n / 2] = self.get_powers(unitary, n / 2)
self.powers[n] = self.powers[n / 2] @ self.powers[n / 2]
return self.powers[n]
# get the controls, if using optimization
def get_controls(self):
"""Get the control gates for the circuit
While computing exponent, we also
compute the smaller powers
Returns:
controls(dict) : dictionary containing the relevant controlled unitary gates
key : iteration number, value : controlled U gate
"""
n_iters = self.precision
exp = 2 ** (n_iters - 1)
self.get_powers(self.unitary, exp)
# got the powers
controls = {}
# note that iteration 0 has the highest powered matrix and
# then it goes on to get lesser and lesser
iterations = self.precision
for it in range(iterations):
mat = self.powers[exp]
u_gate = UnitaryGate(data=mat)
cu = u_gate.control(num_ctrl_qubits=1, label="CU", ctrl_state="1")
controls[it] = cu
exp /= 2
return controls
def get_circuit_phase(
self,
QC,
clbits,
qubits,
ancilla,
show=False,
backend=None,
save_circ=False,
circ_name="IQPE_circ.JPG",
):
# QC must be atleast size 2
"""Add the experiments pararmeters .., and the shots parameter"""
"""
Returns the circuit phase as a 2-tuple phase : (binary phase,decimal phase)
Arguments:
QC(QuantumCircuit) : the circuit containing the eigenvector of the unitary matrix
clbits(list-like) : the list of the classical bits in which the phase would be saved
qubits(list-like) : the indices of the qubits containing the eigenvector of unitary
ancilla(int) : the ancilliary qubit which would be used as the control qubit
show(bool) : boolean to specify if circuit should be drawn or not
save(bool) : boolean to specify if circuit should be saved or not
(saved as IQPE_circuit.JPG, if true)
backend(IBMQBackend) : backend for running the circuit
NOTE : IBMQ provider must be enabled for execution of circuits on real backends
Raises:
ValueError : if clbits are not equal to precision or non-unique bits specified
or if elements of clbits/qubits are not integer type or ancilla qubit is
same as one of the eigenvector qubits
TypeError : if qubit indices are not integral
Exception : if unitary has less than 2 qubits
Returns :
A 2-tuple specifying the phase of unitary matrix : (binary phase,decimal phase)
Usage Notes :
NOTE : The phase is assumed to be a binary fraction as 0.x1x2x2...xn where n
is the precision specified by the user.
The least significant bit , xn, is saved in the qubit with index
precision-1 and the most significant bit, x1, is saved in the
qubit with index 0 in the phase[0] of tuple.
For example :-
theta = 1/5 # binary representation upto 4 bits : 0.0011
unitary = np.ndarray([[1,0],
[0, np.exp(2*np.pi*1j*(theta))]])
q = QuantumCircuit(6,4)
q.x(4) # the eigenvector qubit
qpe = get_circuit_phase(precision = 4,unitary = unitary,unknown = True)
athens = provider.get_backend('ibmq_athens')
phase = iqpe.get_circuit_phase(
QC=q, clbits=[0, 1, 2, 3], qubits=[4], ancilla=3, show=True,backend = athens)
# phase[0] would contain a 4-bit phase representation
# phase[1] would contain the decimal representation of the phase
"""
# handle qubits in circuit
if len(QC.qubits) < 2:
raise Exception("Quantum Circuit needs to have atleast size 2")
# handle classical bits
if len(clbits) != self.precision:
raise ValueError(
"Exactly", self.precision, "classical bits needed for measurement"
)
elif len(set(clbits)) != len(clbits):
raise ValueError("Non-unique classical bits given for measurement")
elif not all(isinstance(i, int) for i in clbits):
raise ValueError("All classical indices must be integer type")
# qubit and ancilla need to be integers
if type(ancilla) is not int:
raise TypeError("Ancilla indix need to be specified as integer")
elif not all(isinstance(i, int) for i in qubits):
raise TypeError(
"The indices containing the eigenvector must be integer type "
)
elif len(set(qubits)) != len(qubits):
raise ValueError("Non-unique qubits given for the eigenvector")
elif ancilla in qubits:
raise Exception("Ancilla can not be equal to a qubit index ")
res = []
# start with the iteration
phase = -2 * np.pi
factor = 0
iterations = self.precision
# generate the qubit list on which the Unitary is applied
qargs = [ancilla]
for q in qubits:
qargs.append(q)
if self.unknown == True:
# no matrix repr is available -> means .control method can be applied easily
exponent = 2 ** (iterations - 1)
CU = self.unitary.control(num_ctrl_qubits=1, label="CU", ctrl_state=1)
for it in range(iterations):
# start
QC.reset(ancilla)
QC.h(ancilla)
# add the inverse rotation
inv_phase = phase * factor
QC.p(inv_phase, ancilla)
# add the controlled Unitary of iteration it
if self.unknown == False:
QC = QC.compose(self.controls[it], qubits=qargs)
else:
# need to add exponential amount of matrices
for _ in range(int(exponent)):
QC = QC.compose(CU, qubits=qargs)
exponent /= 2
# add H gate
QC.h(ancilla)
QC.measure(ancilla, clbits[it])
# or, iterate in reverse manner , no of steps ->
# clbits[it] as it is the absolute
# classical register index
if backend == None: # simulating
counts = (
execute(QC, backend=Aer.get_backend("qasm_simulator"), shots=1)
.result()
.get_counts()
)
else:
job = execute(
QC,
shots=1,
backend=backend,
job_name="Iter " + str(it + 1),
optimization_level=3,
)
display(job_monitor(job))
counts = job.result().get_counts()
# we will have only one single key in the dict
key = list(counts.keys())[0][::-1]
# try adding x based on clasical
curr_bit = key[clbits[it]]
res.append(int(curr_bit))
# if bit measured is 1
if curr_bit == "1":
factor += 1 / 2 # add the phase factor
factor = factor / 2 # shift each towards one weight right
if it + 1 == iterations:
if show == True:
if save_circ == False:
display(QC.draw("mpl"))
else:
display(QC.draw(output="mpl", filename=circ_name, scale=0.8))
# phase has now been stored in the clbits
# returning its binary representation
# need to reverse as LSB is stored at the zeroth index and
# not the last
res = res[::-1]
# find decimal phase
dec = 0
weight = 1 / 2
for k in res:
dec += (weight) * k
weight /= 2
return (res, dec)
def get_estimate_plot_phase(
theta=None,
unitary=None,
unknown=True,
experiments=1,
iters=9,
show_circ=False,
save=False,
backend=None,
):
"""
Displays an estimate plot of the phase that is found through the IQPE
algorithm for SINGLE qubit phase unitaries
theta(float) : contains the actual theta (if some theoretical assumption is known)
unitary(ndarray / QuantumCircuit / UnitaryGate) :
the unitary for which phase needs to be determined
unknown(bool) : boolean variable to specify whether the optimization in unitary
application is to be used
experiments(int) : the number of experiments for which each iteration is to be run
iters(int) : the max number of iterations to be run ( circuit is run from precision
2 -> iters)
show_circ(bool) : boolean variable to specify whether circuit needs to be drawn or not
save(bool) : boolean variable specifying whether plot needs to be saved or
not (saved as IQPE Plots/Estimate_plot_theta.jpg)
backend(IBMBackend) : ibmq backend on which the circuit should be run (if None,
qasm_simulator is used)
Example :-
provider = IBMQ.get_provider('ibm-q')
casb = provider.get_backend('ibmq-casablanca)
U = np.array([[1,0],
[0, np.exp(2*np.pi*1j(0.524))]])
get_estimate_plot(unitary = U, iters = 10,unknown= True, save=True,backend = casb)
"""
import os
if theta is None and unitary is None:
raise Exception("Atleast one of theta or unitary is needed.")
if theta > 1 or theta < 0:
raise ValueError("Theta must be specified as a float val between 0 and 1")
if unitary is None:
unitary = np.array([[1, 0], [0, np.exp(2 * np.pi * 1j * (theta))]])
estimates, errors = [], []
avg_phase, avg_error = {}, {}
for prec in range(2, iters):
print("\n\nITERATION NUMBER", prec - 1, "...\n\n")
iqpe = IQPE(precision=prec, unitary=unitary, unknown=unknown)
dec_phase, abs_errors = [], []
for exp in range(experiments):
# single qubit rotation matrices
q = QuantumCircuit(2, prec)
q.x(1)
# simulate the matrix on a circuit
phase = iqpe.get_circuit_phase(
QC=q,
clbits=[i for i in range(prec)],
qubits=[1],
ancilla=0,
show=show_circ,
backend=backend,
)
# add the phase and the error ...
dec_phase.append(phase[1])
print("Binary Phase in experiment", exp, phase[0])
if theta is not None:
ae = np.round(abs(phase[1] - theta), 5)
abs_errors.append(ae)
# run experiments number of times AND get the avg phase
avg_phase[prec] = sum(dec_phase) / len(dec_phase)
avg_error[prec] = sum(abs_errors) / len(abs_errors)
print("Decimal Phase :", avg_phase[prec])
print("Absolute Error :", avg_error[prec])
if theta is not None:
print("Percentage error :", avg_error[prec] * 100 / theta, "%")
# append to graph
estimates.append(avg_phase[prec])
errors.append(avg_error[prec])
# choose color
colors = ["r", "g", "c", "m", "y"]
c1 = np.random.choice(colors)[0]
c2 = np.random.choice(colors)[0]
while c2 == c1:
c2 = np.random.choice(colors)[0]
plt.figure(figsize=(9, 7))
plt.grid(True)
# plot
plt.plot(
[i for i in range(2, iters)],
estimates,
alpha=0.6,
marker="o",
color=c1,
label="Estimates",
linestyle="dashed",
linewidth=2,
)
plt.plot(
[i for i in range(2, iters)],
errors,
alpha=0.6,
marker="s",
color=c2,
label="Absoulte error",
linestyle="dotted",
linewidth=2,
)
if theta != None:
plt.plot([0, iters], [theta, theta], color="black", label="Actual phase")
plt.title("IQPE estimates for $\\theta =" + str(theta) + "$", fontsize=16)
plt.xlabel("Number of iterations ", fontsize=14)
plt.ylabel("Estimates by IQPE", fontsize=14)
plt.legend()
if save:
os.makedirs("IQPE Plots", exist_ok=True)
plt.savefig("IQPE Plots/Estimate_plot_" + str(theta) + ".jpg", dpi=200)
|
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/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.mappers.second_quantization import LogarithmicMapper
mapper = LogarithmicMapper(2)
from qiskit_nature.second_q.mappers import LogarithmicMapper
mapper = LogarithmicMapper(2)
from qiskit_nature.second_q.mappers import LogarithmicMapper
mapper = LogarithmicMapper(padding=2)
from qiskit_nature.circuit.library import HartreeFock
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
converter = QubitConverter(JordanWignerMapper())
init_state = HartreeFock(num_spin_orbitals=6, num_particles=(2, 1), qubit_converter=converter)
print(init_state.draw())
from qiskit_nature.second_q.circuit.library import HartreeFock
from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter
converter = QubitConverter(JordanWignerMapper())
init_state = HartreeFock(num_spatial_orbitals=3, num_particles=(2, 1), qubit_converter=converter)
print(init_state.draw())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
import sys, getpass
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
print('Qconfig loaded from %s.' % Qconfig.__file__)
except:
APItoken = getpass.getpass('Please input your token and hit enter: ')
qx_config = {
"APItoken": APItoken,
"url":"https://quantumexperience.ng.bluemix.net/api"}
print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.')
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from pprint import pprint
# importing QISKit
from qiskit import QuantumProgram, QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import available_backends, execute, register, least_busy
# import basic plot tools
from qiskit.tools.visualization import plot_histogram, circuit_drawer
backend = 'local_qasm_simulator' # run on local simulator by default
# Uncomment the following lines to run on a real device
# register(qx_config['APItoken'], qx_config['url'])
# backend = least_busy(available_backends({'simulator': False, 'local': False}))
# print("the best backend is " + backend)
# Creating registers
tq = QuantumRegister(3)
tc0 = ClassicalRegister(1)
tc1 = ClassicalRegister(1)
tc2 = ClassicalRegister(1)
# Quantum circuit to make the shared entangled state
teleport = QuantumCircuit(tq, tc0,tc1,tc2)
teleport.h(tq[1])
teleport.cx(tq[1], tq[2])
teleport.ry(np.pi/4,tq[0])
teleport.cx(tq[0], tq[1])
teleport.h(tq[0])
teleport.barrier()
teleport.measure(tq[0], tc0[0])
teleport.measure(tq[1], tc1[0])
teleport.z(tq[2]).c_if(tc0, 1)
teleport.x(tq[2]).c_if(tc1, 1)
teleport.measure(tq[2], tc2[0])
circuit_drawer(teleport)
teleport_job = execute(teleport, 'local_qasm_simulator') # note that this circuit doesn't run on a real device
teleport_result = teleport_job.result()
data = teleport_result.get_counts(teleport)
alice = {}
alice['00'] = data['0 0 0'] + data['1 0 0']
alice['10'] = data['0 1 0'] + data['1 1 0']
alice['01'] = data['0 0 1'] + data['1 0 1']
alice['11'] = data['0 1 1'] + data['1 1 1']
plot_histogram(alice)
bob = {}
bob['0'] = data['0 0 0'] + data['0 1 0'] + data['0 0 1'] + data['0 1 1']
bob['1'] = data['1 0 0'] + data['1 1 0'] + data['1 0 1'] + data['1 1 1']
plot_histogram(bob)
# Creating registers
sdq = QuantumRegister(2)
sdc = ClassicalRegister(2)
# Quantum circuit to make the shared entangled state
superdense = QuantumCircuit(sdq, sdc)
superdense.h(sdq[0])
superdense.cx(sdq[0], sdq[1])
# For 00, do nothing
# For 01, apply $X$
#shared.x(q[0])
# For 01, apply $Z$
#shared.z(q[0])
# For 11, apply $XZ$
superdense.z(sdq[0])
superdense.x(sdq[0])
superdense.barrier()
superdense.cx(sdq[0], sdq[1])
superdense.h(sdq[0])
superdense.measure(sdq[0], sdc[0])
superdense.measure(sdq[1], sdc[1])
circuit_drawer(superdense)
superdense_job = execute(superdense, backend)
superdense_result = superdense_job.result()
plot_histogram(superdense_result.get_counts(superdense))
|
https://github.com/peiyong-addwater/Hackathon-QNLP
|
peiyong-addwater
|
import collections
import pickle
import warnings
warnings.filterwarnings("ignore")
import os
from random import shuffle
import random
from discopy.tensor import Tensor
from discopy import Word
from discopy.rigid import Functor
from discopy import grammar
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from jax import numpy as jnp
import numpy as np
from lambeq import AtomicType, IQPAnsatz, remove_cups, NumpyModel, spiders_reader
from lambeq import BobcatParser, TreeReader, cups_reader, DepCCGParser
from lambeq import Dataset
from lambeq import QuantumTrainer, SPSAOptimizer
from lambeq import TketModel
from lambeq import Rewriter
from pytket.extensions.qiskit import AerBackend
import seaborn as sns
import matplotlib.pyplot as plt
from pytket.circuit.display import render_circuit_jupyter
pd.set_option('display.width', 1000)
pd.options.display.max_colwidth=80
print(os.getcwd())
warnings.filterwarnings("ignore")
os.environ["TOKENIZERS_PARALLELISM"] = "false"
BATCH_SIZE = 20
EPOCHS = 50
SEED = 0
TRAIN_INDEX_RATIO = 0.02
VAL_INDEX_RATIO = TRAIN_INDEX_RATIO + 0.001
TEST_INDEX_RATIO = VAL_INDEX_RATIO + 0.001
assert TEST_INDEX_RATIO <= 1
def load_pickled_dict_to_df(filename):
saved_dict = pickle.load(open(filename, 'rb'))
df = pd.DataFrame.from_dict(saved_dict)
df = df.sample(frac=1, random_state=SEED).reset_index(drop=True)
sentiment = []
for i in df['target']:
if i == "Positive":
sentiment.append(1)
else:
sentiment.append(0)
df["Sentiment"] = sentiment
return df
cleaned_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data.pkl')
cleaned_lemmatized_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data_lematize.pkl')
cleaned_lemmatized_stemmed_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data_stem_lematize.pkl')
#cleaned_qnlp = load_pickled_dict_to_df(cleaned_qnlp_filename)
cleaned_lemmatized_qnlp = load_pickled_dict_to_df(cleaned_lemmatized_qnlp_filename)
cleaned__lemmatized_stemmed_qnlp = load_pickled_dict_to_df(cleaned_lemmatized_stemmed_qnlp_filename)
#cleaned_qnlp.head(10)
#cleaned_qnlp.info()
#sns.countplot(x = "target", data = cleaned_qnlp)
cleaned_lemmatized_qnlp.head(10)
cleaned_lemmatized_qnlp.info()
sns.countplot(x='target', data = cleaned_lemmatized_qnlp)
cleaned__lemmatized_stemmed_qnlp.head(10)
cleaned__lemmatized_stemmed_qnlp.info()
sns.countplot(x='target', data = cleaned__lemmatized_stemmed_qnlp)
# parser = BobcatParser(verbose='text')
# parser = DepCCGParser(root_cats=['S[dcl]'])
# parser = spiders_reader
parser = TreeReader()
NUM_DATA_1 = 2578
rewriter = Rewriter(['prepositional_phrase', 'determiner', 'auxiliary', 'connector',
'coordination', 'object_rel_pronoun', 'subject_rel_pronoun',
'postadverb', 'preadverb'])
def rewrite(diagram):
# diagram = rewriter(diagram)
return remove_cups(diagram)
def create_diagrams_and_labels(total_df, NUM_DATA = 2578):
total_text = total_df['data'].tolist()
total_labels = total_df["Sentiment"].tolist()
total_labels = [[t, 1-t] for t in total_labels] # [1, 0] for positive, [0, 1] for negative
train_diagrams = parser.sentences2diagrams(total_text[:round(NUM_DATA*TRAIN_INDEX_RATIO)])
train_labels = total_labels[:round(NUM_DATA*TRAIN_INDEX_RATIO)]
dev_diagrams = parser.sentences2diagrams(total_text[round(NUM_DATA*TRAIN_INDEX_RATIO):round(NUM_DATA*VAL_INDEX_RATIO)])
dev_labels = total_labels[round(NUM_DATA*TRAIN_INDEX_RATIO):round(NUM_DATA*VAL_INDEX_RATIO)]
test_diagrams = parser.sentences2diagrams(total_text[round(NUM_DATA*VAL_INDEX_RATIO):round(NUM_DATA*TEST_INDEX_RATIO)])
test_labels = total_labels[round(NUM_DATA*VAL_INDEX_RATIO):round(NUM_DATA*TEST_INDEX_RATIO)]
return train_diagrams, train_labels, dev_diagrams, dev_labels, test_diagrams, test_labels
raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(cleaned__lemmatized_stemmed_qnlp, NUM_DATA_1)
print(len(raw_train_diagrams_1))
raw_train_diagrams_1[0].draw(figsize=(12,3))
train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1]
dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1]
test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1]
train_diagrams_1[0].draw(figsize=(6,5))
alternate_parser = BobcatParser(verbose='text')
dig_0 = alternate_parser.sentence2diagram(cleaned__lemmatized_stemmed_qnlp['data'].tolist()[0])
grammar.draw(dig_0, figsize=(14,3), fontsize=12)
ansatz_1 = IQPAnsatz({AtomicType.NOUN: 1, AtomicType.SENTENCE: 1, AtomicType.PREPOSITIONAL_PHRASE: 1, AtomicType.NOUN_PHRASE:1, AtomicType.CONJUNCTION:1}, n_layers=1, n_single_qubit_params=3)
train_circuits_1 = [ansatz_1(diagram) for diagram in train_diagrams_1]
dev_circuits_1 = [ansatz_1(diagram) for diagram in dev_diagrams_1]
test_circuits_1 = [ansatz_1(diagram) for diagram in test_diagrams_1]
train_circuits_1[0].draw(figsize=(9, 12))
# train_circuits_1[0].draw(figsize=(9, 12))
render_circuit_jupyter(train_circuits_1[0].to_tk())
[(s, s.size) for s in train_circuits_1[0].free_symbols]
all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1
from sympy import default_sort_key
vocab_1 = sorted(
{sym for circ in all_circuits_1 for sym in circ.free_symbols},
key=default_sort_key
)
print(len(vocab_1))
params_1 = jnp.array(np.random.rand(len(vocab_1)))
from tqdm.notebook import tqdm
np_circuits = []
for c in tqdm(train_circuits_1):
np_circuits.append(c.lambdify(*vocab_1)(*params_1))
for c in tqdm(np_circuits):
print(c.eval().array)
def sigmoid(x):
return 1 / (1 + jnp.exp(-x))
def loss_1(tensors):
# Lambdify
np_circuits = [c.lambdify(*vocab_1)(*tensors) for c in train_circuits_1]
# Compute predictions
predictions = sigmoid(jnp.array([[jnp.real(jnp.conjugate(c.eval().array[0])*c.eval().array[0]), jnp.real(jnp.conjugate(c.eval().array[1])*c.eval().array[1])] for c in np_circuits]))
# binary cross-entropy loss
cost = -jnp.sum(train_targets_1 * jnp.log2(predictions)) / len(train_targets_1)
return cost
from jax import jit, grad
training_loss = jit(loss_1)
gradient = jit(grad(loss_1))
training_losses = []
LR = 1.0
for i in range(EPOCHS):
gr = gradient(params_1)
params_1 = params_1 - LR*gr
training_losses.append(float(training_loss(params_1)))
if (i + 1) % 1 == 0:
print(f"Epoch {i + 1} - loss {training_losses[-1]}")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
# You can reverse the order of the qubits.
from qiskit.quantum_info import DensityMatrix
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.t(1)
qc.s(0)
qc.cx(0,1)
matrix = DensityMatrix(qc)
plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.measure(0,0)
qc.x(0).c_if(0, 0)
qc.draw(output='mpl')
from qiskit import QuantumRegister, ClassicalRegister
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
qc = QuantumCircuit(q, c)
qc.h([0, 1, 2])
qc.barrier()
qc.measure(q, c)
qc.draw('mpl')
print(bin(3))
print(bin(7))
qc.x(2).c_if(c, 3) # for the 011 case
qc.x(2).c_if(c, 7) # for the 111 case
qc.draw(output='mpl')
nq = 2
m = 2
q = QuantumRegister(nq, 'q')
c = ClassicalRegister(m, 'c')
qc_S = QuantumCircuit(q,c)
qc_S.h(0)
qc_S.x(1)
qc_S.draw('mpl')
from math import pi
cu_circ = QuantumCircuit(2)
cu_circ.cp(pi/2, 0, 1)
cu_circ.draw('mpl')
for _ in range(2 ** (m - 1)):
qc_S.cp(pi/2, 0, 1)
qc_S.draw('mpl')
def x_measurement(qc, qubit, cbit):
"""Measure 'qubit' in the X-basis, and store the result in 'cbit'"""
qc.h(qubit)
qc.measure(qubit, cbit)
x_measurement(qc_S, q[0], c[0])
qc_S.draw('mpl')
qc_S.reset(0)
qc_S.h(0)
qc_S.draw('mpl')
qc_S.p(-pi/2, 0).c_if(c, 1)
qc_S.draw('mpl')
## 2^t c-U operations (with t=m-2)
for _ in range(2 ** (m - 2)):
qc_S.cp(pi/2, 0, 1)
x_measurement(qc_S, q[0], c[1])
qc_S.draw('mpl')
import matplotlib.pyplot as plt
from qiskit.tools.visualization import plot_histogram
from qiskit_aer.primitives import Sampler
sampler = Sampler()
job = sampler.run(qc_S)
result = job.result()
dist0 = result.quasi_dists[0]
key_new = [str(key/2**m) for key in list(dist0.keys())]
dist1 = dict(zip(key_new, dist0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(dist0, ax=ax[0])
plot_histogram(dist1, ax=ax[1])
plt.tight_layout()
nq = 3 # number of qubits
m = 3 # number of classical bits
q = QuantumRegister(nq,'q')
c = ClassicalRegister(m,'c')
qc = QuantumCircuit(q,c)
qc.h(0)
qc.x([1, 2])
qc.draw('mpl')
cu_circ = QuantumCircuit(nq)
cu_circ.mcp(pi/4, [0, 1], 2)
cu_circ.draw('mpl')
for _ in range(2 ** (m - 1)):
qc.mcp(pi/4, [0, 1], 2)
qc.draw('mpl')
x_measurement(qc, q[0], c[0])
qc.draw('mpl')
qc.reset(0)
qc.h(0)
qc.draw('mpl')
qc.p(-pi/2, 0).c_if(c, 1)
qc.draw('mpl')
for _ in range(2 ** (m - 2)):
qc.mcp(pi/4, [0, 1], 2)
x_measurement(qc, q[0], c[1])
qc.draw('mpl')
# initialization of qubit q0
qc.reset(0)
qc.h(0)
# phase correction
qc.p(-pi/4, 0).c_if(c, 1)
qc.p(-pi/2, 0).c_if(c, 2)
qc.p(-3*pi/2, 0).c_if(c, 3)
# c-U operations
for _ in range(2 ** (m - 3)):
qc.mcp(pi/4, [0, 1], 2)
# X measurement
qc.h(0)
qc.measure(0, 2)
qc.draw('mpl')
result = sampler.run(qc).result()
dist0 = result.quasi_dists[0]
key_new = [str(key/2**m) for key in list(dist0.keys())]
dist1 = dict(zip(key_new, dist0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(dist0, ax=ax[0])
plot_histogram(dist1, ax=ax[1])
plt.tight_layout()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/abhishekchak52/quantum-computing-course
|
abhishekchak52
|
# %pip install numpy==1.19 qiskit==0.20 pylatexenc # Please uncomment this line if you are running on Google Colab
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute
from qiskit.providers.aer import QasmSimulator
from qiskit.visualization import *
import qiskit
from packaging.version import parse as parse_version
assert parse_version(np.__version__) >= parse_version('1.19'), "Please install the correct version of numpy using the command 'pip install --upgrade numpy==1.19'"
assert parse_version(qiskit.__qiskit_version__['qiskit-terra']) >= parse_version('0.15'), "Please make sure you have the correct version of Qiskit installed or run this on IBM Quantum Experience"
assert parse_version(qiskit.__qiskit_version__['qiskit-aer']) >= parse_version('0.6'), "Please make sure you have the correct version of Qiskit installed or run this on IBM Quantum Experience"
assert parse_version(qiskit.__qiskit_version__['qiskit']) >= parse_version('0.20'),"Please make sure you have the correct version of Qiskit installed or run this on IBM Quantum Experience"
from cryptography.fernet import Fernet
import base64
basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'cx', 'barrier', 'measure']
secret_message = b'gAAAAABfevgMDRKfpM75bCBMUfAvaUW_Fjs2PxFYkYOSCldJTUnl8oLKVZRaiPitXqwQwbMTx4YwSCf_n0HQ-RIBvLa58AN4Pi7Fp9hFxGtjwzIpWUXIUr-BGE_9SLvjUGgsQCyrhK9ZJ5Yy9R5F6w4Me0Csr19UU3IqQQIP3ffhInE5o68_CI_URCjHXpBUnztJoDmlBnZz3Ka5NykfUN22iulaFvXOyw=='
print(f"The secret message is {secret_message.decode()}")
num_qubits = 64
rng = np.random.default_rng(seed=10)
alice_state = rng.integers(0, 2, size=num_qubits)
bob_basis = rng.integers(0, 2, size=num_qubits)
print(f"Alice's State:\t {np.array2string(alice_state, separator='')}")
print(f"Bob's Bases:\t {np.array2string(bob_basis, separator='')}")
def make_b92_circ(enc_state, meas_basis):
'''
A function that makes a B92 QKD protocol simulation circuit
enc_state: array of 0s and 1s denoting the state to be encoded using the following scheme:
0 -> |0>
1 -> |+>
meas_basis: array of 0s and 1s denoting the basis to be used for measurement
0 -> Hadamard Basis
1 -> Computational Basis
Note that both enc_state and meas_basis are arrays of integers, so if you are using them in
if statements, compare them to integer values like 0 and 1 (without quotes).
Since this is a function, you only have access to the variables enc_state and meas_basis.
You may define other local variables. One such variable, num_qubits has been defined for you.
This is the number of qubits in the B92 simulation QuantumCircuit()
'''
num_qubits = len(enc_state)
b92 = QuantumCircuit(num_qubits)
# Sender prepares qubits
# Add code below to encode the state in qubits
for index in range(len(enc_state)):
if enc_state[index] == 1:
b92.h(index)
b92.barrier()
# Receiver measures the received qubits
# Add code below to change basis for measurements. DO NOT add a measure() or measure_all()
for index in range(len(meas_basis)):
if meas_basis[index] == 0:
b92.h(index)
# Do not change below this line
b92.measure_all()
return b92
try:
b92_circ = make_b92_circ(alice_state, bob_basis)
assert list(b92_circ.count_ops()) != [], "Circuit cannot be empty"
assert set(b92_circ.count_ops().keys()).difference(basis_gates) == set(), f"Only the following basic gates are allowed: {basis_gates}"
assert all([type(gate[0]) == qiskit.circuit.measure.Measure for gate in b92_circ.data[-b92_circ.num_qubits:len(b92_circ.data)]]), "Measurement must be the last operation in a circuit."
assert b92_circ.count_ops()['measure'] == b92_circ.num_qubits, "Please do not add or remove measurements."
temp_key = execute(
b92_circ.reverse_bits(),
backend=QasmSimulator(),
shots=1,
seed_simulator=10
).result().get_counts().most_frequent()
assert temp_key == bin(16228741048440553634)[2:], "Your circuit did not perform as expected. Please check the gates again."
print(f"Bob's results:\t{temp_key}\nYour answer is correct.")
except AssertionError as e:
print(f'Your code has an error: {e.args[0]}')
except Exception as e:
print(f'This error occured: {e.args[0]}')
def b92_sifting(enc_state, meas_basis, meas_result):
'''
The function that implements key sifting for the B92 QKD protocol.
enc_state: array of 0s and 1s denoting the state to be encoded.
(Array of integers)
meas_basis: array of 0s and 1s denoting the basis to be used for measurement.
(Array of integers)
meas_result: A string of characters representing the results of measurement after the
B92 QKD protocol. Note that this is a string and its elements are characters,
so while using any if statements, compare the elements to '0' and '1' (with quotes)
Since this is a function, you only have access to the variables enc_state, meas_basis and meas_result.
You may define other local variables. num_qubits has been defined for you.
This is the number of qubits in the B92 simulation QuantumCircuit.
sender_key and receiver_key are initialised as two empty strings. You may append bits using the +=
operation as shown in the BB84 notebook. Note that you can only add characters. To change from other
data types to characters, you may use str(). Check the BB84 notebook for examples.
'''
num_qubits = len(enc_state)
sender_key = ''
receiver_key = ''
# Loop over all bits in the meas_result string and add the necessary bits to both sender_key and receiver_key
# Add your code below
for i in range(len(meas_result)):
if meas_result[i] == '1': # Only choose bits where Bob measured a 1
sender_key += str(enc_state[i])
receiver_key += str(meas_basis[i])
# Do not change bolow this line.
return (sender_key, receiver_key)
try:
alice_key, bob_key = b92_sifting(alice_state, bob_basis, temp_key)
assert ''.join([str(x ^ y) for x, y in zip(alice_key.encode(), bob_key.encode())]) != '1'*len(alice_key), "Please check your measurement convention"
assert alice_key == bob_key, "They keys are different for Alice and Bob."
assert alice_key == bob_key == bin(49522)[2:], "They keys is incorrect. Please check your solutions."
print(f"Alice's Key: \t{alice_key}\nBob's Key: \t{bob_key}\nYour answer is correct.")
g = Fernet(base64.b64encode(bob_key.encode()*2))
print(f"The secret message is: {g.decrypt(secret_message).decode()}")
except AssertionError as e:
print(f'Your code has an error: {e.args[0]}')
except Exception as e:
print(f'This error occured: {e.args[0]}')
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit.circuit import Parameter
from qiskit import pulse
from qiskit.test.mock.backends.almaden import *
phase = Parameter('phase')
with pulse.build(FakeAlmaden()) as phase_test_sched:
pulse.shift_phase(phase, pulse.drive_channel(0))
phase_test_sched.instructions # ()
|
https://github.com/kaelynj/Qiskit-HubbardModel
|
kaelynj
|
#Jupyter notebook to check if imports work correctly
%matplotlib inline
import sys
sys.path.append('./src')
import HubbardEvolutionChain as hc
import ClassicalHubbardEvolutionChain as chc
from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister
from qiskit.compiler import transpile, assemble
from qiskit.quantum_info import Operator
from qiskit.tools.monitor import job_monitor
from qiskit.tools.jupyter import *
import qiskit.visualization as qvis
import random as rand
import scipy.linalg as la
provider = IBMQ.load_account()
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from matplotlib import rcParams
rcParams['text.usetex'] = True
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters: x (int), n (int, number of digits)"""
binry = format(x, 'b').zfill(n)
sup = list( reversed( binry[0:int(len(binry)/2)] ) )
sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) )
return format(x, 'b').zfill(n)
#Energy Measurement Functions
#Measure the total repulsion from circuit run
def measure_repulsion(U, num_sites, results, shots):
repulsion = 0.
#Figure out how to include different hoppings later
for state in results:
for i in range( int( len(state)/2 ) ):
if state[i]=='1':
if state[i+num_sites]=='1':
repulsion += U*results.get(state)/shots
return repulsion
def measure_hopping(hopping, pairs, circuit, num_qubits):
#Add diagonalizing circuit
for pair in pairs:
circuit.cnot(pair[0],pair[1])
circuit.ch(pair[1],pair[0])
circuit.cnot(pair[0],pair[1])
#circuit.measure(pair[0],pair[0])
#circuit.measure(pair[1],pair[1])
circuit.measure_all()
#Run circuit
backend = Aer.get_backend('qasm_simulator')
shots = 8192
max_credits = 10 #Max number of credits to spend on execution
#print("Computing Hopping")
hop_exp = execute(circuit, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(hop_exp)
result = hop_exp.result()
counts = result.get_counts(circuit)
#print(counts)
#Compute energy
#print(pairs)
for pair in pairs:
hop_eng = 0.
#print('Pair is: ',pair)
for state in counts:
#print('State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[0],' Val: ',state[num_qubits-pair[0]])
if state[num_qubits-1-pair[0]]=='1':
prob_01 = counts.get(state)/shots
#print('Check state is: ',state)
for comp_state in counts:
#print('Comp State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[1],' Val: ',comp_state[num_qubits-pair[0]])
if comp_state[num_qubits-1-pair[1]]=='1':
#print('Comp state is: ',comp_state)
hop_eng += -hopping*(prob_01 - counts.get(comp_state)/shots)
return hop_eng
#nsites, excitations, total_time, dt, hop, U, trotter_steps
dt = 0.25 #Delta t
total_time = 5.
#time_steps = int(T/dt)
hop = 1.0 #Hopping parameter
#t = [1.0, 2.]
U = 2. #On-Site repulsion
#time_steps = 10
nsites = 3
trotter_steps = 1000
excitations = np.array([1])
numq = 2*nsites
num_steps = int(total_time/dt)
print('Num Steps: ',num_steps)
print('Total Time: ', total_time)
data = np.zeros((2**numq, num_steps))
energies = np.zeros(num_steps)
for t_step in range(0, num_steps):
#Create circuit with t_step number of steps
q = QuantumRegister(numq)
c = ClassicalRegister(numq)
qcirc = QuantumCircuit(q,c)
#=========USE THIS REGION TO SET YOUR INITIAL STATE==============
#Loop over each excitation
for flip in excitations:
qcirc.x(flip)
#===============================================================
qcirc.barrier()
#Append circuit with Trotter steps needed
hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps)
#Measure the circuit
for i in range(numq):
qcirc.measure(i, i)
#Choose provider and backend
provider = IBMQ.get_provider()
#backend = Aer.get_backend('statevector_simulator')
backend = Aer.get_backend('qasm_simulator')
#backend = provider.get_backend('ibmq_qasm_simulator')
#backend = provider.get_backend('ibmqx4')
#backend = provider.get_backend('ibmqx2')
#backend = provider.get_backend('ibmq_16_melbourne')
shots = 8192
max_credits = 10 #Max number of credits to spend on execution
job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits)
#job_monitor(job_exp)
result = job_exp.result()
counts = result.get_counts(qcirc)
print(result.get_counts(qcirc))
print("Job: ",t_step+1, " of ", num_steps," computing energy...")
#Store results in data array and normalize them
for i in range(2**numq):
if counts.get(get_bin(i,numq)) is None:
dat = 0
else:
dat = counts.get(get_bin(i,numq))
data[i,t_step] = dat/shots
#=======================================================
#Compute energy of system
#Compute repulsion energies
repulsion_energy = measure_repulsion(U, nsites, counts, shots)
print('Repulsion: ', repulsion_energy)
#Compute hopping energies
#Get list of hopping pairs
even_pairs = []
for i in range(0,nsites-1,2):
#up_pair = [i, i+1]
#dwn_pair = [i+nsites, i+nsites+1]
even_pairs.append([i, i+1])
even_pairs.append([i+nsites, i+nsites+1])
odd_pairs = []
for i in range(1,nsites-1,2):
odd_pairs.append([i, i+1])
odd_pairs.append([i+nsites, i+nsites+1])
#Start with even hoppings, initialize circuit and find hopping pairs
q = QuantumRegister(numq)
c = ClassicalRegister(numq)
qcirc = QuantumCircuit(q,c)
#Loop over each excitation
for flip in excitations:
qcirc.x(flip)
qcirc.barrier()
#Append circuit with Trotter steps needed
hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps)
'''for pair in odd_pairs:
qcirc.cnot(pair[0],pair[1])
qcirc.ch(pair[1],pair[0])
qcirc.cnot(pair[0],pair[1])
qcirc.measure(pair[0],pair[0])
qcirc.measure(pair[1],pair[1])
#circuit.draw()
print(t_step)
'''
#break
even_hopping = measure_hopping(hop, even_pairs, qcirc, numq)
print('Even hopping: ', even_hopping)
#===============================================================
#Now do the same for the odd hoppings
#Start with even hoppings, initialize circuit and find hopping pairs
q = QuantumRegister(numq)
c = ClassicalRegister(numq)
qcirc = QuantumCircuit(q,c)
#Loop over each excitation
for flip in excitations:
qcirc.x(flip)
qcirc.barrier()
#Append circuit with Trotter steps needed
hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps)
odd_hopping = measure_hopping(hop, odd_pairs, qcirc, numq)
print('Odd hopping: ',odd_hopping)
total_energy = repulsion_energy + even_hopping + odd_hopping
print(total_energy)
energies[t_step] = total_energy
print("Total Energy is: ", total_energy)
print("Job: ",t_step+1, " of ", num_steps," complete")
#qcirc.draw()
plt.plot(energies)
print(np.ptp(energies))
#Trotter Steps=1000
plt.plot(energies)
print(np.ptp(energies))
#Trotter Steps=100
plt.plot(energies)
print(np.ptp(energies))
#Trotter Steps=50
plt.plot(energies)
print(np.ptp(energies))
#Trotter Steps=10
plt.plot(energies)
print(np.ptp(energies))
#Trotter Steps=100
|
https://github.com/kaelynj/Qiskit-HubbardModel
|
kaelynj
|
#Jupyter notebook to check if imports work correctly
%matplotlib inline
import sys
sys.path.append('./src')
import HubbardEvolutionChain as hc
import ClassicalHubbardEvolutionChain as chc
import FullClassicalHubbardEvolutionChain as fhc
from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister
from qiskit.compiler import transpile, assemble
from qiskit.quantum_info import Operator
from qiskit.tools.monitor import job_monitor
from qiskit.tools.jupyter import *
import qiskit.visualization as qvis
import random as rand
import scipy.linalg as la
provider = IBMQ.load_account()
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from matplotlib import rcParams
rcParams['text.usetex'] = True
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters: x (int), n (int, number of digits)"""
binry = format(x, 'b').zfill(n)
sup = list( reversed( binry[0:int(len(binry)/2)] ) )
sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) )
return format(x, 'b').zfill(n)
#==========Set Parameters of the System=============#
dt = 0.25 #Delta t
T = 5.
time_steps = int(T/dt)
t = 1.0 #Hopping parameter
#t = [1.0, 2.]
U = 2. #On-Site repulsion
#time_steps = 10
nsites = 3
trotter_slices = 10
initial_state = np.array([1])
'''#Run simulation
run_results1 = hc.sys_evolve(nsites, initial_state, T, dt, t, U, 10)
run_results2 = hc.sys_evolve(nsites, initial_state, T, dt, t, U, 40)
run_results3, eng3 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 150)
run_results4 = hc.sys_evolve(nsites, initial_state, T, dt, t, U, 100)
#print(True if np.isscalar(initial_state) else False)
'''
#Fidelity measurements
#run_results1, engs1 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 10)
run_results2 = hc.sys_evolve_den(nsites, initial_state, T, dt, t, U, 40)
#run_results3, engs3 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 100)
#run_results4, engs4 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 150)
#Collect data on how Trotter steps change energy range
trotter_range = [10, 20, 30, 40, 50, 60, 70, 80]
eng_range = []
#engs = []
#runs = []
'''
for trot_step in trotter_range:
run_results3, eng3 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, trot_step)
runs.append(run_results3[:,-1])
eng_range.append(np.ptp(eng3))
engs.append(eng3)
'''
#sample_run = run_results3[:,-1]
#print(sample_run)
#print(run_results3[:,-1],' ',len(run_results3[:,-1]))
#print(tp_run[-1],' ',len(tp_run[-1]))
#Plot the raw data as a colormap
#xticks = np.arange(2**(nsites*2))
xlabels=[]
print("Time Steps: ",time_steps, " Step Size: ",dt)
for i in range(2**(nsites*2)):
xlabels.append(hc.get_bin(i,6))
fig, ax = plt.subplots(figsize=(10,20))
c = ax.pcolor(np.transpose(runs), cmap='binary')
ax.set_title('Basis State Amplitude', fontsize=22)
plt.yticks(np.arange(2**(nsites*2)), xlabels, size=18)
plt.xticks(np.arange(0,13), trotter_range, size=18)
ax.set_xlabel('No. of Trotter Steps', fontsize=22)
ax.set_ylabel('State', fontsize=26)
plt.show()
#plt.plot(trotter_range, eng_range)
#plt.xlabel('No. of Trotter Steps', fontsize=18)
#plt.ylabel('Energy Range', fontsize=18)
proc_data = np.zeros([2*nsites, len(trotter_range)])
runs_array = np.array(runs)
for step in range(0,len(trotter_range)):
for i in range(0,2**(2*nsites)):
num = ''.join( list( reversed(hc.get_bin(i,2*nsites)) ) )
#print('i: ', i,' step: ',step)
for mode in range(len(num)):
if num[mode]=='1':
proc_data[mode, step] += runs_array[step, i]
norm = 0.
for mode in range(len(num)):
norm += proc_data[mode, step]
proc_data[:,step] = proc_data[:,step] / norm
print(proc_data[0,:])
#============ Run Classical Evolution ==============#
#Define our basis states
#States for 3 electrons with net spin up
'''
states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]],
[[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]],
[[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ]
'''
#States for 2 electrons in singlet state
states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]],
[[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]],
[[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ]
#'''
#States for a single electron
#states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ]
#Possible initial wavefunctions
#wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state (101010)
wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state (010010)
#wfk = [0., 0., 0., 0., 0., 1., 0., 0., 0.] #2 electron initial state (010001)
#wfk = [0., -1., 0.] #1 electron initial state
#System parameters
t = 1.0
U = 2.
classical_time_step = 0.01
classical_total_time = 500*0.01
times = np.arange(0., classical_total_time, classical_time_step)
states = fhc.get_states(numsites)
evolution, engs = chc.sys_evolve(states, wfk, t, U, classical_total_time, classical_time_step)
print(evolution[-25])
#System parameters
t = 1.0
U = 2.
classical_time_step = 0.01
classical_total_time = 500*0.01
times = np.arange(0., classical_total_time, classical_time_step)
states = fhc.get_states(nsites)
#print(states)
#print(states[64])
wfk_full = np.zeros(len(states), dtype=np.complex_)
target_state = [[0,1], [0,0]]
target_index = 0
for l in range(len(states)):
if len(target_state) == sum([1 for i, j in zip(target_state, states[l]) if i == j]):
print('Target state found at: ',l)
target_index = l
#wfk_full[18] = 1. #010010
#wfk_full[21] = 1. #010101
#wfk_full[42] = 1. #101010
wfk_full[2] = 1. #000010
#wfk_full[target_index] = 1.
#wfk_full[2] = 0.5 - 0.5*1j
#wfk_full[0] = 1/np.sqrt(2)
print(wfk_full)
evolution, engs, wfks = fhc.sys_evolve(states, wfk_full, t, U, classical_total_time, classical_time_step)
#print(wfks[-26])
#print(run_results1[-1])
tst = np.outer(np.conj(wfks[-25]),wfks[-25])
#print(times[-25])
#print(np.shape(tst))
def fidelity(numerical_density, quantum_density):
sqrt_quantum = la.sqrtm(quantum_density)
fidelity_matrix = np.matmul(sqrt_quantum, np.matmul(numerical_density,sqrt_quantum))
fidelity_matrix = la.sqrtm(fidelity_matrix)
trace = np.trace(fidelity_matrix)
trace2 = np.conj(trace)*trace
#Try tr(rho*sigma)+sqrt(det(rho)*det(sigma))
fidelity = np.trace(np.matmul(numerical_density, quantum_density)) + np.sqrt(np.linalg.det(numerical_density)*np.linalg.det(quantum_density))
return fidelity
print("Fidelity")
print( fidelity( run_results2[-1], tst) )
print('============================')
print('Trace')
print('Numerical: ',np.trace(tst))
print('Quantum: ',np.trace(run_results2[-1]))
print('============================')
print('Square Trace')
print('Numerical: ',np.trace(np.matmul(tst, tst)))
print('Quantum: ',np.trace(np.matmul(run_results2[-1], run_results2[-1])))
print('============================')
fidelities = []
fidelities.append(fidelity(tst, run_results1[-1]))
fidelities.append(fidelity(tst, run_results2[-1]))
fidelities.append(fidelity(tst, run_results3[-1]))
fidelities.append(fidelity(tst, run_results4[-1]))
trotters = [10, 40, 100, 150]
plt.plot(trotters, fidelities)
#Calculate RootMeanSquare
rms = np.zeros(len(trotter_range))
for trotter_index in range(len(trotter_range)):
sq_diff = 0.
for mode in range(2*nsites):
sq_diff += (evolution[-25, mode] - proc_data[mode, trotter_index])**2
rms[trotter_index] = np.sqrt(sq_diff / 2*nsites)
plt.plot(trotter_range, rms)
plt.xlabel('Trotter Steps', fontsize=14)
plt.ylabel('RMS',fontsize=14)
plt.title('RMS for 1 Electrons 010000', fontsize=14)
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
for i in range(nsites):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(trotter_range, proc_data[i,:], marker="^", color=str(colors[i]), label=strup)
ax2.plot(trotter_range, proc_data[i+nsites,:], marker="v", linestyle='--', color=str(colors[i]), label=strdwn)
ax2.plot(trotter_range, np.full(len(trotter_range), evolution[-1, i]), linestyle='-', color=str(colors[i]),label=strup)
ax2.plot(trotter_range, np.full(len(trotter_range), evolution[-1, i+nsites]), linestyle='-', color=str(colors[i]),label=strdwn)
#ax2.set_ylim(0, 0.55)
#ax2.set_xlim(0, time_steps*dt+dt/2.)
#ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2))
#ax2.set_yticks(np.arange(0,0.55, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Probability Convergence for 3 electrons', fontsize=22)
ax2.set_xlabel('Number of Trotter Steps', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax2.legend(fontsize=20)
processed_data3 = hc.process_run(nsites, time_steps, dt, run_results3)
tdat = np.arange(0.,T, dt)
norm_dat = [np.sum(x) for x in np.transpose(processed_data3)]
print(norm_dat)
print(eng3)
#plt.plot(norm_dat)
plt.plot(tdat, eng3, label='80 Steps')
plt.plot(times, engs, label='Numerical')
plt.xlabel('Time', fontsize=18)
plt.ylabel('Energy',fontsize=18)
plt.ylim(-1e-5, 1e-5)
plt.legend()
print(np.ptp(eng3))
## ============ Run Classical Evolution ==============
#Define our basis states
#States for 3 electrons with net spin up
'''
states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]],
[[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]],
[[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ]
'''
#States for 2 electrons in singlet state
states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]],
[[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]],
[[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ]
#'''
#States for a single electron
#states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ]
#Possible initial wavefunctions
#wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state
wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state
#wfk = [0., 1., 0.] #1 electron initial state
#System parameters for evolving system numerically
t = 1.0
U = 2.
classical_time_step = 0.01
classical_total_time = 500*0.01
times = np.arange(0., classical_total_time, classical_time_step)
evolution, engs = chc.sys_evolve(states, wfk, t, U, classical_total_time, classical_time_step)
#Get norms and energies as a function of time. Round to 10^-12
norms = np.array([np.sum(x) for x in evolution])
norms = np.around(norms, 12)
engs = np.around(engs, 12)
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
fig3, ax3 = plt.subplots(1, 2, figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
cos = np.cos(np.sqrt(2)*times)**2
sit1 = "Site "+str(1)+r'$\uparrow$'
sit2 = "Site "+str(2)+r'$\uparrow$'
sit3 = "Site "+str(3)+r'$\uparrow$'
#ax2.plot(times, evolve[:,0], marker='.', color='k', linewidth=2, label=sit1)
#ax2.plot(times, evolve[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2)
#ax2.plot(times, evolve[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3)
#ax2.plot(times, cos, label='cosdat')
#ax2.plot(times, np.zeros(len(times)))
for i in range(3):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(times, evolution[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
ax2.plot(times, evolution[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
#ax2.set_ylim(0, 1.)
ax2.set_xlim(0, classical_total_time)
#ax2.set_xlim(0, 1.)
ax2.set_xticks(np.arange(0,classical_total_time, 0.2))
#ax2.set_yticks(np.arange(0,1.1, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax2.legend(fontsize=20)
#Plot energy and normalization
ax3[0].plot(times, engs, color='b')
ax3[1].plot(times, norms, color='r')
ax3[0].set_xlabel('Time', fontsize=24)
ax3[0].set_ylabel('Energy [t]', fontsize=24)
ax3[1].set_xlabel('Time', fontsize=24)
ax3[1].set_ylabel('Normalization', fontsize=24)
print(evolution)
#processed_data1 = hc.process_run(nsites, time_steps, dt, run_results1)
#processed_data2 = hc.process_run(nsites, time_steps, dt, run_results2)
processed_data3 = hc.process_run(nsites, time_steps, dt, run_results3)
#processed_data4 = hc.process_run(nsites, time_steps, dt, run_results4)
timesq = np.arange(0, time_steps*dt, dt)
#Create plots of the processed data
#fig0, ax0 = plt.subplots(figsize=(20,10))
fig1, ax1 = plt.subplots(figsize=(20,10))
fig2, ax2 = plt.subplots(figsize=(20,10))
fig3, ax3 = plt.subplots(figsize=(20,10))
fig4, ax4 = plt.subplots(figsize=(20,10))
fig5, ax5 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
'''
#Plot energies
ax0.plot(timesq, eng1, color=str(colors[0]), label='10 Steps')
ax0.plot(timesq, eng2, color=str(colors[1]), label='20 Steps')
ax0.plot(timesq, eng3, color=str(colors[2]), label='40 Steps')
ax0.plot(timesq, eng4, color=str(colors[3]), label='60 Steps')
ax0.legend(fontsize=20)
ax0.set_xlabel("Time", fontsize=24)
ax0.set_ylabel("Total Energy", fontsize=24)
ax0.tick_params(labelsize=16)
'''
#Site 1
strup = "10 Steps"+r'$\uparrow$'
strdwn = "10 Steps"+r'$\downarrow$'
#ax1.plot(timesq, processed_data1[0,:], marker="^", color=str(colors[0]), label=strup)
#ax1.plot(timesq, processed_data1[0+nsites,:], linestyle='--', marker="v", color=str(colors[0]), label=strdwn)
strup = "40 Steps"+r'$\uparrow$'
strdwn = "40 Steps"+r'$\downarrow$'
#ax1.plot(timesq, processed_data2[0,:], marker="^", color=str(colors[1]), label=strup)
#ax1.plot(timesq, processed_data2[0+nsites,:], linestyle='--', marker="v", color=str(colors[1]), label=strdwn)
strup = "80 Steps"+r'$\uparrow$'
strdwn = "80 Steps"+r'$\downarrow$'
ax1.plot(timesq, processed_data3[0,:], marker="^", color=str(colors[2]), label=strup)
ax1.plot(timesq, processed_data3[0+nsites,:],linestyle='--', marker="v", color=str(colors[2]), label=strdwn)
strup = "100 Steps"+r'$\uparrow$'
strdwn = "100 Steps"+r'$\downarrow$'
#ax1.plot(timesq, processed_data3[0,:], marker="^", color=str(colors[3]), label=strup)
#ax1.plot(timesq, processed_data3[0+nsites,:], linestyle='--', marker="v", color=str(colors[3]), label=strdwn)
strup = "Exact"+r'$\uparrow$'
strdwn = "Exact"+r'$\downarrow$'
#1e numerical evolution
ax1.plot(times, evolution[:,0], linestyle='-', color='k', linewidth=2, label=strup)
ax1.plot(times, evolution[:,0+nsites], linestyle='--', color='k', linewidth=2, label=strdwn)
#2e+ numerical evolution
#ax1.plot(times, mode_evolve[:,0], linestyle='-', color='k', linewidth=2, label=strup)
#ax1.plot(times, mode_evolve[:,0+nsites], linestyle='--', color='k', linewidth=2, label=strdwn)
#Site 2
strup = "10 Steps"+r'$\uparrow$'
strdwn = "10 Steps"+r'$\downarrow$'
#ax2.plot(timesq, processed_data1[1,:], marker="^", color=str(colors[0]), label=strup)
#ax2.plot(timesq, processed_data1[1+nsites,:], marker="v", linestyle='--',color=str(colors[0]), label=strdwn)
strup = "40 Steps"+r'$\uparrow$'
strdwn = "40 Steps"+r'$\downarrow$'
#ax2.plot(timesq, processed_data2[1,:], marker="^", color=str(colors[1]), label=strup)
#ax2.plot(timesq, processed_data2[1+nsites,:], marker="v", linestyle='--',color=str(colors[1]), label=strdwn)
strup = "80 Steps"+r'$\uparrow$'
strdwn = "80 Steps"+r'$\downarrow$'
ax2.plot(timesq, processed_data3[1,:], marker="^", color=str(colors[2]), label=strup)
ax2.plot(timesq, processed_data3[1+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn)
strup = "100 Steps"+r'$\uparrow$'
strdwn = "100 Steps"+r'$\downarrow$'
#ax2.plot(timesq, processed_data4[1,:], marker="^", color=str(colors[3]), label=strup)
#ax2.plot(timesq, processed_data4[1+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn)
#1e numerical evolution
strup = "Exact"+r'$\uparrow$'
strdwn = "Exact"+r'$\downarrow$'
ax2.plot(times, evolution[:,1], linestyle='-', color='k', linewidth=2, label=strup)
ax2.plot(times, evolution[:,1+nsites], linestyle='--', color='k', linewidth=2, label=strdwn)
#2e+ numerical evolution
#ax2.plot(times, mode_evolve[:,1], linestyle='-', color='k', linewidth=2, label=strup)
#ax2.plot(times, mode_evolve[:,1+nsites], linestyle='--', color='k', linewidth=2, label=strdwn)
#Site 3
strup = "10 Steps"+r'$\uparrow$'
strdwn = "10 Steps"+r'$\downarrow$'
#ax3.plot(timesq, processed_data1[2,:], marker="^", color=str(colors[0]), label=strup)
#ax3.plot(timesq, processed_data1[2+nsites,:], marker="v", linestyle='--', color=str(colors[0]), label=strdwn)
strup = "40 Steps"+r'$\uparrow$'
strdwn = "40 Steps"+r'$\downarrow$'
#ax3.plot(timesq, processed_data2[2,:], marker="^", color=str(colors[1]), label=strup)
#ax3.plot(timesq, processed_data2[2+nsites,:], marker="v", linestyle='--', color=str(colors[1]), label=strdwn)
strup = "80 Steps"+r'$\uparrow$'
strdwn = "80 Steps"+r'$\downarrow$'
ax3.plot(timesq, processed_data3[2,:], marker="^", color=str(colors[2]), label=strup)
ax3.plot(timesq, processed_data3[2+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn)
strup = "100 Steps"+r'$\uparrow$'
strdwn = "100 Steps"+r'$\downarrow$'
#ax3.plot(timesq, processed_data4[2,:], marker="^", color=str(colors[3]), label=strup)
#ax3.plot(timesq, processed_data4[2+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn)
#1e numerical evolution
strup = "Exact"+r'$\uparrow$'
strdwn = "Exact"+r'$\downarrow$'
ax3.plot(times, evolution[:,2], linestyle='-', color='k', linewidth=2, label=strup)
ax3.plot(times, evolution[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn)
#2e+ numerical evolution
#ax3.plot(times, mode_evolve[:,2], linestyle='-', color='k', linewidth=2, label=strup)
#ax3.plot(times, mode_evolve[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn)
#Site 4
r'''
strup = "10 Steps"+r'$\uparrow$'
strdwn = "10 Steps"+r'$\downarrow$'
#ax4.plot(timesq, processed_data1[3,:], marker="^", color=str(colors[0]), label=strup)
#ax4.plot(timesq, processed_data1[3+nsites,:], marker="v", linestyle='--', color=str(colors[0]), label=strdwn)
strup = "40 Steps"+r'$\uparrow$'
strdwn = "40 Steps"+r'$\downarrow$'
#ax4.plot(timesq, processed_data2[3,:], marker="^", color=str(colors[1]), label=strup)
#ax4.plot(timesq, processed_data2[3+nsites,:], marker="v", linestyle='--', color=str(colors[1]), label=strdwn)
strup = "150 Steps"+r'$\uparrow$'
strdwn = "150 Steps"+r'$\downarrow$'
ax4.plot(timesq, processed_data3[3,:], marker="^", color=str(colors[2]), label=strup)
ax4.plot(timesq, processed_data3[3+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn)
strup = "100 Steps"+r'$\uparrow$'
strdwn = "100 Steps"+r'$\downarrow$'
#ax4.plot(timesq, processed_data4[3,:], marker="^", color=str(colors[3]), label=strup)
#ax4.plot(timesq, processed_data4[3+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn)
#1e numerical evolution
strup = "Exact"+r'$\uparrow$'
strdwn = "Exact"+r'$\downarrow$'
ax4.plot(times, evolution[:,3], linestyle='-', color='k', linewidth=2, label=strup)
ax4.plot(times, evolution[:,3+nsites], linestyle='--', color='k', linewidth=2, label=strdwn)
#2e+ numerical evolution
#ax3.plot(times, mode_evolve[:,2], linestyle='-', color='k', linewidth=2, label=strup)
#ax3.plot(times, mode_evolve[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn)
#Site 5
strup = "10 Steps"+r'$\uparrow$'
strdwn = "10 Steps"+r'$\downarrow$'
ax5.plot(timesq, processed_data1[4,:], marker="^", color=str(colors[0]), label=strup)
ax5.plot(timesq, processed_data1[4+nsites,:], marker="v", linestyle='--', color=str(colors[0]), label=strdwn)
strup = "40 Steps"+r'$\uparrow$'
strdwn = "40 Steps"+r'$\downarrow$'
#ax5.plot(timesq, processed_data2[4,:], marker="^", color=str(colors[1]), label=strup)
#ax5.plot(timesq, processed_data2[4+nsites,:], marker="v", linestyle='--', color=str(colors[1]), label=strdwn)
strup = "150 Steps"+r'$\uparrow$'
strdwn = "150 Steps"+r'$\downarrow$'
ax5.plot(timesq, processed_data3[4,:], marker="^", color=str(colors[2]), label=strup)
ax5.plot(timesq, processed_data3[4+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn)
strup = "100 Steps"+r'$\uparrow$'
strdwn = "100 Steps"+r'$\downarrow$'
#ax5.plot(timesq, processed_data4[4,:], marker="^", color=str(colors[3]), label=strup)
#ax5.plot(timesq, processed_data4[4+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn)
#1e numerical evolution
strup = "Exact"+r'$\uparrow$'
strdwn = "Exact"+r'$\downarrow$'
ax5.plot(times, evolution[:,4], linestyle='-', color='k', linewidth=2, label=strup)
ax5.plot(times, evolution[:,4+nsites], linestyle='--', color='k', linewidth=2, label=strdwn)
#2e+ numerical evolution
#ax3.plot(times, mode_evolve[:,2], linestyle='-', color='k', linewidth=2, label=strup)
#ax3.plot(times, mode_evolve[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn)
r'''
#ax2.set_ylim(0, 0.55)
#ax2.set_xlim(0, time_steps*dt+dt/2.)
#ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2))
#ax2.set_yticks(np.arange(0,0.55, 0.05))
ax1.tick_params(labelsize=16)
ax2.tick_params(labelsize=16)
ax3.tick_params(labelsize=16)
ax4.tick_params(labelsize=16)
ax5.tick_params(labelsize=16)
ax1.set_title(r"Time Evolution of Site 1: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22)
ax2.set_title(r"Time Evolution of Site 2: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22)
ax3.set_title(r"Time Evolution of Site 3: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22)
ax4.set_title(r"Time Evolution of Site 4: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22)
ax5.set_title(r"Time Evolution of Site 5: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22)
ax1.set_xlabel('Time', fontsize=24)
ax2.set_xlabel('Time', fontsize=24)
ax3.set_xlabel('Time', fontsize=24)
ax4.set_xlabel('Time', fontsize=24)
ax5.set_xlabel('Time', fontsize=24)
ax1.set_ylabel('Probability', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax3.set_ylabel('Probability', fontsize=24)
ax4.set_ylabel('Probability', fontsize=24)
ax5.set_ylabel('Probability', fontsize=24)
ax1.legend(fontsize=20)
ax2.legend(fontsize=20)
ax3.legend(fontsize=20)
ax4.legend(fontsize=20)
ax5.legend(fontsize=20)
#==== Cell to Implement Energy Measurement Functions ====#
def sys_evolve(nsites, excitations, total_time, dt, hop, U, trotter_steps):
#Check for correct data types of input
if not isinstance(nsites, int):
raise TypeError("Number of sites should be int")
if np.isscalar(excitations):
raise TypeError("Initial state should be list or numpy array")
if not np.isscalar(total_time):
raise TypeError("Evolution time should be scalar")
if not np.isscalar(dt):
raise TypeError("Time step should be scalar")
if not isinstance(trotter_steps, int):
raise TypeError("Number of trotter slices should be int")
numq = 2*nsites
num_steps = int(total_time/dt)
print('Num Steps: ',num_steps)
print('Total Time: ', total_time)
data = np.zeros((2**numq, num_steps))
energies = np.zeros(num_steps)
for t_step in range(0, num_steps):
#Create circuit with t_step number of steps
q = QuantumRegister(numq)
c = ClassicalRegister(numq)
qcirc = QuantumCircuit(q,c)
#=========USE THIS REGION TO SET YOUR INITIAL STATE==============
#Loop over each excitation
for flip in excitations:
qcirc.x(flip)
#===============================================================
qcirc.barrier()
#Append circuit with Trotter steps needed
hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps)
#Measure the circuit
for i in range(numq):
qcirc.measure(i, i)
#Choose provider and backend
provider = IBMQ.get_provider()
#backend = Aer.get_backend('statevector_simulator')
backend = Aer.get_backend('qasm_simulator')
#backend = provider.get_backend('ibmq_qasm_simulator')
#backend = provider.get_backend('ibmqx4')
#backend = provider.get_backend('ibmqx2')
#backend = provider.get_backend('ibmq_16_melbourne')
shots = 8192
max_credits = 10 #Max number of credits to spend on execution
job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits)
#job_monitor(job_exp)
result = job_exp.result()
counts = result.get_counts(qcirc)
#print(result.get_counts(qcirc))
print("Job: ",t_step+1, " of ", num_steps," computing energy...")
#Store results in data array and normalize them
for i in range(2**numq):
if counts.get(get_bin(i,numq)) is None:
dat = 0
else:
dat = counts.get(get_bin(i,numq))
data[i,t_step] = dat/shots
#=======================================================
#Compute energy of system
#Compute repulsion energies
repulsion_energy = measure_repulsion(U, nsites, counts, shots)
#Compute hopping energies
#Get list of hopping pairs
even_pairs = []
for i in range(0,nsites-1,2):
#up_pair = [i, i+1]
#dwn_pair = [i+nsites, i+nsites+1]
even_pairs.append([i, i+1])
even_pairs.append([i+nsites, i+nsites+1])
odd_pairs = []
for i in range(1,nsites-1,2):
odd_pairs.append([i, i+1])
odd_pairs.append([i+nsites, i+nsites+1])
#Start with even hoppings, initialize circuit and find hopping pairs
q = QuantumRegister(numq)
c = ClassicalRegister(numq)
qcirc = QuantumCircuit(q,c)
#Loop over each excitation
for flip in excitations:
qcirc.x(flip)
qcirc.barrier()
#Append circuit with Trotter steps needed
hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps)
even_hopping = measure_hopping(hop, even_pairs, qcirc, numq)
#===============================================================
#Now do the same for the odd hoppings
#Start with even hoppings, initialize circuit and find hopping pairs
q = QuantumRegister(numq)
c = ClassicalRegister(numq)
qcirc = QuantumCircuit(q,c)
#Loop over each excitation
for flip in excitations:
qcirc.x(flip)
qcirc.barrier()
#Append circuit with Trotter steps needed
hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps)
odd_hopping = measure_hopping(hop, odd_pairs, qcirc, numq)
total_energy = repulsion_energy + even_hopping + odd_hopping
energies[t_step] = total_energy
print("Total Energy is: ", total_energy)
print("Job: ",t_step+1, " of ", num_steps," complete")
return data, energies
#Measure the total repulsion from circuit run
def measure_repulsion(U, num_sites, results, shots):
repulsion = 0.
#Figure out how to include different hoppings later
for state in results:
for i in range( int( len(state)/2 ) ):
if state[i]=='1':
if state[i+num_sites]=='1':
repulsion += U*results.get(state)/shots
return repulsion
def measure_hopping(hopping, pairs, circuit, num_qubits):
#Add diagonalizing circuit
for pair in pairs:
circuit.cnot(pair[0],pair[1])
circuit.ch(pair[1],pair[0])
circuit.cnot(pair[0],pair[1])
#circuit.measure(pair[0],pair[0])
#circuit.measure(pair[1],pair[1])
circuit.measure_all()
#Run circuit
backend = Aer.get_backend('qasm_simulator')
shots = 8192
max_credits = 10 #Max number of credits to spend on execution
#print("Computing Hopping")
hop_exp = execute(circuit, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(hop_exp)
result = hop_exp.result()
counts = result.get_counts(circuit)
#print(counts)
#Compute energy
#print(pairs)
for pair in pairs:
hop_eng = 0.
#print('Pair is: ',pair)
for state in counts:
#print('State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[0],' Val: ',state[num_qubits-pair[0]])
if state[num_qubits-1-pair[0]]=='1':
prob_01 = counts.get(state)/shots
#print('Check state is: ',state)
for comp_state in counts:
#print('Comp State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[1],' Val: ',comp_state[num_qubits-pair[0]])
if comp_state[num_qubits-1-pair[1]]=='1':
#print('Comp state is: ',comp_state)
hop_eng += -hopping*(prob_01 - counts.get(comp_state)/shots)
return hop_eng
#Try by constructing the matrix and finding the eigenvalues
N = 3
Nup = 2
Ndwn = N - Nup
t = 1.0
U = 2.
#Check if two states are different by a single hop
def hop(psii, psij):
#Check spin down
hopp = 0
if psii[0]==psij[0]:
#Create array of indices with nonzero values
indi = np.nonzero(psii[1])[0]
indj = np.nonzero(psij[1])[0]
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -t
return hopp
#Check spin up
if psii[1]==psij[1]:
indi = np.nonzero(psii[0])[0]
indj = np.nonzero(psij[0])[0]
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -t
return hopp
return hopp
#On-site terms
def repel(l,state):
if state[0][l]==1 and state[1][l]==1:
return state
else:
return []
#States for 3 electrons with net spin up
'''
states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]],
[[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]],
[[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ]
'''
#States for 2 electrons in singlet state
states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]],
[[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]],
[[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ]
#'''
#States for a single electron
states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ]
#'''
H = np.zeros((len(states),len(states)) )
#Construct Hamiltonian matrix
for i in range(len(states)):
psi_i = states[i]
for j in range(len(states)):
psi_j = states[j]
if j==i:
for l in range(0,len(states[0][0])):
if psi_i == repel(l,psi_j):
H[i,j] = U
break
else:
H[i,j] = hop(psi_i, psi_j)
print(H)
results = la.eig(H)
print()
for i in range(len(results[0])):
print('Eigenvalue: ',results[0][i])
print('Eigenvector: \n',results[1][i])
print()
dens_ops = []
eigs = []
for vec in results[1]:
dens_ops.append(np.outer(results[1][i],results[1][i]))
eigs.append(results[0][i])
print(dens_ops)
#Loop/function to flip through states
mode_list = []
num_sites = 3
print(len(states[0][0]))
for i in range(0,2*num_sites):
index_list = []
for state_index in range(0,len(states)):
state = states[state_index]
#print(state[0])
#print(state[1])
#Check spin-up modes
if i < num_sites:
if state[0][i]==1:
index_list.append(state_index)
#Check spin-down modes
else:
if state[1][i-num_sites]==1:
index_list.append(state_index)
if index_list:
mode_list.append(index_list)
print(mode_list)
wfk0 = 1/np.sqrt(2)*results[1][0] - 1/np.sqrt(2)*results[1][2]
print(np.dot(np.conj(wfk0), np.dot(H, wfk0)))
dtc = 0.01
tsteps = 500
times = np.arange(0., tsteps*dtc, dtc)
t_op = la.expm(-1j*H*dtc)
#print(np.subtract(np.identity(len(H)), dt*H*1j))
#print(t_op)
#wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state
#wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state
wfk = [0., 1., 0.] #1 electron initial state
evolve = np.zeros([tsteps, len(wfk)])
energies = np.zeros(tsteps)
mode_evolve = np.zeros([tsteps, 6])
mode_evolve = np.zeros([tsteps, len(mode_list)])
evolve[0] = wfk
energies[0] = np.dot(np.conj(wfk), np.dot(H, wfk))
print(energies[0])
excitations = 3.
#Loop to find occupation of each mode
for i in range(0,len(mode_list)):
wfk_sum = 0.
for j in mode_list[i]:
wfk_sum += evolve[0][j]
mode_evolve[0][i] = wfk_sum / excitations
print(mode_evolve)
print('========================================================')
#Figure out how to generalize this later
'''
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2.
mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2.
mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2.
'''
'''
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3.
mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3.
#'''
#print(mode_evolve[0])
#Define density matrices
print(mode_evolve)
print()
print()
for t in range(1, tsteps):
#t_op = la.expm(-1j*H*t*dtc)
wfk = np.dot(t_op, wfk)
evolve[t] = np.multiply(np.conj(wfk), wfk)
energies[t] = np.dot(np.conj(wfk), np.dot(H, wfk))
norm = np.sum(evolve[t])
#print(evolve[t])
#Store data in modes rather than basis defined in 'states' variable
''' #Procedure for two electrons
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2)
mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2)
mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2)
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2)
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2)
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2)
#Procedure for half-filling
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3.
mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3.
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3.
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3.
#'''
#print(mode_evolve[t])
#print(np.linalg.norm(evolve[t]))
#print(len(evolve[:,0]) )
#print(len(times))
#print(evolve[:,0])
#print(min(evolve[:,0]))
print(energies)
timesq = np.arange(0, time_steps*dt, dt)
for i in range(nsites):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(timesq, processed_data[i,:], marker="^", color=str(colors[i]), label=strup)
ax2.plot(timesq, processed_data[i+nsites,:], marker="v", color=str(colors[i]), label=strdwn)
#ax2.set_ylim(0, 0.55)
ax2.set_xlim(0, time_steps*dt+dt/2.)
#ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2))
#ax2.set_yticks(np.arange(0,0.55, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax2.legend(fontsize=20)
#Process and plot data
'''The procedure here is, for each fermionic mode, add the probability of every state containing
that mode (at a given time step), and renormalize the data based on the total occupation of each mode.
Afterwards, plot the data as a function of time step for each mode.'''
def process_run(num_sites, time_steps, results):
proc_data = np.zeros((2*num_sites, time_steps))
timesq = np.arange(0.,time_steps*dt, dt)
#Sum over time steps
for t in range(time_steps):
#Sum over all possible states of computer
for i in range(2**(2*num_sites)):
#num = get_bin(i, 2*nsite)
num = ''.join( list( reversed(hc.get_bin(i,2*nsites)) ) )
#For each state, check which mode(s) it contains and add them
for mode in range(len(num)):
if num[mode]=='1':
proc_data[mode,t] += results[i,t]
#Renormalize these sums so that the total occupation of the modes is 1
norm = 0.0
for mode in range(len(num)):
norm += proc_data[mode,t]
proc_data[:,t] = proc_data[:,t] / norm
return proc_data
'''
At this point, proc_data is a 2d array containing the occupation
of each mode, for every time step
'''
processed_data = process_run(nsites, time_steps, run_results)
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
for i in range(nsites):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(timesq, processed_data[i,:], marker="^", color=str(colors[i]), label=strup)
ax2.plot(timesq, processed_data[i+nsites,:], marker="v", color=str(colors[i]), label=strdwn)
#ax2.set_ylim(0, 0.55)
ax2.set_xlim(0, time_steps*dt+dt/2.)
#ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2))
#ax2.set_yticks(np.arange(0,0.55, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax2.legend(fontsize=20)
|
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/nahumsa/volta
|
nahumsa
|
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import unittest
import qiskit
from qiskit import BasicAer
from qiskit.opflow import X, Y, Z
from qiskit.utils import QuantumInstance
from volta.observables import sample_hamiltonian
class TestObservables(unittest.TestCase):
def setUp(self):
# Simulator
self.backend = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"), shots=10000
)
# ZZ expectation value of 1
self.qcZ = qiskit.QuantumCircuit(2)
# XX expectation value of 1
self.qcX = qiskit.QuantumCircuit(2)
self.qcX.h(range(2))
# YY expectation value of 1
self.qcY = qiskit.QuantumCircuit(2)
self.qcY.h(range(2))
self.qcY.s(range(2))
def test_ZZ(self):
want = 1.0
# observables made by hand
# got = measure_zz(self.qcZ, self.backend)
hamiltonian = Z ^ Z
got = sample_hamiltonian(hamiltonian, self.backend, self.qcZ)
decimalPlace = 2
message = "ZZ measurement not working for state Zero^Zero."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_XX(self):
want = 1.0
# observables made by hand
# got = measure_xx(self.qcX, self.backend)
hamiltonian = X ^ X
got = sample_hamiltonian(hamiltonian, self.backend, self.qcX)
decimalPlace = 2
message = "XX measurement not working for state Plus^Plus."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_YY(self):
want = 1.0
# observables made by hand
# got = measure_yy(self.qcY, self.backend)
hamiltonian = Y ^ Y
got = sample_hamiltonian(hamiltonian, self.backend, self.qcY)
decimalPlace = 2
message = "YY measurement not working for state iPlus^iPlus."
self.assertAlmostEqual(want, got, decimalPlace, message)
if __name__ == "__main__":
unittest.main(argv=[""], verbosity=2, exit=False)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit_nature.second_q.hamiltonians 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.second_q_op()
print(hamiltonian_ferm)
# get the transformation matrix W and orbital energies {epsilon_j}
(
transformation_matrix,
orbital_energies,
transformed_constant,
) = hamiltonian.diagonalizing_bogoliubov_transform()
print(f"Shape of matrix W: {transformation_matrix.shape}")
print(f"Orbital energies: {orbital_energies}")
print(f"Transformed constant: {transformed_constant}")
from qiskit_nature.second_q.circuit.library import FermionicGaussianState
occupied_orbitals = (0, 2)
eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant
print(f"Eigenvalue: {eig}")
circuit = FermionicGaussianState(transformation_matrix, occupied_orbitals=occupied_orbitals)
circuit.draw("mpl")
from qiskit.quantum_info import Statevector
from qiskit_nature.second_q.mappers 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(f"Hamiltonian conserves particle number: {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(f"Shape of matrix W: {transformation_matrix.shape}")
print(f"Orbital energies: {orbital_energies}")
print(f"Transformed constant: {transformed_constant}")
from qiskit_nature.second_q.circuit.library import SlaterDeterminant
occupied_orbitals = (0, 2)
eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant
print(f"Eigenvalue: {eig}")
circuit = SlaterDeterminant(transformation_matrix[list(occupied_orbitals)])
circuit.draw("mpl")
from qiskit_nature.second_q.circuit.library import BogoliubovTransform
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import random_hermitian, random_statevector, state_fidelity
from scipy.linalg import expm
# create Hamiltonian
n_modes = 5
hermitian_part = np.array(random_hermitian(n_modes))
hamiltonian = QuadraticHamiltonian(hermitian_part=hermitian_part)
# diagonalize Hamiltonian
(
transformation_matrix,
orbital_energies,
_,
) = hamiltonian.diagonalizing_bogoliubov_transform()
# set simulation time and construct time evolution circuit
time = 1.0
register = QuantumRegister(n_modes)
circuit = QuantumCircuit(register)
bog_circuit = BogoliubovTransform(transformation_matrix)
# change to the diagonal basis of the Hamiltonian
circuit.append(bog_circuit.inverse(), register)
# perform time evolution by applying z rotations
for q, energy in zip(register, orbital_energies):
circuit.rz(-energy * time, q)
# change back to the original basis
circuit.append(bog_circuit, register)
# simulate the circuit
initial_state = random_statevector(2**n_modes)
final_state = initial_state.evolve(circuit)
# compute the correct state by direct exponentiation
hamiltonian_jw = JordanWignerMapper().map(hamiltonian.second_q_op()).to_matrix()
exact_evolution_op = expm(-1j * time * hamiltonian_jw)
expected_state = exact_evolution_op @ np.array(initial_state)
# check that the simulated state is correct
fidelity = state_fidelity(final_state, expected_state)
np.testing.assert_allclose(fidelity, 1.0, atol=1e-8)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/hephaex/Quantum-Computing-Awesome-List
|
hephaex
|
from qiskit import *
from math import pi
import numpy as np
from qiskit.visualization import plot_bloch_multivector, plot_histogram
qc = QuantumCircuit(3)
for qubit in range(3):
qc.h(qubit)
qc.draw()
backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc, backend).result().get_statevector()
print(final_state)
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
qc.draw()
backend = Aer.get_backend('unitary_simulator')
unitary = execute(qc, backend).result().get_unitary()
print(unitary)
qiskit.__qiskit_version__
qc = QuantumCircuit(3)
qc.x(0)
qc.z(1)
qc.h(2)
qc.draw()
unitary = execute(qc, backend).result().get_unitary()
print(unitary)
qc = QuantumCircuit(2)
# Apply H-gate to the first:
qc.h(0)
qc.draw()
backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,backend).result().get_statevector()
print(final_state)
qc = QuantumCircuit(2)
# Apply H-gate to the first:
qc.h(0)
# Apply a CNOT:
qc.cx(0,1)
qc.draw()
final_state = Aer.get_backend('statevector_simulator')
final_state = execute(qc, backend).result().get_statevector()
print(final_state)
results = execute(qc,backend).result().get_counts()
plot_histogram(results)
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
qc.cx(0,1)
qc.draw()
backend = Aer.get_backend('statevector_simulator')
result = execute(qc, backend).result().get_statevector()
print(result)
result = execute(qc, backend).result().get_counts()
plot_histogram(result)
backend = Aer.get_backend('unitary_simulator')
unitary = execute(qc, backend).result().get_unitary()
print(unitary)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from IPython.display import HTML
HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code for QISKit exercises."></form>''')
from initialize import *
#initialize quantum program
my_alg = initialize(circuit_name = 'deutsch', qubit_number=2, bit_number=1, backend = 'local_qasm_simulator', shots = 1024)
#add gates to the circuit
my_alg.q_circuit.x(my_alg.q_reg[1]) # initializes ancilla qubit
my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit
my_alg.q_circuit.h(my_alg.q_reg[1]) # applies H gate to second qubit
my_alg.q_circuit.cx(my_alg.q_reg[0],my_alg.q_reg[1]) ## applies CX gate as the query function
my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit
my_alg.q_circuit.h(my_alg.q_reg[1]) # applies H gate to second qubit
my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit
print('List of gates:')
for circuit in my_alg.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_alg.circ_name)
print('\nThe measured outcomes of the circuits are:',counts)
from initialize import *
#initialize quantum program
my_alg = initialize(circuit_name = 'ber_vaz', qubit_number=3, bit_number=2, backend = 'local_qasm_simulator', shots = 1024)
#add gates to the circuit
my_alg.q_circuit.x(my_alg.q_reg[2]) # initializes ancilla qubit
my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit
my_alg.q_circuit.h(my_alg.q_reg[1]) # applies H gate to second qubit
my_alg.q_circuit.h(my_alg.q_reg[2]) # applies H gate to third qubit
my_alg.q_circuit.cx(my_alg.q_reg[1],my_alg.q_reg[2]) ## applies CX gate as the query function
my_alg.q_circuit.cx(my_alg.q_reg[0],my_alg.q_reg[2]) ## applies CX gate as the query function
my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit
my_alg.q_circuit.h(my_alg.q_reg[1]) # applies H gate to second qubit
my_alg.q_circuit.h(my_alg.q_reg[2]) # applies H gate to third qubit
my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit
my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures the second qubit and store the result in the second bit
print('List of gates:')
for circuit in my_alg.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_alg.circ_name)
print('\nThe measured outcomes of the circuits are:',counts)
from initialize import *
#initialize quantum program
my_alg = initialize(circuit_name = 'simon', qubit_number=4, bit_number=4, backend = 'local_qasm_simulator', shots = 1024)
#add gates to the circuit
my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit
my_alg.q_circuit.h(my_alg.q_reg[1]) # applies H gate to second qubit
my_alg.q_circuit.cx(my_alg.q_reg[0],my_alg.q_reg[2]) ## applies CX gate as the query function
my_alg.q_circuit.cx(my_alg.q_reg[0],my_alg.q_reg[3]) ## applies CX gate as the query function
my_alg.q_circuit.cx(my_alg.q_reg[1],my_alg.q_reg[2]) ## applies CX gate as the query function
my_alg.q_circuit.cx(my_alg.q_reg[1],my_alg.q_reg[3]) ## applies CX gate as the query function
my_alg.q_circuit.measure(my_alg.q_reg[2], my_alg.c_reg[2]) # measures the third qubit
my_alg.q_circuit.measure(my_alg.q_reg[3], my_alg.c_reg[3]) # measures the fourth qubit
my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit
my_alg.q_circuit.h(my_alg.q_reg[1]) # applies H gate to second qubit
my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit
my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures the second qubit
print('List of gates:')
for circuit in my_alg.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_alg.circ_name)
print('\nThe measured outcomes of the circuits are:',counts)
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 8 18:22:28 2022
Created on Thu Oct 13 10:29:00 2022
@author: pej
"""
import numpy as np
import pandas as pd
from qiskit import QuantumCircuit
from MultiQubitGate.functions import multiqubit
from BasicFunctions.functions import getBinary, getState
from Phase.PhaseFunctions.computeAmplFromShots import computeAmplFromShots
####################################################################
####################################################################
####################################################################
####################################################################
################### When c0 == 0
def getImagPart(df_ampl, ### amplitude |c_j| computed from shots
circ_U,
circ_UQU,
Q,
significant_figure,
nspins,
shots,
j_ref,
machine_precision=10,
):
'''
for the scenario where j_ref=0 is NOT in df_ampl.index
or c_0 == 0
'''
# ################## FOR COMPARISON
# #### df_comp_exact, ### this is exact c_j for benchmark
# circ_state = getState(circ_UQU, machine_precision)
# vec=circ_state[df_ampl.index, : ]
# df_comp_exact = pd.DataFrame(vec, df_ampl.index)
# ##################
circ_adj = QuantumCircuit(nspins+1)
_gamma = np.pi/10
circ_adj.ry(_gamma, qubit=-1) ### R_gamma
circ_adj.x(qubit=-1) ### X
### U
### attaches U to the q=1 ... q=n qubits, while q=0 is the ancillary
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U) )
### control-Q ; Ancillary - n target
for (q,o) in enumerate(Q):
if o==1:
circ_adj.cx(-1, q)
if o==2:
circ_adj.cy(-1, q)
if o==3:
circ_adj.cz(-1, q)
### U^
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U).inverse())
### control-P_{0 j_ref}
circ_adj.x(qubit=nspins)
J1 = list(getBinary(j_ref, nspins)) + [0]
for (q,o) in enumerate(J1):
if o==1:
circ_adj.cx(nspins, q)
circ_adj.x(nspins)
### H on ancillary
circ_adj.h(nspins)
#################### for each j2 The T_{j_ref -> j2} is different
indexs = df_ampl.index ### the observed bit strings from shots; j's
parts_imag= [[ 0]] # ref
part_indexs=[j_ref]
for j2 in indexs:
############################################ LEVEL0
################### LEVEL00
#### T Gate
p_12_int = j2^j_ref
## operator
P_12 = getBinary(p_12_int, nspins).tolist()+[0] #bitstring array of p12
mult_gate, op_count = multiqubit(P_12, np.pi/4) # turned into T gate
circ_uhu_adj = circ_adj.compose( mult_gate ) #add to the circuit
################### LEVEL01
##### from shots
m1, __ = computeAmplFromShots(circ_uhu_adj, shots, j_ref)
m1 = np.round(m1, significant_figure)
#### amplitude from shots
c2_2 = df_ampl[0][j2]**2 ### |c_j|^2
c2_2 = np.round(c2_2, significant_figure)
#### compute the sin of theta
imag_part = (m1 - (1/4) * c2_2**2 * (np.cos(_gamma/2)**2) - (1/4)*(np.sin(_gamma/2))**2 )/ ((-1/2) * np.cos(_gamma/2) * np.sin(_gamma/2))
#### round to allowed prcision
imag_part = np.round(imag_part, significant_figure)
############################################ LEVEL0 END
### collect results
parts_imag.append([ imag_part,
# df_comp_exact[0][j2].imag
])
part_indexs.append(j2)
parts_imag = pd.DataFrame(parts_imag, index= part_indexs).round(significant_figure)
parts_imag.columns=[ 'c_imag_sim',
# 'c_imag_exct'
]
### !!! TODO
### the row corresponding to j_ref must be taken out
return parts_imag
if __name__=='__main__':
pass
from Amplitude.Amplitude import Amplitude
################################################################
################################################################
##################### FOR TEST #######################
################################################################
################################################################
################################################################
################################################################
################################################################
def getRandomU(nspins, num_layers=10):
circ = QuantumCircuit(nspins)
for l in range(num_layers):
for i in range(nspins):
##############
q=np.random.randint(nspins)
g=np.random.randint(1, 4)
p=np.random.uniform(-1,1)
if g==1:
circ.rx(p,q)
if g==2:
circ.ry(p,q)
if g==2:
circ.rz(p,q)
##############
q=np.random.randint(nspins-1)
circ.cnot(q, q+1)
return circ
################################################################
################################################################
def getRandomQ(nspins):
Q = np.random.randint(0,2, size=nspins)
return Q
################################################################
################################################################
def getCircUQU(circ, Q):
circ_uhu=QuantumCircuit.copy(circ)
for (q,o) in enumerate(Q):
if o==0:
pass
if o==1:
circ_uhu.x(q)
if o==2:
circ_uhu.y(q)
if o==3:
circ_uhu.z(q)
circ_uhu=circ_uhu.compose(QuantumCircuit.copy(circ).inverse())
return circ_uhu
################################################################
################################################################
seed = 1211
np.random.seed(seed)
################################################################
################################################################
nspins = 6 # >=2
num_layers =2
num_itr =1
machine_precision = 10
shots = 1000
eta = 100
significant_figures = 3#np.log10(np.sqrt(shots)).astype(int)
circ_U = getRandomU(nspins, num_layers)
Q = getRandomQ(nspins)
circ_UQU = getCircUQU(circ_U, Q)
print('Q=', Q)
## ### amplitude |c_j| computed from shots
localAmplitudeObj = Amplitude(circ_U, circ_UQU, shots, eta, significant_figures, machine_precision)
localAmplitudeObj()
df_ampl = localAmplitudeObj.df_ampl
######## EXCLUDE index 0
try:
df_ampl = df_ampl.drop(index=0)
# df_ampl_bm = df_ampl_bm.drop(index=0)
except:
pass
print('df_ampl')
print(df_ampl)
print()
# print('df_ampl_bm')
# print(df_ampl_bm)
# print()
#### choose the ref
j_ref = np.random.randint(0, 2**nspins)
while j_ref in df_ampl.index:
j_ref = np.random.randint(0, 2**nspins)
print('j_ref = ' , j_ref)
print('number of js = ' , df_ampl.shape[0])
parts_imag = getImagPart(df_ampl, ### amplitude |c_j| computed from shots
circ_U,
circ_UQU,
Q,
significant_figures,
nspins,
shots,
j_ref,
)
print(parts_imag)
# print('\n\n##### sign errors')
# num_error = 0
# for jj in parts_imag.index:
# if parts_imag['c_imag_exct'][jj]>=0 and parts_imag['c_imag_sim'][jj]>=0:
# num_error+= 0
# else:
# if parts_imag['c_imag_exct'][jj]<0 and parts_imag['c_imag_sim'][jj]<0:
# num_error+= 0
# else:
# print(parts_imag['c_imag_exct'][jj], ' ', parts_imag['c_imag_sim'][jj])
# num_error+= 1
# print('error %= ',
# np.round(num_error/parts_imag.shape[0]*100, 2),
# 'num incorrect = ',
# num_error,
# 'total = ',
# parts_imag.shape[0]
# )
# print('\n\n##### L2 norm')
# error_L2 = 0
# for jj in parts_imag.index:
# diff = np.abs(parts_imag['c_imag_exct'][jj] - parts_imag['c_imag_sim'][jj])
# error = diff/( + 10**(-1*significant_figures) + np.abs(parts_imag['c_imag_exct'][jj] ) )
# print(error)
# error_L2+= error/parts_imag.shape[0]
# print('---')
# print(error_L2)
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
# Constant Oracle
const_oracle = QuantumCircuit(n+1)
# Random output
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw()
# Balanced Oracle
balanced_oracle = QuantumCircuit(n+1)
# Binary string length
b_str = "101"
# For each qubit in our circuit
# we place an X-gate if the corresponding digit in b_str is 1
# or do nothing if the digit is 0
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw()
# Creating the controlled-NOT gates
# using each input qubit as a control
# and the output as a target
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Wrapping the controls in X-gates
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw()
# Viewing the output
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/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 ^ I ^ 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 ^ I ^ 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 ^ I ^ 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 ^ I ^ 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)
) + J_z * ((( 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ Z ^ 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 ^ Z)))
- B_X * (( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ 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 ^ I ^ 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 ^ I ^ 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 ^ I ^ 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)
)
# 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(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(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')
plt.show()
# HAMILTONIAN 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 ^ I ^ 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 ^ I ^ 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 ^ I ^ 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 ^ I ^ 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)
# ) + J_z * ((( 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ 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 ^ Z ^ 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 ^ Z)))
# - B_X * (( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ 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 ^ I ^ 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 ^ I ^ 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 ^ I ^ 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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
p = 0.2
import numpy as np
from qiskit.circuit import QuantumCircuit
class BernoulliA(QuantumCircuit):
"""A circuit representing the Bernoulli A operator."""
def __init__(self, probability):
super().__init__(1) # circuit on 1 qubit
theta_p = 2 * np.arcsin(np.sqrt(probability))
self.ry(theta_p, 0)
class BernoulliQ(QuantumCircuit):
"""A circuit representing the Bernoulli Q operator."""
def __init__(self, probability):
super().__init__(1) # circuit on 1 qubit
self._theta_p = 2 * np.arcsin(np.sqrt(probability))
self.ry(2 * self._theta_p, 0)
def power(self, k):
# implement the efficient power of Q
q_k = QuantumCircuit(1)
q_k.ry(2 * k * self._theta_p, 0)
return q_k
A = BernoulliA(p)
Q = BernoulliQ(p)
from qiskit.algorithms import EstimationProblem
problem = EstimationProblem(
state_preparation=A, # A operator
grover_operator=Q, # Q operator
objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0
)
from qiskit.primitives import Sampler
sampler = Sampler()
from qiskit.algorithms import AmplitudeEstimation
ae = AmplitudeEstimation(
num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy
sampler=sampler,
)
ae_result = ae.estimate(problem)
print(ae_result.estimation)
import matplotlib.pyplot as plt
# plot estimated values
gridpoints = list(ae_result.samples.keys())
probabilities = list(ae_result.samples.values())
plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities))
plt.axvline(p, color="r", ls="--")
plt.xticks(size=15)
plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.title("Estimated Values", size=15)
plt.ylabel("Probability", size=15)
plt.xlabel(r"Amplitude $a$", size=15)
plt.ylim((0, 1))
plt.grid()
plt.show()
print("Interpolated MLE estimator:", ae_result.mle)
ae_circuit = ae.construct_circuit(problem)
ae_circuit.decompose().draw(
"mpl", style="iqx"
) # decompose 1 level: exposes the Phase estimation circuit!
from qiskit import transpile
basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"]
transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx")
from qiskit.algorithms import IterativeAmplitudeEstimation
iae = IterativeAmplitudeEstimation(
epsilon_target=0.01, # target accuracy
alpha=0.05, # width of the confidence interval
sampler=sampler,
)
iae_result = iae.estimate(problem)
print("Estimate:", iae_result.estimation)
iae_circuit = iae.construct_circuit(problem, k=3)
iae_circuit.draw("mpl", style="iqx")
from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation
mlae = MaximumLikelihoodAmplitudeEstimation(
evaluation_schedule=3, # log2 of the maximal Grover power
sampler=sampler,
)
mlae_result = mlae.estimate(problem)
print("Estimate:", mlae_result.estimation)
from qiskit.algorithms import FasterAmplitudeEstimation
fae = FasterAmplitudeEstimation(
delta=0.01, # target accuracy
maxiter=3, # determines the maximal power of the Grover operator
sampler=sampler,
)
fae_result = fae.estimate(problem)
print("Estimate:", fae_result.estimation)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
import numpy as np
import random
from qiskit import QuantumCircuit, Aer, execute
from math import log2, ceil, pi, sin
#=====================================================================================================================
simulator = Aer.get_backend('statevector_simulator')
def disp_isv(circ, msg="", all=True, precision=1e-8):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
qb = int(log2(len(statevector)))
print("\n============ State Vector ============", msg)
s = 0
for i in statevector:
if (all == True): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
else:
if (abs(i) > precision): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
s = s+1
print("============..............============")
return
#=====================================================================================================================
def U_init(qcirc, dummy, search):
# product state qubits not part of search qubits does not matter even if superposed
# qcirc.i(dummy)
# qcirc.x(dummy)
qcirc.h(dummy)
# qcirc.ry(0.25,dummy)
return
#=====================================================================================================================
def U_oracle1(sz):
print("Oracle marks {0000}")
tgt_reg = list(range(0,sz))
oracle = QuantumCircuit(len(tgt_reg))
oracle.x(tgt_reg)
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x(tgt_reg)
return oracle
def U_oracle2(sz):
print("Oracle marks {0000, 1111}")
tgt_reg = list(range(0,sz))
oracle = QuantumCircuit(len(tgt_reg))
# 0000
oracle.x(tgt_reg)
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x(tgt_reg)
# 1111
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
return oracle
def U_oracle3(sz):
print("Oracle marks {0000, 0101, 1111}")
tgt_reg = list(range(0,sz))
oracle = QuantumCircuit(len(tgt_reg))
# 0000
oracle.x(tgt_reg)
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x(tgt_reg)
# 0101
oracle.x(tgt_reg[1])
oracle.x(tgt_reg[3])
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x(tgt_reg[3])
oracle.x(tgt_reg[1])
# 1111
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
return oracle
def U_oracle5(sz):
print("Oracle marks {0111, 1111, 1001, 1011, 0101}")
tgt_reg = list(range(0,sz))
oracle = QuantumCircuit(len(tgt_reg))
oracle.h([2,3])
oracle.ccx(0,1,2)
oracle.h(2)
oracle.x(2)
oracle.ccx(0,2,3)
oracle.x(2)
oracle.h(3)
oracle.x([1,3])
oracle.h(2)
oracle.mct([0,1,3],2)
oracle.x([1,3])
oracle.h(2)
return oracle
#=====================================================================================================================
# def U_diffuser(sz):
# # Amplitude amplification on all qubits except count
# tgt_reg = list(range(0,sz))
# diffuser = QuantumCircuit(len(tgt_reg))
# diffuser.h(tgt_reg)
# diffuser.x(tgt_reg)
# diffuser.h(tgt_reg[0])
# diffuser.mct(tgt_reg[1:],tgt_reg[0])
# diffuser.h(tgt_reg[0])
# diffuser.x(tgt_reg)
# diffuser.h(tgt_reg)
# return diffuser
def U_diffuser(sz):
# https://qiskit.org/textbook/ch-algorithms/quantum-counting.html
tgt_reg = list(range(0,sz))
diffuser = QuantumCircuit(len(tgt_reg))
diffuser.h(tgt_reg[1:])
diffuser.x(tgt_reg[1:])
diffuser.z(tgt_reg[0])
diffuser.mct(tgt_reg[1:],tgt_reg[0])
diffuser.x(tgt_reg[1:])
diffuser.h(tgt_reg[1:])
diffuser.z(tgt_reg[0])
return diffuser
#=====================================================================================================================
def U_QFT(n):
# n-qubit QFT circuit
qft = QuantumCircuit(n)
def swap_registers(qft, n):
for qubit in range(n//2):
qft.swap(qubit, n-qubit-1)
return qft
def qft_rotations(qft, n):
# Performs qft on the first n qubits in circuit (without swaps)
if n == 0:
return qft
n -= 1
qft.h(n)
for qubit in range(n):
qft.cu1(np.pi/2**(n-qubit), qubit, n)
qft_rotations(qft, n)
qft_rotations(qft, n)
swap_registers(qft, n)
return qft
#=====================================================================================================================
qnos = [1, 4, 6]
dummy = list(range(sum(qnos[0:0]),sum(qnos[0:1])))
search = list(range(sum(qnos[0:1]),sum(qnos[0:2])))
count = list(range(sum(qnos[0:2]),sum(qnos[0:3])))
qcirc_width = sum(qnos[0:3])
qcirc = QuantumCircuit(qcirc_width, len(count))
#=====================================================================================================================
# Create controlled Grover oracle circuit
oracle = U_oracle3(len(search)).to_gate()
c_oracle = oracle.control()
c_oracle.label = "cGO"
# Create controlled Grover diffuser circuit
# diffuser = U_diffuser(len(search)).to_gate()
diffuser = U_diffuser(len(dummy)+len(search)).to_gate()
c_diffuser = diffuser.control()
c_diffuser.label = "cGD"
# Create inverse QFT circuit
iqft = U_QFT(len(count)).to_gate().inverse()
iqft.label = "iQFT"
#=====================================================================================================================
# qcirc.ry(0.55,search) # probability of states assumed to be equal in counting
qcirc.h(search)
qcirc.barrier()
U_init(qcirc, dummy, search)
# print()
# disp_isv(qcirc, "Step: Search state vector", all=False, precision=1e-4)
qcirc.h(count)
qcirc.barrier()
viewMarking = 1
# Begin controlled Grover iterations
iterations = 1
for qb in count:
for i in range(iterations):
qcirc.append(c_oracle, [qb] + search)
# qcirc.append(c_diffuser, [qb] + search)
qcirc.append(c_diffuser, [qb] + dummy + search)
iterations *= 2
qcirc.barrier()
# Inverse QFT
qcirc.append(iqft, count)
qcirc.barrier()
# Measure counting qubits
qcirc.measure(count, range(len(count)))
# print()
# print(qcirc.draw())
#=====================================================================================================================
emulator = Aer.get_backend('qasm_simulator')
job = execute(qcirc, emulator, shots=2048 )
hist = job.result().get_counts()
# print(hist)
measured_int = int(max(hist, key=hist.get),2)
theta = (measured_int/(2**len(count)))*pi*2
# counter = 2**len(search) * (1 - sin(theta/2)**2)
# print("Number of solutions = %d" % round(counter))
counter = 2**(len(dummy)+len(search)) * (1 - sin(theta/2)**2)
print("Number of solutions = %d" % round(counter))
#=====================================================================================================================
# RESULT: 6 count bits are required to detect all 16 possibilities while searching a 4 bit database
# searchbits = 4
# print("\nDetectable solutions with 4 count bits:")
# countbits = 4
# for i in range(0,countbits**2):
# theta = (i/(2**countbits))*pi*2
# counter = 2**searchbits * (1 - sin(theta/2)**2)
# print(round(counter),"|",end='')
# print("\nDetectable solutions with 5 count bits:")
# countbits = 5
# for i in range(0,countbits**2):
# theta = (i/(2**countbits))*pi*2
# counter = 2**searchbits * (1 - sin(theta/2)**2)
# print(round(counter),"|",end='')
# print("\nDetectable solutions with 6 count bits:")
# countbits = 6
# for i in range(0,countbits**2):
# theta = (i/(2**countbits))*pi*2
# counter = 2**searchbits * (1 - sin(theta/2)**2)
# print(round(counter),"|",end='')
#=====================================================================================================================
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Choose the drawer you like best:
from qiskit.tools.visualization import matplotlib_circuit_drawer as draw
#from qiskit.tools.visualization import circuit_drawer as draw
from qiskit import IBMQ
IBMQ.load_accounts() # make sure you have setup your token locally to use this
%matplotlib inline
import matplotlib.pyplot as plt
def show_results(D):
# D is a dictionary with classical bits as keys and count as value
# example: D = {'000': 497, '001': 527}
plt.bar(range(len(D)), list(D.values()), align='center')
plt.xticks(range(len(D)), list(D.keys()))
plt.show()
from qiskit import Aer
# See a list of available local simulators
print("Aer backends: ", Aer.backends())
# see a list of available remote backends (these are freely given by IBM)
print("IBMQ Backends: ", IBMQ.backends())
# execute circuit and either display a histogram of the results
def execute_locally(qc, draw_circuit=False):
# Compile and run the Quantum circuit on a simulator backend
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
result_counts = result_sim.get_counts(qc)
# Print the results
print("simulation: ", result_sim, result_counts)
if draw_circuit: # draw the circuit
draw(qc)
else: # or show the results
show_results(result_counts)
from qiskit.backends.ibmq import least_busy
import time
# Compile and run on a real device backend
def execute_remotely(qc, draw_circuit=False):
if draw_circuit: # draw the circuit
draw(qc)
try:
# select least busy available device and execute.
least_busy_device = least_busy(IBMQ.backends(simulator=False))
print("Running on current least busy device: ", least_busy_device)
# running the job
job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10)
lapse, interval = 0, 10
while job_exp.status().name != 'DONE':
print('Status @ {} seconds'.format(interval * lapse))
print(job_exp.status())
time.sleep(interval)
lapse += 1
print(job_exp.status())
exp_result = job_exp.result()
result_counts = exp_result.get_counts(qc)
# Show the results
print("experiment: ", exp_result, result_counts)
if not draw_circuit: # show the results
show_results(result_counts)
except:
print("All devices are currently unavailable.")
def new_circuit(size):
# Create a Quantum Register with size qubits
qr = QuantumRegister(size)
# Create a Classical Register with size bits
cr = ClassicalRegister(size)
# Create a Quantum Circuit acting on the qr and cr register
return qr, cr, QuantumCircuit(qr, cr)
qr, cr, circuit = new_circuit(2)
# H gate on qubit 0
circuit.h(qr[0]);
circuit.cx(qr[0], qr[1]);
# measure the qubits
circuit.measure(qr, cr);
# Try both commands:
execute_locally(circuit,draw_circuit=True)
# execute_locally(circuit,draw_circuit=False)
print(circuit.qasm())
# create the circuit
qr, cr, circuit = new_circuit(2)
# H gate on qubit 0
circuit.h(qr[0]);
# X gate on qubit 1
circuit.x(qr[1]);
circuit.cx(qr[0], qr[1]);
# measure the qubits
circuit.measure(qr, cr);
# Try both commands:
execute_locally(circuit,draw_circuit=True)
# execute_locally(circuit,draw_circuit=False)
# create the circuit
qr, cr, circuit = new_circuit(2)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1]);
circuit.h(qr);
circuit.measure(qr, cr)
execute_locally(circuit,draw_circuit=True)
qr, cr, circuit = new_circuit(2)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.h(qr)
circuit.measure(qr, cr);
execute_remotely(circuit)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests basic functionality of the transpile function"""
import copy
import io
import math
import os
import sys
import unittest
from logging import StreamHandler, getLogger
from test import combine # pylint: disable=wrong-import-order
from unittest.mock import patch
import numpy as np
import rustworkx as rx
from ddt import data, ddt, unpack
from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister, pulse, qasm3, qpy
from qiskit.circuit import (
Clbit,
ControlFlowOp,
ForLoopOp,
Gate,
IfElseOp,
Parameter,
Qubit,
Reset,
SwitchCaseOp,
WhileLoopOp,
)
from qiskit.circuit.classical import expr
from qiskit.circuit.delay import Delay
from qiskit.circuit.library import (
CXGate,
CZGate,
HGate,
RXGate,
RYGate,
RZGate,
SXGate,
U1Gate,
U2Gate,
UGate,
XGate,
)
from qiskit.circuit.measure import Measure
from qiskit.compiler import transpile
from qiskit.converters import circuit_to_dag
from qiskit.dagcircuit import DAGOpNode, DAGOutNode
from qiskit.exceptions import QiskitError
from qiskit.providers.backend import BackendV2
from qiskit.providers.fake_provider import (
FakeBoeblingen,
FakeMelbourne,
FakeMumbaiV2,
FakeNairobiV2,
FakeRueschlikon,
FakeSherbrooke,
FakeVigo,
)
from qiskit.providers.options import Options
from qiskit.pulse import InstructionScheduleMap
from qiskit.quantum_info import Operator, random_unitary
from qiskit.test import QiskitTestCase, slow_test
from qiskit.tools import parallel
from qiskit.transpiler import CouplingMap, Layout, PassManager, TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements, GateDirection, VF2PostLayout
from qiskit.transpiler.passmanager_config import PassManagerConfig
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager, level_0_pass_manager
from qiskit.transpiler.target import InstructionProperties, Target
class CustomCX(Gate):
"""Custom CX gate representation."""
def __init__(self):
super().__init__("custom_cx", 2, [])
def _define(self):
self._definition = QuantumCircuit(2)
self._definition.cx(0, 1)
def connected_qubits(physical: int, coupling_map: CouplingMap) -> set:
"""Get the physical qubits that have a connection to this one in the coupling map."""
for component in coupling_map.connected_components():
if physical in (qubits := set(component.graph.nodes())):
return qubits
raise ValueError(f"physical qubit {physical} is not in the coupling map")
@ddt
class TestTranspile(QiskitTestCase):
"""Test transpile function."""
def test_empty_transpilation(self):
"""Test that transpiling an empty list is a no-op. Regression test of gh-7287."""
self.assertEqual(transpile([]), [])
def test_pass_manager_none(self):
"""Test passing the default (None) pass manager to the transpiler.
It should perform the default qiskit flow:
unroll, swap_mapper, cx_direction, cx_cancellation, optimize_1q_gates
and should be equivalent to using tools.compile
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
coupling_map = [[1, 0]]
basis_gates = ["u1", "u2", "u3", "cx", "id"]
backend = BasicAer.get_backend("qasm_simulator")
circuit2 = transpile(
circuit,
backend=backend,
coupling_map=coupling_map,
basis_gates=basis_gates,
)
circuit3 = transpile(
circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates
)
self.assertEqual(circuit2, circuit3)
def test_transpile_basis_gates_no_backend_no_coupling_map(self):
"""Verify transpile() works with no coupling_map or backend."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
basis_gates = ["u1", "u2", "u3", "cx", "id"]
circuit2 = transpile(circuit, basis_gates=basis_gates, optimization_level=0)
resources_after = circuit2.count_ops()
self.assertEqual({"u2": 2, "cx": 4}, resources_after)
def test_transpile_non_adjacent_layout(self):
"""Transpile pipeline can handle manual layout on non-adjacent qubits.
circuit:
.. parsed-literal::
βββββ
qr_0: β€ H ββββ ββββββββββββ -> 1
ββββββββ΄ββ
qr_1: ββββββ€ X ββββ βββββββ -> 2
ββββββββ΄ββ
qr_2: βββββββββββ€ X ββββ ββ -> 3
ββββββββ΄ββ
qr_3: ββββββββββββββββ€ X β -> 5
βββββ
device:
0 - 1 - 2 - 3 - 4 - 5 - 6
| | | | | |
13 - 12 - 11 - 10 - 9 - 8 - 7
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
coupling_map = FakeMelbourne().configuration().coupling_map
basis_gates = FakeMelbourne().configuration().basis_gates
initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]]
new_circuit = transpile(
circuit,
basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)}
for instruction in new_circuit.data:
if isinstance(instruction.operation, CXGate):
self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map)
def test_transpile_qft_grid(self):
"""Transpile pipeline can handle 8-qubit QFT on 14-qubit grid."""
qr = QuantumRegister(8)
circuit = QuantumCircuit(qr)
for i, _ in enumerate(qr):
for j in range(i):
circuit.cp(math.pi / float(2 ** (i - j)), qr[i], qr[j])
circuit.h(qr[i])
coupling_map = FakeMelbourne().configuration().coupling_map
basis_gates = FakeMelbourne().configuration().basis_gates
new_circuit = transpile(circuit, basis_gates=basis_gates, coupling_map=coupling_map)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)}
for instruction in new_circuit.data:
if isinstance(instruction.operation, CXGate):
self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map)
def test_already_mapped_1(self):
"""Circuit not remapped if matches topology.
See: https://github.com/Qiskit/qiskit-terra/issues/342
"""
backend = FakeRueschlikon()
coupling_map = backend.configuration().coupling_map
basis_gates = backend.configuration().basis_gates
qr = QuantumRegister(16, "qr")
cr = ClassicalRegister(16, "cr")
qc = QuantumCircuit(qr, cr)
qc.cx(qr[3], qr[14])
qc.cx(qr[5], qr[4])
qc.h(qr[9])
qc.cx(qr[9], qr[8])
qc.x(qr[11])
qc.cx(qr[3], qr[4])
qc.cx(qr[12], qr[11])
qc.cx(qr[13], qr[4])
qc.measure(qr, cr)
new_qc = transpile(
qc,
coupling_map=coupling_map,
basis_gates=basis_gates,
initial_layout=Layout.generate_trivial_layout(qr),
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)}
cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"]
cx_qubits_physical = [
[qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits
]
self.assertEqual(
sorted(cx_qubits_physical), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]]
)
def test_already_mapped_via_layout(self):
"""Test that a manual layout that satisfies a coupling map does not get altered.
See: https://github.com/Qiskit/qiskit-terra/issues/2036
circuit:
.. parsed-literal::
βββββ βββββ β βββ
qn_0: β€ H ββββ βββββββββββββ βββ€ H βββββ€Mββββ -> 9
βββββ β β βββββ β ββ₯β
qn_1: ββββββββΌβββββββββββββΌββββββββββββ«ββββ -> 6
β β β β
qn_2: ββββββββΌβββββββββββββΌββββββββββββ«ββββ -> 5
β β β β
qn_3: ββββββββΌβββββββββββββΌββββββββββββ«ββββ -> 0
β β β β
qn_4: ββββββββΌβββββββββββββΌββββββββββββ«ββββ -> 1
ββββββββ΄βββββββββββββ΄βββββββ β β βββ
qn_5: β€ H ββ€ X ββ€ P(2) ββ€ X ββ€ H ββββββ«ββ€Mβ -> 4
ββββββββββββββββββββββββββββ β β ββ₯β
cn: 2/βββββββββββββββββββββββββββββββββ©βββ©β
0 1
device:
0 -- 1 -- 2 -- 3 -- 4
| |
5 -- 6 -- 7 -- 8 -- 9
| |
10 - 11 - 12 - 13 - 14
| |
15 - 16 - 17 - 18 - 19
"""
basis_gates = ["u1", "u2", "u3", "cx", "id"]
coupling_map = [
[0, 1],
[0, 5],
[1, 0],
[1, 2],
[2, 1],
[2, 3],
[3, 2],
[3, 4],
[4, 3],
[4, 9],
[5, 0],
[5, 6],
[5, 10],
[6, 5],
[6, 7],
[7, 6],
[7, 8],
[7, 12],
[8, 7],
[8, 9],
[9, 4],
[9, 8],
[9, 14],
[10, 5],
[10, 11],
[10, 15],
[11, 10],
[11, 12],
[12, 7],
[12, 11],
[12, 13],
[13, 12],
[13, 14],
[14, 9],
[14, 13],
[14, 19],
[15, 10],
[15, 16],
[16, 15],
[16, 17],
[17, 16],
[17, 18],
[18, 17],
[18, 19],
[19, 14],
[19, 18],
]
q = QuantumRegister(6, name="qn")
c = ClassicalRegister(2, name="cn")
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[5])
qc.cx(q[0], q[5])
qc.p(2, q[5])
qc.cx(q[0], q[5])
qc.h(q[0])
qc.h(q[5])
qc.barrier(q)
qc.measure(q[0], c[0])
qc.measure(q[5], c[1])
initial_layout = [
q[3],
q[4],
None,
None,
q[5],
q[2],
q[1],
None,
None,
q[0],
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
]
new_qc = transpile(
qc, coupling_map=coupling_map, basis_gates=basis_gates, initial_layout=initial_layout
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)}
cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"]
cx_qubits_physical = [
[qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits
]
self.assertEqual(sorted(cx_qubits_physical), [[9, 4], [9, 4]])
def test_transpile_bell(self):
"""Test Transpile Bell.
If all correct some should exists.
"""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
circuits = transpile(qc, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpile_one(self):
"""Test transpile a single circuit.
Check that the top-level `transpile` function returns
a single circuit."""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
circuit = transpile(qc, backend)
self.assertIsInstance(circuit, QuantumCircuit)
def test_transpile_two(self):
"""Test transpile two circuits.
Check that the transpiler returns a list of two circuits.
"""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
qubit_reg2 = QuantumRegister(2)
clbit_reg2 = ClassicalRegister(2)
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
qc_extra = QuantumCircuit(qubit_reg, qubit_reg2, clbit_reg, clbit_reg2, name="extra")
qc_extra.measure(qubit_reg, clbit_reg)
circuits = transpile([qc, qc_extra], backend)
self.assertIsInstance(circuits, list)
self.assertEqual(len(circuits), 2)
for circuit in circuits:
self.assertIsInstance(circuit, QuantumCircuit)
def test_transpile_singleton(self):
"""Test transpile a single-element list with a circuit.
Check that `transpile` returns a single-element list.
See https://github.com/Qiskit/qiskit-terra/issues/5260
"""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
circuits = transpile([qc], backend)
self.assertIsInstance(circuits, list)
self.assertEqual(len(circuits), 1)
self.assertIsInstance(circuits[0], QuantumCircuit)
def test_mapping_correction(self):
"""Test mapping works in previous failed case."""
backend = FakeRueschlikon()
qr = QuantumRegister(name="qr", size=11)
cr = ClassicalRegister(name="qc", size=11)
circuit = QuantumCircuit(qr, cr)
circuit.u(1.564784764685993, -1.2378965763410095, 2.9746763177861713, qr[3])
circuit.u(1.2269835563676523, 1.1932982847014162, -1.5597357740824318, qr[5])
circuit.cx(qr[5], qr[3])
circuit.p(0.856768317675967, qr[3])
circuit.u(-3.3911273825190915, 0.0, 0.0, qr[5])
circuit.cx(qr[3], qr[5])
circuit.u(2.159209321625547, 0.0, 0.0, qr[5])
circuit.cx(qr[5], qr[3])
circuit.u(0.30949966910232335, 1.1706201763833217, 1.738408691990081, qr[3])
circuit.u(1.9630571407274755, -0.6818742967975088, 1.8336534616728195, qr[5])
circuit.u(1.330181833806101, 0.6003162754946363, -3.181264980452862, qr[7])
circuit.u(0.4885914820775024, 3.133297443244865, -2.794457469189904, qr[8])
circuit.cx(qr[8], qr[7])
circuit.p(2.2196187596178616, qr[7])
circuit.u(-3.152367609631023, 0.0, 0.0, qr[8])
circuit.cx(qr[7], qr[8])
circuit.u(1.2646005789809263, 0.0, 0.0, qr[8])
circuit.cx(qr[8], qr[7])
circuit.u(0.7517780502091939, 1.2828514296564781, 1.6781179605443775, qr[7])
circuit.u(0.9267400575390405, 2.0526277839695153, 2.034202361069533, qr[8])
circuit.u(2.550304293455634, 3.8250017126569698, -2.1351609599720054, qr[1])
circuit.u(0.9566260876600556, -1.1147561503064538, 2.0571590492298797, qr[4])
circuit.cx(qr[4], qr[1])
circuit.p(2.1899329069137394, qr[1])
circuit.u(-1.8371715243173294, 0.0, 0.0, qr[4])
circuit.cx(qr[1], qr[4])
circuit.u(0.4717053496327104, 0.0, 0.0, qr[4])
circuit.cx(qr[4], qr[1])
circuit.u(2.3167620677708145, -1.2337330260253256, -0.5671322899563955, qr[1])
circuit.u(1.0468499525240678, 0.8680750644809365, -1.4083720073192485, qr[4])
circuit.u(2.4204244021892807, -2.211701932616922, 3.8297006565735883, qr[10])
circuit.u(0.36660280497727255, 3.273119149343493, -1.8003362351299388, qr[6])
circuit.cx(qr[6], qr[10])
circuit.p(1.067395863586385, qr[10])
circuit.u(-0.7044917541291232, 0.0, 0.0, qr[6])
circuit.cx(qr[10], qr[6])
circuit.u(2.1830003849921527, 0.0, 0.0, qr[6])
circuit.cx(qr[6], qr[10])
circuit.u(2.1538343756723917, 2.2653381826084606, -3.550087952059485, qr[10])
circuit.u(1.307627685019188, -0.44686656993522567, -2.3238098554327418, qr[6])
circuit.u(2.2046797998462906, 0.9732961754855436, 1.8527865921467421, qr[9])
circuit.u(2.1665254613904126, -1.281337664694577, -1.2424905413631209, qr[0])
circuit.cx(qr[0], qr[9])
circuit.p(2.6209599970201007, qr[9])
circuit.u(0.04680566321901303, 0.0, 0.0, qr[0])
circuit.cx(qr[9], qr[0])
circuit.u(1.7728411151289603, 0.0, 0.0, qr[0])
circuit.cx(qr[0], qr[9])
circuit.u(2.4866395967434443, 0.48684511243566697, -3.0069186877854728, qr[9])
circuit.u(1.7369112924273789, -4.239660866163805, 1.0623389015296005, qr[0])
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits = transpile(circuit, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpiler_layout_from_intlist(self):
"""A list of ints gives layout to correctly map circuit.
virtual physical
q1_0 - 4 ---[H]---
q2_0 - 5
q2_1 - 6 ---[H]---
q3_0 - 8
q3_1 - 9
q3_2 - 10 ---[H]---
"""
qr1 = QuantumRegister(1, "qr1")
qr2 = QuantumRegister(2, "qr2")
qr3 = QuantumRegister(3, "qr3")
qc = QuantumCircuit(qr1, qr2, qr3)
qc.h(qr1[0])
qc.h(qr2[1])
qc.h(qr3[2])
layout = [4, 5, 6, 8, 9, 10]
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
new_circ = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circ.qubits)}
mapped_qubits = []
for instruction in new_circ.data:
mapped_qubits.append(qubit_indices[instruction.qubits[0]])
self.assertEqual(mapped_qubits, [4, 6, 10])
def test_mapping_multi_qreg(self):
"""Test mapping works for multiple qregs."""
backend = FakeRueschlikon()
qr = QuantumRegister(3, name="qr")
qr2 = QuantumRegister(1, name="qr2")
qr3 = QuantumRegister(4, name="qr3")
cr = ClassicalRegister(3, name="cr")
qc = QuantumCircuit(qr, qr2, qr3, cr)
qc.h(qr[0])
qc.cx(qr[0], qr2[0])
qc.cx(qr[1], qr3[2])
qc.measure(qr, cr)
circuits = transpile(qc, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpile_circuits_diff_registers(self):
"""Transpile list of circuits with different qreg names."""
backend = FakeRueschlikon()
circuits = []
for _ in range(2):
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.measure(qr, cr)
circuits.append(circuit)
circuits = transpile(circuits, backend)
self.assertIsInstance(circuits[0], QuantumCircuit)
def test_wrong_initial_layout(self):
"""Test transpile with a bad initial layout."""
backend = FakeMelbourne()
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
bad_initial_layout = [
QuantumRegister(3, "q")[0],
QuantumRegister(3, "q")[1],
QuantumRegister(3, "q")[2],
]
with self.assertRaises(TranspilerError):
transpile(qc, backend, initial_layout=bad_initial_layout)
def test_parameterized_circuit_for_simulator(self):
"""Verify that a parameterized circuit can be transpiled for a simulator backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.rz(theta, qr[0])
transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator"))
expected_qc = QuantumCircuit(qr)
expected_qc.append(RZGate(theta), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameterized_circuit_for_device(self):
"""Verify that a parameterized circuit can be transpiled for a device backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.rz(theta, qr[0])
transpiled_qc = transpile(
qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr)
)
qr = QuantumRegister(14, "q")
expected_qc = QuantumCircuit(qr, global_phase=-1 * theta / 2.0)
expected_qc.append(U1Gate(theta), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameter_expression_circuit_for_simulator(self):
"""Verify that a circuit including expressions of parameters can be
transpiled for a simulator backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
square = theta * theta
qc.rz(square, qr[0])
transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator"))
expected_qc = QuantumCircuit(qr)
expected_qc.append(RZGate(square), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameter_expression_circuit_for_device(self):
"""Verify that a circuit including expressions of parameters can be
transpiled for a device backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
square = theta * theta
qc.rz(square, qr[0])
transpiled_qc = transpile(
qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr)
)
qr = QuantumRegister(14, "q")
expected_qc = QuantumCircuit(qr, global_phase=-1 * square / 2.0)
expected_qc.append(U1Gate(square), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_final_measurement_barrier_for_devices(self):
"""Verify BarrierBeforeFinalMeasurements pass is called in default pipeline for devices."""
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm"))
layout = Layout.generate_trivial_layout(*circ.qregs)
orig_pass = BarrierBeforeFinalMeasurements()
with patch.object(BarrierBeforeFinalMeasurements, "run", wraps=orig_pass.run) as mock_pass:
transpile(
circ,
coupling_map=FakeRueschlikon().configuration().coupling_map,
initial_layout=layout,
)
self.assertTrue(mock_pass.called)
def test_do_not_run_gatedirection_with_symmetric_cm(self):
"""When the coupling map is symmetric, do not run GateDirection."""
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm"))
layout = Layout.generate_trivial_layout(*circ.qregs)
coupling_map = []
for node1, node2 in FakeRueschlikon().configuration().coupling_map:
coupling_map.append([node1, node2])
coupling_map.append([node2, node1])
orig_pass = GateDirection(CouplingMap(coupling_map))
with patch.object(GateDirection, "run", wraps=orig_pass.run) as mock_pass:
transpile(circ, coupling_map=coupling_map, initial_layout=layout)
self.assertFalse(mock_pass.called)
def test_optimize_to_nothing(self):
"""Optimize gates up to fixed point in the default pipeline
See https://github.com/Qiskit/qiskit-terra/issues/2035
"""
# βββββ βββββββββββββββ βββββ
# q0_0: β€ H ββββ βββ€ X ββ€ Y ββ€ Z ββββ βββ€ H ββββ βββββ ββ
# ββββββββ΄ββββββββββββββββββββ΄ββββββββββ΄βββββ΄ββ
# q0_1: ββββββ€ X βββββββββββββββββ€ X βββββββ€ X ββ€ X β
# βββββ βββββ ββββββββββ
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.x(qr[0])
circ.y(qr[0])
circ.z(qr[0])
circ.cx(qr[0], qr[1])
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.cx(qr[0], qr[1])
after = transpile(circ, coupling_map=[[0, 1], [1, 0]], basis_gates=["u3", "u2", "u1", "cx"])
expected = QuantumCircuit(QuantumRegister(2, "q"), global_phase=-np.pi / 2)
msg = f"after:\n{after}\nexpected:\n{expected}"
self.assertEqual(after, expected, msg=msg)
def test_pass_manager_empty(self):
"""Test passing an empty PassManager() to the transpiler.
It should perform no transformations on the circuit.
"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
resources_before = circuit.count_ops()
pass_manager = PassManager()
out_circuit = pass_manager.run(circuit)
resources_after = out_circuit.count_ops()
self.assertDictEqual(resources_before, resources_after)
def test_move_measurements(self):
"""Measurements applied AFTER swap mapping."""
backend = FakeRueschlikon()
cmap = backend.configuration().coupling_map
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "move_measurements.qasm"))
lay = [0, 1, 15, 2, 14, 3, 13, 4, 12, 5, 11, 6]
out = transpile(circ, initial_layout=lay, coupling_map=cmap, routing_method="stochastic")
out_dag = circuit_to_dag(out)
meas_nodes = out_dag.named_nodes("measure")
for meas_node in meas_nodes:
is_last_measure = all(
isinstance(after_measure, DAGOutNode)
for after_measure in out_dag.quantum_successors(meas_node)
)
self.assertTrue(is_last_measure)
@data(0, 1, 2, 3)
def test_init_resets_kept_preset_passmanagers(self, optimization_level):
"""Test initial resets kept at all preset transpilation levels"""
num_qubits = 5
qc = QuantumCircuit(num_qubits)
qc.reset(range(num_qubits))
num_resets = transpile(qc, optimization_level=optimization_level).count_ops()["reset"]
self.assertEqual(num_resets, num_qubits)
@data(0, 1, 2, 3)
def test_initialize_reset_is_not_removed(self, optimization_level):
"""The reset in front of initializer should NOT be removed at beginning"""
qr = QuantumRegister(1, "qr")
qc = QuantumCircuit(qr)
qc.initialize([1.0 / math.sqrt(2), 1.0 / math.sqrt(2)], [qr[0]])
qc.initialize([1.0 / math.sqrt(2), -1.0 / math.sqrt(2)], [qr[0]])
after = transpile(qc, basis_gates=["reset", "u3"], optimization_level=optimization_level)
self.assertEqual(after.count_ops()["reset"], 2, msg=f"{after}\n does not have 2 resets.")
def test_initialize_FakeMelbourne(self):
"""Test that the zero-state resets are remove in a device not supporting them."""
desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)]
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2]])
out = transpile(qc, backend=FakeMelbourne())
out_dag = circuit_to_dag(out)
reset_nodes = out_dag.named_nodes("reset")
self.assertEqual(len(reset_nodes), 3)
def test_non_standard_basis(self):
"""Test a transpilation with a non-standard basis"""
qr1 = QuantumRegister(1, "q1")
qr2 = QuantumRegister(2, "q2")
qr3 = QuantumRegister(3, "q3")
qc = QuantumCircuit(qr1, qr2, qr3)
qc.h(qr1[0])
qc.h(qr2[1])
qc.h(qr3[2])
layout = [4, 5, 6, 8, 9, 10]
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
circuit = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["h"], initial_layout=layout
)
dag_circuit = circuit_to_dag(circuit)
resources_after = dag_circuit.count_ops()
self.assertEqual({"h": 3}, resources_after)
def test_hadamard_to_rot_gates(self):
"""Test a transpilation from H to Rx, Ry gates"""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.h(0)
expected = QuantumCircuit(qr, global_phase=np.pi / 2)
expected.append(RYGate(theta=np.pi / 2), [0])
expected.append(RXGate(theta=np.pi), [0])
circuit = transpile(qc, basis_gates=["rx", "ry"], optimization_level=0)
self.assertEqual(circuit, expected)
def test_basis_subset(self):
"""Test a transpilation with a basis subset of the standard basis"""
qr = QuantumRegister(1, "q1")
qc = QuantumCircuit(qr)
qc.h(qr[0])
qc.x(qr[0])
qc.t(qr[0])
layout = [4]
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
circuit = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["u3"], initial_layout=layout
)
dag_circuit = circuit_to_dag(circuit)
resources_after = dag_circuit.count_ops()
self.assertEqual({"u3": 1}, resources_after)
def test_check_circuit_width(self):
"""Verify transpilation of circuit with virtual qubits greater than
physical qubits raises error"""
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
qc = QuantumCircuit(15, 15)
with self.assertRaises(TranspilerError):
transpile(qc, coupling_map=cmap)
@data(0, 1, 2, 3)
def test_ccx_routing_method_none(self, optimization_level):
"""CCX without routing method."""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.cx(1, 2)
out = transpile(
qc,
routing_method="none",
basis_gates=["u", "cx"],
initial_layout=[0, 1, 2],
seed_transpiler=0,
coupling_map=[[0, 1], [1, 2]],
optimization_level=optimization_level,
)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_ccx_routing_method_none_failed(self, optimization_level):
"""CCX without routing method cannot be routed."""
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
with self.assertRaises(TranspilerError):
transpile(
qc,
routing_method="none",
basis_gates=["u", "cx"],
initial_layout=[0, 1, 2],
seed_transpiler=0,
coupling_map=[[0, 1], [1, 2]],
optimization_level=optimization_level,
)
@data(0, 1, 2, 3)
def test_ms_unrolls_to_cx(self, optimization_level):
"""Verify a Rx,Ry,Rxx circuit transpile to a U3,CX target."""
qc = QuantumCircuit(2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
out = transpile(qc, basis_gates=["u3", "cx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_ms_can_target_ms(self, optimization_level):
"""Verify a Rx,Ry,Rxx circuit can transpile to an Rx,Ry,Rxx target."""
qc = QuantumCircuit(2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_cx_can_target_ms(self, optimization_level):
"""Verify a U3,CX circuit can transpiler to a Rx,Ry,Rxx target."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.rz(math.pi / 4, [0, 1])
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_measure_doesnt_unroll_ms(self, optimization_level):
"""Verify a measure doesn't cause an Rx,Ry,Rxx circuit to unroll to U3,CX."""
qc = QuantumCircuit(2, 2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
qc.measure([0, 1], [0, 1])
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertEqual(qc, out)
@data(
["cx", "u3"],
["cz", "u3"],
["cz", "rx", "rz"],
["rxx", "rx", "ry"],
["iswap", "rx", "rz"],
)
def test_block_collection_runs_for_non_cx_bases(self, basis_gates):
"""Verify block collection is run when a single two qubit gate is in the basis."""
twoq_gate, *_ = basis_gates
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.cx(1, 0)
qc.cx(0, 1)
qc.cx(0, 1)
out = transpile(qc, basis_gates=basis_gates, optimization_level=3)
self.assertLessEqual(out.count_ops()[twoq_gate], 2)
@unpack
@data(
(["u3", "cx"], {"u3": 1, "cx": 1}),
(["rx", "rz", "iswap"], {"rx": 6, "rz": 12, "iswap": 2}),
(["rx", "ry", "rxx"], {"rx": 6, "ry": 5, "rxx": 1}),
)
def test_block_collection_reduces_1q_gate(self, basis_gates, gate_counts):
"""For synthesis to non-U3 bases, verify we minimize 1q gates."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
out = transpile(qc, basis_gates=basis_gates, optimization_level=3)
self.assertTrue(Operator(out).equiv(qc))
self.assertTrue(set(out.count_ops()).issubset(basis_gates))
for basis_gate in basis_gates:
self.assertLessEqual(out.count_ops()[basis_gate], gate_counts[basis_gate])
@combine(
optimization_level=[0, 1, 2, 3],
basis_gates=[
["u3", "cx"],
["rx", "rz", "iswap"],
["rx", "ry", "rxx"],
],
)
def test_translation_method_synthesis(self, optimization_level, basis_gates):
"""Verify translation_method='synthesis' gets to the basis."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
out = transpile(
qc,
translation_method="synthesis",
basis_gates=basis_gates,
optimization_level=optimization_level,
)
self.assertTrue(Operator(out).equiv(qc))
self.assertTrue(set(out.count_ops()).issubset(basis_gates))
def test_transpiled_custom_gates_calibration(self):
"""Test if transpiled calibrations is equal to custom gates circuit calibrations."""
custom_180 = Gate("mycustom", 1, [3.14])
custom_90 = Gate("mycustom", 1, [1.57])
circ = QuantumCircuit(2)
circ.append(custom_180, [0])
circ.append(custom_90, [1])
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
with pulse.build() as q1_y90:
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1))
# Add calibration
circ.add_calibration(custom_180, [0], q0_x180)
circ.add_calibration(custom_90, [1], q1_y90)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
layout_method="trivial",
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
self.assertEqual(list(transpiled_circuit.count_ops().keys()), ["mycustom"])
self.assertEqual(list(transpiled_circuit.count_ops().values()), [2])
def test_transpiled_basis_gates_calibrations(self):
"""Test if the transpiled calibrations is equal to basis gates circuit calibrations."""
circ = QuantumCircuit(2)
circ.h(0)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration("h", [0], q0_x180)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
def test_transpile_calibrated_custom_gate_on_diff_qubit(self):
"""Test if the custom, non calibrated gate raises QiskitError."""
custom_180 = Gate("mycustom", 1, [3.14])
circ = QuantumCircuit(2)
circ.append(custom_180, [0])
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration(custom_180, [1], q0_x180)
backend = FakeBoeblingen()
with self.assertRaises(QiskitError):
transpile(circ, backend=backend, layout_method="trivial")
def test_transpile_calibrated_nonbasis_gate_on_diff_qubit(self):
"""Test if the non-basis gates are transpiled if they are on different qubit that
is not calibrated."""
circ = QuantumCircuit(2)
circ.h(0)
circ.h(1)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration("h", [1], q0_x180)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
self.assertEqual(set(transpiled_circuit.count_ops().keys()), {"u2", "h"})
def test_transpile_subset_of_calibrated_gates(self):
"""Test transpiling a circuit with both basis gate (not-calibrated) and
a calibrated gate on different qubits."""
x_180 = Gate("mycustom", 1, [3.14])
circ = QuantumCircuit(2)
circ.h(0)
circ.append(x_180, [0])
circ.h(1)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
circ.add_calibration(x_180, [0], q0_x180)
circ.add_calibration("h", [1], q0_x180) # 'h' is calibrated on qubit 1
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"u2", "mycustom", "h"})
def test_parameterized_calibrations_transpile(self):
"""Check that gates can be matched to their calibrations before and after parameter
assignment."""
tau = Parameter("tau")
circ = QuantumCircuit(3, 3)
circ.append(Gate("rxt", 1, [2 * 3.14 * tau]), [0])
def q0_rxt(tau):
with pulse.build() as q0_rxt:
pulse.play(pulse.library.Gaussian(20, 0.4 * tau, 3.0), pulse.DriveChannel(0))
return q0_rxt
circ.add_calibration("rxt", [0], q0_rxt(tau), [2 * 3.14 * tau])
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"})
circ = circ.assign_parameters({tau: 1})
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"})
def test_inst_durations_from_calibrations(self):
"""Test that circuit calibrations can be used instead of explicitly
supplying inst_durations.
"""
qc = QuantumCircuit(2)
qc.append(Gate("custom", 1, []), [0])
with pulse.build() as cal:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
qc.add_calibration("custom", [0], cal)
out = transpile(qc, scheduling_method="alap")
self.assertEqual(out.duration, cal.duration)
@data(0, 1, 2, 3)
def test_multiqubit_gates_calibrations(self, opt_level):
"""Test multiqubit gate > 2q with calibrations works
Adapted from issue description in https://github.com/Qiskit/qiskit-terra/issues/6572
"""
circ = QuantumCircuit(5)
custom_gate = Gate("my_custom_gate", 5, [])
circ.append(custom_gate, [0, 1, 2, 3, 4])
circ.measure_all()
backend = FakeBoeblingen()
with pulse.build(backend, name="custom") as my_schedule:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(1)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(2)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(3)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(4)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(1)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(2)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(3)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(4)
)
circ.add_calibration("my_custom_gate", [0, 1, 2, 3, 4], my_schedule, [])
trans_circ = transpile(circ, backend, optimization_level=opt_level, layout_method="trivial")
self.assertEqual({"measure": 5, "my_custom_gate": 1, "barrier": 1}, trans_circ.count_ops())
@data(0, 1, 2, 3)
def test_circuit_with_delay(self, optimization_level):
"""Verify a circuit with delay can transpile to a scheduled circuit."""
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500, 1)
qc.cx(0, 1)
out = transpile(
qc,
scheduling_method="alap",
basis_gates=["h", "cx"],
instruction_durations=[("h", 0, 200), ("cx", [0, 1], 700)],
optimization_level=optimization_level,
)
self.assertEqual(out.duration, 1200)
def test_delay_converts_to_dt(self):
"""Test that a delay instruction is converted to units of dt given a backend."""
qc = QuantumCircuit(2)
qc.delay(1000, [0], unit="us")
backend = FakeRueschlikon()
backend.configuration().dt = 0.5e-6
out = transpile([qc, qc], backend)
self.assertEqual(out[0].data[0].operation.unit, "dt")
self.assertEqual(out[1].data[0].operation.unit, "dt")
out = transpile(qc, dt=1e-9)
self.assertEqual(out.data[0].operation.unit, "dt")
def test_scheduling_backend_v2(self):
"""Test that scheduling method works with Backendv2."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = FakeMumbaiV2()
out = transpile([qc, qc], backend, scheduling_method="alap")
self.assertIn("delay", out[0].count_ops())
self.assertIn("delay", out[1].count_ops())
@data(1, 2, 3)
def test_no_infinite_loop(self, optimization_level):
"""Verify circuit cost always descends and optimization does not flip flop indefinitely."""
qc = QuantumCircuit(1)
qc.ry(0.2, 0)
out = transpile(
qc, basis_gates=["id", "p", "sx", "cx"], optimization_level=optimization_level
)
# Expect a -pi/2 global phase for the U3 to RZ/SX conversion, and
# a -0.5 * theta phase for RZ to P twice, once at theta, and once at 3 pi
# for the second and third RZ gates in the U3 decomposition.
expected = QuantumCircuit(
1, global_phase=-np.pi / 2 - 0.5 * (-0.2 + np.pi) - 0.5 * 3 * np.pi
)
expected.p(-np.pi, 0)
expected.sx(0)
expected.p(np.pi - 0.2, 0)
expected.sx(0)
error_message = (
f"\nOutput circuit:\n{out!s}\n{Operator(out).data}\n"
f"Expected circuit:\n{expected!s}\n{Operator(expected).data}"
)
self.assertEqual(out, expected, error_message)
@data(0, 1, 2, 3)
def test_transpile_preserves_circuit_metadata(self, optimization_level):
"""Verify that transpile preserves circuit metadata in the output."""
circuit = QuantumCircuit(2, metadata={"experiment_id": "1234", "execution_number": 4})
circuit.h(0)
circuit.cx(0, 1)
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
res = transpile(
circuit,
basis_gates=["id", "p", "sx", "cx"],
coupling_map=cmap,
optimization_level=optimization_level,
)
self.assertEqual(circuit.metadata, res.metadata)
@data(0, 1, 2, 3)
def test_transpile_optional_registers(self, optimization_level):
"""Verify transpile accepts circuits without registers end-to-end."""
qubits = [Qubit() for _ in range(3)]
clbits = [Clbit() for _ in range(3)]
qc = QuantumCircuit(qubits, clbits)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 2)
qc.measure(qubits, clbits)
out = transpile(qc, FakeBoeblingen(), optimization_level=optimization_level)
self.assertEqual(len(out.qubits), FakeBoeblingen().configuration().num_qubits)
self.assertEqual(len(out.clbits), len(clbits))
@data(0, 1, 2, 3)
def test_translate_ecr_basis(self, optimization_level):
"""Verify that rewriting in ECR basis is efficient."""
circuit = QuantumCircuit(2)
circuit.append(random_unitary(4, seed=1), [0, 1])
circuit.barrier()
circuit.cx(0, 1)
circuit.barrier()
circuit.swap(0, 1)
circuit.barrier()
circuit.iswap(0, 1)
res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=optimization_level)
self.assertEqual(res.count_ops()["ecr"], 9)
self.assertTrue(Operator(res).equiv(circuit))
def test_optimize_ecr_basis(self):
"""Test highest optimization level can optimize over ECR."""
circuit = QuantumCircuit(2)
circuit.swap(1, 0)
circuit.iswap(0, 1)
res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=3)
self.assertEqual(res.count_ops()["ecr"], 1)
self.assertTrue(Operator(res).equiv(circuit))
def test_approximation_degree_invalid(self):
"""Test invalid approximation degree raises."""
circuit = QuantumCircuit(2)
circuit.swap(0, 1)
with self.assertRaises(QiskitError):
transpile(circuit, basis_gates=["u", "cz"], approximation_degree=1.1)
def test_approximation_degree(self):
"""Test more approximation gives lower-cost circuit."""
circuit = QuantumCircuit(2)
circuit.swap(0, 1)
circuit.h(0)
circ_10 = transpile(
circuit,
basis_gates=["u", "cx"],
translation_method="synthesis",
approximation_degree=0.1,
)
circ_90 = transpile(
circuit,
basis_gates=["u", "cx"],
translation_method="synthesis",
approximation_degree=0.9,
)
self.assertLess(circ_10.depth(), circ_90.depth())
@data(0, 1, 2, 3)
def test_synthesis_translation_method_with_single_qubit_gates(self, optimization_level):
"""Test that synthesis basis translation works for solely 1q circuit"""
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.h(2)
res = transpile(
qc,
basis_gates=["id", "rz", "x", "sx", "cx"],
translation_method="synthesis",
optimization_level=optimization_level,
)
expected = QuantumCircuit(3, global_phase=3 * np.pi / 4)
expected.rz(np.pi / 2, 0)
expected.rz(np.pi / 2, 1)
expected.rz(np.pi / 2, 2)
expected.sx(0)
expected.sx(1)
expected.sx(2)
expected.rz(np.pi / 2, 0)
expected.rz(np.pi / 2, 1)
expected.rz(np.pi / 2, 2)
self.assertEqual(res, expected)
@data(0, 1, 2, 3)
def test_synthesis_translation_method_with_gates_outside_basis(self, optimization_level):
"""Test that synthesis translation works for circuits with single gates outside bassis"""
qc = QuantumCircuit(2)
qc.swap(0, 1)
res = transpile(
qc,
basis_gates=["id", "rz", "x", "sx", "cx"],
translation_method="synthesis",
optimization_level=optimization_level,
)
if optimization_level != 3:
self.assertTrue(Operator(qc).equiv(res))
self.assertNotIn("swap", res.count_ops())
else:
# Optimization level 3 eliminates the pointless swap
self.assertEqual(res, QuantumCircuit(2))
@data(0, 1, 2, 3)
def test_target_ideal_gates(self, opt_level):
"""Test that transpile() with a custom ideal sim target works."""
theta = Parameter("ΞΈ")
phi = Parameter("Ο")
lam = Parameter("Ξ»")
target = Target(num_qubits=2)
target.add_instruction(UGate(theta, phi, lam), {(0,): None, (1,): None})
target.add_instruction(CXGate(), {(0, 1): None})
target.add_instruction(Measure(), {(0,): None, (1,): None})
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
result = transpile(qc, target=target, optimization_level=opt_level)
self.assertEqual(Operator.from_circuit(result), Operator.from_circuit(qc))
@data(0, 1, 2, 3)
def test_transpile_with_custom_control_flow_target(self, opt_level):
"""Test transpile() with a target and constrol flow ops."""
target = FakeMumbaiV2().target
target.add_instruction(ForLoopOp, name="for_loop")
target.add_instruction(WhileLoopOp, name="while_loop")
target.add_instruction(IfElseOp, name="if_else")
target.add_instruction(SwitchCaseOp, name="switch_case")
circuit = QuantumCircuit(6, 1)
circuit.h(0)
circuit.measure(0, 0)
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with circuit.for_loop((1,)):
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with else_:
circuit.cx(3, 4)
circuit.cz(3, 5)
circuit.append(CustomCX(), [4, 5], [])
with circuit.while_loop((circuit.clbits[0], True)):
circuit.cx(3, 4)
circuit.cz(3, 5)
circuit.append(CustomCX(), [4, 5], [])
with circuit.switch(circuit.cregs[0]) as case_:
with case_(0):
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with case_(1):
circuit.cx(1, 2)
circuit.cz(1, 3)
circuit.append(CustomCX(), [2, 3], [])
transpiled = transpile(
circuit, optimization_level=opt_level, target=target, seed_transpiler=12434
)
# Tests of the complete validity of a circuit are mostly done at the indiviual pass level;
# here we're just checking that various passes do appear to have run.
self.assertIsInstance(transpiled, QuantumCircuit)
# Assert layout ran.
self.assertIsNot(getattr(transpiled, "_layout", None), None)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
# Assert unrolling ran.
self.assertNotIsInstance(instruction.operation, CustomCX)
# Assert translation ran.
self.assertNotIsInstance(instruction.operation, CZGate)
# Assert routing ran.
_visit_block(
transpiled,
qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)},
)
@data(1, 2, 3)
def test_transpile_identity_circuit_no_target(self, opt_level):
"""Test circuit equivalent to identity is optimized away for all optimization levels >0.
Reproduce taken from https://github.com/Qiskit/qiskit-terra/issues/9217
"""
qr1 = QuantumRegister(3, "state")
qr2 = QuantumRegister(2, "ancilla")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr1, qr2, cr)
qc.h(qr1[0])
qc.cx(qr1[0], qr1[1])
qc.cx(qr1[1], qr1[2])
qc.cx(qr1[1], qr1[2])
qc.cx(qr1[0], qr1[1])
qc.h(qr1[0])
empty_qc = QuantumCircuit(qr1, qr2, cr)
result = transpile(qc, optimization_level=opt_level)
self.assertEqual(empty_qc, result)
@data(0, 1, 2, 3)
def test_initial_layout_with_loose_qubits(self, opt_level):
"""Regression test of gh-10125."""
qc = QuantumCircuit([Qubit(), Qubit()])
qc.cx(0, 1)
transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level)
self.assertIsNotNone(transpiled.layout)
self.assertEqual(
transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]})
)
@data(0, 1, 2, 3)
def test_initial_layout_with_overlapping_qubits(self, opt_level):
"""Regression test of gh-10125."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(bits=qr1[:])
qc = QuantumCircuit(qr1, qr2)
qc.cx(0, 1)
transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level)
self.assertIsNotNone(transpiled.layout)
self.assertEqual(
transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]})
)
@combine(opt_level=[0, 1, 2, 3], basis=[["rz", "x"], ["rx", "z"], ["rz", "y"], ["ry", "x"]])
def test_paulis_to_constrained_1q_basis(self, opt_level, basis):
"""Test that Pauli-gate circuits can be transpiled to constrained 1q bases that do not
contain any root-Pauli gates."""
qc = QuantumCircuit(1)
qc.x(0)
qc.barrier()
qc.y(0)
qc.barrier()
qc.z(0)
transpiled = transpile(qc, basis_gates=basis, optimization_level=opt_level)
self.assertGreaterEqual(set(basis) | {"barrier"}, transpiled.count_ops().keys())
self.assertEqual(Operator(qc), Operator(transpiled))
@ddt
class TestPostTranspileIntegration(QiskitTestCase):
"""Test that the output of `transpile` is usable in various other integration contexts."""
def _regular_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
base.cz(1, 4)
base.cx(1, 5)
base.measure(1, 1)
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4]).c_if(base.cregs[0], 3)
base.ry(a, 4)
base.measure(4, 2)
return base
def _control_flow_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
with base.if_test((base.cregs[0], 1)) as else_:
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
with else_:
base.cz(1, 4)
with base.for_loop((1, 2)):
base.cx(1, 5)
base.measure(2, 2)
with base.while_loop((2, False)):
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4])
base.ry(a, 4)
base.measure(4, 2)
with base.switch(base.cregs[0]) as case_:
with case_(0, 1):
base.cz(3, 5)
with case_(case_.DEFAULT):
base.cz(1, 4)
base.append(CustomCX(), [2, 4])
base.append(CustomCX(), [3, 4])
return base
def _control_flow_expr_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
with base.if_test(expr.equal(base.cregs[0], 1)) as else_:
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
with else_:
base.cz(1, 4)
with base.for_loop((1, 2)):
base.cx(1, 5)
base.measure(2, 2)
with base.while_loop(expr.logic_not(bits[2])):
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4])
base.ry(a, 4)
base.measure(4, 2)
with base.switch(expr.bit_and(base.cregs[0], 2)) as case_:
with case_(0, 1):
base.cz(3, 5)
with case_(case_.DEFAULT):
base.cz(1, 4)
base.append(CustomCX(), [2, 4])
base.append(CustomCX(), [3, 4])
return base
@data(0, 1, 2, 3)
def test_qpy_roundtrip(self, optimization_level):
"""Test that the output of a transpiled circuit can be round-tripped through QPY."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMelbourne(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit can be round-tripped through QPY."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMumbaiV2(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be round-tripped
through QPY."""
if optimization_level == 3 and sys.platform == "win32":
self.skipTest(
"This test case triggers a bug in the eigensolver routine on windows. "
"See #10345 for more details."
)
backend = FakeMelbourne()
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
basis_gates=backend.configuration().basis_gates
+ ["if_else", "for_loop", "while_loop", "switch_case"],
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be round-tripped
through QPY."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_expr(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow including `Expr` nodes can
be round-tripped through QPY."""
if optimization_level == 3 and sys.platform == "win32":
self.skipTest(
"This test case triggers a bug in the eigensolver routine on windows. "
"See #10345 for more details."
)
backend = FakeMelbourne()
transpiled = transpile(
self._control_flow_expr_circuit(),
backend=backend,
basis_gates=backend.configuration().basis_gates
+ ["if_else", "for_loop", "while_loop", "switch_case"],
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_expr_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow including `Expr` nodes can
be round-tripped through QPY."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qasm3_output(self, optimization_level):
"""Test that the output of a transpiled circuit can be dumped into OpenQASM 3."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMelbourne(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(qasm3.dumps(transpiled).strip(), str)
@data(0, 1, 2, 3)
def test_qasm3_output_control_flow(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be dumped into
OpenQASM 3."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(
qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(),
str,
)
@data(0, 1, 2, 3)
def test_qasm3_output_control_flow_expr(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow and `Expr` nodes can be
dumped into OpenQASM 3."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(
qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(),
str,
)
@data(0, 1, 2, 3)
def test_transpile_target_no_measurement_error(self, opt_level):
"""Test that transpile with a target which contains ideal measurement works
Reproduce from https://github.com/Qiskit/qiskit-terra/issues/8969
"""
target = Target()
target.add_instruction(Measure(), {(0,): None})
qc = QuantumCircuit(1, 1)
qc.measure(0, 0)
res = transpile(qc, target=target, optimization_level=opt_level)
self.assertEqual(qc, res)
def test_transpile_final_layout_updated_with_post_layout(self):
"""Test that the final layout is correctly set when vf2postlayout runs.
Reproduce from #10457
"""
def _get_index_layout(transpiled_circuit: QuantumCircuit, num_source_qubits: int):
"""Return the index layout of a transpiled circuit"""
layout = transpiled_circuit.layout
if layout is None:
return list(range(num_source_qubits))
pos_to_virt = {v: k for k, v in layout.input_qubit_mapping.items()}
qubit_indices = []
for index in range(num_source_qubits):
qubit_idx = layout.initial_layout[pos_to_virt[index]]
if layout.final_layout is not None:
qubit_idx = layout.final_layout[transpiled_circuit.qubits[qubit_idx]]
qubit_indices.append(qubit_idx)
return qubit_indices
vf2_post_layout_called = False
def callback(**kwargs):
nonlocal vf2_post_layout_called
if isinstance(kwargs["pass_"], VF2PostLayout):
vf2_post_layout_called = True
self.assertIsNotNone(kwargs["property_set"]["post_layout"])
backend = FakeVigo()
qubits = 3
qc = QuantumCircuit(qubits)
for i in range(5):
qc.cx(i % qubits, int(i + qubits / 2) % qubits)
tqc = transpile(qc, backend=backend, seed_transpiler=4242, callback=callback)
self.assertTrue(vf2_post_layout_called)
self.assertEqual([3, 2, 1], _get_index_layout(tqc, qubits))
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestLogTranspile(QiskitTestCase):
"""Testing the log_transpile option."""
def setUp(self):
super().setUp()
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel("DEBUG")
self.output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.output))
self.circuit = QuantumCircuit(QuantumRegister(1))
def assertTranspileLog(self, log_msg):
"""Runs the transpiler and check for logs containing specified message"""
transpile(self.circuit)
self.output.seek(0)
# Filter unrelated log lines
output_lines = self.output.readlines()
transpile_log_lines = [x for x in output_lines if log_msg in x]
self.assertTrue(len(transpile_log_lines) > 0)
def test_transpile_log_time(self):
"""Check Total Transpile Time is logged"""
self.assertTranspileLog("Total Transpile Time")
class TestTranspileCustomPM(QiskitTestCase):
"""Test transpile function with custom pass manager"""
def test_custom_multiple_circuits(self):
"""Test transpiling with custom pass manager and multiple circuits.
This tests created a deadlock, so it needs to be monitored for timeout.
See: https://github.com/Qiskit/qiskit-terra/issues/3925
"""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
pm_conf = PassManagerConfig(
initial_layout=None,
basis_gates=["u1", "u2", "u3", "cx"],
coupling_map=CouplingMap([[0, 1]]),
backend_properties=None,
seed_transpiler=1,
)
passmanager = level_0_pass_manager(pm_conf)
transpiled = passmanager.run([qc, qc])
expected = QuantumCircuit(QuantumRegister(2, "q"))
expected.append(U2Gate(0, 3.141592653589793), [0])
expected.cx(0, 1)
self.assertEqual(len(transpiled), 2)
self.assertEqual(transpiled[0], expected)
self.assertEqual(transpiled[1], expected)
@ddt
class TestTranspileParallel(QiskitTestCase):
"""Test transpile() in parallel."""
def setUp(self):
super().setUp()
# Force parallel execution to True to test multiprocessing for this class
original_val = parallel.PARALLEL_DEFAULT
def restore_default():
parallel.PARALLEL_DEFAULT = original_val
self.addCleanup(restore_default)
parallel.PARALLEL_DEFAULT = True
@data(0, 1, 2, 3)
def test_parallel_multiprocessing(self, opt_level):
"""Test parallel dispatch works with multiprocessing."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = FakeMumbaiV2()
pm = generate_preset_pass_manager(opt_level, backend)
res = pm.run([qc, qc])
for circ in res:
self.assertIsInstance(circ, QuantumCircuit)
@data(0, 1, 2, 3)
def test_parallel_with_target(self, opt_level):
"""Test that parallel dispatch works with a manual target."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
target = FakeMumbaiV2().target
res = transpile([qc] * 3, target=target, optimization_level=opt_level)
self.assertIsInstance(res, list)
for circ in res:
self.assertIsInstance(circ, QuantumCircuit)
@data(0, 1, 2, 3)
def test_parallel_dispatch(self, opt_level):
"""Test that transpile in parallel works for all optimization levels."""
backend = FakeRueschlikon()
qr = QuantumRegister(16)
cr = ClassicalRegister(16)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
for k in range(1, 15):
qc.cx(qr[0], qr[k])
qc.measure(qr, cr)
qlist = [qc for k in range(15)]
tqc = transpile(
qlist, backend=backend, optimization_level=opt_level, seed_transpiler=424242
)
result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result()
counts = result.get_counts()
for count in counts:
self.assertTrue(math.isclose(count["0000000000000000"], 500, rel_tol=0.1))
self.assertTrue(math.isclose(count["0111111111111111"], 500, rel_tol=0.1))
def test_parallel_dispatch_lazy_cal_loading(self):
"""Test adding calibration by lazy loading in parallel environment."""
class TestAddCalibration(TransformationPass):
"""A fake pass to test lazy pulse qobj loading in parallel environment."""
def __init__(self, target):
"""Instantiate with target."""
super().__init__()
self.target = target
def run(self, dag):
"""Run test pass that adds calibration of SX gate of qubit 0."""
dag.add_calibration(
"sx",
qubits=(0,),
schedule=self.target["sx"][(0,)].calibration, # PulseQobj is parsed here
)
return dag
backend = FakeMumbaiV2()
# This target has PulseQobj entries that provides a serialized schedule data
pass_ = TestAddCalibration(backend.target)
pm = PassManager(passes=[pass_])
self.assertIsNone(backend.target["sx"][(0,)]._calibration._definition)
qc = QuantumCircuit(1)
qc.sx(0)
qc_copied = [qc for _ in range(10)]
qcs_cal_added = pm.run(qc_copied)
ref_cal = backend.target["sx"][(0,)].calibration
for qc_test in qcs_cal_added:
added_cal = qc_test.calibrations["sx"][((0,), ())]
self.assertEqual(added_cal, ref_cal)
@data(0, 1, 2, 3)
def test_backendv2_and_basis_gates(self, opt_level):
"""Test transpile() with BackendV2 and basis_gates set."""
backend = FakeNairobiV2()
qc = QuantumCircuit(5)
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.cz(0, 3)
qc.cz(0, 4)
qc.measure_all()
tqc = transpile(
qc,
backend=backend,
basis_gates=["u", "cz"],
optimization_level=opt_level,
seed_transpiler=12345678942,
)
op_count = set(tqc.count_ops())
self.assertEqual({"u", "cz", "measure", "barrier"}, op_count)
for inst in tqc.data:
if inst.operation.name not in {"u", "cz"}:
continue
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
self.assertIn(qubits, backend.target.qargs)
@data(0, 1, 2, 3)
def test_backendv2_and_coupling_map(self, opt_level):
"""Test transpile() with custom coupling map."""
backend = FakeNairobiV2()
qc = QuantumCircuit(5)
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.cz(0, 3)
qc.cz(0, 4)
qc.measure_all()
cmap = CouplingMap.from_line(5, bidirectional=False)
tqc = transpile(
qc,
backend=backend,
coupling_map=cmap,
optimization_level=opt_level,
seed_transpiler=12345678942,
)
op_count = set(tqc.count_ops())
self.assertTrue({"rz", "sx", "x", "cx", "measure", "barrier"}.issuperset(op_count))
for inst in tqc.data:
if len(inst.qubits) == 2:
qubit_0 = tqc.find_bit(inst.qubits[0]).index
qubit_1 = tqc.find_bit(inst.qubits[1]).index
self.assertEqual(qubit_1, qubit_0 + 1)
def test_transpile_with_multiple_coupling_maps(self):
"""Test passing a different coupling map for every circuit"""
backend = FakeNairobiV2()
qc = QuantumCircuit(3)
qc.cx(0, 2)
# Add a connection between 0 and 2 so that transpile does not change
# the gates
cmap = CouplingMap.from_line(7)
cmap.add_edge(0, 2)
with self.assertRaisesRegex(TranspilerError, "Only a single input coupling"):
# Initial layout needed to prevent transpiler from relabeling
# qubits to avoid doing the swap
transpile(
[qc] * 2,
backend,
coupling_map=[backend.coupling_map, cmap],
initial_layout=(0, 1, 2),
)
@data(0, 1, 2, 3)
def test_backend_and_custom_gate(self, opt_level):
"""Test transpile() with BackendV2, custom basis pulse gate."""
backend = FakeNairobiV2()
inst_map = InstructionScheduleMap()
inst_map.add("newgate", [0, 1], pulse.ScheduleBlock())
newgate = Gate("newgate", 2, [])
circ = QuantumCircuit(2)
circ.append(newgate, [0, 1])
tqc = transpile(
circ, backend, inst_map=inst_map, basis_gates=["newgate"], optimization_level=opt_level
)
self.assertEqual(len(tqc.data), 1)
self.assertEqual(tqc.data[0].operation, newgate)
qubits = tuple(tqc.find_bit(x).index for x in tqc.data[0].qubits)
self.assertIn(qubits, backend.target.qargs)
@ddt
class TestTranspileMultiChipTarget(QiskitTestCase):
"""Test transpile() with a disjoint coupling map."""
def setUp(self):
super().setUp()
class FakeMultiChip(BackendV2):
"""Fake multi chip backend."""
def __init__(self):
super().__init__()
graph = rx.generators.directed_heavy_hex_graph(3)
num_qubits = len(graph) * 3
rng = np.random.default_rng(seed=12345678942)
rz_props = {}
x_props = {}
sx_props = {}
measure_props = {}
delay_props = {}
self._target = Target("Fake multi-chip backend", num_qubits=num_qubits)
for i in range(num_qubits):
qarg = (i,)
rz_props[qarg] = InstructionProperties(error=0.0, duration=0.0)
x_props[qarg] = InstructionProperties(
error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7)
)
sx_props[qarg] = InstructionProperties(
error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7)
)
measure_props[qarg] = InstructionProperties(
error=rng.uniform(1e-3, 1e-1), duration=rng.uniform(1e-8, 9e-7)
)
delay_props[qarg] = None
self._target.add_instruction(XGate(), x_props)
self._target.add_instruction(SXGate(), sx_props)
self._target.add_instruction(RZGate(Parameter("theta")), rz_props)
self._target.add_instruction(Measure(), measure_props)
self._target.add_instruction(Delay(Parameter("t")), delay_props)
cz_props = {}
for i in range(3):
for root_edge in graph.edge_list():
offset = i * len(graph)
edge = (root_edge[0] + offset, root_edge[1] + offset)
cz_props[edge] = InstructionProperties(
error=rng.uniform(1e-5, 5e-3), duration=rng.uniform(1e-8, 9e-7)
)
self._target.add_instruction(CZGate(), cz_props)
@property
def target(self):
return self._target
@property
def max_circuits(self):
return None
@classmethod
def _default_options(cls):
return Options(shots=1024)
def run(self, circuit, **kwargs):
raise NotImplementedError
self.backend = FakeMultiChip()
@data(0, 1, 2, 3)
def test_basic_connected_circuit(self, opt_level):
"""Test basic connected circuit on disjoint backend"""
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_triple_circuit(self, opt_level):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
if opt_level == 0:
with self.assertRaises(TranspilerError):
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
return
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
def test_disjoint_control_flow(self):
"""Test control flow circuit on disjoint coupling map."""
qc = QuantumCircuit(6, 1)
qc.h(0)
qc.ecr(0, 1)
qc.cx(0, 2)
qc.measure(0, 0)
with qc.if_test((qc.clbits[0], True)):
qc.reset(0)
qc.cz(1, 0)
qc.h(3)
qc.cz(3, 4)
qc.cz(3, 5)
target = self.backend.target
target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)})
target.add_instruction(IfElseOp, name="if_else")
tqc = transpile(qc, target=target)
edges = set(target.build_coupling_map().graph.edge_list())
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
elif len(qargs) == 2:
self.assertIn(qargs, edges)
self.assertIn(instruction.operation.name, target)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
def test_disjoint_control_flow_shared_classical(self):
"""Test circuit with classical data dependency between connected components."""
creg = ClassicalRegister(19)
qc = QuantumCircuit(25)
qc.add_register(creg)
qc.h(0)
for i in range(18):
qc.cx(0, i + 1)
for i in range(18):
qc.measure(i, creg[i])
with qc.if_test((creg, 0)):
qc.h(20)
qc.ecr(20, 21)
qc.ecr(20, 22)
qc.ecr(20, 23)
qc.ecr(20, 24)
target = self.backend.target
target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)})
target.add_instruction(IfElseOp, name="if_else")
tqc = transpile(qc, target=target)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
@slow_test
@data(2, 3)
def test_six_component_circuit(self, opt_level):
"""Test input circuit with more than 1 component per backend component."""
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
def test_six_component_circuit_level_1(self):
"""Test input circuit with more than 1 component per backend component."""
opt_level = 1
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_shared_classical_between_components_condition(self, opt_level):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(19)
qc = QuantumCircuit(25)
qc.add_register(creg)
qc.h(0)
for i in range(18):
qc.cx(0, i + 1)
for i in range(18):
qc.measure(i, creg[i])
qc.ecr(20, 21).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
@data(0, 1, 2, 3)
def test_shared_classical_between_components_condition_large_to_small(self, opt_level):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(2)
qc = QuantumCircuit(25)
qc.add_register(creg)
# Component 0
qc.h(24)
qc.cx(24, 23)
qc.measure(24, creg[0])
qc.measure(23, creg[1])
# Component 1
qc.h(0).c_if(creg, 0)
for i in range(18):
qc.ecr(0, i + 1).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=123456789)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[23]], coupling_map),
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in [23, 24]}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(19)}, components[1])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
# The first node should be a measurement
self.assertIsInstance(first_meas_node.op, Measure)
# This should be in the first component
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while isinstance(op_node, DAGOpNode):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
@data(1, 2, 3)
def test_shared_classical_between_components_condition_large_to_small_reverse_index(
self, opt_level
):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(2)
qc = QuantumCircuit(25)
qc.add_register(creg)
# Component 0
qc.h(0)
qc.cx(0, 1)
qc.measure(0, creg[0])
qc.measure(1, creg[1])
# Component 1
qc.h(24).c_if(creg, 0)
for i in range(23, 5, -1):
qc.ecr(24, i).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
connected_qubits(initial_layout[qc.qubits[6]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(2)}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(6, 25)}, components[1])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
# The first node should be a measurement
self.assertIsInstance(first_meas_node.op, Measure)
# This shoulde be in the first ocmponent
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while isinstance(op_node, DAGOpNode):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
@data(1, 2, 3)
def test_chained_data_dependency(self, opt_level):
"""Test 3 component circuit with shared clbits between each component."""
creg = ClassicalRegister(1)
qc = QuantumCircuit(30)
qc.add_register(creg)
# Component 0
qc.h(0)
for i in range(9):
qc.cx(0, i + 1)
measure_op = Measure()
qc.append(measure_op, [9], [creg[0]])
# Component 1
qc.h(10).c_if(creg, 0)
for i in range(11, 20):
qc.ecr(10, i).c_if(creg, 0)
measure_op = Measure()
qc.append(measure_op, [19], [creg[0]])
# Component 2
qc.h(20).c_if(creg, 0)
for i in range(21, 30):
qc.cz(20, i).c_if(creg, 0)
measure_op = Measure()
qc.append(measure_op, [29], [creg[0]])
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
connected_qubits(initial_layout[qc.qubits[10]], coupling_map),
connected_qubits(initial_layout[qc.qubits[20]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10)}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10, 20)}, components[1])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(20, 30)}, components[2])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIsInstance(first_meas_node.op, Measure)
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while not isinstance(op_node.op, Measure):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while not isinstance(op_node.op, Measure):
self.assertIn(qubit_map[op_node.qargs[0]], components[2])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIn(qubit_map[op_node.qargs[0]], components[2])
@data("sabre", "stochastic", "basic", "lookahead")
def test_basic_connected_circuit_dense_layout(self, routing_method):
"""Test basic connected circuit on disjoint backend"""
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
# Lookahead swap skipped for performance
@data("sabre", "stochastic", "basic")
def test_triple_circuit_dense_layout(self, routing_method):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data("sabre", "stochastic", "basic", "lookahead")
def test_triple_circuit_invalid_layout(self, routing_method):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
with self.assertRaises(TranspilerError):
transpile(
qc,
self.backend,
layout_method="trivial",
routing_method=routing_method,
seed_transpiler=42,
)
# Lookahead swap skipped for performance reasons
@data("sabre", "stochastic", "basic")
def test_six_component_circuit_dense_layout(self, routing_method):
"""Test input circuit with more than 1 component per backend component."""
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops(self, opt_level):
"""Test qubits without operations aren't ever used."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(3)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
tqc = transpile(qc, target=target, optimization_level=opt_level)
invalid_qubits = {3, 4}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_with_routing(self, opt_level):
"""Test qubits without operations aren't ever used."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)})
target.add_instruction(
CXGate(),
{edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0), (2, 3)]},
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(1, 3)
qc.cx(0, 3)
tqc = transpile(qc, target=target, optimization_level=opt_level)
invalid_qubits = {
4,
}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_circuit_too_large(self, opt_level):
"""Test qubits without operations aren't ever used and error if circuit needs them."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
with self.assertRaises(TranspilerError):
transpile(qc, target=target, optimization_level=opt_level)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_circuit_too_large_disconnected(
self, opt_level
):
"""Test qubits without operations aren't ever used if a disconnected circuit needs them."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(5)
qc.x(0)
qc.x(1)
qc.x(3)
qc.x(4)
with self.assertRaises(TranspilerError):
transpile(qc, target=target, optimization_level=opt_level)
@data(0, 1, 2, 3)
def test_transpile_does_not_affect_backend_coupling(self, opt_level):
"""Test that transpiliation of a circuit does not mutate the `CouplingMap` stored by a V2
backend. Regression test of gh-9997."""
if opt_level == 3:
raise unittest.SkipTest("unitary resynthesis fails due to gh-10004")
qc = QuantumCircuit(127)
for i in range(1, 127):
qc.ecr(0, i)
backend = FakeSherbrooke()
original_map = copy.deepcopy(backend.coupling_map)
transpile(qc, backend, optimization_level=opt_level)
self.assertEqual(original_map, backend.coupling_map)
@combine(
optimization_level=[0, 1, 2, 3],
scheduling_method=["asap", "alap"],
)
def test_transpile_target_with_qubits_without_delays_with_scheduling(
self, optimization_level, scheduling_method
):
"""Test qubits without operations aren't ever used."""
no_delay_qubits = [1, 3, 4]
target = Target(num_qubits=5, dt=1)
target.add_instruction(
XGate(), {(i,): InstructionProperties(duration=160) for i in range(4)}
)
target.add_instruction(
HGate(), {(i,): InstructionProperties(duration=160) for i in range(4)}
)
target.add_instruction(
CXGate(),
{
edge: InstructionProperties(duration=800)
for edge in [(0, 1), (1, 2), (2, 0), (2, 3)]
},
)
target.add_instruction(
Delay(Parameter("t")), {(i,): None for i in range(4) if i not in no_delay_qubits}
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(1, 3)
qc.cx(0, 3)
tqc = transpile(
qc,
target=target,
optimization_level=optimization_level,
scheduling_method=scheduling_method,
)
invalid_qubits = {
4,
}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
if isinstance(inst.operation, Delay):
self.assertNotIn(tqc.find_bit(bit).index, no_delay_qubits)
|
https://github.com/nagarx/Quantum-KNN-Classifier-using-Qiskit
|
nagarx
|
# Classical computing modules
import numpy as np
import pandas as pd
import seaborn as sns
from statistics import mode
# Dataset
from sklearn import datasets, preprocessing
from sklearn.model_selection import train_test_split
# Quantum computing modules
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import Statevector
# Load the dataset
iris = datasets.load_iris()
feature_labels = iris.feature_names
class_labels = iris.target_names
# Extract the data
X = iris.data
y = np.array([iris.target])
M = 4
# Print the features and classes
print("Features: ", feature_labels)
print("Classes: ", class_labels)
df = pd.DataFrame(data = np.concatenate((X, y.T), axis = 1), columns = feature_labels[0:M] + ["Species"])
sns.pairplot(df, hue = 'Species')
min_max_scaler = preprocessing.MinMaxScaler(feature_range=(0, 1))
min_max_scaler.fit(X)
X_normalized = min_max_scaler.transform(X)
df2 = pd.DataFrame(data = np.concatenate((X_normalized, y.T), axis = 1), columns = feature_labels[0:M] + ["Species"])
sns.pairplot(df2, hue = 'Species')
N_train = 100 # Training dataset size
X_train, X_test, y_train, y_test = train_test_split(X_normalized, y[0], train_size=N_train)
# Select a sample test sample for classification
test_index = int(np.random.rand()*len(X_test))
phi_test = X_test[test_index]
# Create the encoded feature vector
for i in range(M):
phi_i = [np.sqrt(phi_test[i]), np.sqrt(1- phi_test[i])]
if i == 0:
phi = phi_i
else:
phi = np.kron(phi_i, phi)
# Validate the statevector
print('Valid statevector: ', Statevector(phi).is_valid())
N = int(np.ceil(np.log2(N_train)))
psi = np.zeros(2**(M + N)) # Task 9
for i in range(N_train):
# Encode |i>
i_vec = np.zeros(2**N)
i_vec[i] = 1
# Encode |x>
x = X_train[i, :]
for j in range(M):
dummy = [np.sqrt(x[j]), np.sqrt(1- x[j])]
if j == 0:
x_vec = dummy
else:
x_vec = np.kron(dummy, x_vec)
psi_i = np.kron(x_vec, i_vec)
# Task 9
psi += psi_i
psi /= np.sqrt(N_train)
# Check the validity of the statevector
assert Statevector(psi).is_valid(), "The statevector is not square-normalized."
index_reg = QuantumRegister(N, 'i')
train_reg = QuantumRegister(M, 'train')
test_reg = QuantumRegister(M, 'test')
p = QuantumRegister(1, 'similarity')
# Create the quantum circuit
qknn = QuantumCircuit()
# Add registers to the circuit
qknn.add_register(index_reg)
qknn.add_register(train_reg)
qknn.add_register(test_reg)
qknn.add_register(p)
# Draw the quantum circuit
qknn.draw('mpl')
# Initialize the training register
qknn.initialize(psi, index_reg[0:N] + train_reg[0:M])
# Initialize the test register
qknn.initialize(phi, test_reg)
# Draw qknn
qknn.draw('mpl')
from modules import swap_test
# Apply the Quantum SWAP Test module to the quantum circuit
qknn.append(swap_test(M), train_reg[0:M] + test_reg[0:M] + [p[0]])
# Draw qknn
qknn.draw('mpl')
# Create the classical register
meas_reg_len = N + 1
meas_reg = ClassicalRegister(meas_reg_len, 'meas')
qknn.add_register(meas_reg)
# Measure the qubits
qknn.measure(index_reg[0::] + p[0::], meas_reg)
# Draw qknn
qknn.draw('mpl', fold = -1)
backend = Aer.get_backend('qasm_simulator')
counts_knn = execute(qknn, backend, shots = 15000).result().get_counts()
result_arr = np.zeros((N_train, 3))
for count in counts_knn:
i_dec = int(count[1::], 2)
phase = int(count[0], 2)
if phase == 0:
result_arr[i_dec, 0] += counts_knn[count]
else:
result_arr[i_dec, 1] += counts_knn[count]
for i in range(N_train):
prob_1 = result_arr[i][1]/(result_arr[i][0] + result_arr[i][1])
result_arr[i][2] = 1 - 2*prob_1
# Find the indexes of minimum distance
k = 10
k_min_dist_arr = result_arr[:, 2].argsort()[::-1][:k]
# Determine the class of the test sample
y_pred = mode(y_train[k_min_dist_arr])
y_exp = y_test[test_index]
print('Predicted class of the test sample is {}.'.format(y_pred))
print('Expected class of the test sample is {}.'.format(y_exp))
def q_knn_module(test_index, psi, k=10):
phi_test = X_test[test_index]
# Create the encoded feature vector
for i in range(M):
phi_i = [np.sqrt(phi_test[i]), np.sqrt(1- phi_test[i])]
if i == 0:
phi = phi_i
else:
phi = np.kron(phi, phi_i)
# Create the quantum circuit
qknn = QuantumCircuit()
# Add registers to circuit
qknn.add_register(index_reg)
qknn.add_register(train_reg)
qknn.add_register(test_reg)
qknn.add_register(p)
# Initialize train reg
qknn.initialize(psi, index_reg[0:N] + train_reg[0:M])
# Initialize test reg
qknn.initialize(phi, test_reg)
# Apply the swap test module to the quantum circuit
qknn.append(swap_test(M), train_reg[0:M] + test_reg[0:M] + [p[0]])
# Create the classical register
meas_reg_len = N+1
meas_reg = ClassicalRegister(meas_reg_len, 'meas')
qknn.add_register(meas_reg)
# Measure the qubits
qknn.measure(index_reg[0::] + p[0::], meas_reg)
# Circuit execution
backend = Aer.get_backend('qasm_simulator')
counts_knn = execute(qknn, backend, shots = 10000).result().get_counts()
# Decoding the results
result_arr = np.zeros((N_train, 3))
for count in counts_knn:
i_dec = int(count[1::], 2)
phase = int(count[0], 2)
if phase == 0:
result_arr[i_dec, 0] += counts_knn[count]
else:
result_arr[i_dec, 1] += counts_knn[count]
# Computing similarity
for i in range(N_train):
prob_1 = result_arr[i][1]/(result_arr[i][0] + result_arr[i][1])
result_arr[i][2] = 1 - 2*prob_1
# Find the indices of minimum distance
k_min_dist_arr = result_arr[:, 2].argsort()[::-1][:k]
# Determine the class of the test sample
y_pred = mode(y_train[k_min_dist_arr])
y_exp = y_test[test_index]
return y_pred, y_exp
y_pred_arr = []
y_exp_arr = []
for test_indx in range(len(X_test)):
y_pred, y_exp = q_knn_module(test_indx, psi)
y_pred_arr.append(y_pred)
y_exp_arr.append(y_exp)
t = 0
f = 0
for i in range(len(X_test)):
if y_pred_arr[i] == y_exp_arr[i]:
t += 1
else:
f += 1
print('Model accuracy is {}%.'.format(t/(t+f) *100))
|
https://github.com/strangequarkkk/BB84-Protocol-for-QKD
|
strangequarkkk
|
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
qc.barrier()
# Alice now sends the qubit to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
# Alice now sends the qubit to Bob
# but Eve intercepts and tries to read it
qc.measure(0, 0)
qc.barrier()
# Eve then passes this on to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
n = 100
## Step 1
# Alice generates bits.
alice_bits = np.random.randint(0,2,n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = np.random.randint(0,2,n)
# Function to compare the bits & bases generated by alice, and then 'encode' the message. Basically determines the state of the qubit/photon to send.
def encode_message(bits, bases):
message = []
for i in range(n):
qc = QuantumCircuit(1,1)
if bases[i] == 0: # Prepare qubit in Z-basis
if bits[i] == 0:
pass
else:
qc.x(0)
else: # Prepare qubit in X-basis
if bits[i] == 0:
qc.h(0)
else:
qc.x(0)
qc.h(0)
qc.barrier()
message.append(qc)
return message
# Alice computes the encoded message using the function defined above.
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = np.random.randint(0,2,n)
# Function to decode the message sent by alice by comparing qubit/photon states with Bob's generated bases.
def measure_message(message, bases):
backend = Aer.get_backend('aer_simulator')
measurements = []
for q in range(n):
if bases[q] == 0: # measuring in Z-basis
message[q].measure(0,0)
if bases[q] == 1: # measuring in X-basis
message[q].h(0)
message[q].measure(0,0)
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(message[q], shots=1, memory=True)
result = aer_sim.run(qobj).result()
measured_bit = int(result.get_memory()[0])
measurements.append(measured_bit)
return measurements
# Decode the message according to his bases
bob_results = measure_message(message, bob_bases)
## Step 4
# Function to perform sifting i.e. disregard the bits for which Bob's & A;ice's bases didnot match.
def remove_garbage(a_bases, b_bases, bits):
good_bits = []
for q in range(n):
if a_bases[q] == b_bases[q]:
# If both used the same basis, add
# this to the list of 'good' bits
good_bits.append(bits[q])
return good_bits
# Performing sifting for Alice's and Bob's bits.
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
print("Alice's key after sifting (without interception)", alice_key)
print("Bob's key after sifting (without interception) ", bob_key)
# # Step 5
# # Function for parameter estimation i.e. determining the error rate by comparing subsets taen from both Alice's key & Bob's key.
# def sample_bits(bits, selection):
# sample = []
# for i in selection:
# # use np.mod to make sure the
# # bit we sample is always in
# # the list range
# i = np.mod(i, len(bits))
# # pop(i) removes the element of the
# # list at index 'i'
# sample.append(bits.pop(i))
# return sample
# # Performing parameter estimation & disregarding the bits used for comparison from Alice's & Bob's key.
# sample_size = 15
# bit_selection = np.random.randint(0,n,size=sample_size)
# bob_sample = sample_bits(bob_key, bit_selection)
# alice_sample = sample_bits(alice_key, bit_selection)
num = 0
for i in range(0,len(bob_key)):
if alice_key[i] == bob_key[i]:
num = num + 1
matching_bits = (num/len(bob_key))*100
print(matching_bits,"% of the bits match.")
## Step 1
alice_bits = np.random.randint(2, size=n)
## Step 2
alice_bases = np.random.randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = np.random.randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = np.random.randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
print("Alice's key after sifting (with interception)", alice_key)
print("Bob's key after sifting (with interception) ", bob_key)
# ## Step 5
# sample_size = 15
# bit_selection = np.random.randint(n, size=sample_size)
# bob_sample = sample_bits(bob_key, bit_selection)
# alice_sample = sample_bits(alice_key, bit_selection)
num = 0
for i in range(0,len(bob_key)):
if alice_key[i] == bob_key[i]:
num = num + 1
matching_bits = (num/len(bob_key))*100
print(matching_bits,"% of the bits match.")
plt.rcParams['axes.linewidth'] = 2
mpl.rcParams['font.family'] = ['Georgia']
plt.figure(figsize=(10.5,6))
ax=plt.axes()
ax.set_title('')
ax.set_xlabel('$n$ (Number of bits drawn from the sifted keys for determining error rate)',fontsize = 18,labelpad=10)
ax.set_ylabel(r'$P(Eve\ detected)$',fontsize = 18,labelpad=10)
ax.xaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on')
ax.yaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on')
ax.tick_params(axis='x', labelsize=20)
ax.tick_params(axis='y', labelsize=20)
ax. xaxis. label. set_size(20)
ax. yaxis. label. set_size(20)
n = 30
x = np.arange(n+1)
y = 1 - 0.75**x
ax.plot(x,y,color = plt.cm.rainbow(np.linspace(0, 1, 5))[0], marker = "s", markerfacecolor='r')
|
https://github.com/abbarreto/qiskit3
|
abbarreto
|
%run init.ipynb
def pf(t,r):
f = (1-r**t)/(1-r) - t
return f
from mpl_toolkits import mplot3d
def pf_3d(th,ph):
import matplotlib
matplotlib.rcParams.update({'font.size':12});
#plt.figure(figsize = (6,4,4), dpi = 100)
x = np.linspace(0, 1, 20)
y = np.linspace(0, 1, 20)
X, Y = np.meshgrid(x, y)
Z = pf(X,Y)
fig = plt.figure();
ax = plt.axes(projection="3d")
ax.plot_wireframe(X, Y, Z, color='blue')
ax.set_xlabel(r'$\lambda$')
ax.set_ylabel(r'$t$'); ax.set_zlabel(r'$r$')
ax.view_init(th, ph)
fig.tight_layout()
plt.show()
interactive(pf_3d, th = (0,90,10), ph = (0,360,10))
import numpy as np
import math
from matplotlib import pyplot as plt
x = np.arange(0.1,5,0.1) # d tau/dt
y = np.log(np.sinh(x/2)/math.sinh(1/2)) #faz beta*hbat*omega/2 = 1
plt.plot(x,y)
plt.show()
x = np.arange(0,10,0.1) # x = hb*omega, kT=1
y1 = np.exp(-x) # dtau/dt = 1
y2 = np.exp(-0.5*x) # dtau/dt = 0.5
y3 = np.exp(-1.5*x) # dtau/dt = 1.5
plt.plot(x,y1,label='1')
plt.plot(x,y2,label='0.5')
plt.plot(x,y3,label='1.5')
plt.legend()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
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/Axect/QuantumAlgorithms
|
Axect
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
# Constant Oracle
const_oracle = QuantumCircuit(n+1)
# Random output
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw()
# Balanced Oracle
balanced_oracle = QuantumCircuit(n+1)
# Binary string length
b_str = "101"
# For each qubit in our circuit
# we place an X-gate if the corresponding digit in b_str is 1
# or do nothing if the digit is 0
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw()
# Creating the controlled-NOT gates
# using each input qubit as a control
# and the output as a target
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Wrapping the controls in X-gates
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw()
# Viewing the output
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_gate_map
backend = FakeVigoV2()
plot_gate_map(backend)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
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("../utils/")
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)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(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"])
t3_st_qcs = transpile(t3_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, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
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[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
# with open("jobs_" + str(backend) + "_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(filename, "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_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump(backend.properties(), f)
retrieved_jobs = jobs
retrieved_cal_job = cal_job
cal_results = retrieved_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 retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
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/Zhaoyilunnn/qdao
|
Zhaoyilunnn
|
"""
Generate the walk-through example circuit
Pleas run in qcs root directory
"""
import sys
sys.path.append(".")
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
from qdao.engine import Engine
if __name__ == "__main__":
# circ_path = "qdao/benchmarks/qasm/random_8_5_max_operands_2_gen.qasm"
circ_path = "qdao/benchmarks/qasm/random_5_2_max_operands_2_gen.qasm"
circ = QuantumCircuit.from_qasm_file(circ_path)
# Show and save original circuit
fig = circ.draw(output="mpl")
print(circ.draw(output="latex_source"))
plt.show()
plt.savefig("complete_circ.pdf")
# engine = Engine(circuit=circ, num_primary=6, num_local=4)
engine = Engine(circuit=circ, num_primary=4, num_local=1)
sub_circs = engine._part.run(circ)
for i, sc in enumerate(sub_circs):
sc.circ.data.pop(-1)
print(sc.real_qubits)
print(sc.circ.draw(output="latex_source"))
fig = sc.circ.draw(output="mpl")
plt.show()
plt.savefig("sub_circ-{}.pdf".format(i))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 42
from qiskit.circuit import Parameter
from qiskit import QuantumCircuit
params1 = [Parameter("input1"), Parameter("weight1")]
qc1 = QuantumCircuit(1)
qc1.h(0)
qc1.ry(params1[0], 0)
qc1.rx(params1[1], 0)
qc1.draw("mpl")
from qiskit.quantum_info import SparsePauliOp
observable1 = SparsePauliOp.from_list([("Y" * qc1.num_qubits, 1)])
from qiskit_machine_learning.neural_networks import EstimatorQNN
estimator_qnn = EstimatorQNN(
circuit=qc1, observables=observable1, input_params=[params1[0]], weight_params=[params1[1]]
)
estimator_qnn
from qiskit.circuit import ParameterVector
inputs2 = ParameterVector("input", 2)
weights2 = ParameterVector("weight", 4)
print(f"input parameters: {[str(item) for item in inputs2.params]}")
print(f"weight parameters: {[str(item) for item in weights2.params]}")
qc2 = QuantumCircuit(2)
qc2.ry(inputs2[0], 0)
qc2.ry(inputs2[1], 1)
qc2.cx(0, 1)
qc2.ry(weights2[0], 0)
qc2.ry(weights2[1], 1)
qc2.cx(0, 1)
qc2.ry(weights2[2], 0)
qc2.ry(weights2[3], 1)
qc2.draw(output="mpl")
from qiskit_machine_learning.neural_networks import SamplerQNN
sampler_qnn = SamplerQNN(circuit=qc2, input_params=inputs2, weight_params=weights2)
sampler_qnn
estimator_qnn_input = algorithm_globals.random.random(estimator_qnn.num_inputs)
estimator_qnn_weights = algorithm_globals.random.random(estimator_qnn.num_weights)
print(
f"Number of input features for EstimatorQNN: {estimator_qnn.num_inputs} \nInput: {estimator_qnn_input}"
)
print(
f"Number of trainable weights for EstimatorQNN: {estimator_qnn.num_weights} \nWeights: {estimator_qnn_weights}"
)
sampler_qnn_input = algorithm_globals.random.random(sampler_qnn.num_inputs)
sampler_qnn_weights = algorithm_globals.random.random(sampler_qnn.num_weights)
print(
f"Number of input features for SamplerQNN: {sampler_qnn.num_inputs} \nInput: {sampler_qnn_input}"
)
print(
f"Number of trainable weights for SamplerQNN: {sampler_qnn.num_weights} \nWeights: {sampler_qnn_weights}"
)
estimator_qnn_forward = estimator_qnn.forward(estimator_qnn_input, estimator_qnn_weights)
print(
f"Forward pass result for EstimatorQNN: {estimator_qnn_forward}. \nShape: {estimator_qnn_forward.shape}"
)
sampler_qnn_forward = sampler_qnn.forward(sampler_qnn_input, sampler_qnn_weights)
print(
f"Forward pass result for SamplerQNN: {sampler_qnn_forward}. \nShape: {sampler_qnn_forward.shape}"
)
estimator_qnn_forward_batched = estimator_qnn.forward(
[estimator_qnn_input, estimator_qnn_input], estimator_qnn_weights
)
print(
f"Forward pass result for EstimatorQNN: {estimator_qnn_forward_batched}. \nShape: {estimator_qnn_forward_batched.shape}"
)
sampler_qnn_forward_batched = sampler_qnn.forward(
[sampler_qnn_input, sampler_qnn_input], sampler_qnn_weights
)
print(
f"Forward pass result for SamplerQNN: {sampler_qnn_forward_batched}. \nShape: {sampler_qnn_forward_batched.shape}"
)
estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward(
estimator_qnn_input, estimator_qnn_weights
)
print(
f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad}"
)
print(
f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}"
)
sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward(
sampler_qnn_input, sampler_qnn_weights
)
print(
f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad}"
)
print(
f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}"
)
estimator_qnn.input_gradients = True
sampler_qnn.input_gradients = True
estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward(
estimator_qnn_input, estimator_qnn_weights
)
print(
f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad.shape}"
)
print(
f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}"
)
sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward(
sampler_qnn_input, sampler_qnn_weights
)
print(
f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad.shape}"
)
print(
f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}"
)
observable2 = SparsePauliOp.from_list([("Z" * qc1.num_qubits, 1)])
estimator_qnn2 = EstimatorQNN(
circuit=qc1,
observables=[observable1, observable2],
input_params=[params1[0]],
weight_params=[params1[1]],
)
estimator_qnn_forward2 = estimator_qnn2.forward(estimator_qnn_input, estimator_qnn_weights)
estimator_qnn_input_grad2, estimator_qnn_weight_grad2 = estimator_qnn2.backward(
estimator_qnn_input, estimator_qnn_weights
)
print(f"Forward output for EstimatorQNN1: {estimator_qnn_forward.shape}")
print(f"Forward output for EstimatorQNN2: {estimator_qnn_forward2.shape}")
print(f"Backward output for EstimatorQNN1: {estimator_qnn_weight_grad.shape}")
print(f"Backward output for EstimatorQNN2: {estimator_qnn_weight_grad2.shape}")
parity = lambda x: "{:b}".format(x).count("1") % 2
output_shape = 2 # parity = 0, 1
sampler_qnn2 = SamplerQNN(
circuit=qc2,
input_params=inputs2,
weight_params=weights2,
interpret=parity,
output_shape=output_shape,
)
sampler_qnn_forward2 = sampler_qnn2.forward(sampler_qnn_input, sampler_qnn_weights)
sampler_qnn_input_grad2, sampler_qnn_weight_grad2 = sampler_qnn2.backward(
sampler_qnn_input, sampler_qnn_weights
)
print(f"Forward output for SamplerQNN1: {sampler_qnn_forward.shape}")
print(f"Forward output for SamplerQNN2: {sampler_qnn_forward2.shape}")
print(f"Backward output for SamplerQNN1: {sampler_qnn_weight_grad.shape}")
print(f"Backward output for SamplerQNN2: {sampler_qnn_weight_grad2.shape}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/LeanderThiessen/antisymmetrization-circuit
|
LeanderThiessen
|
#General Imports
import numpy as np
import matplotlib.pyplot as plt
import time
from itertools import product,permutations
from string import ascii_lowercase as asc
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
#Qiskit Imports
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile
from qiskit.circuit.library.standard_gates import MCXGate, CXGate, XGate, CSwapGate
from qiskit.circuit.library import Diagonal
from qiskit.quantum_info import partial_trace,purity
#############FUNCTIONS###########################################################################################################
#wrapper for measuring time taken by function 'func'
def timeis(func):
def wrap(*args,**kwargs):
start = time.time()
result = func(*args,**kwargs)
end = time.time()
if measure_time:
print("{} took {:.2f}s".format(func.__name__,end-start))
return result
return wrap
#check if inputs are valid
def check_inputs(n,m):
if n == 1:
print("Case n=1 currently not supported")
correct = 1
if m>2**n:
correct == 0
if correct == 1:
print("Inputs valid")
return 0
#initialize quantum circuit with electron register, swap_ancillas, record_ancillas, collision_ancillas
def initialize_circuit(n,m,L):
circuit = QuantumCircuit()
#add main electron register (seed/target)
for e in range(m):
r_q = QuantumRegister(n,'{}'.format(asc[e]))#asc[i]=ith letter of the alphabe
c = QuantumCircuit(r_q)
circuit = circuit.combine(c)
#add ancillas for comparator_swaps
for k in range(int(np.ceil(m/2))):
anc_q = QuantumRegister(n-1,'anc_{}'.format(k))
c = QuantumCircuit(anc_q)
circuit = circuit.combine(c)
#add 'record' register for storing outcomes of comparators
for l in range(L):
anc_q = QuantumRegister(1,'record_{}'.format(l))
c = QuantumCircuit(anc_q)
circuit = circuit.combine(c)
#add ancillas to store the occurence of collisions between pairs of electrons
for c in range(m-1):
anc_q = QuantumRegister(1,'coll_record_{}'.format(c))
c = QuantumCircuit(anc_q)
circuit = circuit.combine(c)
#add one ancilla to store if all other collision ancillas are '1'
anc_q = QuantumRegister(1,'collision_test')
c = QuantumCircuit(anc_q)
circuit = circuit.combine(c)
return circuit
#returns x in binary format as string of length n, incl leading zeros
def binary_n(x,n):
return bin(x)[2:].zfill(n)
#initializes j-th electron register with number x
def binary_init(circuit,n,m,input):
for k,e in enumerate(input):
e_bin = binary_n(e,n)
for i in range(n):
if e_bin[i]=='1':
circuit.append(XGate(),[i+k*n])
return circuit
#Apply a Hadamard gate to each qubit in the electron register
def Hadamard(circuit,n,m):
for q in range(n*m):
circuit.h(q)
return circuit
#Compare bits at positions x and y, only output=(x<y) to position anc
def bit_compare(circuit,cbits,control,debug=True):
x = cbits[0]
y = cbits[1]
anc = cbits[2]
if debug:
circuit.barrier()
#control='01' for initial sorting and '10' for collision detection
circuit.append(MCXGate(2,ctrl_state=control),[x,y,anc])
if debug:
circuit.barrier()
return circuit
#split the array 'index' into array of pairs of adjacent indices; first entry is (e.g.) [0] if number of entries of index is odd
def get_subsets(index):
#index = [0,1,2,3] -> result = [[0,1],[2,3]]
#index = [0,1,2,3,4] -> result = [[0],[1,2],[3,4]]
M = len(index)
result = []
if M % 2 != 0:
result.append(np.array([0]))
n_split = int((M-1)/2)
for s in np.split(index[1:M],n_split):
result.append(s)
else:
result = np.split(index,M/2)
return result
#get position of first qubit in swap_control ancilla register
def get_first_swap_ctrl(n,m):
#n_comp_parallel is the number of comparators that are applied in each layer
#n*m = main register for storing electron registers;
#(n_comp_parallel)*(n-1) = fixed ancilla register needed for compare_n
n_comp_parallel = int(np.ceil(m/2))
ctrl_0 = n*m + (n-1)*n_comp_parallel
return ctrl_0
#get position of first qubit in collision_control ancilla register
def get_first_coll_ctrl(n,m,L):
coll_0 = get_first_swap_ctrl(n,m) + L
return coll_0
#return pairs of electron indices that need to be compared in collision-detection step
def get_coll_sets(m):
ind = np.arange(m)
if m == 2:
sets_a = [np.array([0,1])]
sets_b = []
return sets_a,sets_b
if m % 2 == 0:
sets_a = np.split(ind,m/2)
sets_b = np.split(ind[1:-1],(m-2)/2)
else:
sets_a = np.split(ind[:-1],(m-1)/2)
sets_b = np.split(ind[1:],(m-1)/2)
#all gates in sets_a can be applied in parallel
#all gates in sets_b can be applied in parallel
return sets_a,sets_b
#returns the first qubit position of the ancilla register used for swap of i and j (only really tested for m<6)
def get_anc(n,m,i,j):
if abs(j-i) == 1:
anc_reg = int( np.min([i,j])/2 )
elif abs(j-i) == 2:
anc_reg = int( np.ceil( np.min([i,j])/2 ))
else:
anc_reg = int( np.min([i,j]) )
anc = n*m + anc_reg*(n-1)
return anc
#Implement 'Compare2' function (Fig 3); input: two 2bit numbers, output: two 1bit numbers with same ordering
def compare_2(circuit,x_0,x_1,y_0,y_1,anc):
#Notation: x = 2^1*x_0 + x_1 (reverse from paper!!)
#compares numbers x,y and outputs two bits x',y' (at positions x_1 and y_1) with the same ordering
circuit.append(XGate(),[anc])
circuit.append(CXGate(),[y_0,x_0])
circuit.append(CXGate(),[y_1,x_1])
circuit.append(CSwapGate(),[x_0,x_1,anc])
circuit.append(CSwapGate(),[x_0,y_0,y_1])
circuit.append(CXGate(),[y_1,x_1])
return circuit
#Generalisation of 'compare2' two nbit numbers, output: two 1bit numbers with same ordering at positions x1,y1
def compare_n(circuit,n,m,i,j,l,L,debug):
index = np.arange(n)
subsets = get_subsets(index)
M = len(subsets)
anc = get_anc(n,m,i,j)
for s in subsets:
if len(s)==2:
if debug:
circuit.barrier()
x_0 = s[0] + i*n
x_1 = s[1] + i*n
y_0 = s[0] + j*n
y_1 = s[1] + j*n
circuit = compare_2(circuit,x_0,x_1,y_0,y_1,anc)
anc += 1
while (len(subsets)>1):
index = np.array([subsets[k][-1] for k in range(M)])
subsets = get_subsets(index)
M = len(subsets)
for s in subsets:
if len(s)==2:
if debug:
circuit.barrier()
x_0 = s[0] + i*n
x_1 = s[1] + i*n
y_0 = s[0] + j*n
y_1 = s[1] + j*n
circuit = compare_2(circuit,x_0,x_1,y_0,y_1,anc)
anc += 1
########################################################################################################################################
#at this point the bits x_1 and y_1 have the same ordering as numbers stored in registers i and j
#e(i)<e(j) -> x_1=0 and y_1=1
#e(i)>e(j) -> x_1=1 and y_1=0
#e(i)=e(j) -> x_1=0 y_1=0 if e(i) even or x_1=1 y_1=1 if e(i) odd
#prepare output for bit_compare function; anc iterates through the second ancilla register (+1 for each comparator)
#l = current swap; each new swap gets a new ancilla for storing the outcome
anc = get_first_swap_ctrl(n,m) + l
cbits = x_1,y_1,anc
return circuit,cbits
#apply diagonal phase shift to qubit i, conditioned on qubit 'ctrl'
def cphase_shift(circuit,ctrl,i):
target = i*n
CDiag = Diagonal([-1,-1]).control(1)
CDiag = CDiag.to_gate()
CDiag.label = "D" #doesn't work currently
circuit.append(CDiag,[ctrl,target])
return circuit
#performs swap of registers i and j conditioned on ancilla qubit 'ctrl'
def swap_registers(circuit,n,i,j,ctrl,debug):
for g in range(n):
circuit.append(CSwapGate(),[ctrl,i*n+g,j*n+g])
if debug:
circuit.barrier()
return circuit
#compare electron registers i and j; swap registers iff e(i)<(j); l=current swap (0 to L)
def comparator_swap(n,m,i,j,l,L,phase,debug):
#Perform comparison to generate output qubits "cbits"
circuit_compute = initialize_circuit(n,m,L)
circuit_compute,cbits = compare_n(circuit_compute,n,m,i,j,l,L,debug)
#Add bit_compare between the two output qubits and store in ancilla
circuit_bit_compare = initialize_circuit(n,m,L)
circuit_bit_compare = bit_compare(circuit_bit_compare,cbits,'10',debug)
#add uncomputing step only of the comparison circuit
circuit_uncompute = circuit_compute.inverse()
#Swap registers based on control ancilla
circuit_swap = initialize_circuit(n,m,L)
#apply a conditioned phase shift to the first qubit of the register pair; is only called when sn is applied backwards, that's why it's (phase,swap) and not (swap,phase)
if phase:
circuit_swap = cphase_shift(circuit_swap,cbits[2],i)
circuit_swap = swap_registers(circuit_swap,n,i,j,cbits[2],debug)
#Combine circuits
circuit_comparator = circuit_compute + circuit_bit_compare + circuit_uncompute + circuit_swap
return circuit_comparator
#Apply the sorting network sn, where each comparator stores the outcome in ctrl_register
def apply_sorting_network(circuit,n,m,sn,L,phase,debug):
for l,swap in enumerate(sn):
#swap = [i, j, direction]; dir = 0 : descending (from the top); dir = 1 : ascending (from the top)
if swap[2]==0:
i = swap[0]
j = swap[1]
if swap[2]==1:
i = swap[1]
j = swap[0]
circuit_comparator = comparator_swap(n,m,i,j,l,L,phase,debug)
circuit = circuit + circuit_comparator
return circuit
#Apply the reverse of the sorting networkl sn for antisymmetrizing the input state
def apply_reverse_sorting_network(circuit,n,m,sn,L,phase,debug):
circuit_sn = initialize_circuit(n,m,L)
circuit_sn = apply_sorting_network(circuit_sn,n,m,sn,L,phase,debug)
#reverse all gates in the circuit
circuit_reverse_sn = circuit_sn.inverse()
circuit = circuit + circuit_reverse_sn
return circuit
#reset first register to [|0>,|0>,|0>,...] (all zeros)
def reset_electrons(circuit,n,m):
circuit.barrier()
for g in range(m):
g_indices = np.arange(g*n,(g+1)*n) #classical register positions for electron g
for g_i in g_indices:
circuit.reset(g_i)
return circuit
#reset all registers except for the main electron register
def reset_ancillas(circuit,n,m,L):
circuit.barrier()
start = n*m
end = get_first_coll_ctrl(n,m,L) + m
for q in range(start,end):
circuit.reset(q)
return circuit
#Perform comparisons between all adjacent electron registers, with ctrl ancilla in the coll_register
def collision_compare(circuit,n,m,L,debug):
#all sets in sets_a can be applied simultaneously (same for sets_b); both for loops are otherwise identical and could be combined
sets_a,sets_b = get_coll_sets(m)
c = 0
for s in sets_a:
circuit_coll_test = initialize_circuit(n,m,L)
i = s[0]
j = s[1]
circuit_coll_test,cbits = compare_n(circuit_coll_test,n,m,i,j,0,L,debug)
x_1 = cbits[0]
y_1 = cbits[1]
coll_anc = get_first_coll_ctrl(n,m,L) + c
cbits = [x_1,y_1,coll_anc]
circuit_coll_test_reverse = circuit_coll_test.inverse()
circuit = circuit + circuit_coll_test
circuit = bit_compare(circuit,cbits,'01',debug)
circuit = circuit + circuit_coll_test_reverse
c+=1
for s in sets_b:
circuit_coll_test = initialize_circuit(n,m,L)
i = s[0]
j = s[1]
circuit_coll_test,cbits = compare_n(circuit_coll_test,n,m,i,j,0,L,debug)
x_1 = cbits[0]
y_1 = cbits[1]
coll_anc = get_first_coll_ctrl(n,m,L) + c
cbits = [x_1,y_1,coll_anc]
circuit_coll_test_reverse = circuit_coll_test.inverse()
circuit = circuit + circuit_coll_test
circuit = bit_compare(circuit,cbits,'01',debug)
circuit = circuit + circuit_coll_test_reverse
c+=1
return circuit
#apply X gate on last qubit, conditioned on all other coll_ancillas being 1 (which means that all elctron registers are different)
def collision_test(circuit,n,m,L,debug):
coll_ctrl_0 = get_first_coll_ctrl(n,m,L)
control = ''
qubits = []
for i in range(m-1):
control = control + '1'
qubits.append(coll_ctrl_0+i)
qubits.append(coll_ctrl_0+m-1)
circuit.append(MCXGate(m-1,ctrl_state=control),qubits)
return circuit
#not necessary
#returns True if output contains only unique elements; returns False otherwise (if two or more elements are the same)
def collision_check_old(output):
if len(output) == len(set(output)):
return True
else:
return False
#Perform measurement on last qubit in coll_register
def measure_collisions(circuit,n,m,L):
#add classical register to store measurement result
c_q = QuantumRegister(0)
c_reg = ClassicalRegister(1,'collision_check')
c = QuantumCircuit(c_q,c_reg)
circuit = circuit.combine(c)
#perform measurements on each electron register and store in separate memorey
circuit.measure(get_first_coll_ctrl(n,m,L) + m - 1, 0)
return circuit
#Add classical registers and apply measurements on the main electron register
def measure_electrons(circuit,n,m):
circuit.barrier()
for g in range(m):
#Add classicla register to store measurement outcomes
c_q = QuantumRegister(0)
c_reg = ClassicalRegister(n,'mem_{}'.format(asc[g]))
c = QuantumCircuit(c_q,c_reg)
circuit = circuit.combine(c)
#perform measurements on each electron register and store in separate memorey
circuit.measure(np.arange(g*n,(g+1)*n),np.arange(g*n + 1,(g+1)*n + 1))
return circuit
#Build the circuit with all gates and measurements
@timeis
def build_circuit(n,m,input,sn,L,debug=True):
#Initialize the circuit with the right number of qubits and ancillas
circuit = initialize_circuit(n,m,L)
#Apply Hadamard gates to each qubit in the first register
circuit = Hadamard(circuit,n,m)
#Apply the sorting network sn
phase = False
circuit = apply_sorting_network(circuit,n,m,sn,L,phase,debug)
#apply comparisons between all adjacent electron registers and store outcome in coll_register
circuit = collision_compare(circuit,n,m,L,debug)
#check if outcome of all comparisons is "not_equal"; flip last qubit in coll_register if this is the case
circuit = collision_test(circuit,n,m,L,debug)
#measure last qubit in coll_register, which stores (no collisions = 1) or (collisions = 0); result is kept until the end of the simulation and result accepted if (no collisions == True)
circuit = measure_collisions(circuit,n,m,L)
#Measurements: classical register 0 stores the random sorted array that can still include collisions
#circuit = measure_electrons(circuit,n,m)
#Reset main electron register
circuit = reset_electrons(circuit,n,m)
#Initialize main electron register in given input product state
circuit = binary_init(circuit,n,m,input)
#Apply the reverse of 'apply_sorting_network' and add a conditioned phase shift after each swap (this antisymmetrizes the input state)
phase = True
circuit = apply_reverse_sorting_network(circuit,n,m,sn,L,phase,debug)
#Reset all ancilla qubits and only keep the main electron register (disable for testing final state for antisymmetry)
#circuit = reset_ancillas(circuit,n,m,L)
#Measure electron register (for testing)
#circuit = measure_electrons(circuit,n,m)
return circuit
#Simulate circuit using specified backend and return simulation result
@timeis
def simulate(circuit,backend,shots):
simulator = Aer.get_backend(backend)
#transpile the circuit into the supported set of gates
circuit = transpile(circuit,backend=simulator)
result = simulator.run(circuit,shots=shots).result()
return result
#turns simulation result 'counts' into list of decimal numbers corresponding to the electron registers; only use if shots=1 or all outcomes are the same
def convert_output_to_decimal(counts,n,m):
output_list = list(counts.keys())[0][::-1]
coll_test = output_list[0]
output_list = output_list[2:]
output = []
offset = 0
for g in range(m):
start = g*n + offset
end = (g+1)*n + offset
g_out = int(output_list[start:end],2)
output.append(g_out)
offset += 1
output_0 = output[0:m]
return coll_test,output_0
#draw the circuit using size,name as input if plot==True
@timeis
def draw_circuit(circuit,plot_scale,fname):
circuit.draw(output='mpl',fold=-1,scale=plot_scale,plot_barriers=True)
plt.savefig(fname,dpi=700)
return 0
def plot_circuit(circuit,plot_scale,fname,plot=True):
if plot:
draw_circuit(circuit,plot_scale,fname)
plt.show()
return 0
print("Plot disabled")
return 0
#plot sorting network by itself, using cnot as directed comparator (only for visualizationo)
def plot_sorting_network(sn,m):
circuit_sn = QuantumCircuit(m)
for s in sn:
if s[2] == 0:
i,j = s[0],s[1]
else:
i,j = s[1],s[0]
circuit_sn.cz(i,j)
circuit_sn.draw(output='mpl')
plt.show()
return 0
#Generate a bitonic sorting network for m electrons; dir=0 (descending), dir=1 (ascending)
def sorting_network_bitonic(m,dir):
sn = []
def compAndSwap(i,j,dir):
sn.append([i,j,dir])
def bitonic_sort(low, cnt, dir):
if cnt>1:
k = cnt//2
dir_n = (dir + 1) % 2
bitonic_sort(low, k, dir_n)#n_dir
bitonic_sort(low + k, cnt-k, dir)#dir
bitonic_merge(low, cnt, dir)
def bitonic_merge(low, cnt, dir):
if cnt>1:
k = greatestPowerOfTwoLessThan(cnt)
i = low
while i < low+cnt-k:
compAndSwap(i, i+k, dir)
i+=1
bitonic_merge(low,k,dir)
bitonic_merge(low+k,cnt-k,dir)
def greatestPowerOfTwoLessThan(cnt):
i=1
while (2**i)<cnt:
i+=1
return 2**(i-1)
bitonic_sort(0,m,dir)
L = len(sn)
return sn,L
#Test if sorting network correctly sorts all possible inputs
def test_sn(sn,n,m):
all_inputs = list(product(range(2**n),repeat=m))
fail = 0
count = 0
for input in all_inputs:
input = np.array(input)
temp = np.copy(input)
for s in sn:
if s[2]==0:
i = s[0]
j = s[1]
if s[2]==1:
i = s[1]
j = s[0]
if input[i]<input[j]:
input[i],input[j] = input[j],input[i]
should_be = np.sort(temp)[::-1]
if (input == should_be).all():
fail += 0
else:
fail += 1
print(f"Testing sorting network {count}/{len(all_inputs)}",end="\r")
count+=1
print(" ", end = "\r")
if fail == 0:
print("Sorting network correct\n")
return 1
else:
print("Error in sorting network\n")
return 0
#Returns all steps of sorting network with corresponding ancilla registers (for testing)
def test_sn_anc(sn,n,m):
for s in sn:
i = s[0]
j = s[1]
anc = get_anc(n,m,i,j)
anc_reg = int((anc-n*m)/(n-1))
print(f"[{i},{j}] anc_reg={anc_reg}")
return 0
#Output density matrix of electron register (target) and compute purity, doesnt actually test antisymmetry yet!
def test_antisymmetry(result,n,m,L):
sv = result.get_statevector()
trace_out = list(np.arange(n*m,get_first_coll_ctrl(n,m,L)+m))
#print(f"Tracing out qubits: {trace_out}")
rho_e = partial_trace(sv,trace_out)
if rho_e.is_valid():
print("Target state is valid density matrix\n")
else:
print("Target state is not valid density matrix")
#print(rho_e)
p = purity(rho_e)
print(f"Purity of target state = {p}\n")
return p
###################MAINPART############################################################################################################
#Parameters
#n: number of qubits per electron; N = 2^n orbitals
n=3
#m: number of electrons
m=4
#input: list of orbitals the electrons are initialized in; needs to be in descending order, without repetitions
input = [5,4,3,2]
#dir: ordering descending (dir=0) or ascending (dir=1)
dir = 0
#plot and save the circuit
plot = True
#include barriers between comparators in the circuit for visualization
debug = False
#measure time of functions: {build_circuit, simulate, draw_circuit}
measure_time = True
#size of the plot
plot_scale = 0.2
#simulation method
backend = 'statevector_simulator'#'aer_simulator'
#number of circuit repetitions in 'simulate'
shots = 1
#check valid inputs
check_inputs(n,m)
#Generate sorting network
sn,L = sorting_network_bitonic(m,dir)
#Test sorting network
test_sn(sn,n,m)
#Plot sorting network
plot_sorting_network(sn,m)
#Build circuit
circuit = build_circuit(n,m,input,sn,L,debug)
#Simulate
result = simulate(circuit,backend,shots)
counts = result.get_counts(circuit)
print(f"Counts: {counts}\n")
#Test if final state is antisymmetric
test_antisymmetry(result,n,m,L)
output_list = list(counts.keys())[0][::-1]
coll_test = output_list[0]
if coll_test == '1':
print("No collisions detected - continue\n")
else:
print("Collisions detected - repeat\n")
#plot circuit
plot_circuit(circuit,plot_scale,f"Plots/Circuit_m{m}_n{n}_debug{debug}",plot)
|
https://github.com/suvoooo/Qubits-Qiskit
|
suvoooo
|
# !pip3 install qiskit
import qiskit as q
import matplotlib.pyplot as plt
from qiskit import IBMQ
qr = q.QuantumRegister(2)
cr = q.ClassicalRegister(2)
circuit = q.QuantumCircuit(qr, cr)
circuit.draw()
circuit.h(qr[0]) # apply hadamard gate on first qubit.
circuit.h(qr[1]) # apply hadamard gate on second qubit.
# apply cnot gate.
display(circuit.draw())
#### see the state-vector
statevec = q.Aer.get_backend('statevector_simulator')
final_state = q.execute(circuit, statevec).result().get_statevector()
q.visualization.plot_bloch_multivector(final_state)
circuit.measure(qr, cr)
circuit.draw(scale=2)
#### simulate result on a local computer
simulator = q.Aer.get_backend(name='qasm_simulator')
results = q.execute(circuit, backend=simulator, ).result()
q.visualization.plot_histogram(results.get_counts(circuit))
### try a different circuit where we apply X gate before applying H gate.
qr1 = q.QuantumRegister(3)
cr1 = q.ClassicalRegister(3)
circuit1 = q.QuantumCircuit(qr1, cr1)
# circuit1.draw()
circuit1.h(qr1[0]) # apply the H gate on q0
circuit1.h(qr1[1]) # apply H gate on q_1
circuit1.h(qr1[2]) # add H gate on q_2
### draw the circuit
circuit1.draw()
#### plt the state vector
statevec1 = q.Aer.get_backend('statevector_simulator')
final_state1 = q.execute(circuit1, statevec1).result().get_statevector()
q.visualization.plot_bloch_multivector(final_state1) # the state doesn't not change after application of the CNOT gate
#### unchanged state as expected
circuit1.measure(qr1, cr1)
circuit1.draw(scale=2)
circuit1.measure(qr1, cr1)
### simulate result on local computer
simulator1 = q.Aer.get_backend('qasm_simulator')
results1 = q.execute(circuit1, backend=simulator1, ).result()
q.visualization.plot_histogram(results1.get_counts(circuit1))
# Now we will use IBM Quantum Computer to see the result
IBMQ.save_account('your token')
IBMQ.load_account()
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmq_valencia') # check which computer has 0 jobs on queue
job = q.execute(circuit1, backend=qcomp)
q_result = job.result()
q.visualization.plot_histogram(q_result.get_counts(circuit1))
|
https://github.com/Interlin-q/diskit
|
Interlin-q
|
import numpy as np
from numpy import pi
# importing Qiskit
from qiskit import QuantumCircuit, transpile, assemble, Aer
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(3)
qc.h(2)
qc.cp(pi/2, 1, 2)
qc.cp(pi/4, 0, 2)
qc.h(1)
qc.cp(pi/2, 0, 1)
qc.h(0)
qc.swap(0, 2)
qc.draw()
def qft_rotations(circuit, n):
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
qft_rotations(circuit, n)
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
qc = QuantumCircuit(4)
qft(qc,4)
qc.draw()
# Create the circuit
qc = QuantumCircuit(3)
# Encode the state 5 (101 in binary)
qc.x(0)
qc.x(2)
qc.draw()
sim = Aer.get_backend("aer_simulator")
qc_init = qc.copy()
qc_init.save_statevector()
statevector = sim.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
qft(qc, 3)
qc.draw()
qc.save_statevector()
statevector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(statevector)
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit.circuit import QuantumCircuit
from qiskit.visualization import dag_drawer
from qiskit.converters import circuit_to_dag
# Create basic Bell circuit
qc = QuantumCircuit(2, 1)
qc.x(1)
qc.h(0)
qc.cx(0, 1)
display(qc.draw('mpl', cregbundle=False))
print(qc._data)
# Convert circuit to dag and display dag
dag = circuit_to_dag(qc)
display(dag_drawer(dag))
# Using pre-6567 branch
for node in dag.topological_nodes():
if node.type == "op":
print(type(node), node.type, node.op)
else:
print(type(node), node.type, node.wire)
# Using post-6567 branch
from qiskit.dagcircuit import DAGOpNode
for node in dag.topological_nodes():
if isinstance(node, DAGOpNode):
print(type(node), node.op)
else:
print(type(node), node.wire)
<class 'qiskit.dagcircuit.dagnode.DAGInNode'> Qubit(QuantumRegister(2, 'q'), 0)
<class 'qiskit.dagcircuit.dagnode.DAGOpNode'> <qiskit.circuit.library.standard_gates.h.HGate object at 0x7f65b6f89d30>
<class 'qiskit.dagcircuit.dagnode.DAGInNode'> Qubit(QuantumRegister(2, 'q'), 1)
<class 'qiskit.dagcircuit.dagnode.DAGOpNode'> <qiskit.circuit.library.standard_gates.x.XGate object at 0x7f65b6f89fd0>
<class 'qiskit.dagcircuit.dagnode.DAGOpNode'> <qiskit.circuit.library.standard_gates.x.CXGate object at 0x7f65b6f89400>
<class 'qiskit.dagcircuit.dagnode.DAGOutNode'> Qubit(QuantumRegister(2, 'q'), 0)
<class 'qiskit.dagcircuit.dagnode.DAGOutNode'> Qubit(QuantumRegister(2, 'q'), 1)
<class 'qiskit.dagcircuit.dagnode.DAGInNode'> Clbit(ClassicalRegister(1, 'c'), 0)
<class 'qiskit.dagcircuit.dagnode.DAGOutNode'> Clbit(ClassicalRegister(1, 'c'), 0)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# let's start with a zero matrix
A = [
[0,0,0],
[0,0,0],
[0,0,0]
]
# we will randomly construct 3 columns
from random import randrange
for j in range(3): # each column is iteratively constructed
total = 100 # we will start with 100 and randomly distribute it into three parties
for i in range(2): # we will determine the first two entries randomly
picked_probability = randrange(total)
A[i][j] = picked_probability # the value of the i-th row in j-th column
total = total - picked_probability # remaining part to distribute in the next iteration
A[2][j] = total # the last row (in the j-th column) takes the remaining part after two iterations
# let's print matrix A before the normalization
# the entries are between 0 and 100
print("matrix A before normalization:")
for i in range(3):
print(A[i])
print("the column summations must be 100")
# let's normalize the entries by dividing every element with 100
for i in range(3):
for j in range(3):
A[i][j] /=100 # shorter form of A[i][j] = A[i][j] / 100
# let's print matrix A after the normalization
print() # print an empty line
print("matrix A after normalization:")
for i in range(3):
print(A[i])
print("the column summations must be 1")
# Asja's probabilistic operator (coin flip protocol)
A = [
[0.6,0.3],
[0.4,0.7]
]
# one-step evolution of Asja's probabilistic operator on a given probabilistic state
def asja(prelist):
newlist=[0,0]
for i in range(2): # for each row
for j in range(2): # for each column
newlist[i] = newlist[i] + prelist[j] * A[i][j] # summation of pairwise multiplication
return newlist # return the new state
# initial state
state = [1,0]
# after one step
state = asja(state)
print("after one step, the state is",state)
# the new state is correct
# let's check one more step
state = asja(state)
print("after two steps, the state is",state)
# this is also correct
#
# then, let's evolve the system for more steps
for i in [3,6,9,12,24,48,96]:
# start from the initial state
state = [1,0]
for t in range(i): # apply asja t times
state = asja(state)
# print the result
print(state,"after",(t+1),"steps")
def evolve(Op,state):
newstate=[]
for i in range(len(Op)): # for each row
# we calculate the corresponding entry of the new state
newstate.append(0) # we set this value to 0 for the initialization
for j in range(len(state)): # for each element in state
newstate[i] = newstate[i] + Op[i][j] * state[j] # summation of pairwise multiplications
return newstate # return the new probabilistic state
# test the function
# operator for the test
A = [
[0.4,0.6,0],
[0.2,0.1,0.7],
[0.4,0.3,0.3]
]
# state for test
v = [0.1,0.3,0.6]
newstate = evolve(A,v)
print(newstate)
for step in [5,10,20,40]:
new_state = [0.1,0.3,0.6] # initial state
for i in range(step):
new_state = evolve(A,new_state)
print(new_state)
# change the initial state
for step in [5,10,20,40]:
new_state = [1,0,0] # initial state
for i in range(step):
new_state = evolve(A,new_state)
print(new_state)
# for random number generation
from random import randrange
# we will use evolve function
def evolve(Op,state):
newstate=[]
for i in range(len(Op)): # for each row
newstate.append(0)
for j in range(len(state)): # for each element in state
newstate[i] = newstate[i] + Op[i][j] * state[j] # summation of pairwise multiplications
return newstate # return the new probabilistic state
# the initial state
state = [0.5, 0, 0.5, 0]
# probabilistic operator for symbol a
A = [
[0.5, 0, 0, 0],
[0.25, 1, 0, 0],
[0, 0, 1, 0],
[0.25, 0, 0, 1]
]
# probabilistic operator for symbol b
B = [
[1, 0, 0, 0],
[0, 1, 0.25, 0],
[0, 0, 0.5, 0],
[0, 0, 0.25, 1]
]
#
# your solution is here
#
length = 40
total = 50
# total = 1000 # we will also test our code for 1000 strings
# we will check 5 cases
# let's use a list
cases = [0,0,0,0,0]
for i in range(total): # total number of strings
Na = 0
Nb = 0
string = ""
state = [0.5, 0, 0.5, 0]
for j in range(length): # generate random string
if randrange(2) == 0:
Na = Na + 1 # new symbol is a
string = string + "a"
state = evolve(A,state) # update the probabilistic state by A
else:
Nb = Nb + 1 # new symbol is b
string = string + "b"
state = evolve(B,state) # update the probabilistic state by B
# now we have the final state
p0 = state[0] + state [1] # the probabilities of being in 00 and 01
p1 = state[2] + state[3] # the probabilities of being in 10 and 11
#print() # print an empty line
print("(Na-Nb) is",Na-Nb,"and","(p0-p1) is",p0-p1)
# let's check possible different cases
# start with the case in which both are nonzero
# then their multiplication is nonzero
# let's check the sign of their multiplication
if (Na-Nb) * (p0-p1) < 0:
print("they have opposite sign")
cases[0] = cases[0] + 1
elif (Na-Nb) * (p0-p1) > 0:
print("they have the same sign")
cases[1] = cases[1] + 1
# one of them should be zero
elif (Na-Nb) == 0:
if (p0-p1) == 0:
print("both are zero")
cases[2] = cases[2] + 1
else:
print("(Na-Nb) is zero, but (p0-p1) is nonzero")
cases[3] = cases[3] + 1
elif (p0-p1) == 0:
print("(Na-Nb) is nonzero, but (p0-p1) is zero")
cases[4] = cases[4] + 1
# check the case(s) observed and the case(s) not observed
print() # print an empty line
print(cases)
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
import qutip as qt # I use QuTip for the tensor and trace function
import numpy as np
H = qt.Qobj(np.matrix([[1.0 , 0.0 , 0.0 , 0.0 ]
,[0.0 , 0.0 ,-1.0 , 0.0 ]
,[0.0 ,-1.0 , 0.0 , 0.0 ]
,[0.0 , 0.0 , 0.0 , 1.0 ]]))
H
Id = qt.qeye(2); Sx = qt.sigmax(); Sy = qt.sigmay(); Sz = qt.sigmaz();
Pauli = [Id,Sx,Sy,Sz]
PauliLabels = ['Id' , 'Sx' , 'Sy' , 'Sz']
aij = 0;
for i in range(4):
for j in range(4):
PauliTensor = qt.Qobj(qt.tensor(Pauli[i], Pauli[j]).data.toarray(),dims=[[4],[4]]) # Tensor product of the pauli matrices (sigma_i (tensor) sigma_j), dims[[4],[4]] equal to dimens of H
aij = 0.25*( (PauliTensor*H ).tr()) #Elements of the descomposition
label1 = PauliLabels[i] #Label i to print
label2 = PauliLabels[j] #Label j to print
if aij!= 0:
print(aij, '*', label1, '(tensor)', label2 ) # Print the descomposition of the matrix
Id_tensor_Id = qt.tensor(Pauli[0], Pauli[0])
sx_tensor_sx = qt.tensor(Pauli[1], Pauli[1])
sy_tensor_sy = qt.tensor(Pauli[2], Pauli[2])
sz_tensor_sz = qt.tensor(Pauli[3], Pauli[3])
H_descomposition = 0.5*Id_tensor_Id - 0.5*sx_tensor_sx - 0.5*sy_tensor_sy + 0.5*sz_tensor_sz
H_descomposition_Dim = qt.Qobj(H_descomposition.data.toarray(),dims=[[4],[4]])
H_descomposition_Dim
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt
def ansatz(circuit,angle):
circuit.h(0); circuit.id(1) #Apply (H \otimes I) |00>
circuit.cx(0,1) #Apply (CX)
circuit.rx(angle, 0); circuit.id(1) #Apply (Rx \otimes I)
return circuit
ansatzCircuit = QuantumCircuit(2)
ansatzCircuit = ansatz(ansatzCircuit,np.pi/4)
ansatzCircuit.draw()
def zz_meas(angle):
qc = QuantumCircuit(2) # qc is the quantum register of the qubits, in this case 2 qubits
qc = ansatz(qc,angle)
qc.measure_all()
return qc
zz = zz_meas(np.pi/4)
zz.draw()
def yy_meas(angle):
qc = QuantumCircuit(2) # qc is the quantum register of the qubits, in this case 2 qubits
qc = ansatz(qc,angle)
qc.barrier()
qc.h(0); qc.h(1) #Apply (H \otimes H) |00>
qc.sdg(0); qc.sdg(1) #Apply (S^{\dagger} \otimes S^{\dagger})
qc.measure_all()
return qc
yy = yy_meas(np.pi/4)
yy.draw()
def xx_meas(angle):
qc = QuantumCircuit(2) # qc is the quantum register of the qubits, in this case 2 qubits
qc = ansatz(qc,angle)
qc.barrier()
qc.h(0); qc.h(1) #Apply (H \otimes H) |00>
qc.measure_all()
return qc
xx = xx_meas(np.pi/4)
xx.draw()
def expectation(qcGiven):
simulator = Aer.get_backend('qasm_simulator') #Simulator for the measures
result = execute(qcGiven, backend = simulator, shots=10000).result() # Execute the quantum circuit (qcGiven) 10000 times
counts = result.get_counts(qcGiven) #Count the results
# 'if' for the times that there are not measure in the state [3]
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zzCounts = counts['00'] + counts['11'] - counts['01'] - counts['10']
zzCounts = zzCounts / total_counts
#plot_histogram(counts)
return zzCounts
E = []; # List where the estimations of the eigenvalue will be stored
anglelist = np.linspace(0.0,2*np.pi,200) # Parameter \theta for the minimization
def Eigenvalue_Approx(xx,yy,zz):
xx_value = expectation(xx)
yy_value = expectation(yy)
zz_value = expectation(zz)
EigenValue = 0.5 - (0.5)*xx_value - (0.5)*yy_value + (0.5)*zz_value # Estimate the expectation value of the matriz H
return EigenValue
for theta in anglelist:
xx = xx_meas(theta)
yy = yy_meas(theta)
zz = zz_meas(theta)
E.append(Eigenvalue_Approx(xx,yy,zz))
plt.figure(figsize = (10,4))
plt.plot(anglelist,E , linewidth=5)
plt.grid()
plt.xlabel(r'$\theta$', fontsize = 22)
plt.ylabel(r'$<{\psi(\theta)} | H |{\psi(\theta)} >$' , fontsize = 20)
plt.yticks(fontsize = 16)
plt.xticks([0.0, np.pi/4, np.pi/2, 3*np.pi/4 , np.pi, 5*np.pi/4 , 3*np.pi/2, 7*np.pi/4 , 2*np.pi],
[r'$0$', r'$\pi/4$', r'$\pi/2$', r'$3\pi/4$', r'$\pi$', r'$5\pi/4$', r'$3\pi/2$' , r'$7\pi/4$', r'$2\pi$' ], fontsize = 16)
plt.show()
MimimumEigenvalue = np.amin(E)
print('The estimated minimum eigenvalue of the matrix H from VQE algorithm is: {}'.format(MimimumEigenvalue))
evalsH, eketsH =H.eigenstates()
MimimumEigenvalue_Exact = np.amin(evalsH)
print('The exact minimum eigenvalue of the matrix H is: {}'.format(MimimumEigenvalue_Exact))
evalsH
evalsH[0]
|
https://github.com/duartefrazao/Quantum-Finance-Algorithms
|
duartefrazao
|
from qiskit import Aer
from qiskit.circuit.library import TwoLocal
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.aqua.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import COBYLA
from .aux_functions import IncompatibleArguments
import numpy as np
import matplotlib.pyplot as plt
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, assemble, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
#Quadratic
from qiskit.optimization import QuadraticProgram
from docplex.mp.advmodel import AdvModel
from qiskit.optimization.converters import IntegerToBinary,LinearEqualityToPenalty,InequalityToEquality,QuadraticProgramToQubo
def portfolio_optimization(assets,mu,sigma,num_assets_portfolio,risk_aversion,penalty,alternating):
if len(mu) != sigma.shape[0] or len(mu) != sigma.shape[1] or len(mu) != len(assets):
raise IncompatibleArguments("Sigma, mu and assets need to be equal in size")
""" if not 0 <= risk_aversion <= 1:
raise IncompatibleArguments("Risk aversion needs to be in [0,1]") """
if not 0 < num_assets_portfolio <= len(assets):
raise IncompatibleArguments("Number of assets to include in the portfolio needs to be smaller or equal to the number of assets passed")
#Initialize binary variable array
mdl = AdvModel('docplex model')
mdl.init_numpy()
decision_vars = np.array([])
""" if qaoa:
ancila_odd = mdl.binary_var("ancila_odd")
ancila_even = mdl.binary_var("ancila_even") """
for asset in assets:
decision_vars = np.append(decision_vars,[mdl.binary_var(str(asset))])
#Terms
vec_ones = np.ones(len(decision_vars)) #helper vector
num_assets_chosen = np.matmul(vec_ones.T,decision_vars)
expected_returns_portfolio = np.matmul(mu.T,decision_vars)/num_assets_portfolio
variance_portfolio = np.matmul(decision_vars.T,np.dot(sigma,decision_vars))/num_assets_portfolio #*2 as covariance is a symetric matrix
#Objective function
#if not qaoa:
if alternating:
mdl.minimize(- expected_returns_portfolio + (risk_aversion * variance_portfolio))
#mdl.minimize(- expected_returns_portfolio + (risk_aversion * variance_portfolio) + ancila_even*0 + ancila_odd*0 )
else:
mdl.minimize(- expected_returns_portfolio + (risk_aversion * variance_portfolio) + penalty*((num_assets_chosen - num_assets_portfolio)**2))
qubo = QuadraticProgram()
qubo.from_docplex(mdl)
#print(qubo.export_as_lp_string())
#qubo.binary_var("ancila")
return qubo
def portfolio_optimization_binary(assets,mu,sigma,num_assets_portfolio,risk_aversion,penalty,max_allocation):
if len(mu) != sigma.shape[0] or len(mu) != sigma.shape[1] or len(mu) != len(assets):
raise IncompatibleArguments("Sigma, mu and assets need to be equal in size")
""" if not 0 <= risk_aversion <= 1:
raise IncompatibleArguments("Risk aversion needs to be in [0,1]") """
""" if not 0 < num_assets_portfolio <= len(assets):
raise IncompatibleArguments("Number of assets to include in the portfolio needs to be smaller or equal to the number of assets passed")
"""
#Initialize binary variable array
mdl = AdvModel('docplex model')
mdl.init_numpy()
decision_vars = np.array([])
for asset in assets:
decision_vars = np.append(decision_vars,[mdl.integer_var(name=str(asset),lb=0,ub=max_allocation)])
#Terms
vec_ones = np.ones(len(decision_vars)) #helper vector
num_assets_chosen = np.matmul(vec_ones.T,decision_vars)
expected_returns_portfolio = np.matmul(mu.T,decision_vars)
variance_portfolio = np.matmul(decision_vars.T,np.dot(sigma,decision_vars)) #*2 as covariance is a symetric matrix
#Objective function
#mdl.minimize(- expected_returns_portfolio + (risk_aversion * variance_portfolio) + penalty*((num_assets_chosen - max_allocation)**2))
mdl.minimize(((num_assets_chosen - max_allocation)**2))
qubo = QuadraticProgram()
qubo.from_docplex(mdl)
""" int2bin = IntegerToBinary()
qp_eq_bin = int2bin.convert(qubo) """
conv = QuadraticProgramToQubo()
qp_eq_bin = conv.convert(qubo)
print(qp_eq_bin.export_as_lp_string())
return qubo
def portfolio_optimization_binary_count(assets,mu,sigma,max_assets,risk_aversion,penalty,max_allocation):
if len(mu) != sigma.shape[0] or len(mu) != sigma.shape[1] or len(mu) != len(assets):
raise IncompatibleArguments("Sigma, mu and assets need to be equal in size")
""" if not 0 <= risk_aversion <= 1:
raise IncompatibleArguments("Risk aversion needs to be in [0,1]") """
""" if not 0 < num_assets_portfolio <= len(assets):
raise IncompatibleArguments("Number of assets to include in the portfolio needs to be smaller or equal to the number of assets passed")
"""
#Initialize binary variable array
mdl = AdvModel('docplex model')
mdl.init_numpy()
allocation_vars = np.array([])
presence_vars = np.array([])
for asset in assets:
allocation_vars = np.append(allocation_vars,[mdl.integer_var(name=str(asset),lb=0,ub=max_allocation)])
presence_vars = np.append(presence_vars,[mdl.binary_var(name=('b'+str(asset)))])
#Terms
vec_ones = np.ones(len(allocation_vars)) #helper vector
num_allocations = np.matmul(vec_ones.T,allocation_vars)
expected_returns_portfolio = 10000*np.matmul(mu.T,allocation_vars)
variance_portfolio = 10000*np.matmul(allocation_vars.T,np.dot(sigma,allocation_vars)) / 2 #*2 as covariance is a symetric matrix
#Objective function
mdl.minimize(- expected_returns_portfolio
+ (risk_aversion * variance_portfolio)
+ penalty*((num_allocations - max_allocation)**2))
for asset in range(len(presence_vars)):
mdl.add_constraint(allocation_vars[0]>=presence_vars[0])
mdl.add_constraint(allocation_vars[0]<= max_allocation * presence_vars[0])
#mdl.add_constraint(allocation_vars[0] <= presence_vars[0] + allocation_vars[0]*presence_vars[0])
qubo = QuadraticProgram()
qubo.from_docplex(mdl)
conv = QuadraticProgramToQubo()
qp_eq_bin = conv.convert(qubo)
"""
int2bin = IntegerToBinary()
qp_eq_bin = int2bin.convert(qubo)
lineq2penalty = LinearEqualityToPenalty()
qp_eq_bin = lineq2penalty.convert(qp_eq_bin) """
#mdl.add_constraint(allocation_vars[0]*presence_vars[0] >= 0)
print(qp_eq_bin.export_as_lp_string())
return qubo
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
from qiskit import *
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
%matplotlib inline
circuit.draw(output='mpl')
circuit.h(qr[0])
circuit.draw(output = 'mpl')
circuit.cx(qr[0], qr[1])
circuit.draw(output='mpl')
circuit.measure(qr, cr)
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
execute(circuit, backend=simulator)
result = execute(circuit, backend=simulator).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
from qiskit import IBMQ
MY_API_TOKEN = "b32678329f7f6dd426b8cf18f20bea23c2cd056b0bee2b4bcf49744b612e598f20f7170a8da4bfd99b009b6fa59d596edea7a6926fd388be158843d8e******"
IBMQ.save_account(MY_API_TOKEN, overwrite=True)
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider.backends()
backend = provider.get_backend('ibmq_santiago')
job =execute(circuit, backend= backend)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
# plot_histogram
plot_histogram(result.get_counts(circuit))
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
from qiskit.circuit.library import SwapGate, iSwapGate
from qiskit import QuantumCircuit
from qiskit.quantum_info import random_unitary
from weylchamber import g1g2g3, c1c2c3, WeylChamber
from qiskit.quantum_info import Operator
import matplotlib.pyplot as plt
N = 500
# generate (a,b,c) ->swap-> (a',b',c') pairs
a_pairs, b_pairs, c_pairs = [], [], []
for _ in range(N):
U = random_unitary(4).data
U_prime = SwapGate().to_matrix() @ U
abc = g1g2g3(U)
abc_prime = g1g2g3(U_prime)
a_pairs.append((abc[0], abc_prime[0]))
b_pairs.append((abc[1], abc_prime[1]))
c_pairs.append((abc[2], abc_prime[2]))
# plot
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
for i, (pairs, label) in enumerate(zip([a_pairs, b_pairs, c_pairs], ["a", "b", "c"])):
axes[i].scatter(*zip(*pairs), s=1)
axes[i].set_xlabel(f"{label}")
axes[i].set_ylabel(f"{label}'")
axes[i].set_title(f"{label} vs {label}'")
plt.show()
# experiment with random scattering
N = 400
# generate U + SWAP + U + SWAP
U = iSwapGate().power(3 / 4)
coords = []
for _ in range(N):
qc = QuantumCircuit(2)
qc.append(U, [0, 1])
# random 1Q gate
qc.append(random_unitary(2).to_instruction(), [0])
qc.append(random_unitary(2).to_instruction(), [1])
qc.append(U, [0, 1])
qc.append(random_unitary(2).to_instruction(), [0])
qc.append(random_unitary(2).to_instruction(), [1])
qc.swap(0, 1)
# get coordinates
coords.append(c1c2c3(Operator(qc).data))
# plot
w = WeylChamber()
for c in coords:
w.add_point(*c)
w.plot()
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Creat a Quantum Circuit with Single Qubit
# With default Initial State as [1,0] or |0>
qc=QuantumCircuit(1)
#Declare the Initial State as [0,1] or |1>
initial_state=[0,1]
qc.initialize(initial_state,0)
# Apply the Pauli x-Gate on the qubit
qc.x(0)
# Draw the Circuit
# qc.draw()
qc.draw()
#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)
from qiskit import QuantumCircuit
qc = QuantumCircuit(1)
qc.x(0)
qc.draw('mpl')
#Visualize the output as an animation
from qiskit.visualization import visualize_transition
visualize_transition(qc)
|
https://github.com/adlrocha/cryptoq
|
adlrocha
|
from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister, Aer
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info import process_fidelity
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel, errors
from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle
import math
from qiskit.tools.visualization import plot_histogram
import numpy as np
import matplotlib.pyplot as plot
import string
from qiskit import IBMQ
IBMQ.load_accounts()
# Noise matrix
x = np.identity(16)
theta = 0.01
x[0][0] = math.cos(theta)
x[1][0] = math.sin(theta)
x[0][1] = -math.sin(theta)
x[1][1] = math.cos(theta)
def cheatingMatrices():
c1 = np.identity(2)
f = 1/math.sqrt(2)
c1[0][0] = f
c1[1][0] = -f
c1[0][1] = f
c1[1][1] = f
c2 = np.identity(2)
c2[0][0] = f
c2[1][0] = f
c2[0][1] = f
c2[1][1] = -f
return c1, c2
def rotationMatrix(theta):
x = np.identity(2)
x[0][0] = math.cos(theta)
x[1][0] = math.sin(theta)
x[0][1] = -math.sin(theta)
x[1][1] = math.cos(theta)
return x
#theta1 and theta2 eavsdroppter error
def generateQK(num_bits, theta1=0, theta2=0, securityThresh=1000, simulation=True, withHist=False):
# Create the circuit
cx_circ = parityCircuit(theta1, theta2)
if simulation:
# Execute the circuit
print("Running on simulation...")
job = execute(cx_circ, backend = Aer.get_backend('qasm_simulator'), shots=256*num_bits, memory=True)
result = job.result()
else:
# Execute the circuit
print("Running on real quantum computer...")
job = execute(cx_circ, backend = IBMQ.get_backend('ibmqx2'), shots=256*num_bits, memory=True)
result = job.result()
# Print circuit.
# print(cx_circ)
# Print the result
if withHist:
counts = result.get_counts(cx_circ)
plot.bar(counts.keys(), counts.values(), 1.0, color='g')
plot.show()
memory = result.get_memory()
num_bits = int(num_bits)
# memory = memory[len(memory)-num_bits: len(memory)]
res = {'A': '', 'B': '', 'errorCounter':0, 'valid': True}
counter = 0
i = len(memory)-1
while len(res["A"]) != num_bits:
# print('Memory', memory[i], i)
# Check if error in parity bit and discard if there is
if memory[i][4] == '0':
counter+=1
else:
res["A"] = res["A"] + memory[i][1]
res["B"] = res["B"] + memory[i][2]
# SecurityThreshold from which we discard the key
if counter >= securityThresh:
res['valid'] = False
res["errorCounter"] = counter
return res
i-=1
res["errorCounter"] = counter
return res
# ParityCircuit for random bit generator and parity bit
def parityCircuit(theta1=0, theta2=0):
# Noise rotation matrix.
n1 = rotationMatrix(theta1)
n2 = rotationMatrix(theta2)
n = np.kron(n1, n2)
# Noise operator
id_op = Operator(n)
truthtable = "10011001"
oracle = TruthTableOracle(truthtable)
or_cx = oracle.construct_circuit()
# print(oracle.output_register)
v = oracle.variable_register
o = oracle.output_register
cr1 = ClassicalRegister(3)
cr2 = ClassicalRegister(1)
cx_circ = QuantumCircuit(v, cr2)
or_cx.add_register(cr1)
cx_circ.h(v[1])
cx_circ.cx(v[1], v[0])
cx_circ.unitary(id_op, v[1:3], label='idop')
total_cx = cx_circ + or_cx
total_cx.measure(v, cr1)
total_cx.measure(o, cr2)
return total_cx
# ParityCircuit for random bit generator and parity bit
def parityCircuitCheating(cheating=False, cheatingType=0):
if cheating:
# Cheating operator
c1 = cheatingMatrices()[cheatingType]
else:
c1 = np.identity(2)
id_op = Operator(c1)
truthtable = "10011001"
oracle = TruthTableOracle(truthtable)
or_cx = oracle.construct_circuit()
# print(oracle.output_register)
v = oracle.variable_register
o = oracle.output_register
cr1 = ClassicalRegister(3)
cr2 = ClassicalRegister(1)
cx_circ = QuantumCircuit(v, cr2)
or_cx.add_register(cr1)
cx_circ.h(v[1])
cx_circ.cx(v[1], v[0])
cx_circ.unitary(id_op, v[cheatingType+1:cheatingType+2], label='idop')
total_cx = cx_circ + or_cx
total_cx.measure(v, cr1)
total_cx.measure(o, cr2)
return total_cx
def quantumConsensus(nodes=3, cheating=False, cheatingType=[0,0,0]):
# Placeholder for the nodes results
res = dict(zip(string.ascii_uppercase, range(1, nodes+1)))
toSend = dict(zip(string.ascii_uppercase, range(1, nodes+1)))
# While two nodes with the same value
while sum(res.values()) != 1:
# Placeholder for all measurements
pkts = ''
for i in range(nodes):
cx_circ = parityCircuitCheating(cheating, cheatingType[i])
job = execute(cx_circ, backend = Aer.get_backend('qasm_simulator'), shots=1, memory=True)
result = job.result()
memory = result.get_memory()
res[list(res.keys())[i]] = int(memory[0][1])
#Adding measurements
pkts += memory[0][2]
pkts += memory[0][1]
print(res)
print(res)
tmp = res.copy()
for value in tmp:
if res[value] == 1:
res['winner'] = value
# Corner case
print(pkts)
toSend[list(toSend.keys())[0]] = pkts[0] + pkts[len(pkts)-1]
#Adding proper nodes
for i in range(0, nodes):
# Preparing the packets
toSend[list(toSend.keys())[i]] = pkts[2*i] + pkts[2*i-1]
return res, toSend
def network3nodes(cheating, cheatingType):
res = quantumConsensus(3, cheating, cheatingType)
toSend = res[1]
# Cheat check
if toSend['A'][1] == toSend['C'][0]:
print('As validation correct')
else:
print('As validation failed. Someone cheating')
if toSend['B'][1] == toSend['A'][0]:
print('Bs validation correct')
else:
print('Bs validation failed. Someone cheating')
if toSend['C'][1] == toSend['B'][0]:
print('Cs validation correct')
else:
print('Cs validation failed. Someone cheating')
return res[0]
# print(generateQK(8, 1, 0.5, 100, False))
# print(quantumConsensus())
# print(network3nodes(False, [0,0,0]))
# print(cheatingMatrices())
# print(parityCircuit())
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from IPython.display import YouTubeVideo
YouTubeVideo('BYKc2RnQMqo', width=858, height=540)
!pip install qiskit --quiet
!pip install qiskit-aer --quiet
!pip install pylatexenc --quiet
# @markdown ### **1. Import `Qiskit` and essential packages** { display-mode: "form" }
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.circuit.library import QFT
from qiskit_aer import AerSimulator
from fractions import Fraction
import random
import sympy
import math
# @markdown ### **2. Controlled Modular Multiplication for $U(x) = a^x mod N$** { display-mode: "form" }
class CtrlMultCircuit(QuantumCircuit):
def __init__(self, a, binary_power, N):
super().__init__(N.bit_length())
self.a = a
self.power = 2 ** binary_power # Convert binary to decimal
self.N = N
self.name = f'{self.a}^{self.power} mod {self.N}'
self._create_circuit()
def _create_circuit(self):
for dec_power in range(self.power):
a_exp = self.a ** dec_power % self.N
for i in range(self.num_qubits):
if a_exp >> i & 1: self.x(i)
for j in range(i + 1, self.num_qubits):
if a_exp >> j & 1: self.swap(i, j)
# @markdown ### **3. Quantum Phase Estimation with `Modular Exponentiation` and `Quantum Fourier Transform` to find period $r$** { display-mode: "form" }
# @markdown 
class QPECircuit(QuantumCircuit):
def __init__(self, a, N):
super().__init__(2 * N.bit_length(), N.bit_length())
self.a = a
self.N = N
self._create_circuit()
def _modular_exponentiation(self):
for qbit_idx in range(self.num_qubits // 2):
self.append(
CtrlMultCircuit(self.a, qbit_idx, self.N).to_gate().control(),
[qbit_idx] + list(range(self.num_qubits // 2, 2 * self.num_qubits // 2))
)
def _create_circuit(self):
self.h(range(self.num_qubits // 2)) # Apply Hadamard gates to the first n qubits
self.x(self.num_qubits - 1)
self.barrier()
self._modular_exponentiation() # Apply controlled modular exponentiation
self.barrier()
self.append(
QFT(self.num_qubits // 2, inverse=True),
range(self.num_qubits // 2) # Apply inverse QFT to the first n qubits
)
def collapse(self, simulator):
self.measure(range(self.num_qubits // 2), range(self.num_qubits // 2))
transpiled_circuit = transpile(self, simulator)
self.collapse_result = simulator.run(transpiled_circuit, memory=True).result()
return self.collapse_result
# @markdown ### **4. Completed Shor's Algorithm for Integer Factorization** { display-mode: "form" }
class ShorAlgorithm:
def __init__(self, N, max_attempts=-1, random_coprime_only=False, simulator=None):
self.N = N
self.simulator = simulator
self.max_attempts = max_attempts # -1 for all possible values of a
self.random_coprime_only = random_coprime_only # True to select only coprime values of a and N
def execute(self):
is_N_invalid = self._is_N_invalid()
if is_N_invalid: return is_N_invalid
# Only coprime values remain if random_coprime_only is enabled,
# Otherwise select a random integer in [2, N) as initial guess
a_values = [a for a in range(2, self.N) if not self.random_coprime_only or (math.gcd(a, self.N) == 1)]
print(f'[INFO] {len(a_values)} possible values of a: {a_values}')
self.max_attempts = len(a_values) if self.max_attempts <= -1 else min(self.max_attempts, len(a_values))
attempts_count = 0
while attempts_count < self.max_attempts:
print(f'\n===== Attempt {attempts_count + 1}/{self.max_attempts} =====')
attempts_count += 1
self.chosen_a = random.choice(a_values)
self.r = 1
print(f'[START] Chosen base a: {self.chosen_a}')
if not self.random_coprime_only:
gcd = math.gcd(self.chosen_a, self.N)
if gcd != 1:
print(f'=> {self.chosen_a} and {self.N} share common factor: {self.N} = {gcd} * {self.N // gcd}')
return gcd, self.N // gcd
print(f'>>> {self.chosen_a} and {self.N} are coprime => Perform Quantum Phase Estimation to find {self.chosen_a}^r - 1 = 0 (MOD {self.N})')
if not self._quantum_period_finding():
a_values.remove(self.chosen_a)
self.r = self.chosen_a = self.qpe_circuit = None
continue
factors = self._classical_postprocess()
if factors: return factors
a_values.remove(self.chosen_a)
self.r = self.chosen_a = self.qpe_circuit = None
print(f'[FAIL] No non-trivial factors found after {self.max_attempts} attempts.')
def _is_N_invalid(self):
if self.N <= 3:
print('[ERR] N must be > 3')
return 1, self.N
if self.N % 2 == 0:
print(f'=> {self.N} is an even number: {self.N} = 2 * {self.N // 2}')
return 2, self.N // 2
if sympy.isprime(self.N):
print(f'=> {self.N} is a prime number: {self.N} = 1 * {self.N}')
return 1, self.N
max_exponent = int(math.log2(self.N)) # Start with a large exponent and reduce
for k in range(max_exponent, 1, -1):
p = round(self.N ** (1 / k))
if p ** k == self.N:
print(f'=> {self.N} is a power of prime: {self.N} = {p}^{k}')
return p, k
return False
def _quantum_period_finding(self):
while self.chosen_a ** self.r % self.N != 1: # QPE + continued fractions may find wrong r
self.qpe_circuit = QPECircuit(self.chosen_a, self.N) # Find phase s/r
result = self.qpe_circuit.collapse(self.simulator)
state_bin = result.get_memory()[0]
state_dec = int(state_bin, 2) # Convert to decimal
bits_count = 2 ** (self.N.bit_length() - 1)
phase = state_dec / bits_count
# Continued fraction to find r
self.r = Fraction(phase).limit_denominator(self.N).denominator # Get fraction that most closely approximates phase
if self.r > self.N or self.r == 1: # Safety check to avoid infinite loops
print(f'[ERR] Invalid period found: r = {self.r} => Retry with different a.')
return False
print(f'>>> Output State: |{state_bin}β© = {state_dec} (dec) => Phase = {state_dec} / {bits_count} = {phase:.3f}')
return True
def _classical_postprocess(self):
# Classical postprocessing to find factors from the period
print(f'>>> Found r = {self.r} => a^{{r/2}} Β± 1 = {self.chosen_a:.0f}^{self.r/2:.0f} Β± 1')
if self.r % 2 != 0:
print(f'[ERR] r = {self.r} is odd => Retry with different a.')
return None
int1, int2 = self.chosen_a ** (self.r // 2) - 1, self.chosen_a ** (self.r // 2) + 1
if int1 % self.N == 0 or int2 % self.N == 0:
print(f'[ERR] {self.chosen_a}^{self.r/2:.0f} Β± 1 is a multiple of {self.N} => Retry with different a.')
return None
factor1, factor2 = math.gcd(int1, self.N), math.gcd(int2, self.N)
if factor1 not in [1, self.N] and factor2 not in [1, self.N]: # Check to see if factor is non-trivial
print(f'[DONE] Successfully found non-trivial factors: {self.N} = {factor1} * {factor2}')
return factor1, factor2
print(f'[FAIL] Trivial factors found: [1, {self.N}] => Retry with different a.')
return None
# @markdown ### **5. Run the Factorization** { display-mode: "form" }
number_to_factor = 21 # @param {type:"slider", min: 15, max: 55, step: 1}
max_attempts = -1 # @param {type:"slider", min:-1, max:100, step:10}
random_coprime_only = False # @param {type:"boolean"}
# @markdown ***Note**: `max_attempts` will be limited to number of available values.
shor = ShorAlgorithm(number_to_factor, max_attempts, random_coprime_only, AerSimulator())
factors = shor.execute()
try: display(shor.qpe_circuit.draw(output='mpl', fold=-1))
except Exception: pass
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
def calculate_energy(J, Ο):
return sum(J_ij*Ο[i]*Ο[i+1] for i, J_ij in enumerate(J))
J = [1.0, -1.0]
Ο = [+1, -1, +1]
calculate_energy(J, Ο)
import itertools
for Ο in itertools.product(*[{+1,-1} for _ in range(3)]):
print(calculate_energy(J, Ο), Ο)
import dimod
J = {(0, 1): 1.0, (1, 2): -1.0}
h = {0:0, 1:0, 2:0}
model = dimod.BinaryQuadraticModel(h, J, 0.0, dimod.SPIN)
sampler = dimod.SimulatedAnnealingSampler()
response = sampler.sample(model, num_reads=10)
[solution.energy for solution in response.data()].count(-2)
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit import BasicAer
np.set_printoptions(precision=3, suppress=True)
backend = BasicAer.get_backend('statevector_simulator')
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
circuit.z(q[0])
job = execute(circuit, backend)
state = job.result().get_statevector(circuit)
print(state)
circuit = QuantumCircuit(q, c)
circuit.x(q[0])
circuit.z(q[0])
job = execute(circuit, backend)
state = job.result().get_statevector(circuit)
print(state)
def calculate_energy_expectation(state, hamiltonian):
return float(np.dot(state.T.conj(), np.dot(hamiltonian, state)).real)
Z = np.array([[1, 0], [0, -1]])
IZ = np.kron(np.eye(2), Z)
ZI = np.kron(Z, np.eye(2))
ZZ = np.kron(Z, Z)
H = -ZZ + -0.5*(ZI+IZ)
Ο = np.kron([[1], [0]], [[1], [0]])
calculate_energy_expectation(Ο, H)
circuit = QuantumCircuit(q, c)
circuit.x(q[0])
circuit.z(q[0])
job = execute(circuit, backend)
state = job.result().get_statevector(circuit)
print("Pauli-X, then Pauli-Z:", state)
circuit = QuantumCircuit(q, c)
circuit.z(q[0])
circuit.x(q[0])
job = execute(circuit, backend)
state = job.result().get_statevector(circuit)
print("Pauli-Z, then Pauli-X:", state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
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()
|
https://github.com/QuantumVic/discrete-time-quantum-walks
|
QuantumVic
|
from qiskit import *
import numpy as np
import matplotlib as mpl
from qiskit.tools.visualization import plot_histogram, plot_state_city
state_sim = Aer.get_backend('statevector_simulator')
qasm_sim = Aer.get_backend('qasm_simulator')
qiskit.__qiskit_version__ #developed in q0.14.0, q-terra0.11.0
# Definition of c_Increment, c_Decrement gates
def increment(qc,qr):
for i in range(num_qubits - 1):
qc.mct(qr[0:num_qubits - 1 - i], qr[num_qubits - 1 - i] , qr_aux)
def decrement(qc,qr):
for i in range(num_qubits - 1):
qc.x(qr[0:num_qubits - 1 - i])
qc.mct(qr[0:num_qubits - 1 - i], qr[num_qubits - 1 - i], qr_aux)
qc.x(qr[0:num_qubits - 1 - i])
# Definition of QW cycle
def quantum_walk(qc,qr,num_steps):
for i in range(num_steps):
qc.h(qr[0])
increment(qc,qr)
decrement(qc,qr)
# Input total number of qubits = nodes + coin
num_qubits = 7
# Define qRegister and qCircuit
qr = QuantumRegister(num_qubits, 'qr')
cr = ClassicalRegister(num_qubits - 1, 'cr')
# We need (num_control - 2) aux qubits for mct
if num_qubits > 3:
qr_aux = QuantumRegister(num_qubits - 3, 'aux')
qc = QuantumCircuit(qr,qr_aux,cr)
else:
qr_aux = None
qc = QuantumCircuit(qr,cr)
# Initialization for symmetric state 1/sqrt(2) [|0> + i|1>] of coin
qc.h(qr[0])
qc.s(qr[0])
qc.barrier(qr,qr_aux)
# Initialization for middle state |1000...> of nodes
qc.x(qr[num_qubits - 1])
qc.barrier(qr,qr_aux)
# Running the QW
quantum_walk(qc,qr,1)
qc.measure(qr[1:num_qubits],cr)
qc.draw(output='mpl')
# Execute the circuit
result = execute(qc, qasm_sim).result()
results_dict = result.get_counts()
# Convert the results to decimal value of cReg and plot
results_dec = {}
for key, value in results_dict.items():
results_dec[str(int(key,2))] = value
plot_histogram(results_dec)
|
https://github.com/xijia-tao/comp3316-a4-code
|
xijia-tao
|
import matplotlib.pyplot as plt
import numpy as np
import math
# importing Qiskit
from qiskit import Aer, transpile, assemble
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
qpe = QuantumCircuit(4, 3)
qpe.x(3)
qpe.draw()
for qubit in range(3):
qpe.h(qubit)
qpe.draw()
angle = 2*math.pi/8
repetitions = 1
for counting_qubit in range(3):
for i in range(repetitions):
qpe.cp(math.pi/4, counting_qubit, 3)
repetitions *= 2
qpe.draw()
def qft_dagger(qc, n):
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-math.pi/float(2**(j-m)), m, j)
qc.h(j)
qpe.barrier()
qft_dagger(qpe, 3)
qpe.barrier()
qpe.draw()
for n in range(3):
qpe.measure(n, n)
qpe.draw()
aer_sim = Aer.get_backend('aer_simulator')
shots = 2048
t_qpe = transpile(qpe, aer_sim)
qobj = assemble(t_qpe, shots=shots)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
qpe2 = QuantumCircuit(4, 3)
for qubit in range(3):
qpe2.h(qubit)
qpe2.x(3)
angle = 2*math.pi/3
repetitions = 1
for counting_qubit in range(3):
for i in range(repetitions):
qpe2.cp(angle, counting_qubit, 3);
repetitions *= 2
qft_dagger(qpe2, 3)
for n in range(3):
qpe2.measure(n, n)
qpe2.draw()
aer_sim = Aer.get_backend('aer_simulator')
shots = 2048
t_qpe2 = transpile(qpe2, aer_sim)
qobj = assemble(t_qpe2, shots=shots)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
qpe3 = QuantumCircuit(6, 5)
for qubit in range(5):
qpe3.h(qubit)
qpe3.x(5)
angle = 2*math.pi/3
repetitions = 1
for counting_qubit in range(5):
for i in range(repetitions):
qpe3.cp(angle, counting_qubit, 5);
repetitions *= 2
qft_dagger(qpe3, 5)
for n in range(5):
qpe3.measure(n, n)
qpe3.draw()
aer_sim = Aer.get_backend('aer_simulator')
shots = 2048
t_qpe3 = transpile(qpe3, aer_sim)
qobj = assemble(t_qpe3, shots=shots)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
|
https://github.com/Simultonian/hamilutor-qiskit
|
Simultonian
|
from typing import Callable
from qiskit import QuantumCircuit
from ..grouping.grouper import Grouper
from ..trotter.simple import trotter_from_terms
from ..utils import circuit_constructor, get_el
def generic(
grouper_class: Callable[[set[str]], Grouper],
orderer: Callable[[set[str]], list[str]],
h: dict[str, float],
t: float = 1.0,
reps: int = 1,
) -> QuantumCircuit:
"""
A generic trotterization constructor.
Inputs:
- grouper: Pauli grouper
- orderer: Function that orders the diagonalized terms
- h: Hamiltonian in dictionary form
- t: Float representing time of evolution
- reps: Repetitions for Trotterization.
Returns: QuantumCircuit that will simulate the Hamiltonian
"""
pauli_list = set(h.keys())
if len(pauli_list) == 0:
raise ValueError("Input Hamiltonian was empty.")
# size of any pauli operator
first = get_el(pauli_list)
num_qubits = len(first)
grouper = grouper_class(pauli_list)
groups = grouper.groups
group_circs = []
# Get relevant circuits for all the groups
for group in groups:
pauli = get_el(group)
# Diagonalizing circuits
diag_circ = circuit_constructor(grouper.circuit(pauli))
diag_circ_c = diag_circ.inverse()
# Setting the order according to ordere
ordered = orderer(group)
ordered_tuples = []
for p in ordered:
coeff, term = grouper.diagonalize(p)
coeff = (t / reps) * h[p] * coeff
ordered_tuples.append((term, coeff))
# time will be scaled down by reps
exp_circ = trotter_from_terms(ordered_tuples)
final_circuit = QuantumCircuit(num_qubits)
# TODO: Issue 30
# Combining the three sections
final_circuit = diag_circ.compose(exp_circ)
final_circuit = final_circuit.compose(diag_circ_c)
group_circs.append(final_circuit)
final_circuit = QuantumCircuit(num_qubits)
for _ in range(reps):
for group_circ in group_circs:
final_circuit = final_circuit.compose(group_circ)
return final_circuit
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Black-box state preparation
Grover, Lov K. "Synthesis of quantum superpositions by quantum computation."
Physical review letters 85.6 (2000): 1334.
Gate U2 in PRL 85.6 (2000) is implemented with uniformly controlled rotations
"""
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library import UCRYGate, UCRZGate
from qiskit.circuit.library import UnitaryGate
from qclib.gates.initialize import Initialize
class BlackBoxInitialize(Initialize):
"""
Black-box state preparation
Grover, Lov K. "Synthesis of quantum superpositions by quantum computation."
Physical review letters 85.6 (2000): 1334.
Gate U2 in PRL 85.6 (2000) is implemented with uniformly controlled rotations
"""
def __init__(self, params, label=None):
self._name = "blackbox"
self._get_num_qubits(params)
self.num_qubits += 1
if label is None:
label = "BBSP"
super().__init__(self._name, self.num_qubits, params, label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
n_amplitudes = len(self.params)
theta = 2 * np.arccos(np.abs(self.params))
phi = -2 * np.angle(self.params)
ury_gate = UCRYGate(list(theta))
urz_gate = UCRZGate(list(phi))
gate_u = QuantumCircuit(self.num_qubits, name="U")
gate_u.h(gate_u.qubits[1:])
gate_u.append(ury_gate, gate_u.qubits)
gate_u.append(urz_gate, gate_u.qubits)
gate_u = gate_u.to_instruction()
it_matrix = [[-1, 0], [0, 1]]
gate_it = UnitaryGate(it_matrix)
gate_it.name = "I_t"
gate_is = gate_it.control(self.num_qubits - 1, ctrl_state=0)
gate_is.name = "I_s"
repetitions = (np.pi / 4) * (
np.sqrt(n_amplitudes) / np.linalg.norm(self.params)
)
repetitions = int(repetitions)
q_circuit = QuantumCircuit(self.num_qubits)
for _ in range(repetitions):
q_circuit.append(gate_u, q_circuit.qubits)
q_circuit.append(gate_it, q_circuit.qubits[0:1])
q_circuit.append(gate_u.inverse(), q_circuit.qubits)
q_circuit.append(gate_is, q_circuit.qubits)
q_circuit.append(gate_u, q_circuit.qubits)
if repetitions % 2 == 1:
q_circuit.global_phase = np.pi
return q_circuit
@staticmethod
def initialize(q_circuit, state, qubits=None):
if qubits is None:
q_circuit.append(BlackBoxInitialize(state), q_circuit.qubits)
else:
q_circuit.append(BlackBoxInitialize(state), qubits)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# -*- 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 copy
import itertools
from functools import reduce
import logging
import json
from operator import iadd as op_iadd, isub as op_isub
import sys
import numpy as np
from scipy import sparse as scisparse
from scipy import linalg as scila
from qiskit import ClassicalRegister, QuantumCircuit
from qiskit.quantum_info import Pauli
from qiskit.qasm import pi
from qiskit.assembler.run_config import RunConfig
from qiskit.tools import parallel_map
from qiskit.tools.events import TextProgressBar
from qiskit.aqua import AquaError, aqua_globals
from qiskit.aqua.utils import PauliGraph, compile_and_run_circuits, find_regs_by_name
from qiskit.aqua.utils.backend_utils import is_statevector_backend
logger = logging.getLogger(__name__)
class Operator(object):
"""
Operators relevant for quantum applications
Note:
For grouped paulis representation, all operations will always convert it to paulis and then convert it back.
(It might be a performance issue.)
"""
def __init__(self, paulis=None, grouped_paulis=None, matrix=None, coloring="largest-degree"):
"""
Args:
paulis ([[float, Pauli]]): each list contains a coefficient (real number) and a corresponding Pauli class object.
grouped_paulis ([[[float, Pauli]]]): each list of list contains a grouped paulis.
matrix (numpy.ndarray or scipy.sparse.csr_matrix) : a 2-D sparse matrix represents operator (using CSR format internally)
coloring (bool): method to group paulis.
"""
self._paulis = paulis
self._coloring = coloring
self._grouped_paulis = grouped_paulis
if matrix is not None:
matrix = matrix if scisparse.issparse(matrix) else scisparse.csr_matrix(matrix)
matrix = matrix if scisparse.isspmatrix_csr(matrix) else matrix.to_csr(copy=True)
self._matrix = matrix
self._to_dia_matrix(mode="matrix")
# use for fast lookup whether or not the paulis is existed.
self._simplify_paulis()
self._summarize_circuits = False
def _extend_or_combine(self, rhs, mode, operation=op_iadd):
"""
Add two operators either extend (in-place) or combine (copy) them.
The addition performs optimized combiniation of two operators.
If `rhs` has identical basis, the coefficient are combined rather than
appended.
Args:
rhs (Operator): to-be-combined operator
mode (str): in-place or not.
Returns:
Operator: the operator.
"""
if mode == 'inplace':
lhs = self
elif mode == 'non-inplace':
lhs = copy.deepcopy(self)
if lhs._paulis is not None and rhs._paulis is not None:
for pauli in rhs._paulis:
pauli_label = pauli[1].to_label()
idx = lhs._paulis_table.get(pauli_label, None)
if idx is not None:
lhs._paulis[idx][0] = operation(lhs._paulis[idx][0], pauli[0])
else:
lhs._paulis_table[pauli_label] = len(lhs._paulis)
new_pauli = copy.deepcopy(pauli)
new_pauli[0] = operation(0.0, pauli[0])
lhs._paulis.append(new_pauli)
elif lhs._grouped_paulis is not None and rhs._grouped_paulis is not None:
lhs._grouped_paulis_to_paulis()
rhs._grouped_paulis_to_paulis()
lhs = operation(lhs, rhs)
lhs._paulis_to_grouped_paulis()
elif lhs._matrix is not None and rhs._matrix is not None:
lhs._matrix = operation(lhs._matrix, rhs._matrix)
lhs._to_dia_matrix(mode='matrix')
else:
raise TypeError("the representations of two Operators should be the same. ({}, {})".format(
lhs.representations, rhs.representations))
return lhs
def __add__(self, rhs):
"""Overload + operation"""
return self._extend_or_combine(rhs, 'non-inplace', op_iadd)
def __iadd__(self, rhs):
"""Overload += operation"""
return self._extend_or_combine(rhs, 'inplace', op_iadd)
def __sub__(self, rhs):
"""Overload - operation"""
return self._extend_or_combine(rhs, 'non-inplace', op_isub)
def __isub__(self, rhs):
"""Overload -= operation"""
return self._extend_or_combine(rhs, 'inplace', op_isub)
def __neg__(self):
"""Overload unary - """
ret = copy.deepcopy(self)
ret.scaling_coeff(-1.0)
return ret
def __eq__(self, rhs):
"""Overload == operation"""
if self._matrix is not None and rhs._matrix is not None:
return np.all(self._matrix == rhs._matrix)
if self._paulis is not None and rhs._paulis is not None:
if len(self._paulis) != len(rhs._paulis):
return False
for coeff, pauli in self._paulis:
found_pauli = False
rhs_coeff = 0.0
for coeff2, pauli2 in rhs._paulis:
if pauli == pauli2:
found_pauli = True
rhs_coeff = coeff2
break
if not found_pauli and rhs_coeff != 0.0: # since we might have 0 weights of paulis.
return False
if coeff != rhs_coeff:
return False
return True
if self._grouped_paulis is not None and rhs._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
rhs._grouped_paulis_to_paulis()
return self.__eq__(rhs)
def __ne__(self, rhs):
""" != """
return not self.__eq__(rhs)
def __str__(self):
"""Overload str()"""
curr_repr = ""
length = ""
group = None
if self._paulis is not None:
curr_repr = 'paulis'
length = len(self._paulis)
elif self._grouped_paulis is not None:
curr_repr = 'grouped_paulis'
group = len(self._grouped_paulis)
length = sum([len(gp) - 1 for gp in self._grouped_paulis])
elif self._matrix is not None:
curr_repr = 'matrix'
length = "{}x{}".format(2 ** self.num_qubits, 2 ** self.num_qubits)
ret = "Representation: {}, qubits: {}, size: {}{}".format(
curr_repr, self.num_qubits, length, "" if group is None else " (number of groups: {})".format(group))
return ret
def copy(self):
"""Get a copy of self."""
return copy.deepcopy(self)
def chop(self, threshold=1e-15):
"""
Eliminate the real and imagine part of coeff in each pauli by `threshold`.
If pauli's coeff is less then `threshold` in both real and imagine parts, the pauli is removed.
To align the internal representations, all available representations are chopped.
The chopped result is stored back to original property.
Note: if coeff is real-only, the imag part is skipped.
Args:
threshold (float): threshold chops the paulis
"""
def chop_real_imag(coeff, threshold):
temp_real = coeff.real if np.absolute(coeff.real) >= threshold else 0.0
temp_imag = coeff.imag if np.absolute(coeff.imag) >= threshold else 0.0
if temp_real == 0.0 and temp_imag == 0.0:
return 0.0
else:
new_coeff = temp_real + 1j * temp_imag
return new_coeff
if self._paulis is not None:
for i in range(len(self._paulis)):
self._paulis[i][0] = chop_real_imag(self._paulis[i][0], threshold)
paulis = [x for x in self._paulis if x[0] != 0.0]
self._paulis = paulis
self._paulis_table = {pauli[1].to_label(): i for i, pauli in enumerate(self._paulis)}
if self._dia_matrix is not None:
self._to_dia_matrix('paulis')
elif self._grouped_paulis is not None:
grouped_paulis = []
for group_idx in range(1, len(self._grouped_paulis)):
for pauli_idx in range(len(self._grouped_paulis[group_idx])):
self._grouped_paulis[group_idx][pauli_idx][0] = chop_real_imag(
self._grouped_paulis[group_idx][pauli_idx][0], threshold)
paulis = [x for x in self._grouped_paulis[group_idx] if x[0] != 0.0]
grouped_paulis.append(paulis)
self._grouped_paulis = grouped_paulis
if self._dia_matrix is not None:
self._to_dia_matrix('grouped_paulis')
elif self._matrix is not None:
rows, cols = self._matrix.nonzero()
for row, col in zip(rows, cols):
self._matrix[row, col] = chop_real_imag(self._matrix[row, col], threshold)
self._matrix.eliminate_zeros()
if self._dia_matrix is not None:
self._to_dia_matrix('matrix')
def _simplify_paulis(self):
"""
Merge the paulis (grouped_paulis) whose bases are identical but the pauli with zero coefficient
would not be removed.
Usually used in construction.
"""
if self._paulis is not None:
new_paulis = []
new_paulis_table = {}
for curr_paulis in self._paulis:
pauli_label = curr_paulis[1].to_label()
new_idx = new_paulis_table.get(pauli_label, None)
if new_idx is not None:
new_paulis[new_idx][0] += curr_paulis[0]
else:
new_paulis_table[pauli_label] = len(new_paulis)
new_paulis.append(curr_paulis)
self._paulis = new_paulis
self._paulis_table = new_paulis_table
elif self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
self._simplify_paulis()
self._paulis_to_grouped_paulis()
def __mul__(self, rhs):
"""
Overload * operation. Only support two Operators have the same representation mode.
Returns:
Operator: the multipled Operator.
Raises:
TypeError, if two Operators do not have the same representations.
"""
if self._paulis is not None and rhs._paulis is not None:
ret_pauli = Operator(paulis=[])
for existed_pauli in self._paulis:
for pauli in rhs._paulis:
basis, sign = Pauli.sgn_prod(existed_pauli[1], pauli[1])
coeff = existed_pauli[0] * pauli[0] * sign
if abs(coeff) > 1e-15:
pauli_term = [coeff, basis]
ret_pauli += Operator(paulis=[pauli_term])
return ret_pauli
elif self._grouped_paulis is not None and rhs._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
rhs._grouped_paulis_to_paulis()
mul_pauli = self * rhs
mul_pauli._paulis_to_grouped_paulis()
ret_grouped_pauli = Operator(paulis=mul_pauli._paulis, grouped_paulis=mul_pauli._grouped_paulis)
return ret_grouped_pauli
elif self._matrix is not None and rhs._matrix is not None:
ret_matrix = self._matrix.dot(rhs._matrix)
return Operator(matrix=ret_matrix)
else:
raise TypeError("the representations of two Operators should be the same. ({}, {})".format(
self.representations, rhs.representations))
@property
def coloring(self):
"""Getter of method of grouping paulis"""
return self._coloring
@coloring.setter
def coloring(self, new_coloring):
"""Setter of method of grouping paulis"""
self._coloring = new_coloring
@property
def aer_paulis(self):
if getattr(self, '_aer_paulis', None) is None:
self.to_paulis()
aer_paulis = []
for coeff, p in self._paulis:
new_coeff = [coeff.real, coeff.imag]
new_p = p.to_label()
aer_paulis.append([new_coeff, new_p])
self._aer_paulis = aer_paulis
return self._aer_paulis
def _to_dia_matrix(self, mode):
"""
Convert the reprenetations into diagonal matrix if possible and then store it back.
For paulis, if all paulis are Z or I (identity), convert to dia_matrix.
Args:
mode (str): "matrix", "paulis" or "grouped_paulis".
"""
if mode not in ['matrix', 'paulis', 'grouped_paulis']:
raise ValueError(
'Mode should be one of "matrix", "paulis", "grouped_paulis"')
if mode == 'matrix' and self._matrix is not None:
dia_matrix = self._matrix.diagonal()
if not scisparse.csr_matrix(dia_matrix).nnz == self._matrix.nnz:
dia_matrix = None
self._dia_matrix = dia_matrix
elif mode == 'paulis' and self._paulis is not None:
if self._paulis == []:
self._dia_matrix = None
else:
valid_dia_matrix_flag = True
dia_matrix = 0.0
for idx in range(len(self._paulis)):
coeff, pauli = self._paulis[idx][0], self._paulis[idx][1]
if not (np.all(np.logical_not(pauli.x))):
valid_dia_matrix_flag = False
break
dia_matrix += coeff * pauli.to_spmatrix().diagonal()
self._dia_matrix = dia_matrix.copy() if valid_dia_matrix_flag else None
elif mode == 'grouped_paulis' and self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
self._to_dia_matrix(mode='paulis')
self._paulis_to_grouped_paulis()
else:
self._dia_matrix = None
@property
def paulis(self):
"""Getter of Pauli list."""
return self._paulis
@property
def grouped_paulis(self):
"""Getter of grouped Pauli list."""
return self._grouped_paulis
@property
def matrix(self):
"""Getter of matrix; if matrix is diagonal, diagonal matrix is returned instead."""
return self._dia_matrix if self._dia_matrix is not None else self._matrix
def enable_summarize_circuits(self):
self._summarize_circuits = True
def disable_summarize_circuits(self):
self._summarize_circuits = False
@property
def representations(self):
"""
Return the available representations in the Operator.
Returns:
list: available representations ([str])
"""
ret = []
if self._paulis is not None:
ret.append("paulis")
if self._grouped_paulis is not None:
ret.append("grouped_paulis")
if self._matrix is not None:
ret.append("matrix")
return ret
@property
def num_qubits(self):
"""
number of qubits required for the operator.
Returns:
int: number of qubits
"""
if self._paulis is not None:
if self._paulis != []:
return len(self._paulis[0][1])
else:
return 0
elif self._grouped_paulis is not None and self._grouped_paulis != []:
return len(self._grouped_paulis[0][0][1])
else:
return int(np.log2(self._matrix.shape[0]))
@staticmethod
def load_from_file(file_name, before_04=False):
"""
Load paulis in a file to construct an Operator.
Args:
file_name (str): path to the file, which contains a list of Paulis and coefficients.
before_04 (bool): support the format < 0.4.
Returns:
Operator class: the loaded operator.
"""
with open(file_name, 'r') as file:
return Operator.load_from_dict(json.load(file), before_04=before_04)
def save_to_file(self, file_name):
"""
Save operator to a file in pauli representation.
Args:
file_name (str): path to the file
"""
with open(file_name, 'w') as f:
json.dump(self.save_to_dict(), f)
@staticmethod
def load_from_dict(dictionary, before_04=False):
"""
Load paulis in a dict to construct an Operator, \
the dict must be represented as follows: label and coeff (real and imag). \
E.g.: \
{'paulis': \
[ \
{'label': 'IIII', \
'coeff': {'real': -0.33562957575267038, 'imag': 0.0}}, \
{'label': 'ZIII', \
'coeff': {'real': 0.28220597164664896, 'imag': 0.0}}, \
... \
] \
} \
Args:
dictionary (dict): dictionary, which contains a list of Paulis and coefficients.
before_04 (bool): support the format < 0.4.
Returns:
Operator: the loaded operator.
"""
if 'paulis' not in dictionary:
raise AquaError('Dictionary missing "paulis" key')
paulis = []
for op in dictionary['paulis']:
if 'label' not in op:
raise AquaError('Dictionary missing "label" key')
pauli_label = op['label']
if 'coeff' not in op:
raise AquaError('Dictionary missing "coeff" key')
pauli_coeff = op['coeff']
if 'real' not in pauli_coeff:
raise AquaError('Dictionary missing "real" key')
coeff = pauli_coeff['real']
if 'imag' in pauli_coeff:
coeff = complex(pauli_coeff['real'], pauli_coeff['imag'])
pauli_label = pauli_label[::-1] if before_04 else pauli_label
paulis.append([coeff, Pauli.from_label(pauli_label)])
return Operator(paulis=paulis)
def save_to_dict(self):
"""
Save operator to a dict in pauli representation.
Returns:
dict: a dictionary contains an operator with pauli representation.
"""
self._check_representation("paulis")
ret_dict = {"paulis": []}
for pauli in self._paulis:
op = {"label": pauli[1].to_label()}
if isinstance(pauli[0], complex):
op["coeff"] = {"real": np.real(pauli[0]),
"imag": np.imag(pauli[0])
}
else:
op["coeff"] = {"real": pauli[0]}
ret_dict["paulis"].append(op)
return ret_dict
def print_operators(self, print_format='paulis'):
"""
Print out the paulis in the selected representation.
Args:
print_format (str): "paulis", "grouped_paulis", "matrix"
Returns:
str: a formated operator.
Raises:
ValueError: if `print_format` is not supported.
"""
ret = ""
if print_format == 'paulis':
self._check_representation("paulis")
for pauli in self._paulis:
ret = ''.join([ret, "{}\t{}\n".format(pauli[1].to_label(), pauli[0])])
if ret == "":
ret = ''.join([ret, "Pauli list is empty."])
elif print_format == 'grouped_paulis':
self._check_representation("grouped_paulis")
for i in range(len(self._grouped_paulis)):
ret = ''.join([ret, 'Post Rotations of TPB set {} '.format(i)])
ret = ''.join([ret, ': {} '.format(self._grouped_paulis[i][0][1].to_label())])
ret = ''.join([ret, '\n'])
for j in range(1, len(self._grouped_paulis[i])):
ret = ''.join([ret, '{} '.format(self._grouped_paulis[i][j][1].to_label())])
ret = ''.join([ret, '{}\n'.format(self._grouped_paulis[i][j][0])])
ret = ''.join([ret, '\n'])
if ret == "":
ret = ''.join([ret, "Grouped pauli list is empty."])
elif print_format == 'matrix':
self._check_representation("matrix")
ret = str(self._matrix.toarray())
else:
raise ValueError('Mode should be one of "matrix", "paulis", "grouped_paulis"')
return ret
def construct_evaluation_circuit(self, operator_mode, input_circuit, backend, use_simulator_operator_mode=False):
"""
Construct the circuits for evaluation.
Args:
operator_mode (str): representation of operator, including paulis, grouped_paulis and matrix
input_circuit (QuantumCircuit): the quantum circuit.
backend (BaseBackend): backend selection for quantum machine.
use_simulator_operator_mode (bool): if aer_provider is used, we can do faster
evaluation for pauli mode on statevector simualtion
Returns:
[QuantumCircuit]: the circuits for evaluation.
"""
if is_statevector_backend(backend):
if operator_mode == 'matrix':
circuits = [input_circuit]
else:
self._check_representation("paulis")
if use_simulator_operator_mode:
circuits = [input_circuit]
else:
n_qubits = self.num_qubits
q = find_regs_by_name(input_circuit, 'q')
circuits = [input_circuit]
for idx, pauli in enumerate(self._paulis):
circuit = QuantumCircuit() + input_circuit
if np.all(np.logical_not(pauli[1].z)) and np.all(np.logical_not(pauli[1].x)): # all I
continue
for qubit_idx in range(n_qubits):
if not pauli[1].z[qubit_idx] and pauli[1].x[qubit_idx]:
circuit.u3(np.pi, 0.0, np.pi, q[qubit_idx]) # x
elif pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]:
circuit.u1(np.pi, q[qubit_idx]) # z
elif pauli[1].z[qubit_idx] and pauli[1].x[qubit_idx]:
circuit.u3(np.pi, np.pi/2, np.pi/2, q[qubit_idx]) # y
circuits.append(circuit)
else:
if operator_mode == 'matrix':
raise AquaError("matrix mode can not be used with non-statevector simulator.")
n_qubits = self.num_qubits
circuits = []
base_circuit = QuantumCircuit() + input_circuit
c = find_regs_by_name(base_circuit, 'c', qreg=False)
if c is None:
c = ClassicalRegister(n_qubits, name='c')
base_circuit.add_register(c)
if operator_mode == "paulis":
self._check_representation("paulis")
for idx, pauli in enumerate(self._paulis):
circuit = QuantumCircuit() + base_circuit
q = find_regs_by_name(circuit, 'q')
c = find_regs_by_name(circuit, 'c', qreg=False)
for qubit_idx in range(n_qubits):
if pauli[1].x[qubit_idx]:
if pauli[1].z[qubit_idx]:
# Measure Y
circuit.u1(-np.pi/2, q[qubit_idx]) # sdg
circuit.u2(0.0, np.pi, q[qubit_idx]) # h
else:
# Measure X
circuit.u2(0.0, np.pi, q[qubit_idx]) # h
circuit.barrier(q)
circuit.measure(q, c)
circuits.append(circuit)
else:
self._check_representation("grouped_paulis")
for idx, tpb_set in enumerate(self._grouped_paulis):
circuit = QuantumCircuit() + base_circuit
q = find_regs_by_name(circuit, 'q')
c = find_regs_by_name(circuit, 'c', qreg=False)
for qubit_idx in range(n_qubits):
if tpb_set[0][1].x[qubit_idx]:
if tpb_set[0][1].z[qubit_idx]:
# Measure Y
circuit.u1(-np.pi/2, q[qubit_idx]) # sdg
circuit.u2(0.0, np.pi, q[qubit_idx]) # h
else:
# Measure X
circuit.u2(0.0, np.pi, q[qubit_idx]) # h
circuit.barrier(q)
circuit.measure(q, c)
circuits.append(circuit)
return circuits
def evaluate_with_result(self, operator_mode, circuits, backend, result, use_simulator_operator_mode=False):
"""
Use the executed result with operator to get the evaluated value.
Args:
operator_mode (str): representation of operator, including paulis, grouped_paulis and matrix
circuits (list of qiskit.QuantumCircuit): the quantum circuits.
backend (str): backend selection for quantum machine.
result (qiskit.Result): the result from the backend.
use_simulator_operator_mode (bool): if aer_provider is used, we can do faster
evaluation for pauli mode on statevector simualtion
Returns:
float: the mean value
float: the standard deviation
"""
avg, std_dev, variance = 0.0, 0.0, 0.0
if is_statevector_backend(backend):
if operator_mode == "matrix":
self._check_representation("matrix")
if self._dia_matrix is None:
self._to_dia_matrix(mode='matrix')
quantum_state = np.asarray(result.get_statevector(circuits[0]))
if self._dia_matrix is not None:
avg = np.sum(self._dia_matrix * np.absolute(quantum_state) ** 2)
else:
avg = np.vdot(quantum_state, self._matrix.dot(quantum_state))
else:
self._check_representation("paulis")
if use_simulator_operator_mode:
temp = result.data(circuits[0])['snapshots']['expectation_value']['test'][0]['value']
avg = temp[0] + 1j * temp[1]
else:
quantum_state = np.asarray(result.get_statevector(circuits[0]))
circuit_idx = 1
for idx, pauli in enumerate(self._paulis):
if np.all(np.logical_not(pauli[1].z)) and np.all(np.logical_not(pauli[1].x)):
avg += pauli[0]
else:
quantum_state_i = np.asarray(result.get_statevector(circuits[circuit_idx]))
avg += pauli[0] * (np.vdot(quantum_state, quantum_state_i))
circuit_idx += 1
else:
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Computing the expectation from measurement results:")
TextProgressBar(sys.stderr)
num_shots = sum(list(result.get_counts(circuits[0]).values()))
if operator_mode == "paulis":
self._check_representation("paulis")
results = parallel_map(Operator._routine_paulis_with_shots,
[(pauli, result.get_counts(circuits[idx]))
for idx, pauli in enumerate(self._paulis)],
num_processes=aqua_globals.num_processes)
for result in results:
avg += result[0]
variance += result[1]
else:
self._check_representation("grouped_paulis")
results = parallel_map(Operator._routine_grouped_paulis_with_shots,
[(tpb_set, result.get_counts(circuits[tpb_idx]))
for tpb_idx, tpb_set in enumerate(self._grouped_paulis)],
num_processes=aqua_globals.num_processes)
for result in results:
avg += result[0]
variance += result[1]
std_dev = np.sqrt(variance / num_shots)
return avg, std_dev
@staticmethod
def _routine_grouped_paulis_with_shots(args):
tpb_set, measured_results = args
avg_paulis = []
avg = 0.0
variance = 0.0
for pauli_idx, pauli in enumerate(tpb_set):
if pauli_idx == 0:
continue
observable = Operator._measure_pauli_z(measured_results, pauli[1])
avg_paulis.append(observable)
avg += pauli[0] * observable
# Compute the covariance matrix elements of tpb_set
# and add up to the total standard deviation
# tpb_set = grouped_paulis, tensor product basis set
for pauli_1_idx, pauli_1 in enumerate(tpb_set):
for pauli_2_idx, pauli_2 in enumerate(tpb_set):
if pauli_1_idx == 0 or pauli_2_idx == 0:
continue
variance += pauli_1[0] * pauli_2[0] * \
Operator._covariance(measured_results, pauli_1[1], pauli_2[1],
avg_paulis[pauli_1_idx-1], avg_paulis[pauli_2_idx-1])
return avg, variance
@staticmethod
def _routine_paulis_with_shots(args):
pauli, measured_results = args
curr_result = Operator._measure_pauli_z(measured_results, pauli[1])
avg = pauli[0] * curr_result
variance = (pauli[0] ** 2) * Operator._covariance(measured_results, pauli[1], pauli[1],
curr_result, curr_result)
return avg, variance
def _eval_directly(self, quantum_state):
self._check_representation("matrix")
if self._dia_matrix is None:
self._to_dia_matrix(mode='matrix')
if self._dia_matrix is not None:
avg = np.sum(self._dia_matrix * np.absolute(quantum_state) ** 2)
else:
avg = np.vdot(quantum_state, self._matrix.dot(quantum_state))
return avg
def eval(self, operator_mode, input_circuit, backend, backend_config=None, compile_config=None,
run_config=None, qjob_config=None, noise_config=None):
"""
Supporting three ways to evaluate the given circuits with the operator.
1. If `input_circuit` is a numpy.ndarray, it will directly perform inner product with the operator.
2. If `backend` is a statevector simulator, use quantum backend to get statevector \
and then evaluate with the operator.
3. Other cases: it use with quanutm backend (simulator or real quantum machine), \
to obtain the mean and standard deviation of measured results.
Args:
operator_mode (str): representation of operator, including paulis, grouped_paulis and matrix
input_circuit (QuantumCircuit or numpy.ndarray): the quantum circuit.
backend (BaseBackend): backend selection for quantum machine.
backend_config (dict): configuration for backend
compile_config (dict): configuration for compilation
run_config (RunConfig): configuration for running a circuit
qjob_config (dict): the setting to retrieve results from quantum backend, including timeout and wait.
noise_config (dict) the setting of noise model for the qasm simulator in the Aer provider.
Returns:
float, float: mean and standard deviation of avg
"""
backend_config = backend_config or {}
compile_config = compile_config or {}
if run_config is not None:
if isinstance(run_config, dict):
run_config = RunConfig(**run_config)
else:
run_config = RunConfig()
qjob_config = qjob_config or {}
noise_config = noise_config or {}
if isinstance(input_circuit, np.ndarray):
avg = self._eval_directly(input_circuit)
std_dev = 0.0
else:
if is_statevector_backend(backend):
run_config.shots = 1
circuits = self.construct_evaluation_circuit(operator_mode, input_circuit, backend)
result = compile_and_run_circuits(circuits, backend=backend, backend_config=backend_config,
compile_config=compile_config, run_config=run_config,
qjob_config=qjob_config, noise_config=noise_config,
show_circuit_summary=self._summarize_circuits)
avg, std_dev = self.evaluate_with_result(operator_mode, circuits, backend, result)
return avg, std_dev
def to_paulis(self):
self._check_representation('paulis')
def to_grouped_paulis(self):
self._check_representation('grouped_paulis')
def to_matrix(self):
self._check_representation('matrix')
def convert(self, input_format, output_format, force=False):
"""
A wrapper for conversion among all representations.
Note that, if the output target is already there, it will skip the conversion.
The result is stored back into its property directly.
Args:
input_format (str): case-insensitive input format,
should be one of "paulis", "grouped_paulis", "matrix"
output_format (str): case-insensitive output format,
should be one of "paulis", "grouped_paulis", "matrix"
force (bool): convert to targeted format regardless its present.
Raises:
ValueError: if the unsupported output_format is specified.
"""
input_format = input_format.lower()
output_format = output_format.lower()
if input_format not in ["paulis", "grouped_paulis", "matrix"]:
raise ValueError(
"Input format {} is not supported".format(input_format))
if output_format not in ["paulis", "grouped_paulis", "matrix"]:
raise ValueError(
"Output format {} is not supported".format(output_format))
if output_format == "paulis" and (self._paulis is None or force):
if input_format == "matrix":
self._matrix_to_paulis()
elif input_format == "grouped_paulis":
self._grouped_paulis_to_paulis()
elif output_format == "grouped_paulis" and (self._grouped_paulis is None or force):
if self._grouped_paulis == []:
return
if input_format == "paulis":
self._paulis_to_grouped_paulis()
elif input_format == "matrix":
self._matrix_to_grouped_paulis()
elif output_format == "matrix" and (self._matrix is None or force):
if input_format == "paulis":
self._paulis_to_matrix()
elif input_format == "grouped_paulis":
self._grouped_paulis_to_matrix()
def _grouped_paulis_to_paulis(self):
"""
Convert grouped paulis to paulis, and save it in internal property directly.
Note:
Ideally, all paulis in grouped_paulis should be unique.
No need to check whether it is existed.
"""
if self._grouped_paulis == []:
return
paulis = []
for group in self._grouped_paulis:
for idx in range(1, len(group)): # the first one is the header.
paulis.append(group[idx])
self._paulis = paulis
self._matrix = None
self._grouped_paulis = None
def _matrix_to_paulis(self):
"""
Convert matrix to paulis, and save it in internal property directly.
Note:
Conversion from Paulis to matrix: H = sum_i alpha_i * Pauli_i
Conversion from matrix to Paulis: alpha_i = coeff * Trace(H.Pauli_i) (dot product of trace)
where coeff = 2^(- # of qubits), # of qubit = log2(dim of matrix)
"""
if self._matrix.nnz == 0:
return
num_qubits = self.num_qubits
coeff = 2 ** (-num_qubits)
paulis = []
# generate all possible paulis basis
for basis in itertools.product('IXYZ', repeat=num_qubits):
pauli_i = Pauli.from_label(''.join(basis))
trace_value = np.sum(self._matrix.dot(pauli_i.to_spmatrix()).diagonal())
alpha_i = trace_value * coeff
if alpha_i != 0.0:
paulis.append([alpha_i, pauli_i])
self._paulis = paulis
self._matrix = None
self._grouped_paulis = None
def _paulis_to_grouped_paulis(self):
"""
Convert paulis to grouped_paulis, and save it in internal property directly.
Groups a list of [coeff,Pauli] into tensor product basis (tpb) sets
"""
if self._paulis == []:
return
if self._coloring is not None:
self._grouped_paulis = PauliGraph(self._paulis, mode=self._coloring).grouped_paulis
else:
temp_paulis = copy.deepcopy(self._paulis)
n = self.num_qubits
grouped_paulis = []
sorted_paulis = []
def check_pauli_in_list(target, pauli_list):
ret = False
for pauli in pauli_list:
if target[1] == pauli[1]:
ret = True
break
return ret
for i in range(len(temp_paulis)):
p_1 = temp_paulis[i]
if not check_pauli_in_list(p_1, sorted_paulis):
paulis_temp = []
# pauli_list_temp.extend(p_1) # this is going to signal the total
# post-rotations of the set (set master)
paulis_temp.append(p_1)
paulis_temp.append(copy.deepcopy(p_1))
paulis_temp[0][0] = 0.0 # zero coeff for HEADER
for j in range(i+1, len(temp_paulis)):
p_2 = temp_paulis[j]
if not check_pauli_in_list(p_2, sorted_paulis) and p_1[1] != p_2[1]:
j = 0
for i in range(n):
# p_2 is identity, p_1 is identity, p_1 and p_2 has same basis
if not ((not p_2[1].z[i] and not p_2[1].x[i]) or
(not p_1[1].z[i] and not p_1[1].x[i]) or
(p_2[1].z[i] == p_1[1].z[i] and
p_2[1].x[i] == p_1[1].x[i])):
break
else:
# update master, if p_2 is not identity
if p_2[1].z[i] or p_2[1].x[i]:
paulis_temp[0][1].update_z(p_2[1].z[i], i)
paulis_temp[0][1].update_x(p_2[1].x[i], i)
j += 1
if j == n:
paulis_temp.append(p_2)
sorted_paulis.append(p_2)
grouped_paulis.append(paulis_temp)
self._grouped_paulis = grouped_paulis
self._matrix = None
self._paulis = None
def _matrix_to_grouped_paulis(self):
"""
Convert matrix to grouped_paulis, and save it in internal property directly.
"""
if self._matrix.nnz == 0:
return
self._matrix_to_paulis()
self._paulis_to_grouped_paulis()
self._matrix = None
self._paulis = None
def _paulis_to_matrix(self):
"""
Convert paulis to matrix, and save it in internal property directly.
If all paulis are Z or I (identity), convert to dia_matrix.
"""
if self._paulis == []:
return
p = self._paulis[0]
hamiltonian = p[0] * p[1].to_spmatrix()
for idx in range(1, len(self._paulis)):
p = self._paulis[idx]
hamiltonian += p[0] * p[1].to_spmatrix()
self._matrix = hamiltonian
self._to_dia_matrix(mode='matrix')
self._paulis = None
self._grouped_paulis = None
def _grouped_paulis_to_matrix(self):
"""
Convert grouped_paulis to matrix, and save it in internal property directly.
If all paulis are Z or I (identity), convert to dia_matrix.
"""
if self._grouped_paulis == []:
return
p = self._grouped_paulis[0][1]
hamiltonian = p[0] * p[1].to_spmatrix()
for idx in range(2, len(self._grouped_paulis[0])):
p = self._grouped_paulis[0][idx]
hamiltonian += p[0] * p[1].to_spmatrix()
for group_idx in range(1, len(self._grouped_paulis)):
group = self._grouped_paulis[group_idx]
for idx in range(1, len(group)):
p = group[idx]
hamiltonian += p[0] * p[1].to_spmatrix()
self._matrix = hamiltonian
self._to_dia_matrix(mode='matrix')
self._paulis = None
self._grouped_paulis = None
@staticmethod
def _measure_pauli_z(data, pauli):
"""
Appropriate post-rotations on the state are assumed.
Args:
data (dict): a dictionary of the form data = {'00000': 10} ({str: int})
pauli (Pauli): a Pauli object
Returns:
float: Expected value of paulis given data
"""
observable = 0.0
num_shots = sum(data.values())
p_z_or_x = np.logical_or(pauli.z, pauli.x)
for key, value in data.items():
bitstr = np.asarray(list(key))[::-1].astype(np.bool)
sign = -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p_z_or_x)) else 1.0
observable += sign * value
observable /= num_shots
return observable
@staticmethod
def _covariance(data, pauli_1, pauli_2, avg_1, avg_2):
"""
Compute the covariance matrix element between two
Paulis, given the measurement outcome.
Appropriate post-rotations on the state are assumed.
Args:
data (dict): a dictionary of the form data = {'00000': 10} ({str:int})
pauli_1 (Pauli): a Pauli class member
pauli_2 (Pauli): a Pauli class member
avg_1 (float): expectation value of pauli_1 on `data`
avg_2 (float): expectation value of pauli_2 on `data`
Returns:
float: the element of the covariance matrix between two Paulis
"""
cov = 0.0
num_shots = sum(data.values())
if num_shots == 1:
return cov
p1_z_or_x = np.logical_or(pauli_1.z, pauli_1.x)
p2_z_or_x = np.logical_or(pauli_2.z, pauli_2.x)
for key, value in data.items():
bitstr = np.asarray(list(key))[::-1].astype(np.bool)
sign_1 = -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p1_z_or_x)) else 1.0
sign_2 = -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p2_z_or_x)) else 1.0
cov += (sign_1 - avg_1) * (sign_2 - avg_2) * value
cov /= (num_shots - 1)
return cov
def two_qubit_reduced_operator(self, m, threshold=10**-13):
"""
Eliminates the central and last qubit in a list of Pauli that has
diagonal operators (Z,I) at those positions
Chemistry specific method:
It can be used to taper two qubits in parity and binary-tree mapped
fermionic Hamiltonians when the spin orbitals are ordered in two spin
sectors, (block spin order) according to the number of particles in the system.
Args:
m (int): number of fermionic particles
threshold (float): threshold for Pauli simplification
Returns:
Operator: a new operator whose qubit number is reduced by 2.
"""
if self._paulis is None or self._paulis == []:
return self
operator_out = Operator(paulis=[])
par_1 = 1 if m % 2 == 0 else -1
par_2 = 1 if m % 4 == 0 else -1
n = self.num_qubits
last_idx = n - 1
mid_idx = n // 2 - 1
for pauli_term in self._paulis: # loop over Pauli terms
coeff_out = pauli_term[0]
# Z operator encountered at qubit n/2-1
if pauli_term[1].z[mid_idx] and not pauli_term[1].x[mid_idx]:
coeff_out = par_2 * coeff_out
# Z operator encountered at qubit n-1
if pauli_term[1].z[last_idx] and not pauli_term[1].x[last_idx]:
coeff_out = par_1 * coeff_out
# TODO: can change to delete
z_temp = []
x_temp = []
for j in range(n - 1):
if j != mid_idx:
z_temp.append(pauli_term[1].z[j])
x_temp.append(pauli_term[1].x[j])
pauli_term_out = [coeff_out, Pauli(np.asarray(z_temp), np.asarray(x_temp))]
if np.absolute(coeff_out) > threshold:
operator_out += Operator(paulis=[pauli_term_out])
operator_out.chop(threshold=threshold)
return operator_out
def get_flat_pauli_list(self):
"""
Get the flat list of paulis
Returns:
list: The list of pauli terms
"""
if self._paulis is not None:
return [] + self._paulis
else:
if self._grouped_paulis is not None:
return [pauli for group in self._grouped_paulis for pauli in group[1:]]
elif self._matrix is not None:
self._check_representation('paulis')
return [] + self._paulis
@staticmethod
def construct_evolution_circuit(slice_pauli_list, evo_time, num_time_slices, state_registers,
ancillary_registers=None, ctl_idx=0, unitary_power=None, use_basis_gates=True,
shallow_slicing=False):
"""
Construct the evolution circuit according to the supplied specification.
Args:
slice_pauli_list (list): The list of pauli terms corresponding to a single time slice to be evolved
evo_time (int): The evolution time
num_time_slices (int): The number of time slices for the expansion
state_registers (QuantumRegister): The Qiskit QuantumRegister corresponding to the qubits of the system
ancillary_registers (QuantumRegister): The optional Qiskit QuantumRegister corresponding to the control
qubits for the state_registers of the system
ctl_idx (int): The index of the qubit of the control ancillary_registers to use
unitary_power (int): The power to which the unitary operator is to be raised
use_basis_gates (bool): boolean flag for indicating only using basis gates when building circuit.
shallow_slicing (bool): boolean flag for indicating using shallow qc.data reference repetition for slicing
Returns:
QuantumCircuit: The Qiskit QuantumCircuit corresponding to specified evolution.
"""
if state_registers is None:
raise ValueError('Quantum state registers are required.')
qc_slice = QuantumCircuit(state_registers)
if ancillary_registers is not None:
qc_slice.add_register(ancillary_registers)
# for each pauli [IXYZ]+, record the list of qubit pairs needing CX's
cnot_qubit_pairs = [None] * len(slice_pauli_list)
# for each pauli [IXYZ]+, record the highest index of the nontrivial pauli gate (X,Y, or Z)
top_XYZ_pauli_indices = [-1] * len(slice_pauli_list)
for pauli_idx, pauli in enumerate(reversed(slice_pauli_list)):
n_qubits = pauli[1].numberofqubits
# changes bases if necessary
nontrivial_pauli_indices = []
for qubit_idx in range(n_qubits):
# pauli I
if not pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]:
continue
if cnot_qubit_pairs[pauli_idx] is None:
nontrivial_pauli_indices.append(qubit_idx)
if pauli[1].x[qubit_idx]:
# pauli X
if not pauli[1].z[qubit_idx]:
if use_basis_gates:
qc_slice.u2(0.0, pi, state_registers[qubit_idx])
else:
qc_slice.h(state_registers[qubit_idx])
# pauli Y
elif pauli[1].z[qubit_idx]:
if use_basis_gates:
qc_slice.u3(pi / 2, -pi / 2, pi / 2, state_registers[qubit_idx])
else:
qc_slice.rx(pi / 2, state_registers[qubit_idx])
# pauli Z
elif pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]:
pass
else:
raise ValueError('Unrecognized pauli: {}'.format(pauli[1]))
if len(nontrivial_pauli_indices) > 0:
top_XYZ_pauli_indices[pauli_idx] = nontrivial_pauli_indices[-1]
# insert lhs cnot gates
if cnot_qubit_pairs[pauli_idx] is None:
cnot_qubit_pairs[pauli_idx] = list(zip(
sorted(nontrivial_pauli_indices)[:-1],
sorted(nontrivial_pauli_indices)[1:]
))
for pair in cnot_qubit_pairs[pauli_idx]:
qc_slice.cx(state_registers[pair[0]], state_registers[pair[1]])
# insert Rz gate
if top_XYZ_pauli_indices[pauli_idx] >= 0:
if ancillary_registers is None:
lam = (2.0 * pauli[0] * evo_time / num_time_slices).real
if use_basis_gates:
qc_slice.u1(lam, state_registers[top_XYZ_pauli_indices[pauli_idx]])
else:
qc_slice.rz(lam, state_registers[top_XYZ_pauli_indices[pauli_idx]])
else:
unitary_power = (2 ** ctl_idx) if unitary_power is None else unitary_power
lam = (2.0 * pauli[0] * evo_time / num_time_slices * unitary_power).real
if use_basis_gates:
qc_slice.u1(lam / 2, state_registers[top_XYZ_pauli_indices[pauli_idx]])
qc_slice.cx(ancillary_registers[ctl_idx], state_registers[top_XYZ_pauli_indices[pauli_idx]])
qc_slice.u1(-lam / 2, state_registers[top_XYZ_pauli_indices[pauli_idx]])
qc_slice.cx(ancillary_registers[ctl_idx], state_registers[top_XYZ_pauli_indices[pauli_idx]])
else:
qc_slice.crz(lam, ancillary_registers[ctl_idx],
state_registers[top_XYZ_pauli_indices[pauli_idx]])
# insert rhs cnot gates
for pair in reversed(cnot_qubit_pairs[pauli_idx]):
qc_slice.cx(state_registers[pair[0]], state_registers[pair[1]])
# revert bases if necessary
for qubit_idx in range(n_qubits):
if pauli[1].x[qubit_idx]:
# pauli X
if not pauli[1].z[qubit_idx]:
if use_basis_gates:
qc_slice.u2(0.0, pi, state_registers[qubit_idx])
else:
qc_slice.h(state_registers[qubit_idx])
# pauli Y
elif pauli[1].z[qubit_idx]:
if use_basis_gates:
qc_slice.u3(-pi / 2, -pi / 2, pi / 2, state_registers[qubit_idx])
else:
qc_slice.rx(-pi / 2, state_registers[qubit_idx])
# repeat the slice
if shallow_slicing:
logger.info('Under shallow slicing mode, the qc.data reference is repeated shallowly. '
'Thus, changing gates of one slice of the output circuit might affect other slices.')
qc_slice.data *= num_time_slices
qc = qc_slice
else:
qc = QuantumCircuit()
for _ in range(num_time_slices):
qc += qc_slice
return qc
@staticmethod
def _suzuki_expansion_slice_matrix(pauli_list, lam, expansion_order):
"""
Compute the matrix for a single slice of the suzuki expansion following the paper
https://arxiv.org/pdf/quant-ph/0508139.pdf
Args:
pauli_list (list): The operator's complete list of pauli terms for the suzuki expansion
lam (complex): The parameter lambda as defined in said paper
expansion_order (int): The order for the suzuki expansion
Returns:
numpy array: The matrix representation corresponding to the specified suzuki expansion
"""
if expansion_order == 1:
left = reduce(
lambda x, y: x @ y,
[scila.expm(lam / 2 * c * p.to_spmatrix().tocsc()) for c, p in pauli_list]
)
right = reduce(
lambda x, y: x @ y,
[scila.expm(lam / 2 * c * p.to_spmatrix().tocsc()) for c, p in reversed(pauli_list)]
)
return left @ right
else:
pk = (4 - 4 ** (1 / (2 * expansion_order - 1))) ** -1
side_base = Operator._suzuki_expansion_slice_matrix(
pauli_list,
lam * pk,
expansion_order - 1
)
side = side_base @ side_base
middle = Operator._suzuki_expansion_slice_matrix(
pauli_list,
lam * (1 - 4 * pk),
expansion_order - 1
)
return side @ middle @ side
@staticmethod
def _suzuki_expansion_slice_pauli_list(pauli_list, lam_coef, expansion_order):
"""
Similar to _suzuki_expansion_slice_matrix, with the difference that this method
computes the list of pauli terms for a single slice of the suzuki expansion,
which can then be fed to construct_evolution_circuit to build the QuantumCircuit.
"""
if expansion_order == 1:
half = [[lam_coef / 2 * c, p] for c, p in pauli_list]
return half + list(reversed(half))
else:
pk = (4 - 4 ** (1 / (2 * expansion_order - 1))) ** -1
side_base = Operator._suzuki_expansion_slice_pauli_list(
pauli_list,
lam_coef * pk,
expansion_order - 1
)
side = side_base * 2
middle = Operator._suzuki_expansion_slice_pauli_list(
pauli_list,
lam_coef * (1 - 4 * pk),
expansion_order - 1
)
return side + middle + side
def evolve(
self,
state_in=None,
evo_time=0,
evo_mode=None,
num_time_slices=0,
quantum_registers=None,
expansion_mode='trotter',
expansion_order=1
):
"""
Carry out the eoh evolution for the operator under supplied specifications.
Args:
state_in: The initial state for the evolution
evo_time (int): The evolution time
evo_mode (str): The mode under which the evolution is carried out.
Currently only support 'matrix' or 'circuit'
num_time_slices (int): The number of time slices for the expansion
quantum_registers (QuantumRegister): The QuantumRegister to build the QuantumCircuit off of
expansion_mode (str): The mode under which the expansion is to be done.
Currently support 'trotter', which follows the expansion as discussed in
http://science.sciencemag.org/content/273/5278/1073,
and 'suzuki', which corresponds to the discussion in
https://arxiv.org/pdf/quant-ph/0508139.pdf
expansion_order (int): The order for suzuki expansion
Returns:
Depending on the evo_mode specified, either return the matrix vector multiplication result
or the constructed QuantumCircuit.
"""
if num_time_slices < 0 or not isinstance(num_time_slices, int):
raise ValueError('Number of time slices should be a non-negative integer.')
if not (expansion_mode == 'trotter' or expansion_mode == 'suzuki'):
raise NotImplementedError('Expansion mode {} not supported.'.format(expansion_mode))
pauli_list = self.get_flat_pauli_list()
if evo_mode == 'matrix':
self._check_representation("matrix")
if num_time_slices == 0:
return scila.expm(-1.j * evo_time * self._matrix.tocsc()) @ state_in
else:
if len(pauli_list) == 1:
approx_matrix_slice = scila.expm(
-1.j * evo_time / num_time_slices * pauli_list[0][0] * pauli_list[0][1].to_spmatrix().tocsc()
)
else:
if expansion_mode == 'trotter':
approx_matrix_slice = reduce(
lambda x, y: x @ y,
[
scila.expm(-1.j * evo_time / num_time_slices * c * p.to_spmatrix().tocsc())
for c, p in pauli_list
]
)
# suzuki expansion
elif expansion_mode == 'suzuki':
approx_matrix_slice = Operator._suzuki_expansion_slice_matrix(
pauli_list,
-1.j * evo_time / num_time_slices,
expansion_order
)
else:
raise ValueError('Unrecognized expansion mode {}.'.format(expansion_mode))
return reduce(lambda x, y: x @ y, [approx_matrix_slice] * num_time_slices) @ state_in
elif evo_mode == 'circuit':
if num_time_slices == 0:
raise ValueError('Number of time slices should be a positive integer for {} mode.'.format(evo_mode))
else:
if quantum_registers is None:
raise ValueError('Quantum registers are needed for circuit construction.')
if len(pauli_list) == 1:
slice_pauli_list = pauli_list
else:
if expansion_mode == 'trotter':
slice_pauli_list = pauli_list
# suzuki expansion
else:
slice_pauli_list = Operator._suzuki_expansion_slice_pauli_list(
pauli_list,
1,
expansion_order
)
return self.construct_evolution_circuit(
slice_pauli_list, evo_time, num_time_slices, quantum_registers
)
else:
raise ValueError('Evolution mode should be either "matrix" or "circuit".')
def is_empty(self):
"""
Check Operator is empty or not.
Returns:
bool: is empty?
"""
if self._matrix is None and self._dia_matrix is None \
and (self._paulis == [] or self._paulis is None) \
and (self._grouped_paulis == [] or self._grouped_paulis is None):
return True
else:
return False
def _check_representation(self, targeted_representation):
"""
Check the targeted representation is existed or not, if not, find available representations
and then convert to the targeted one.
Args:
targeted_representation (str): should be one of paulis, grouped_paulis and matrix
Raises:
ValueError: if the `targeted_representation` is not recognized.
"""
if targeted_representation == 'paulis':
if self._paulis is None:
if self._matrix is not None:
self._matrix_to_paulis()
elif self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
else:
raise AquaError(
"at least having one of the three operator representations.")
elif targeted_representation == 'grouped_paulis':
if self._grouped_paulis is None:
if self._paulis is not None:
self._paulis_to_grouped_paulis()
elif self._matrix is not None:
self._matrix_to_grouped_paulis()
else:
raise AquaError(
"at least having one of the three operator representations.")
elif targeted_representation == 'matrix':
if self._matrix is None:
if self._paulis is not None:
self._paulis_to_matrix()
elif self._grouped_paulis is not None:
self._grouped_paulis_to_matrix()
else:
raise AquaError(
"at least having one of the three operator representations.")
else:
raise ValueError(
'"targeted_representation" should be one of "paulis", "grouped_paulis" and "matrix".'
)
@staticmethod
def row_echelon_F2(matrix_in):
"""
Computes the row Echelon form of a binary matrix on the binary
finite field
Args:
matrix_in (numpy.ndarray): binary matrix
Returns:
numpy.ndarray : matrix_in in Echelon row form
"""
size = matrix_in.shape
for i in range(size[0]):
pivot_index = 0
for j in range(size[1]):
if matrix_in[i, j] == 1:
pivot_index = j
break
for k in range(size[0]):
if k != i and matrix_in[k, pivot_index] == 1:
matrix_in[k, :] = np.mod(matrix_in[k, :] + matrix_in[i, :], 2)
matrix_out_temp = copy.deepcopy(matrix_in)
indices = []
matrix_out = np.zeros(size)
for i in range(size[0] - 1):
if np.array_equal(matrix_out_temp[i, :], np.zeros(size[1])):
indices.append(i)
for row in np.sort(indices)[::-1]:
matrix_out_temp = np.delete(matrix_out_temp, (row), axis=0)
matrix_out[0:size[0] - len(indices), :] = matrix_out_temp
matrix_out = matrix_out.astype(int)
return matrix_out
@staticmethod
def kernel_F2(matrix_in):
"""
Computes the kernel of a binary matrix on the binary finite field
Args:
matrix_in (numpy.ndarray): binary matrix
Returns:
[numpy.ndarray]: the list of kernel vectors
"""
size = matrix_in.shape
kernel = []
matrix_in_id = np.vstack((matrix_in, np.identity(size[1])))
matrix_in_id_ech = (Operator.row_echelon_F2(matrix_in_id.transpose())).transpose()
for col in range(size[1]):
if (np.array_equal(matrix_in_id_ech[0:size[0], col], np.zeros(size[0])) and not
np.array_equal(matrix_in_id_ech[size[0]:, col], np.zeros(size[1]))):
kernel.append(matrix_in_id_ech[size[0]:, col])
return kernel
def find_Z2_symmetries(self):
"""
Finds Z2 Pauli-type symmetries of an Operator
Returns:
[Pauli]: the list of Pauli objects representing the Z2 symmetries
[Pauli]: the list of single - qubit Pauli objects to construct the Cliffors operators
[Operators]: the list of Clifford unitaries to block diagonalize Operator
[int]: the list of support of the single-qubit Pauli objects used to build the clifford operators
"""
Pauli_symmetries = []
sq_paulis = []
cliffords = []
sq_list = []
stacked_paulis = []
if self.is_empty():
logger.info("Operator is empty.")
return [], [], [], []
self._check_representation("paulis")
for pauli in self._paulis:
stacked_paulis.append(np.concatenate((pauli[1].x, pauli[1].z), axis=0).astype(np.int))
stacked_matrix = np.array(np.stack(stacked_paulis))
symmetries = Operator.kernel_F2(stacked_matrix)
if len(symmetries) == 0:
logger.info("No symmetry is found.")
return [], [], [], []
stacked_symmetries = np.stack(symmetries)
symm_shape = stacked_symmetries.shape
for row in range(symm_shape[0]):
Pauli_symmetries.append(Pauli(stacked_symmetries[row, : symm_shape[1] // 2],
stacked_symmetries[row, symm_shape[1] // 2:]))
stacked_symm_del = np.delete(stacked_symmetries, (row), axis=0)
for col in range(symm_shape[1] // 2):
# case symmetries other than one at (row) have Z or I on col qubit
Z_or_I = True
for symm_idx in range(symm_shape[0] - 1):
if not (stacked_symm_del[symm_idx, col] == 0
and stacked_symm_del[symm_idx, col + symm_shape[1] // 2] in (0, 1)):
Z_or_I = False
if Z_or_I:
if ((stacked_symmetries[row, col] == 1 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 0) or
(stacked_symmetries[row, col] == 1 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 1)):
sq_paulis.append(Pauli(np.zeros(symm_shape[1] // 2),
np.zeros(symm_shape[1] // 2)))
sq_paulis[row].z[col] = False
sq_paulis[row].x[col] = True
sq_list.append(col)
break
# case symmetries other than one at (row) have X or I on col qubit
X_or_I = True
for symm_idx in range(symm_shape[0] - 1):
if not (stacked_symm_del[symm_idx, col] in (0, 1) and
stacked_symm_del[symm_idx, col + symm_shape[1] // 2] == 0):
X_or_I = False
if X_or_I:
if ((stacked_symmetries[row, col] == 0 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 1) or
(stacked_symmetries[row, col] == 1 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 1)):
sq_paulis.append(Pauli(np.zeros(symm_shape[1] // 2), np.zeros(symm_shape[1] // 2)))
sq_paulis[row].z[col] = True
sq_paulis[row].x[col] = False
sq_list.append(col)
break
# case symmetries other than one at (row) have Y or I on col qubit
Y_or_I = True
for symm_idx in range(symm_shape[0] - 1):
if not ((stacked_symm_del[symm_idx, col] == 1 and
stacked_symm_del[symm_idx, col + symm_shape[1] // 2] == 1)
or (stacked_symm_del[symm_idx, col] == 0 and
stacked_symm_del[symm_idx, col + symm_shape[1] // 2] == 0)):
Y_or_I = False
if Y_or_I:
if ((stacked_symmetries[row, col] == 0 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 1) or
(stacked_symmetries[row, col] == 1 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 0)):
sq_paulis.append(Pauli(np.zeros(symm_shape[1] // 2), np.zeros(symm_shape[1] // 2)))
sq_paulis[row].z[col] = True
sq_paulis[row].x[col] = True
sq_list.append(col)
break
for symm_idx, Pauli_symm in enumerate(Pauli_symmetries):
cliffords.append(Operator([[1 / np.sqrt(2), Pauli_symm], [1 / np.sqrt(2), sq_paulis[symm_idx]]]))
return Pauli_symmetries, sq_paulis, cliffords, sq_list
@staticmethod
def qubit_tapering(operator, cliffords, sq_list, tapering_values):
"""
Builds an Operator which has a number of qubits tapered off,
based on a block-diagonal Operator built using a list of cliffords.
The block-diagonal subspace is an input parameter, set through the list
tapering_values, which takes values +/- 1.
Args:
operator (Operator): the target operator to be tapered
cliffords ([Operator]): list of unitary Clifford transformation
sq_list ([int]): position of the single-qubit operators that anticommute
with the cliffords
tapering_values ([int]): array of +/- 1 used to select the subspace. Length
has to be equal to the length of cliffords and sq_list
Returns:
Operator : the tapered operator, or empty operator if the `operator` is empty.
"""
if len(cliffords) == 0 or len(sq_list) == 0 or len(tapering_values) == 0:
logger.warning("Cliffords, single qubit list and tapering values cannot be empty.\n"
"Return the original operator instead.")
return operator
if len(cliffords) != len(sq_list):
logger.warning("Number of Clifford unitaries has to be the same as length of single"
"qubit list and tapering values.\n"
"Return the original operator instead.")
return operator
if len(sq_list) != len(tapering_values):
logger.warning("Number of Clifford unitaries has to be the same as length of single"
"qubit list and tapering values.\n"
"Return the original operator instead.")
return operator
if operator.is_empty():
logger.warning("The operator is empty, return the empty operator directly.")
return operator
operator.to_paulis()
for clifford in cliffords:
operator = clifford * operator * clifford
operator_out = Operator(paulis=[])
for pauli_term in operator.paulis:
coeff_out = pauli_term[0]
for idx, qubit_idx in enumerate(sq_list):
if not (not pauli_term[1].z[qubit_idx] and not pauli_term[1].x[qubit_idx]):
coeff_out = tapering_values[idx] * coeff_out
z_temp = np.delete(pauli_term[1].z.copy(), np.asarray(sq_list))
x_temp = np.delete(pauli_term[1].x.copy(), np.asarray(sq_list))
pauli_term_out = [coeff_out, Pauli(z_temp, x_temp)]
operator_out += Operator(paulis=[pauli_term_out])
operator_out.zeros_coeff_elimination()
return operator_out
def zeros_coeff_elimination(self):
"""
Elinminate paulis or grouped paulis whose coefficients are zeros.
The difference from `_simplify_paulis` method is that, this method will not remove duplicated
paulis.
"""
if self._paulis is not None:
new_paulis = [pauli for pauli in self._paulis if pauli[0] != 0]
self._paulis = new_paulis
self._paulis_table = {pauli[1].to_label(): i for i, pauli in enumerate(self._paulis)}
elif self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
self.zeros_coeff_elimination()
self._paulis_to_grouped_paulis()
self._paulis = None
def scaling_coeff(self, scaling_factor):
"""
Constant scale the coefficient in an operator.
Note that: the behavior of scaling in paulis (grouped_paulis) might be different from matrix
Args:
scaling_factor (float): the sacling factor
"""
if self._paulis is not None:
for idx in range(len(self._paulis)):
self._paulis[idx] = [self._paulis[idx][0] * scaling_factor, self._paulis[idx][1]]
elif self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
self._scale_paulis(scaling_factor)
self._paulis_to_grouped_paulis()
elif self._matrix is not None:
self._matrix *= scaling_factor
if self._dia_matrix is not None:
self._dia_matrix *= scaling_factor
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the LayoutTransformation pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.transpiler import CouplingMap, Layout, Target
from qiskit.circuit.library import CXGate
from qiskit.transpiler.passes import LayoutTransformation
class TestLayoutTransformation(QiskitTestCase):
"""
Tests the LayoutTransformation pass.
"""
def test_three_qubit(self):
"""Test if the permutation {0->2,1->0,2->1} is implemented correctly."""
v = QuantumRegister(3, "v") # virtual qubits
coupling = CouplingMap([[0, 1], [1, 2]])
from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2})
to_layout = Layout({v[0]: 2, v[1]: 0, v[2]: 1})
ltpass = LayoutTransformation(
coupling_map=coupling, from_layout=from_layout, to_layout=to_layout, seed=42
)
qc = QuantumCircuit(3)
dag = circuit_to_dag(qc)
output_dag = ltpass.run(dag)
expected = QuantumCircuit(3)
expected.swap(1, 0)
expected.swap(1, 2)
self.assertEqual(circuit_to_dag(expected), output_dag)
def test_four_qubit(self):
"""Test if the permutation {0->3,1->0,2->1,3->2} is implemented correctly."""
v = QuantumRegister(4, "v") # virtual qubits
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2, v[3]: 3})
to_layout = Layout({v[0]: 3, v[1]: 0, v[2]: 1, v[3]: 2})
ltpass = LayoutTransformation(
coupling_map=coupling, from_layout=from_layout, to_layout=to_layout, seed=42
)
qc = QuantumCircuit(4) # input (empty) physical circuit
dag = circuit_to_dag(qc)
output_dag = ltpass.run(dag)
expected = QuantumCircuit(4)
expected.swap(1, 0)
expected.swap(1, 2)
expected.swap(2, 3)
self.assertEqual(circuit_to_dag(expected), output_dag)
def test_four_qubit_with_target(self):
"""Test if the permutation {0->3,1->0,2->1,3->2} is implemented correctly."""
v = QuantumRegister(4, "v") # virtual qubits
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None, (2, 3): None})
from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2, v[3]: 3})
to_layout = Layout({v[0]: 3, v[1]: 0, v[2]: 1, v[3]: 2})
ltpass = LayoutTransformation(target, from_layout=from_layout, to_layout=to_layout, seed=42)
qc = QuantumCircuit(4) # input (empty) physical circuit
dag = circuit_to_dag(qc)
output_dag = ltpass.run(dag)
expected = QuantumCircuit(4)
expected.swap(1, 0)
expected.swap(1, 2)
expected.swap(2, 3)
self.assertEqual(circuit_to_dag(expected), output_dag)
@unittest.skip("rustworkx token_swapper produces correct, but sometimes random output")
def test_full_connected_coupling_map(self):
"""Test if the permutation {0->3,1->0,2->1,3->2} in a fully connected map."""
# TODO: Remove skip when https://github.com/Qiskit/rustworkx/pull/897 is
# merged and released. Should be rustworkx 0.13.1.
v = QuantumRegister(4, "v") # virtual qubits
from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2, v[3]: 3})
to_layout = Layout({v[0]: 3, v[1]: 0, v[2]: 1, v[3]: 2})
ltpass = LayoutTransformation(
coupling_map=None, from_layout=from_layout, to_layout=to_layout, seed=42
)
qc = QuantumCircuit(4) # input (empty) physical circuit
dag = circuit_to_dag(qc)
output_dag = ltpass.run(dag)
expected = QuantumCircuit(4)
expected.swap(1, 0)
expected.swap(2, 1)
expected.swap(3, 2)
self.assertEqual(circuit_to_dag(expected), output_dag)
if __name__ == "__main__":
unittest.main()
|
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
|
alejomonbar
|
%load_ext autoreload
%autoreload 2
# pip install pennylane
import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import NesterovMomentumOptimizer
import tensorflow as tf
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from IPython.display import clear_output
clear_output(wait=False)
import os
import tensorflow as tf
data_train = pd.read_csv("dataset/fair_train.csv")
X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values
data_test = pd.read_csv("dataset/classic_test.csv")
X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values
(X_train.shape, y_train.shape),(X_test.shape, y_test.shape)
dev = qml.device("default.qubit", wires=4)
def block(weights, wires):
qml.CNOT(wires=[wires[0],wires[1]])
qml.RY(weights[0], wires=wires[0])
qml.RY(weights[1], wires=wires[1])
n_wires = 4
n_block_wires = 2
n_params_block = 2
n_blocks = qml.TTN.get_n_blocks(range(n_wires),n_block_wires)
n_blocks
@qml.qnode(dev)
def circuit(weights, x):
qml.AmplitudeEmbedding(x, wires=[0,1,2,3],normalize=True,pad_with=True)
for w in weights:
qml.TTN(range(n_wires),n_block_wires,block, n_params_block, w)
#print(w)
#print(x)
return qml.expval(qml.PauliZ(3))
def variational_classifier(weights, bias, x):
return circuit(weights, x) + bias
def square_loss(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
loss = loss + (l - p) ** 2
loss = loss / len(labels)
return loss
def accuracy(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
if abs(l - p) < 1e-5:
loss = loss + 1
loss = loss / len(labels)
return loss
def cost(weights, bias, X, Y):
#print(1)
predictions = [variational_classifier(weights, bias, x) for x in X]
return square_loss(Y, predictions)
np.random.seed(0)
num_layers = 4
weights_init = 2*np.pi * np.random.randn(num_layers,n_blocks, n_params_block, requires_grad=True)
bias_init = np.array(0.0, requires_grad=True)
print(weights_init, bias_init)
print(qml.draw(circuit,expansion_strategy='device',wire_order=[0,1,2,3])(weights_init,np.asarray(X_train[0])))
for i in weights_init:
print(i[0])
y_train = np.where(y_train < 1, -1, y_train)
y_test = np.where(y_test < 1, -1, y_test)
from sklearn.utils import shuffle
X,y = shuffle(X_train, y_train, random_state=0)
from sklearn.model_selection import train_test_split
opt = NesterovMomentumOptimizer(0.4)
batch_size = 32
num_data = len(y_train)
num_train = 0.9
# train the variational classifier
weights = weights_init
bias = bias_init
print()
cost_g = []
acc_train = []
acc_test = []
plt.show()
for it in range(50):
X_train_70, X_test_30, y_train_70, y_test_30 =train_test_split(np.asarray(X), np.asarray(y), train_size=num_train, test_size=1.0-num_train, shuffle=True)
# Update the weights by one optimizer step
batch_index = np.random.randint(0, len(X_train_70), (batch_size,))
feats_train_batch = X_train_70[batch_index]
Y_train_batch = y_train_70[batch_index]
weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch)
# Compute predictions on train and validation set
predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in X_train_70]
predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in X_test_30]
# Compute accuracy on train and validation set
acc_tra = accuracy(y_train_70, predictions_train)
acc_val = accuracy(y_test_30, predictions_val)
cost_train = cost(weights, bias,X_train, y_train)
cost_g.append(cost_train)
acc_train.append(acc_tra)
acc_test.append(acc_val)
clear_output(wait=True)
plt.plot(cost_g,label='cost')
plt.plot(acc_train,label='acc_train')
plt.plot(acc_test,label='acc_test')
plt.legend(['cost','acc_train','acc_test'])
plt.show()
print(
"Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} "
"".format(it + 1, cost_train, acc_tra, acc_val)
)
print(weights)
x_test = []
for x in X_test.tolist():
x[0]+=1
x_test.append( x/ np.linalg.norm(x))
x_test[0]
y_test_pred = [np.sign(variational_classifier(weights, bias, f)) for f in x_test]
from sklearn.metrics import confusion_matrix, roc_curve, auc
from sklearn.preprocessing import StandardScaler
# demonstration of calculating metrics for a neural network model using sklearn
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import roc_auc_score
accuracy = accuracy_score(y_test, y_test_pred)
print('Accuracy: %f' % accuracy)
# precision tp / (tp + fp)
precision = precision_score(y_test, y_test_pred)
print('Precision: %f' % precision)
# recall: tp / (tp + fn)
recall = recall_score(y_test, y_test_pred)
print('Recall: %f' % recall)
# f1: 2 tp / (2 tp + fp + fn)
f1 = f1_score(y_test, y_test_pred)
print('F1 score: %f' % f1)
# kappa
kappa = cohen_kappa_score(y_test, y_test_pred)
print('Cohens kappa: %f' % kappa)
# ROC AUC
auc = roc_auc_score(y_test, y_test_pred)
print('ROC AUC: %f' % auc)
# confusion matrix
test_matrix = confusion_matrix(y_test, y_test_pred)
print(test_matrix)
ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g')
ax.set_title('Seaborn Confusion Matrix with labels\n\n');
ax.set_xlabel('\nPredicted Values')
ax.set_ylabel('Actual Values ');
ax.xaxis.set_ticklabels(['0','1'])
ax.yaxis.set_ticklabels(['0','1'])
## Display the visualization of the Confusion Matrix.
plt.show()
y_pred_1 = [int(i) for i in y_test_pred ]
y_pred_1 = ["{}\n".format(i) for i in y_pred_1]
with open(r'ttn_4_layers.csv', 'w') as fp:
fp.writelines(y_pred_1)
|
https://github.com/sathayen/qiskit-docker
|
sathayen
|
# Creating quantum circuits
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit import execute, Aer
from qiskit.tools.visualization import circuit_drawer, plot_histogram
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.x(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr, cr)
circuit_drawer(qc)
# Run the circuit
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1024)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
print("Counts dictionary:", counts )
print("Probability = ", counts['00011']/1024)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Checking the version of PYTHON; we only support > 3.5
import sys
if sys.version_info < (3,5):
raise Exception('Please use Python version 3.5 or greater.')
#Importing qiskit and math lib
from qiskit import QuantumProgram
import math
#import Qconfig
pi = math.pi
theta_list = [0.01, 0.02, 0.03, 0.04, 0.05, 1.31, 1.32, 1.33, 1.34, 1.35]
Q_program = QuantumProgram()
#Q_program.set_api(Qconfig.APItoken, Qconfig.config['url'])
def k_means():
# create Quantum Register called "qr" with 5 qubits
qr = Q_program.create_quantum_register("qr", 5)
# create Classical Register called "cr" with 5 bits
cr = Q_program.create_classical_register("cr", 5)
# Creating Quantum Circuit called "qc" involving your Quantum Register "qr"
# and your Classical Register "cr"
qc = Q_program.create_circuit("k_means", [qr], [cr])
#Define a loop to compute the distance between each pair of points
for i in range(9):
for j in range(1,10-i):
# Set the parament theta about different point
theta_1 = theta_list[i]
theta_2 = theta_list[i+j]
#Achieve the quantum circuit via qiskit
qc.h(qr[2])
qc.h(qr[1])
qc.h(qr[4])
qc.u3(theta_1, pi, pi, qr[1])
qc.u3(theta_2, pi, pi, qr[4])
qc.cswap(qr[2], qr[1], qr[4])
qc.h(qr[2])
qc.measure(qr[2], cr[2])
qc.reset(qr)
result = Q_program.execute("k_means", backend = 'local_qasm_simulator')
print(result)
print('theta_1:' + str(theta_1))
print('theta_2:' + str(theta_2))
print( result.get_data("k_means"))
#result = Q_program.execute(["reset"], backend='ibmqx4', shots=1024, timeout=600)
if __name__ == "__main__":
k_means()
%run "../version.ipynb"
|
https://github.com/arian-code/nptel_quantum_assignments
|
arian-code
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit
from qiskit import Aer, transpile
from qiskit.tools.visualization import plot_histogram, plot_state_city
from qiskit import *
from qiskit.tools.monitor import job_monitor
import qiskit.quantum_info as qi
Aer.backends()
simulator = Aer.get_backend('aer_simulator')
# Set initial state to generated statevector
circ = QuantumCircuit(4, 3)
circ.x(3)
circ.barrier()
circ.h(0)
circ.h(1)
circ.h(2)
circ.h(3)
circ.cx(0,3)
circ.cx(2,3)
circ.h(0)
circ.h(1)
circ.h(2)
circ.barrier()
circ.measure([0,1,2], [0,1,2])
circ.draw()
# execute the quantum circuit
backend = BasicAer.get_backend('qasm_simulator') # the device to run on
result = backend.run(transpile(circ, backend), shots=1000).result()
counts = result.get_counts(circ)
print(counts)
plot_histogram(counts)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#
# OUR SOLUTION
#
# initial case
# We assume that the probability of getting head is 1 at the beginning,
# because Asja will start with one euro.
prob_head = 1
prob_tail = 0
#
# first coin-flip
#
# if the last result was head
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
# if the last result was tail
# we know that prob_tail is 0 at the beginning
# but we still keep these two lines to have the same code for each iteration
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
# update the probabilities at the end of coin toss
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
#
# second coin-flip
#
# we do the same calculations
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
#
# third coin-flip
#
# we do the same calculations
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
# print prob_head and prob_tail
print("the probability of getting head",prob_head)
print("the probability of getting tail",prob_tail)
#
# your solution is here
#
|
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)
# Import packages that will be used
import c2qa
import numpy as np
import matplotlib.pyplot as plt
from qiskit import ClassicalRegister, visualization, AncillaRegister
from qiskit_aer.noise import NoiseModel, amplitude_damping_error
from qiskit.quantum_info import state_fidelity, Statevector
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info.operators.predicates import is_unitary_matrix
from math import pi, ceil
from scipy.optimize import curve_fit
# LaTeX typesetting for plt
plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
plt.rcParams['text.usetex'] = True
plt.rc('text.latex', preamble=r'\usepackage{amssymb}')
plt.rc('text.latex', preamble=r'\usepackage{amsmath}')
## Demonstration of amplitude damping circuit
# Define how many qumodes we want, and how many qubits we should use to represent each. Our basis will consist of Fock states |0> to |7>
num_qumodes = 1
num_qubits_per_qumode = 3 # The photon number which the Hilbert space truncates at is 2 ** num_qubits_per_qumode = 8
# Create circuit
qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode)
cr = ClassicalRegister(num_qumodes * num_qubits_per_qumode)
circ = c2qa.CVCircuit(qmr, cr)
# To illustrate photon loss, first initialize the qumode in Fock state |7>
circ.cv_initialize(7, qmr[0])
# Now apply a delay gate and specify gate duration and units
gate_duration = 1
time_unit = "ms"
circ.cv_delay(duration=gate_duration, qumode=qmr[0], unit=time_unit)
# Now set a loss rate -- make it large enough such that we can actually see the loss
photon_loss_rate = 0.5 # This is a loss rate in units of 1/ms
noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circ, time_unit=time_unit)
# To see the loss, we can make a measurement on the qumode and visualise counts with a histogram
circ.cv_measure(qmr[0], cr)
# Use noise pass with simulate
_, _, counts = c2qa.util.simulate(circ, noise_passes=noise_pass)
# Visualise photon loss using a histogram
visualization.plot_histogram(counts)
## Demonstration of photon parity measurement circuit
# Create new circuit with 1 qumode, 1 ancilla qubit, and 1 classical register for anc readout.
qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode)
anc = AncillaRegister(1)
cr = ClassicalRegister(1)
circ = c2qa.CVCircuit(qmr, anc, cr)
circ.initialize([1, 0], anc[0]) # Initialize ancilla qubit in |0> state
# Initialize qumode in either odd parity or even parity Fock state
#circ.cv_initialize(2, qmr) # |2> Fock state
circ.cv_initialize(3, qmr) # |3> Fock state
# Apply hadamard on ancilla qubit
circ.h(anc[0])
# Apply controlled phase space rotation gate on qumode
circ.cv_c_r(pi/2, qmr[0], anc[0])
# Apply unconditional phase space rotation gate to correct global phase
circ.cv_r(-pi/2, qmr[0])
# Apply hadamard on ancilla qubit again, and measure the ancilla qubit.
circ.h(anc[0])
circ.cv_measure(anc, cr)
_, _, counts = c2qa.util.simulate(circ)
# Measurement will return 0 for even parity and 1 for odd parity
print(counts)
# Create empty matrix
empty = np.zeros((2**num_qubits_per_qumode, 2**num_qubits_per_qumode))
## Defining our theoretical operation for U_odd
# Map logical 1's photon loss state |1> back to logical 1. (i.e. |2><1|, where fock_input = <1|, and fock_output = |2>)
u_odd = c2qa.util.fockmap(matrix=empty, fock_input=[1], fock_output=[2])
# Map logical 0's photon loss state |3> to logical 0
u_odd = c2qa.util.fockmap(u_odd, fock_input=[3, 3], fock_output=[0, 4], amplitude=[1/np.sqrt(2), 1/np.sqrt(2)])
# Mappings to satisfy unitary condition
u_odd = c2qa.util.fockmap(u_odd, [5, 6, 7], [5, 6, 7])
u_odd = c2qa.util.fockmap(u_odd, [2, 0], [3, 1])
u_odd = c2qa.util.fockmap(u_odd, [4, 4], [0, 4], 1/np.sqrt(2) * np.array([1, -1]))
# Check that our matrix is indeed unitary
assert(is_unitary_matrix(u_odd))
## Defining our theoretical operation for U_even.
# We will delay the building of the gate until we have the value we need for kt
def u_even(kt):
# Map logical 1 back to logical 1
u_even = c2qa.util.fockmap(empty, 2, 2)
# Map logical 0's error state to logical 0
u_even = c2qa.util.fockmap(u_even, [0, 0, 4, 4], [0, 4, 0, 4], 1/np.sqrt(1 + kt**2) * np.array([1, kt, -kt, 1]))
# Mappings to satisfy unitary condition
u_even = c2qa.util.fockmap(u_even, [1, 3, 5, 6, 7], [1, 3, 5, 6, 7])
# Check that our matrix is indeed unitary
assert(is_unitary_matrix(u_even))
return u_even
# Initialize new circuit
qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode)
cr = ClassicalRegister(num_qumodes * num_qubits_per_qumode)
circ = c2qa.CVCircuit(qmr, cr)
# Initialize qumode in |1_L> error state
circ.cv_initialize([0, 1], qmr)
# Append the u_odd matrix to circuit and measure
circ.cv_gate_from_matrix(u_odd, qmr[0])
circ.cv_measure(qmr[0], cr)
_, _, counts = c2qa.util.simulate(circ)
# We measure |2> Fock state, demonstrating recovery of the logical 1 state
print(counts)
## Run this block to load in the functions we need for the simulation
# Runs circuit simulation
def error_correction_experiment(encoding: str, corrections: int, shots: int, additional_snapshots: int=10, total_circuit_time: int=1, apply_noise: bool=True, return_circuit: bool=False, had_damp: bool=False, identity: bool=False):
multiplier = total_circuit_time
total_circuit_time = int(total_circuit_time * 1000) # Code works with microsecond units, but input is in milliseconds
if corrections > 333:
raise ValueError("Please restrict number of correction procedures to 333 or less")
photon_loss_rate = 0.0005
num_qumodes = 1
num_qubits_per_qumode = 3
qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode)
anc = AncillaRegister(1)
cr = ClassicalRegister(1)
circuit = c2qa.CVCircuit(qmr, anc, cr)
### 1. State Preparation
perf_0 = np.array([1/np.sqrt(2), 0, 0, 0, 1/np.sqrt(2), 0, 0, 0])
perf_1 = np.array([0, 0, 1, 0, 0, 0, 0, 0])
if encoding == 'logi0':
perf_state = perf_0
elif encoding == 'logi1':
perf_state = perf_1
elif encoding == 'logi_xplus':
perf_state = (perf_0 + perf_1)/np.sqrt(2)
elif encoding == 'logi_xminus':
perf_state = (perf_0 - perf_1)/np.sqrt(2)
elif encoding == 'logi_yplus':
perf_state = (perf_0 + 1j * perf_1)/np.sqrt(2)
elif encoding == 'logi_yminus':
perf_state = (perf_0 - 1j * perf_1)/np.sqrt(2)
else:
raise ValueError("Please input a valid state for the encoding")
# Convert type to list
perf_state = list(perf_state)
#print(perf_state, "cv_initialzed this")
# Initialize state
circuit.cv_initialize(perf_state, qmr[0])
### 2. Using instructions stored in schedule, add snapshots, noise, and parity check + recovery operations
schedule = _circuit_scheduler(corrections * multiplier, additional_snapshots * multiplier, total_circuit_time)
schedule_copy = list(schedule.items())
#print(schedule)
adjustment = 0 # For calculating duration timing
snapshot_counter = 0 # For tracking number of snapshots taken
corr_position = [] # For tracking positions at which corrections were finished
u_iden = c2qa.util.fockmap(empty, [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7])
for index, (key, value) in enumerate(list(schedule.items())):
# Instruction at 0Β΅s should always be to take snapshot
if (key == '0') & (value == 'snapshot'):
circuit.save_statevector(label='snapshot_{}'.format(snapshot_counter), pershot=True)
snapshot_counter += 1
continue
elif (key != '0'):
pass
else:
raise Exception("Something seems to have gone wrong here")
# Calculate delay gate durations using prevkey. Adjustment to duration timing is needed depending on previous instruction
prevkey, prevvalue = schedule_copy[index - 1]
delay_dur = int(key) - int(prevkey) + adjustment
#print(delay_dur, key, value)
adjustment = 0
# Apply noise
circuit.cv_delay(duration=delay_dur, qumode=qmr[0], unit="Β΅s")
# Apply snapshot only procedure
if (value == 'snapshot'):
# Don't take duplicate snapshots
if (prevvalue == 'correction') & (int(key) == (int(prevkey) + 3)):
pass
else:
circuit.save_statevector(label='snapshot_{}'.format(snapshot_counter), pershot=True)
snapshot_counter += 1
# Apply snapshot, parity check, recovery, snapshot
elif value == 'correction':
# Find previous corr position, and determine kt_dur with that information
while index > 0:
k, v = list(schedule.items())[index-1]
# Break loop if we iterated till start of dictionary
if (v == 'snapshot') & (k == '0'):
kt_dur = int(key) - int(k)
break
# Skip all snapshot instructions
elif v == 'snapshot':
index -= 1
# Find either snapshot+corr or corr instruction and extract kt_dur
elif v != 'snapshot':
kt_dur = int(key) - int(k)
break
#print(kt_dur)
kt = photon_loss_rate * (kt_dur + 3)
adjustment = -3
# Parity check
circuit.initialize([1, 0], anc[0])
circuit.h(anc[0])
circuit.cv_delay(duration=1, qumode=qmr[0], unit="Β΅s")
# Manually discretize gates by splitting 0.5Β΅s pi/2 rotation into five 0.1Β΅s pi/10 rotations
for _ in range(5):
circuit.cv_c_r(pi/10, qmr[0], anc[0], duration=0.1, unit="Β΅s")
for _ in range(5):
circuit.cv_r(-pi/10, qmr[0], duration=0.1, unit="Β΅s")
# circuit.cv_c_r(pi/2, qmr[0], anc[0], duration=0.5, unit="Β΅s")
# circuit.cv_r(-pi/2, qmr[0], anc[0], duration=0.5, unit="Β΅s")
circuit.cv_delay(duration=1, qumode=qmr[0], unit="Β΅s")
circuit.h(anc[0])
circuit.measure(anc[0], cr[0])
# Apply recovery operation, without or with u_even
if identity:
with circuit.if_test((cr[0], 1), label='Recovery op') as else_:
circuit.cv_gate_from_matrix(u_odd, qmr[0], duration=0.1, unit="ns") #u_odd
circuit.reset(anc[0])
with else_:
circuit.cv_gate_from_matrix(u_iden, qmr[0], duration=0.1, unit="ns") #u_iden
else:
with circuit.if_test((cr[0], 1), label='Recovery op') as else_:
circuit.cv_gate_from_matrix(u_odd, qmr[0], duration=0.1, unit="ns") #u_odd
circuit.reset(anc[0])
with else_:
circuit.cv_gate_from_matrix(u_even(kt), qmr[0], duration=0.1, unit="ns") #u_even(kt)
circuit.save_statevector(label='snapshot_{}'.format(snapshot_counter), pershot=True)
snapshot_counter += 1
corr_position.append(int(key) + 3)
# Apply snapshot, parity check, recovery, followed by another snapshot
else:
circuit.save_statevector(label='snapshot_{}'.format(snapshot_counter), pershot=True)
snapshot_counter += 1
adjustment = -3
# Find previous corr position, and determine kt_dur with that information
while index > 0:
k, v = list(schedule.items())[index-1]
# Break loop if we iterated till start of dictionary
if (v == 'snapshot') & (k == '0'):
kt_dur = int(key) - int(k)
break
# Skip all snapshot instructions
elif v == 'snapshot':
index -= 1
# Find either snapshot+corr or corr instruction and extract kt_dur
elif v != 'snapshot':
kt_dur = int(key) - int(k)
break
#print(kt_dur)
kt = photon_loss_rate * (kt_dur + 3)
# Parity check
circuit.initialize([1, 0], anc[0])
circuit.h(anc[0])
circuit.cv_delay(duration=1, qumode=qmr[0], unit="Β΅s")
# Manually discretize gates by splitting 0.5Β΅s pi/2 rotation into five 0.1Β΅s pi/10 rotations
for _ in range(5): # Manually discretize cv_c_r gate by splitting one 1Β΅s pi rotation into ten 0.1Β΅s pi/10 rotations
circuit.cv_c_r(pi/10, qmr[0], anc[0], duration=0.1, unit="Β΅s")
for _ in range(5):
circuit.cv_r(-pi/10, qmr[0], duration=0.1, unit="Β΅s")
# circuit.cv_c_r(pi/2, qmr[0], anc[0], duration=0.5, unit="Β΅s")
# circuit.cv_r(-pi/2, qmr[0], anc[0], duration=0.5, unit="Β΅s")
circuit.cv_delay(duration=1, qumode=qmr[0], unit="Β΅s")
circuit.h(anc[0])
circuit.measure(anc[0], cr[0])
if identity:
# Recovery operation
with circuit.if_test((cr[0], 1), label='Recovery op') as else_:
circuit.cv_gate_from_matrix(u_odd, qmr[0], duration=0.1, unit="ns") #u_odd
circuit.reset(anc[0])
with else_:
circuit.cv_gate_from_matrix(u_iden, qmr[0], duration=0.1, unit="ns") #u_even(kt)
else:
# Recovery operation
with circuit.if_test((cr[0], 1), label='Recovery op') as else_:
circuit.cv_gate_from_matrix(u_odd, qmr[0], duration=0.1, unit="ns") #u_odd
circuit.reset(anc[0])
with else_:
circuit.cv_gate_from_matrix(u_even(kt), qmr[0], duration=0.1, unit="ns") #u_even(kt)
circuit.save_statevector(label='snapshot_{}'.format(snapshot_counter), pershot=True)
snapshot_counter += 1
corr_position.append(int(key) + 3)
# Final delay gate
finalkey, finalvalue = schedule_copy[-1]
if finalvalue != 'snapshot':
final_gate_delay = total_circuit_time - int(finalkey) - 3
else:
final_gate_delay = total_circuit_time - int(finalkey)
circuit.cv_delay(duration=final_gate_delay, qumode=qmr[0], unit="Β΅s")
if return_circuit:
return circuit
### 3. Define noise parameters
# Noise pass for qumode photon loss
noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit="Β΅s")
# Noise model for hadamard amplitude damping
T1 = 10 # In Β΅s
hgate_duration = 1 # In Β΅s
error = amplitude_damping_error(1 - np.exp(-hgate_duration / T1))
noise_model = NoiseModel()
index, _ = circuit.find_bit(anc[0])
noise_model.add_quantum_error(error, ['h'], [index])
### 4. Simulate circuit
if apply_noise:
if had_damp:
state, result, _ = c2qa.util.simulate(circuit, shots=shots, per_shot_state_vector=True, return_fockcounts=False, noise_passes=noise_pass, noise_model=noise_model)
else:
state, result, _ = c2qa.util.simulate(circuit, shots=shots, per_shot_state_vector=True, return_fockcounts=False, noise_passes=noise_pass)
elif not apply_noise:
state, result, _ = c2qa.util.simulate(circuit, shots=shots, per_shot_state_vector=True, return_fockcounts=False)
### 5. Process data
# Find fidelity and photon probability at each snapshot, across all shots
traced_density_matrices = _state_traceout(circuit, state, result, snapshot_counter)
expectation_list_tuple, fidelity_list, probability_list_tuple = _state_processor(encoding, perf_state, traced_density_matrices)
# Find exact timing of each snapshot (we have to recalculate because no. of snapshots can change due to scheduling conflicts)
snapshot_times = _snapshot_timings(schedule, total_circuit_time)
return expectation_list_tuple, fidelity_list, probability_list_tuple, snapshot_times, corr_position#, circuit, schedule, snapshot_counter
# Trace out qubit for both sets of statevectors
def _state_traceout(circuit, state, result, actual_snapshots):
# Process snapshot and final statevectors
traced_snapshot_density_matrices = []
for i in range(actual_snapshots):
snapshot_list = result.data()['snapshot_{}'.format(i)]
traced_snapshots = []
for statevector in snapshot_list:
traced_snapshots.append(c2qa.util.trace_out_qubits(circuit, statevector))
traced_snapshot_density_matrices.append(traced_snapshots)
traced_final_density_matrices = []
for i in state:
traced_final_density_matrices.append(c2qa.util.trace_out_qubits(circuit, i))
traced_density_matrices = traced_snapshot_density_matrices + [traced_final_density_matrices]
return traced_density_matrices
# Takes traced matrices and finds expectation, fidelity, and photon probability
def _state_processor(encoding, perf_state, traced_density_matrices):
#print(perf_state, "compute fidelity with this")
perf_0 = [1/np.sqrt(2), 0, 0, 0, 1/np.sqrt(2), 0, 0, 0]
perf_1 = [0, 0, 1, 0, 0, 0, 0, 0]
err = [1/np.sqrt(2), 0, 0, 0, -1/np.sqrt(2), 0, 0, 0]
# Bring into qubit space
projector = Operator(np.outer([1, 0], perf_0) + np.outer([0, 1], perf_1))
# Z expectation
if (encoding == 'logi0') or (encoding == 'logi1'):
pauli = np.array([[1, 0], [0, -1]])
# X expectation
elif (encoding == 'logi_xplus') or (encoding == 'logi_xminus'):
#projector = Operator(np.outer([1/np.sqrt(2), 1/np.sqrt(2)], (perf_0 + perf_1)/np.sqrt(2)) + np.outer([1/np.sqrt(2), -1/np.sqrt(2)], (perf_0 - perf_1)/np.sqrt(2)))
pauli = np.array([[0, 1], [1, 0]])
# Y expectation
elif (encoding == 'logi_yplus') or (encoding == 'logi_yminus'):
#projector = Operator(np.outer([1/np.sqrt(2), 1j/np.sqrt(2)], (perf_0 + 1j * perf_1)/np.sqrt(2)) + np.outer([1/np.sqrt(2), 1j/np.sqrt(2)], (perf_0 - 1j * perf_1)/np.sqrt(2)))
pauli = np.array([[0, -1j], [1j, 0]])
# Compute from each density matrix 1) Pauli expectation, 2) fidelity, 3) probability of measuring photon number
expectation_list, exp_prob_list, fidelity_list, probability_listA, probability_listB = [], [], [], [], []
for density_matrix_list in traced_density_matrices:
cycle_list_expectation, cycle_list_exp_prob, cycle_list_fid, cycle_list_probA, cycle_list_probB = [], [], [], [], []
for matrix in density_matrix_list:
#print(matrix.trace())
# Pauli Expectation
qubit_space_projected_state = matrix.evolve(projector)
projection_prob = qubit_space_projected_state.trace()
expectation = (qubit_space_projected_state/projection_prob).expectation_value(pauli)
cycle_list_exp_prob.append(projection_prob)
cycle_list_expectation.append(expectation)
# Fid
cycle_list_fid.append(round(state_fidelity(matrix, Statevector(perf_state)), 6))
# Photon meas prob
cycle_list_probA.append(list(matrix.probabilities(decimals=5))) # Photon number
fid0 = round(state_fidelity(matrix, perf_0), 6)
fiderr = round(state_fidelity(matrix, err), 6)
cycle_list_probB.append([fid0, fiderr]) # w/ respect to specific states
# Avg photon num
#cycle_list_avg_photon.append(c2qa.util.qumode_avg_photon_num(matrix))
expectation_list.append(cycle_list_expectation)
exp_prob_list.append(cycle_list_exp_prob)
fidelity_list.append(cycle_list_fid)
probability_listA.append(cycle_list_probA)
probability_listB.append(cycle_list_probB)
#avg_photon_list.append(cycle_list_avg_photon)
return (expectation_list, exp_prob_list), fidelity_list, (probability_listA, probability_listB)
# Function used to determine order and timing in which snapshots and corrections are done.
def _circuit_scheduler(corrections, snapshots, total_time=1000):
# Schedule snapshots
if snapshots == 0:
pass
else:
snapshot_schedule = {"{}".format(round(i * (total_time/snapshots))): 'snapshot' for i in range(snapshots)}
# Schedule corrections
corr_interval = total_time/(1 + corrections)
correction_schedule = {"{}".format(int((i + 1) * corr_interval)): 'correction' for i in range(corrections)}
# If no corrections, return snapshot_schedule
if corrections == 0:
return snapshot_schedule
# If no snapshots, return correction_schedule with 1 snapshot at start
elif snapshots == 0:
correction_schedule = {**{'0' : 'snapshot'}, **correction_schedule}
return correction_schedule
else:
pass
# Merge the two dicts from above. If duplicate keys exist then concatenate values together.
try:
unsorted_merged_schedule = {**snapshot_schedule, **correction_schedule}
for key, value in list(snapshot_schedule.items()):
if key in list(correction_schedule.keys()):
unsorted_merged_schedule[key] = '{}'.format(value + '+' + correction_schedule[key])
else:
pass
except:
print("_circuit_scheduler() has an error")
# Sort merged dicts
merged_schedule = {key:value for key, value in sorted(unsorted_merged_schedule.items(), key=lambda item: int(item[0]))}
# Ensure that all corrections happen at least 3Β΅s before each snapshot
# but if two successive corrections happen within 3Β΅s of each other, drop the second correction
DictItems = list(merged_schedule.items())
unsorted_cleaned_schedule = dict(merged_schedule)
for index, (key, value) in enumerate(DictItems):
# index == 0 case
if index == 0:
nextkey, _ = DictItems[index + 1]
if (value == 'correction') & (int(key) + 3 > int(nextkey)):
unsorted_cleaned_schedule['{}'.format(str(int(nextkey) - 3))] = unsorted_cleaned_schedule.pop('{}'.format(key))
# index != 0 case
else:
# Automatically break loop when we get to last element of dictionary
try:
nextkey, _ = DictItems[index + 1]
prevkey, _ = DictItems[index - 1]
except:
break
if (value == 'correction') & (int(key) + 3 > int(nextkey)) & (int(prevkey) < int(key) - 3):
unsorted_cleaned_schedule['{}'.format(str(int(nextkey) - 3))] = unsorted_cleaned_schedule.pop('{}'.format(key))
elif (value == 'correction') & (int(key) + 3 > int(nextkey)):
unsorted_cleaned_schedule.pop('{}'.format(key))
print("Due to scheduling conflicts, a correction scheduled at {}Β΅s will be dropped".format(key))
# Sort overall_schedule
cleaned_schedule = {key:value for key, value in sorted(unsorted_cleaned_schedule.items(), key=lambda item: int(item[0]))}
return cleaned_schedule
# Function for extracting snapshot timings (in ms)
def _snapshot_timings(schedule, total_circuit_time):
timings = []
sch_copy = list(schedule.items())
prevkey, prevvalue = 0, 0 # Just so that first iteration doesn't throw an error
for index, (key, value) in enumerate(list(schedule.items())):
if index != 0:
prevkey, prevvalue = sch_copy[index - 1]
if value == 'snapshot':
if (prevvalue == 'correction') & (int(key) == (int(prevkey) + 3)):
pass
else:
timings.append(int(key)/1000)
elif value =='correction':
timings.append((int(key) + 3)/1000)
else:
timings.append(int(key)/1000)
timings.append((int(key) + 3)/1000)
timings.append(total_circuit_time/1000)
return timings
# Function for extracting positions where corrections were done
def correction_positions(corr_positions, correction_avg_fidelity, correction_snapshot_timings):
corr_time = [key/1000 for key in corr_positions]
corr_fid = [correction_avg_fidelity[correction_snapshot_timings.index(timing)] for timing in corr_time]
return corr_time, corr_fid
# Function for fitting exponential curve
def curve_fitter(x, y, sign=1):
popt, pcov = curve_fit(lambda x, b: sign * np.exp(-x/b), x, y)
sigma = np.sqrt(np.diag(pcov))
lifetime = round(popt[0], 2)
uncertainty = round(sigma[0], 3)
return lifetime, uncertainty
### Adjust these parameters ###
num_corr = 1 # per ms, number of correction circuits applied
additional_snaps = 2 # per ms, number of additional snapshots taken in between each correction circuit
noise_only_circ_time = 12 # ms, total duration of noise-only circuit
correction_circ_time = 12 # ms, total duration of correction circuit
shots = 1000 # Number of times circuit is repeated
encoding=['logi0', 'logi1', 'logi_xplus', 'logi_xminus'] # Input 'logi0', 'logi1', 'logi_xplus', 'logi_xminus', 'logi_yplus', or 'logi_yminus'
##
### If you wish to generate the circuit diagram for a particular simulation, uncomment these lines. ###
# noise_circuit = error_correction_experiment(encoding[0], 0, shots, 10, noise_only_circ_time, return_circuit=True)
# correction_circuit = error_correction_experiment(encoding[0], num_corr, shots, additional_snaps, correction_circ_time, return_circuit=True)
# noise_circuit.draw()
# correction_circuit.draw()
## For pyplot formatting
# For formatting graphs
encoding_format = {'logi0': r'$0_L$', 'logi1': r'$1_L$', 'logi_xplus': r'$+_L$', 'logi_xminus':r'$-_L$', 'logi_yplus':r'$+i_L$', 'logi_yminus': r'$-i_L$'}
# Colors for plotting
colors= ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
# Labels for logical states
logical_label = [r'$\lvert 0_L \rangle = (\lvert 0 \rangle + \lvert 4 \rangle)/\sqrt{2}$',
r'$\lvert E_2 \rangle = (\lvert 0 \rangle - \lvert 4 \rangle)/\sqrt{2}$',
r'$\lvert 1_L \rangle$']
# Run simulation with and without correction. Disable u_even
noise_only_simulation_list = []
correction_simulation_list = []
for i in encoding:
noise_only_simulation_list.append(error_correction_experiment(i, 0, shots, additional_snaps, noise_only_circ_time))
correction_simulation_list.append(error_correction_experiment(i, num_corr, shots, additional_snaps, correction_circ_time, identity=True))
## Fidelity visualisation
index = encoding.index('logi1')
value = 'logi1'
_, noise_only_fid, _, noise_only_snapshot_timings, _ = noise_only_simulation_list[index]
_, correction_fid, _, correction_snapshot_timings, corr_position_times = correction_simulation_list[index]
noise_only_avg_fid = [round(np.average(cycle), 4) for cycle in noise_only_fid]
noise_only_avg_fid_error = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in noise_only_fid]
correction_avg_fid = [round(np.average(cycle), 4) for cycle in correction_fid]
correction_avg_fid_error = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in correction_fid]
# Find correction positions
x, y = correction_positions(corr_position_times, correction_avg_fid, correction_snapshot_timings)
# Fit fidelity data using an exponential decay function
noise_only_lifetime, noise_lifetime_uncertainty = curve_fitter(noise_only_snapshot_timings, noise_only_avg_fid)
correction_lifetime_perf, correction_lifetime_uncertainty = curve_fitter(x, y)
# Round values to 2 decimal places
noise_lifetime_uncertainty = round(noise_lifetime_uncertainty, 2)
correction_lifetime_uncertainty = round (correction_lifetime_uncertainty, 2)
# Plot fidelity data w/ uncertainty
plt.figure(figsize=(15,6))
plt.errorbar(noise_only_snapshot_timings, noise_only_avg_fid, yerr=noise_only_avg_fid_error,
label=r'No corrections, ' + '\n' + r'$\tau = $' + str(noise_only_lifetime) + r'ms $\pm$' + str(noise_lifetime_uncertainty) + r'ms',
marker='o', color='#5BCEFA', capsize=3, ecolor='#2a6278', linestyle='None')
plt.errorbar(correction_snapshot_timings, correction_avg_fid, yerr=correction_avg_fid_error,
label=str(num_corr) + r' corrections/ms,' + '\n' + r'$\tau = $' + str(correction_lifetime_perf) + r'ms $\pm$' + str(correction_lifetime_uncertainty) + r'ms',
marker='o', color='#F5A9B8', capsize=3, ecolor='#9c6b75')
# Plot curve fits w/ uncertainty
noise_curve_timing = np.linspace(0, noise_only_circ_time, 100)
plt.plot(noise_curve_timing, np.exp(-noise_curve_timing/noise_only_lifetime))
plt.fill_between(noise_curve_timing, np.exp(-noise_curve_timing/(noise_only_lifetime + noise_lifetime_uncertainty)),
np.exp(-noise_curve_timing/(noise_only_lifetime - noise_lifetime_uncertainty)), color='#5BCEFA', alpha=0.3)
corr_curve_timing = np.linspace(0, correction_circ_time, 100)
plt.plot(corr_curve_timing, np.exp(-corr_curve_timing/correction_lifetime_perf))
plt.fill_between(corr_curve_timing, np.exp(-corr_curve_timing/(correction_lifetime_perf + correction_lifetime_uncertainty)),
np.exp(-corr_curve_timing/(correction_lifetime_perf - correction_lifetime_uncertainty)), color='#F5A9B8', alpha=0.3)
# Plot correction positions
label = 'Correction \n position'
for i in x:
plt.axvline(x=i, color='grey', label=label, linestyle="--")
label = ''
plt.xlabel("Time (ms)", size=20)
plt.ylabel("State fidelity, averaged over {} shots".format(shots), size=20)
plt.title(r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + ' state fidelity without error correction and with ' + str(num_corr) + r' correction(s)/ms ($\hat{U}_{\text{odd}}$ only)', size=20)
plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5)
plt.legend(loc='upper right', fontsize=20)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.show()
## Fidelity visualisation
for index, value in enumerate(encoding):
if value == 'logi1':
continue
_, noise_only_fid_other, _, noise_only_snapshot_timings, _ = noise_only_simulation_list[index]
_, correction_fid_other, _, correction_snapshot_timings, corr_position_times = correction_simulation_list[index]
noise_only_avg_fid_other = [round(np.average(cycle), 4) for cycle in noise_only_fid_other]
noise_only_avg_fid_error_other = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in noise_only_fid_other]
correction_avg_fid_other = [round(np.average(cycle), 4) for cycle in correction_fid_other]
correction_avg_fid_error_other = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in correction_fid_other]
# Find correction positions
x, y = correction_positions(corr_position_times, correction_avg_fid_other, correction_snapshot_timings)
# Plot fidelity data w/ uncertainty
plt.figure(figsize=(15,6))
plt.errorbar(noise_only_snapshot_timings, noise_only_avg_fid_other, yerr=noise_only_avg_fid_error_other,
label=r'No corrections',
marker='o', color='#5BCEFA', capsize=3, ecolor='#2a6278')
plt.errorbar(correction_snapshot_timings, correction_avg_fid_other, yerr=correction_avg_fid_error_other,
label=str(num_corr) + r' corrections/ms',
marker='o', color='#F5A9B8', capsize=3, ecolor='#9c6b75')
# Plot an actual exponential decay as comparison
noise_curve_timing = np.linspace(0, noise_only_circ_time, 100)
plt.plot(noise_curve_timing, np.exp(-noise_curve_timing), label='Exponential curve')
# Plot correction positions
label = 'Correction \n position'
for i in x:
plt.axvline(x=i, color='grey', label=label, linestyle="--")
label = ''
plt.xlabel("Time (ms)", size=20)
plt.ylabel("State fidelity, averaged over {} shots".format(shots), size=20)
plt.title(r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + ' state fidelity without error correction and with ' + str(num_corr) + r' correction(s)/ms ($\hat{U}_{\text{odd}}$ only)', size=20)
plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5)
plt.legend(loc='upper right', fontsize=20)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.show()
# Compute exponential fit across a variety of corrections/ms for |1_L> only
value = 'logi1'
_num_corr = [1, 2, 5, 10]
_correction_circ_time = [12 for _ in _num_corr] #[(i + 1) * 8 for i in range(5)]
_additional_snaps = 0
_shots = 1000
_encoding='logi1'
# Colors for plotting
colors= ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
# Plot noise_only trial as simulated previously
plt.figure(figsize=(15,6))
plt.scatter(noise_only_snapshot_timings, noise_only_avg_fid, marker='o', color='#1f77b4', zorder=3, alpha=0.6, linestyle='None', s= 50)
plt.plot(noise_curve_timing, np.exp(-noise_curve_timing/noise_only_lifetime), label=r'0 corrections, ' + '\n' + r'$\tau$ = ' + str(noise_only_lifetime) + r'ms $\pm$' + str(noise_lifetime_uncertainty) + r'ms', color='#1f77b4')
# Plot all other correction trials w/ lifetimes
for index, _corrections in enumerate(_num_corr):
# print(corrections, "Run starting") # Debug
_, _correction_fid, _, _correction_snapshot_timings, _corr_position_times = error_correction_experiment(_encoding, _corrections, _shots, _additional_snaps, _correction_circ_time[index], identity=True)
_correction_avg_fid = [round(np.average(cycle), 4) for cycle in _correction_fid]
_x, _y = correction_positions(_corr_position_times, _correction_avg_fid, _correction_snapshot_timings)
_lifetime, _lifetime_uncertainty = curve_fitter(_x, _y)
_curve_timing = np.linspace(0, _correction_circ_time[index], 100)
if _additional_snaps != 0:
plt.plot(correction_snapshot_timings, correction_avg_fid, marker='o', color=colors[index + 1], alpha=0.2)
plt.plot(_curve_timing, np.exp(- _curve_timing/_lifetime),
label=str(_num_corr[index]) + r' corrections/ms, ' + '\n' + r'$\tau = $' + str(_lifetime) + r'ms $\pm$' + str(_lifetime_uncertainty) + r'ms', color=colors[index + 1])
plt.scatter(_x, _y, marker='s', color=colors[index + 1], zorder=3, alpha=0.6, linestyle='None', s= 50)
plt.xlabel("Time (ms)", size=20)
plt.ylabel("State fidelity, averaged over {} shots".format(shots), size=20)
plt.title(r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + r' state fidelity for varying circuit parameters ($\hat{U}_{\text{odd}}$ only)', size=20)
plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5)
plt.legend(fontsize=20, bbox_to_anchor=(1.32, 0.5), loc='right')
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.show()
### Adjust these parameters ###
run = [(14, 0), (1, 1), (3, 4), (0, 12)] # Choose single shot to graph. Tuples are formatted as (noise_only_shot, correction_shot).
##
# Plot photon probability for all initial encodings
for index, value in enumerate(encoding):
_, _, noise_only_prob_tuple, noise_only_snapshot_timings, _ = noise_only_simulation_list[index]
_, _, correction_prob_tuple, correction_snapshot_timings, corr_position_times = correction_simulation_list[index]
# Fock state probability visualization, single shot
noise_only_prob, noise_only_prob_logical = noise_only_prob_tuple
correction_prob, correction_prob_logical = correction_prob_tuple
# Runs to plot
run_noise, run_corr = run[index]
noise_only_fock_prob = [i[run_noise] for i in noise_only_prob]
correction_fock_prob = [i[run_corr] for i in correction_prob]
noise_only_fock_prob_logical = [i[run_noise] for i in noise_only_prob_logical]
correction_fock_prob_logical = [i[run_corr] for i in correction_prob_logical]
# Ignore trajectories of Fock states with prob below a certain value.
prob_truncation = 0.005
# Plot both graph in single image
plt.figure(figsize=(15,10))
plt.suptitle('Trajectories of Fock state probability simulations with ' + r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + ' encoding', size=30)
# plt.suptitle('No correction and ' + str(num_corr) + ' correction simulation, with ' +r'$\lvert$' + str(encoding_format.get(encoding)) + r'$\rangle$' + ' encoding', size=20)
## 1a. Noise only circuit plot (photon number)
plt.subplot(2, 1, 1)
plt.subplot(2, 1, 1).xaxis.set_tick_params(labelsize=20)
plt.subplot(2, 1, 1).yaxis.set_tick_params(labelsize=20)
n = len(noise_only_fock_prob[0])
# n, = noise_only_avg_prob[0].shape
for index in range(n):
trajectory = [value[index] for value in noise_only_fock_prob]
# uncert = [value[index] for value in noise_only_fock_prob_error]
if all(i <= prob_truncation for i in trajectory):
continue
state = index
# Rename state |2> = |1_L>
if index == 2:
state=logical_label[2]
plt.plot(noise_only_snapshot_timings, trajectory, marker='s', label=r'$\lvert 2 \rangle =$ ' + str(state), color=colors[index], markersize = 8, linewidth = 3)
else:
plt.plot(noise_only_snapshot_timings, trajectory, marker='o', label=r'$\lvert$' + str(state) + r'$\rangle$', color=colors[index])
## 1b. Noise only circuit plot (logical state)
m = len(noise_only_fock_prob_logical[0])
for index in range(m):
trajectory = [value[index] for value in noise_only_fock_prob_logical]
if all(i <= prob_truncation for i in trajectory):
continue
plt.plot(noise_only_snapshot_timings, trajectory, marker='s', label=str(logical_label[index]), color=colors[index+8], markersize = 8, linewidth = 3)
# Subplot 1 formatting
#plt.ylabel("Probability of measuring Fock state, averaged over over {} shots".format(shots))
plt.ylabel(r'$P(\lvert \psi \rangle$)', size=20)
plt.title(r"Without error correction", size=20)
plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5)
## 2a. Correction circuit plot (photon number)
plt.subplot(2, 1, 2, sharex = plt.subplot(2, 1, 1))
plt.subplot(2, 1, 2).xaxis.set_tick_params(labelsize=20)
plt.subplot(2, 1, 2).yaxis.set_tick_params(labelsize=20)
n = len(correction_fock_prob[0])
# n, = correction_avg_prob[0].shape
for index in range(n):
trajectory = [value[index] for value in correction_fock_prob]
# print(round(np.max(trajectory),4), round(np.median(trajectory),4), round(np.ptp(trajectory),4), index) ### debug
# uncert = [value[index] for value in correction_fock_prob_error]
if all(i <= prob_truncation for i in trajectory):
continue
state = index
# Rename state |2> = |1_L>
if index == 2:
state=logical_label[2]
plt.plot(correction_snapshot_timings, trajectory, marker='s', label=r'$\lvert 2 \rangle =$ ' + str(state), color=colors[index], markersize = 8, linewidth = 3)
else:
plt.plot(correction_snapshot_timings, trajectory, marker='o', label=r'$\lvert$' + str(state) + r'$\rangle$', color=colors[index])
## 1b. Correction circuit plot (logical state)
m = len(correction_fock_prob_logical[0])
for index in range(m):
trajectory = [value[index] for value in correction_fock_prob_logical]
if all(i <= prob_truncation for i in trajectory):
continue
plt.plot(correction_snapshot_timings, trajectory, marker='s', label=str(logical_label[index]), color=colors[index+8], markersize = 8, linewidth = 3)
# Plot correction positions
x, y = correction_positions(corr_position_times, correction_fock_prob, correction_snapshot_timings)
label = 'Correction \n position'
for i in x:
plt.axvline(x=i, color='grey', label=label, linestyle="--")
label = ''
# Subplot 2 formatting
plt.xlabel("Time (ms)", size=20)
#plt.ylabel("Probability of measuring Fock state, averaged over {} shots".format(shots))
plt.ylabel(r'$P(\lvert \psi \rangle$)', size=20)
plt.title("With " + str(num_corr) + r" correction(s)/ms ($\hat{U}_{\text{odd}}$ only)", size=20)
plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5)
# Remove duplicate labels
leg1 = {l:h for h,l in zip(*plt.subplot(2, 1, 1).get_legend_handles_labels())}
leg2 = {l:h for h,l in zip(*plt.subplot(2, 1, 2).get_legend_handles_labels())}
plt.figlegend(*[*zip(*{**leg1, **leg2}.items())][::-1], bbox_to_anchor=(1.15, 0.5), loc = 'right', fontsize=20)
plt.show()
# Run simulation with and without correction. Enable u_even
noise_only_simulation_list = []
correction_simulation_list = []
for i in encoding:
noise_only_simulation_list.append(error_correction_experiment(i, 0, shots, additional_snaps, noise_only_circ_time))
correction_simulation_list.append(error_correction_experiment(i, num_corr, shots, additional_snaps, correction_circ_time))
## Fidelity visualisation
index = encoding.index('logi1')
value = 'logi1'
_, noise_only_fid, _, noise_only_snapshot_timings, _ = noise_only_simulation_list[index]
_, correction_fid, _, correction_snapshot_timings, corr_position_times = correction_simulation_list[index]
noise_only_avg_fid = [round(np.average(cycle), 4) for cycle in noise_only_fid]
noise_only_avg_fid_error = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in noise_only_fid]
correction_avg_fid = [round(np.average(cycle), 4) for cycle in correction_fid]
correction_avg_fid_error = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in correction_fid]
# Find correction positions
x, y = correction_positions(corr_position_times, correction_avg_fid, correction_snapshot_timings)
# Plot fidelity data w/ uncertainty
plt.figure(figsize=(15,6))
plt.errorbar(noise_only_snapshot_timings, noise_only_avg_fid, yerr=noise_only_avg_fid_error,
label=r'No corrections', marker='o', color='#5BCEFA', capsize=3, ecolor='#2a6278')
plt.errorbar(correction_snapshot_timings, correction_avg_fid, yerr=correction_avg_fid_error,
label=str(num_corr) + r' corrections/ms', marker='o', color='#F5A9B8', capsize=3, ecolor='#9c6b75')
# Plot correction positions
label = 'Correction \n position'
for i in x:
plt.axvline(x=i, color='grey', label=label, linestyle="--")
label = ''
# Plot previous logi1 lifetime
plt.plot(noise_curve_timing, np.exp(-noise_curve_timing/correction_lifetime_perf), label=r'Simulation 1 result' + '\n' + r'$\tau = $' + str(correction_lifetime_perf) + r'ms')
plt.xlabel("Time (ms)", size=20)
plt.ylabel("State fidelity, averaged over {} shots".format(shots), size=20)
plt.title(r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + ' state fidelity without error correction and with ' + str(num_corr) + r' correction(s)/ms ($\hat{U}_{\text{odd}}$ and $\hat{U}_{\text{even}}$)', size=20)
plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5)
plt.legend(loc='upper right', fontsize=20)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.show()
## Fidelity visualisation
for index, value in enumerate(encoding):
if value == 'logi1':
continue
_, noise_only_fid_other, _, noise_only_snapshot_timings, _ = noise_only_simulation_list[index]
_, correction_fid_other, _, correction_snapshot_timings, corr_position_times = correction_simulation_list[index]
noise_only_avg_fid_other = [round(np.average(cycle), 4) for cycle in noise_only_fid_other]
noise_only_avg_fid_error_other = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in noise_only_fid_other]
correction_avg_fid_other = [round(np.average(cycle), 4) for cycle in correction_fid_other]
correction_avg_fid_error_other = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in correction_fid_other]
# Find correction positions
x, y = correction_positions(corr_position_times, correction_avg_fid_other, correction_snapshot_timings)
# Plot fidelity data w/ uncertainty
plt.figure(figsize=(15,6))
plt.errorbar(noise_only_snapshot_timings, noise_only_avg_fid_other, yerr=noise_only_avg_fid_error_other,
label=r'No corrections',
marker='o', color='#5BCEFA', capsize=3, ecolor='#2a6278')
plt.errorbar(correction_snapshot_timings, correction_avg_fid_other, yerr=correction_avg_fid_error_other,
label=str(num_corr) + r' corrections/ms',
marker='o', color='#F5A9B8', capsize=3, ecolor='#9c6b75')
# Plot an actual exponential decay as comparison
noise_curve_timing = np.linspace(0, noise_only_circ_time, 100)
plt.plot(noise_curve_timing, np.exp(-noise_curve_timing), label='Exponential curve')
# Plot correction positions
label = 'Correction \n position'
for i in x:
plt.axvline(x=i, color='grey', label=label, linestyle="--")
label = ''
plt.xlabel("Time (ms)", size=20)
plt.ylabel("State fidelity, averaged over {} shots".format(shots), size=20)
plt.title(r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + ' state fidelity without error correction and with ' + str(num_corr) + r' correction(s)/ms ($\hat{U}_{\text{odd}}$ and $\hat{U}_{\text{even}}$)', size=20)
plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5)
plt.legend(loc='upper right', fontsize=20)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.show()
### Adjust these parameters ###
run = [(41, 24), (3, 3), _, _] # Choose single shot to graph. Tuples are formatted as (noise_only_shot, correction_shot).
##
# Plot photon probability for all initial encodings
for index, value in enumerate(encoding):
if index not in [0, 1]:
continue
_, _, noise_only_prob_tuple, noise_only_snapshot_timings, _ = noise_only_simulation_list[index]
_, _, correction_prob_tuple, correction_snapshot_timings, corr_position_times = correction_simulation_list[index]
# Fock state probability visualization, single shot
noise_only_prob, noise_only_prob_logical = noise_only_prob_tuple
correction_prob, correction_prob_logical = correction_prob_tuple
# Runs to plot
run_noise, run_corr = run[index]
noise_only_fock_prob = [i[run_noise] for i in noise_only_prob]
correction_fock_prob = [i[run_corr] for i in correction_prob]
noise_only_fock_prob_logical = [i[run_noise] for i in noise_only_prob_logical]
correction_fock_prob_logical = [i[run_corr] for i in correction_prob_logical]
# Ignore trajectories of Fock states with prob below a certain value.
prob_truncation = 0.005
# Plot both graph in single image
plt.figure(figsize=(15,10))
plt.suptitle('Trajectories of Fock state probability simulations with ' + r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + ' encoding', size=30)
# plt.suptitle('No correction and ' + str(num_corr) + ' correction simulation, with ' +r'$\lvert$' + str(encoding_format.get(encoding)) + r'$\rangle$' + ' encoding', size=20)
## 1a. Noise only circuit plot (photon number)
plt.subplot(2, 1, 1)
plt.subplot(2, 1, 1).xaxis.set_tick_params(labelsize=20)
plt.subplot(2, 1, 1).yaxis.set_tick_params(labelsize=20)
n = len(noise_only_fock_prob[0])
# n, = noise_only_avg_prob[0].shape
for index in range(n):
trajectory = [value[index] for value in noise_only_fock_prob]
# uncert = [value[index] for value in noise_only_fock_prob_error]
if all(i <= prob_truncation for i in trajectory):
continue
state = index
# Rename state |2> = |1_L>
if index == 2:
state=logical_label[2]
plt.plot(noise_only_snapshot_timings, trajectory, marker='s', label=r'$\lvert 2 \rangle =$ ' + str(state), color=colors[index], markersize = 8, linewidth = 3)
else:
plt.plot(noise_only_snapshot_timings, trajectory, marker='o', label=r'$\lvert$' + str(state) + r'$\rangle$', color=colors[index])
## 1b. Noise only circuit plot (logical state)
m = len(noise_only_fock_prob_logical[0])
for index in range(m):
trajectory = [value[index] for value in noise_only_fock_prob_logical]
if all(i <= prob_truncation for i in trajectory):
continue
plt.plot(noise_only_snapshot_timings, trajectory, marker='s', label=str(logical_label[index]), color=colors[index+8], markersize = 8, linewidth = 3)
# Subplot 1 formatting
#plt.ylabel("Probability of measuring Fock state, averaged over over {} shots".format(shots))
plt.ylabel(r'$P(\lvert \psi \rangle$)', size=20)
plt.title(r"Without error correction", size=20)
plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5)
## 2a. Correction circuit plot (photon number)
plt.subplot(2, 1, 2, sharex = plt.subplot(2, 1, 1))
plt.subplot(2, 1, 2).xaxis.set_tick_params(labelsize=20)
plt.subplot(2, 1, 2).yaxis.set_tick_params(labelsize=20)
n = len(correction_fock_prob[0])
# n, = correction_avg_prob[0].shape
for index in range(n):
trajectory = [value[index] for value in correction_fock_prob]
# print(round(np.max(trajectory),4), round(np.median(trajectory),4), round(np.ptp(trajectory),4), index) ### debug
# uncert = [value[index] for value in correction_fock_prob_error]
if all(i <= prob_truncation for i in trajectory):
continue
state = index
# Rename state |2> = |1_L>
if index == 2:
state=logical_label[2]
plt.plot(correction_snapshot_timings, trajectory, marker='s', label=r'$\lvert 2 \rangle =$ ' + str(state), color=colors[index], markersize = 8, linewidth = 3)
else:
plt.plot(correction_snapshot_timings, trajectory, marker='o', label=r'$\lvert$' + str(state) + r'$\rangle$', color=colors[index])
## 1b. Correction circuit plot (logical state)
m = len(correction_fock_prob_logical[0])
for index in range(m):
trajectory = [value[index] for value in correction_fock_prob_logical]
if all(i <= prob_truncation for i in trajectory):
continue
plt.plot(correction_snapshot_timings, trajectory, marker='s', label=str(logical_label[index]), color=colors[index+8], markersize = 8, linewidth = 3)
# Plot correction positions
x, y = correction_positions(corr_position_times, correction_fock_prob, correction_snapshot_timings)
label = 'Correction \n position'
for i in x:
plt.axvline(x=i, color='grey', label=label, linestyle="--")
label = ''
# Subplot 2 formatting
plt.xlabel("Time (ms)", size=20)
#plt.ylabel("Probability of measuring Fock state, averaged over {} shots".format(shots))
plt.ylabel(r'$P(\lvert \psi \rangle$)', size=20)
plt.title("With " + str(num_corr) + r" correction(s)/ms ($\hat{U}_{\text{odd}}$ and $\hat{U}_{\text{even}}$)", size=20)
plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5)
# Remove duplicate labels
leg1 = {l:h for h,l in zip(*plt.subplot(2, 1, 1).get_legend_handles_labels())}
leg2 = {l:h for h,l in zip(*plt.subplot(2, 1, 2).get_legend_handles_labels())}
plt.figlegend(*[*zip(*{**leg1, **leg2}.items())][::-1], bbox_to_anchor=(1.15, 0.5), loc = 'right', fontsize=20)
plt.show()
### Adjust these parameters ###
run = [_, _, (0, 3), (2, 8)] # Choose single shot to graph. Tuples are formatted as (noise_only_shot, correction_shot).
##
# Plot photon probability for all initial encodings
for index, value in enumerate(encoding):
if index not in [2, 3]:
continue
_, _, noise_only_prob_tuple, noise_only_snapshot_timings, _ = noise_only_simulation_list[index]
_, _, correction_prob_tuple, correction_snapshot_timings, corr_position_times = correction_simulation_list[index]
# Fock state probability visualization, single shot
noise_only_prob, noise_only_prob_logical = noise_only_prob_tuple
correction_prob, correction_prob_logical = correction_prob_tuple
# Runs to plot
run_noise, run_corr = run[index]
noise_only_fock_prob = [i[run_noise] for i in noise_only_prob]
correction_fock_prob = [i[run_corr] for i in correction_prob]
noise_only_fock_prob_logical = [i[run_noise] for i in noise_only_prob_logical]
correction_fock_prob_logical = [i[run_corr] for i in correction_prob_logical]
# Ignore trajectories of Fock states with prob below a certain value.
prob_truncation = 0.005
# Plot both graph in single image
plt.figure(figsize=(15,10))
plt.suptitle('Trajectories of Fock state probability simulations with ' + r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + ' encoding', size=30)
# plt.suptitle('No correction and ' + str(num_corr) + ' correction simulation, with ' +r'$\lvert$' + str(encoding_format.get(encoding)) + r'$\rangle$' + ' encoding', size=20)
## 1a. Noise only circuit plot (photon number)
plt.subplot(2, 1, 1)
plt.subplot(2, 1, 1).xaxis.set_tick_params(labelsize=20)
plt.subplot(2, 1, 1).yaxis.set_tick_params(labelsize=20)
n = len(noise_only_fock_prob[0])
# n, = noise_only_avg_prob[0].shape
for index in range(n):
trajectory = [value[index] for value in noise_only_fock_prob]
# uncert = [value[index] for value in noise_only_fock_prob_error]
if all(i <= prob_truncation for i in trajectory):
continue
state = index
# Rename state |2> = |1_L>
if index == 2:
state=logical_label[2]
plt.plot(noise_only_snapshot_timings, trajectory, marker='s', label=r'$\lvert 2 \rangle =$ ' + str(state), color=colors[index], markersize = 8, linewidth = 3)
else:
plt.plot(noise_only_snapshot_timings, trajectory, marker='o', label=r'$\lvert$' + str(state) + r'$\rangle$', color=colors[index])
## 1b. Noise only circuit plot (logical state)
m = len(noise_only_fock_prob_logical[0])
for index in range(m):
trajectory = [value[index] for value in noise_only_fock_prob_logical]
if all(i <= prob_truncation for i in trajectory):
continue
plt.plot(noise_only_snapshot_timings, trajectory, marker='s', label=str(logical_label[index]), color=colors[index+8], markersize = 8, linewidth = 3)
# Subplot 1 formatting
#plt.ylabel("Probability of measuring Fock state, averaged over over {} shots".format(shots))
plt.ylabel(r'$P(\lvert \psi \rangle$)', size=20)
plt.title(r"Without error correction", size=20)
plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5)
## 2a. Correction circuit plot (photon number)
plt.subplot(2, 1, 2, sharex = plt.subplot(2, 1, 1))
plt.subplot(2, 1, 2).xaxis.set_tick_params(labelsize=20)
plt.subplot(2, 1, 2).yaxis.set_tick_params(labelsize=20)
n = len(correction_fock_prob[0])
# n, = correction_avg_prob[0].shape
for index in range(n):
trajectory = [value[index] for value in correction_fock_prob]
# print(round(np.max(trajectory),4), round(np.median(trajectory),4), round(np.ptp(trajectory),4), index) ### debug
# uncert = [value[index] for value in correction_fock_prob_error]
if all(i <= prob_truncation for i in trajectory):
continue
state = index
# Rename state |2> = |1_L>
if index == 2:
state=logical_label[2]
plt.plot(correction_snapshot_timings, trajectory, marker='s', label=r'$\lvert 2 \rangle =$ ' + str(state), color=colors[index], markersize = 8, linewidth = 3)
else:
plt.plot(correction_snapshot_timings, trajectory, marker='o', label=r'$\lvert$' + str(state) + r'$\rangle$', color=colors[index])
## 1b. Correction circuit plot (logical state)
m = len(correction_fock_prob_logical[0])
for index in range(m):
trajectory = [value[index] for value in correction_fock_prob_logical]
if all(i <= prob_truncation for i in trajectory):
continue
plt.plot(correction_snapshot_timings, trajectory, marker='s', label=str(logical_label[index]), color=colors[index+8], markersize = 8, linewidth = 3)
# Plot correction positions
x, y = correction_positions(corr_position_times, correction_fock_prob, correction_snapshot_timings)
label = 'Correction \n position'
for i in x:
plt.axvline(x=i, color='grey', label=label, linestyle="--")
label = ''
# Subplot 2 formatting
plt.xlabel("Time (ms)", size=20)
#plt.ylabel("Probability of measuring Fock state, averaged over {} shots".format(shots))
plt.ylabel(r'$P(\lvert \psi \rangle$)', size=20)
plt.title("With " + str(num_corr) + r" correction(s)/ms ($\hat{U}_{\text{odd}}$ and $\hat{U}_{\text{even}}$)", size=20)
plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5)
# Remove duplicate labels
leg1 = {l:h for h,l in zip(*plt.subplot(2, 1, 1).get_legend_handles_labels())}
leg2 = {l:h for h,l in zip(*plt.subplot(2, 1, 2).get_legend_handles_labels())}
plt.figlegend(*[*zip(*{**leg1, **leg2}.items())][::-1], bbox_to_anchor=(1.15, 0.5), loc = 'right', fontsize=20)
plt.show()
### Adjust these parameters ###
num_corr = 2 # per ms, number of correction circuits applied
additional_snaps = 0 # per ms, number of additional snapshots taken in between each correction circuit
noise_only_circ_time = 2 # ms, total duration of noise-only circuit
correction_circ_time = 5 # ms, total duration of correction circuit
shots = 1000 # Number of times circuit is repeated
encoding=['logi_xplus', 'logi_yplus', 'logi1'] # Input 'logi0', 'logi1', 'logi_xplus', 'logi_xminus', 'logi_yplus', or 'logi_yminus'
##
# Run simulation with and without correction. Enable u_even
noise_only_simulation_list = []
correction_simulation_list = []
for i in encoding:
noise_only_simulation_list.append(error_correction_experiment(i, 0, shots, 2, noise_only_circ_time))
correction_simulation_list.append(error_correction_experiment(i, num_corr, shots, additional_snaps, correction_circ_time))
# Backup chunk
## Pauli Expectation Value visualisation
colors= ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
label = 'Correction \n position'
plt.figure(figsize=(15,6))
# Plot with correction
for index, value in enumerate(encoding):
if value in ['logi0', 'logi_xplus', 'logi_yplus']:
sign = 1
else:
sign = -1
# Plot without correction
(noise_only_pauli_expectation, _), _, _, noise_only_snapshot_timings, _ = noise_only_simulation_list[index]
noise_only_expectation_avg = [np.round(np.average(cycle), 4) for cycle in noise_only_pauli_expectation]
noise_only_expectation_avg_error = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in noise_only_pauli_expectation]
noise_only_lifetime, noise_lifetime_uncertainty = curve_fitter(noise_only_snapshot_timings, noise_only_expectation_avg, sign)
plt.errorbar(noise_only_snapshot_timings, noise_only_expectation_avg, yerr=noise_only_expectation_avg_error,
label=r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + r' no corrections,' + '\n' + r'$\tau$ = ' + str(noise_only_lifetime) + r'ms $\pm$' + str(round(noise_lifetime_uncertainty, 2)) + r'ms',
marker='o', color=colors[-index - 1], capsize=3, ecolor='#2a6278')
noise_curve_timing = np.linspace(0, noise_only_circ_time, 100)
plt.plot(noise_curve_timing, sign * np.exp(-noise_curve_timing/noise_only_lifetime), alpha=0.5, color=colors[-index - 1])
# Plot with correction
(correction_pauli_expectation, _), _, _, correction_snapshot_timings, corr_position_times = correction_simulation_list[index]
correction_expectation_avg = [np.round(np.average(cycle), 4) for cycle in correction_pauli_expectation]
correction_expectation_avg_error = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in correction_pauli_expectation]
correction_lifetime, correction_lifetime_uncertainty = curve_fitter(correction_snapshot_timings, correction_expectation_avg, sign)
plt.errorbar(correction_snapshot_timings, correction_expectation_avg, yerr=correction_expectation_avg_error,
label=r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$ ' + str(num_corr) + r' corrections/ms,' + '\n' + r'$\tau$ = ' + str(correction_lifetime) + r'ms $\pm$' + str(round(correction_lifetime_uncertainty, 2)) + r'ms',
marker='o', color=colors[index], capsize=3, ecolor='#9c6b75')
corr_curve_timing = np.linspace(0, correction_circ_time, 100)
plt.plot(corr_curve_timing, sign * np.exp(-corr_curve_timing/correction_lifetime), alpha=0.5, color=colors[index])
# Plot error correction positions
x, y = correction_positions(corr_position_times, correction_pauli_expectation, correction_snapshot_timings)
for i in x:
plt.axvline(x=i, color='grey', label=label, linestyle="--")
label = ''
plt.xlabel("Time (ms)", size=20)
plt.ylabel("Pauli expectation, averaged over {} shots".format(shots), size=20)
plt.title(r'Pauli expectation for varying logical states ($\hat{U}_{\text{odd}}$ and $\hat{U}_{\text{even}}$)', size=20)
plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5)
plt.legend(fontsize=20, bbox_to_anchor=(1.35, 0.5), loc='right')
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.show()
## All six states on separate charts
encoding = ['logi_xplus', 'logi_xminus', 'logi_yplus', 'logi_yminus', 'logi0', 'logi1']
sign = [1, -1, 1, -1, 1, -1]
for index, i in enumerate(encoding):
noise_only_pauli_tuple, noise_only_fid, noise_only_prob, noise_only_snapshot_timings, _ = error_correction_experiment(i, 0, shots, 3, noise_only_circ_time)
correction_pauli_tuple, correction_fid, correction_prob, correction_snapshot_timings, corr_position_times = error_correction_experiment(i, num_corr, shots, additional_snaps, correction_circ_time)
## Pauli operator decay visualization
noise_only_pauli_expectation, _ = noise_only_pauli_tuple #[[matrix.real for matrix in cycle] for cycle in noise_only_pauli]
correction_pauli_expectation, _ = correction_pauli_tuple
# Compute average expectation and prob across all shots
noise_only_expectation_avg = [np.round(np.average(cycle), 4) for cycle in noise_only_pauli_expectation]
correction_expectation_avg = [np.round(np.average(cycle), 4) for cycle in correction_pauli_expectation]
## Expectation plots
# Fit expectation data using an exponential decay function
noise_only_lifetime, noise_lifetime_uncertainty = curve_fitter(noise_only_snapshot_timings, noise_only_expectation_avg, sign[index])
correction_lifetime, correction_lifetime_uncertainty = curve_fitter(correction_snapshot_timings, correction_expectation_avg, sign[index])
# Plot expectation data
plt.figure(figsize=(15,6))
plt.plot(noise_only_snapshot_timings, noise_only_expectation_avg,
label=r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + r' no corrections,' + '\n' + r'$\tau$ = ' + str(noise_only_lifetime) + r'ms $\pm$' + str(round(noise_lifetime_uncertainty, 2)) + r'ms',
marker='o', color='#5BCEFA')
plt.plot(correction_snapshot_timings, correction_expectation_avg,
label=r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$ ' + str(num_corr) + r' corrections/ms,' + '\n' + r'$\tau$ = ' + str(correction_lifetime) + r'ms $\pm$' + str(round(correction_lifetime_uncertainty, 2)) + r'ms',
marker='o', color='#F5A9B8')
# Plot expectation data curve fits
noise_curve_timing = np.linspace(0, noise_only_circ_time, 100)
plt.plot(noise_curve_timing, sign[index] * np.exp(-noise_curve_timing/noise_only_lifetime))
corr_curve_timing = np.linspace(0, correction_circ_time, 100)
plt.plot(corr_curve_timing, sign[index] * np.exp(-corr_curve_timing/correction_lifetime))
# Plot correction positions
x, y = correction_positions(corr_position_times, correction_expectation_avg, correction_snapshot_timings)
label = 'Correction \n position'
for i in x:
plt.axvline(x=i, color='grey', label=label, linestyle="--")
label = ''
plt.xlabel("Time (ms)", size=20)
plt.ylabel("Pauli expectation, averaged over {} shots".format(shots), size=20)
plt.title(r'Pauli expectation for varying logical states ($\hat{U}_{\text{odd}}$ and $\hat{U}_{\text{even}}$)', size=20)
plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5)
plt.legend(fontsize=20, bbox_to_anchor=(1.35, 0.5), loc='right')
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.show()
|
https://github.com/derek-wang-ibm/coding-with-qiskit
|
derek-wang-ibm
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.draw(output='mpl')
from qiskit.quantum_info import Pauli
ZZ = Pauli('ZZ')
ZI = Pauli('ZI')
IZ = Pauli('IZ')
XX = Pauli('XX')
XI = Pauli('XI')
IX = Pauli('IX')
observables = [ZZ, ZI, IZ, XX, XI, IX]
from qiskit_aer.primitives import Estimator
estimator = Estimator()
job = estimator.run([qc] * len(observables), observables)
job.result()
import matplotlib.pyplot as plt
data = ['ZZ', 'ZI', 'IZ', 'XX', 'XI', 'IX']
values = job.result().values
plt.plot(data, values, '-o')
plt.xlabel('Observables')
plt.ylabel('Expectation value')
plt.show()
def get_qc_for_n_qubit_GHZ_state(n):
qc = QuantumCircuit(n)
qc.h(0)
for i in range(n-1):
qc.cx(i, i+1)
return qc
n = 100
qc = get_qc_for_n_qubit_GHZ_state(n)
qc.draw(output='mpl')
from qiskit.quantum_info import SparsePauliOp
operator_strings = ['Z' + 'I' * i + 'Z' + 'I' * (n-2-i) for i in range(n-1)]
print(operator_strings)
print(len(operator_strings))
operators = [SparsePauliOp(operator_string) for operator_string in operator_strings]
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
backend = QiskitRuntimeService().least_busy(simulator=False, operational=True, min_num_qubits=100)
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend)
qc_transpiled = pass_manager.run(qc)
operators_transpiled_list = [op.apply_layout(qc_transpiled.layout) for op in operators]
from qiskit_ibm_runtime import EstimatorV2 as Estimator
from qiskit_ibm_runtime import EstimatorOptions
options = EstimatorOptions()
options.resilience_level = 1
options.optimization_level = 0
options.dynamical_decoupling.enable = True
options.dynamical_decoupling.sequence_type = "XY4"
estimator = Estimator(backend, options=options)
job = estimator.run([(qc_transpiled, operators_transpiled_list)])
job_id = job.job_id()
print(job_id)
job_id = 'cqq05tz267h0008fj6qg'
service = QiskitRuntimeService()
job = service.job(job_id)
import matplotlib.pyplot as plt
data = list(range(1, len(operators)+1))
result = job.result()[0]
values = result.data.evs
values = [v / values[0] for v in values]
plt.scatter(data, values, marker='o', label='100-qubit GHZ state')
plt.xlabel('Distance between qubits $i$')
plt.ylabel(r'$\langle Z_0 Z_i \rangle / \langle Z_0 Z_1 \rangle$')
plt.legend()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.quantum_info import SparsePauliOp
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit.primitives import Estimator
estimator = Estimator()
job = estimator.run(circuit, observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
circuit = random_circuit(2, 2, seed=1).decompose(reps=1)
observable = SparsePauliOp("IY")
job = estimator.run(circuit, observable)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Observable: {observable.paulis}")
print(f">>> Expectation value: {result.values[0]}")
circuits = (
random_circuit(2, 2, seed=0).decompose(reps=1),
random_circuit(2, 2, seed=1).decompose(reps=1),
)
observables = (
SparsePauliOp("XZ"),
SparsePauliOp("IY"),
)
job = estimator.run(circuits, observables)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f">>> Observables: {[obs.paulis for obs in observables]}")
print(f">>> Expectation values: {result.values.tolist()}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
observable = SparsePauliOp("ZI")
parameter_values = [0, 1, 2, 3, 4, 5]
job = estimator.run(circuit, observable, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Observable: {observable.paulis}")
print(f">>> Parameter values: {parameter_values}")
print(f">>> Expectation value: {result.values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibmq_qasm_simulator")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit_ibm_runtime import Estimator
estimator = Estimator(session=backend)
job = estimator.run(circuit, observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
options = Options(optimization_level=3, environment={"log_level": "INFO"})
from qiskit_ibm_runtime import Options
options = Options()
options.resilience_level = 1
options.execution.shots = 2048
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable).result()
print(f">>> Metadata: {result.metadata[0]}")
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable, shots=1024).result()
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
# optimization_level=3 adds dynamical decoupling
# resilience_level=1 adds readout error mitigation
options = Options(optimization_level=3, resilience_level=1)
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value: {result.values[0]}")
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Session, Estimator
with Session(backend=backend, max_time="1h"):
estimator = Estimator()
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the first run: {result.values[0]}")
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the second run: {result.values[0]}")
from qiskit.circuit.random import random_circuit
sampler_circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
sampler_circuit.measure_all()
display(circuit.draw("mpl"))
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
result = sampler.run(sampler_circuit).result()
print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}")
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the estimator job: {result.values[0]}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
sampler_job = sampler.run(sampler_circuit)
estimator_job = estimator.run(circuit, observable)
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options
# 1. Initialize account
service = QiskitRuntimeService(channel="ibm_quantum")
# 2. Specify options, such as enabling error mitigation
options = Options(resilience_level=1)
# 3. Select a backend.
backend = service.backend("ibmq_qasm_simulator")
# 4. Create a session
with Session(backend=backend):
# 5. Create primitive instances
sampler = Sampler(options=options)
estimator = Estimator(options=options)
# 6. Submit jobs
sampler_job = sampler.run(sampler_circuit)
estimator_job = estimator.run(circuit, observable)
# 7. Get results
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# This is a comment
# A comment is used for explanations/descriptions/etc.
# Comments do not affect the programs
# let's define an integer variable named a
a = 5
# let's print its value
print(a)
# let's define three integer variables named a, b, and c
a = 2
b = 4
c = a + b # summation of a and b
# let's print their values together
print(a,b,c)
# a single space will automatically appear in between
# let's print their values in reverse order
print(c,b,a)
# let's print their summation and multiplication
print(a+b+c,a*b*c)
# let's define variables with string/text values
hw = "hello world" # we can use double quotes
hqw = 'hello quantum world' # we can use single quotes
# let's print them
print(hw)
print(hqw)
# let's print them together by inserting another string in between
print(hw,"and",hqw)
# let's concatenate a few strings
d = "Hello " + 'World' + " but " + 'Quantum ' + "World"
# let's print the result
print(d)
# let's print numeric and string values together
print("a =",a,", b =",b,", a+b =",a+b)
# let's subtract two numbers
d = a-b
print(a,b,d)
# let's divide two numbers
d = a/b
print(a,b,d)
# let's divide integers over integers
# the result is always an integer (with possible integer remainder)
d = 33 // 6
print(d)
# reminder/mod operator
r = 33 % 6
# 33 mod 6 = 3
# or when 33 is divided by 6 over integers, the reminder is 3
# 33 = 5 * 6 + 3
# let's print the result
print(r)
# Booleen variables
t = True
f = False
# let's print their values
print(t,f)
# print their negations
print(not t)
print("the negation of",t,"is",not t)
print(not f)
print("the negation of",f,"is",not f)
# define a float variable
d = -3.4444
# let's print its value and its square
print(d, d * d)
e = (23*13) - (11 * 15)
print(e)
# we can use more than one variable
# left is the variable for the left part of the expression
# we start with the multiplication inside the parentheses
left = 34*11
# we continue with the substruction inside the parentheses
# we reuse the variable named left
left = 123 - left
# we reuse left again for the multiplication with -3
left = -3 * left
# right is the variable for the right part of the expression
# we use the same idea here
right = 23 * 15
right = 5 + right
right = 4 * right
# at the end, we use left for the result
left = left + right
# let's print the result
print(left)
#
# your solution is here
#
#
# your solution is here
#
#
# your solution is here
#
|
https://github.com/Heisenbug-s-Dog/qnn_visualization
|
Heisenbug-s-Dog
|
from google.colab import drive
drive.mount('/content/drive')
!pip install torch==1.3.1
!pip install torchvision==0.4.2
!pip install Pillow==6.2.1
!pip install pennylane==0.7.0
# OpenMP: number of parallel threads.
%env OMP_NUM_THREADS=1
# Plotting
%matplotlib inline
import matplotlib.pyplot as plt
# PyTorch
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import datasets, models, transforms
# Pennylane
import pennylane as qml
from pennylane import numpy as np
# Other tools
import time
import copy
filtered_classes = ['cat', 'dog'] # Subset of CIFAR ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck')
n_qubits = 4 # Number of qubits
quantum = True # If set to "False", the dressed quantum circuit is replaced by
# An enterily classical net (defined by the next parameter).
classical_model = '512_n' # Possible choices: '512_n','512_nq_n','551_512_n'. [nq=n_qubits, n=num_filtered_classes]
step = 0.001 # Learning rate
batch_size = 8 # Number of samples for each training step
num_epochs = 3 # Number of training epochs
q_depth = 5 # Depth of the quantum circuit (number of variational layers)
gamma_lr_scheduler = 1 # Learning rate reduction applied every 10 epochs.
max_layers = 15 # Keep 15 even if not all are used.
q_delta = 0.01 # Initial spread of random quantum weights
rng_seed = 0 # Seed for random number generator
start_time = time.time() # start of the computation timer
torch.manual_seed(rng_seed)
dev = qml.device('default.qubit', wires=n_qubits)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def H_layer(nqubits):
"""Layer of single-qubit Hadamard gates.
"""
for idx in range(nqubits):
qml.Hadamard(wires=idx)
def RY_layer(w):
"""Layer of parametrized qubit rotations around the y axis.
"""
for idx, element in enumerate(w):
qml.RY(element, wires=idx)
def entangling_layer(nqubits):
"""Layer of CNOTs followed by another shifted layer of CNOT.
"""
# In other words it should apply something like :
# CNOT CNOT CNOT CNOT... CNOT
# CNOT CNOT CNOT... CNOT
for i in range(0, nqubits - 1, 2): # Loop over even indices: i=0,2,...N-2
qml.CNOT(wires=[i, i + 1])
for i in range(1, nqubits - 1,2): # Loop over odd indices: i=1,3,...N-3
qml.CNOT(wires=[i, i + 1])
@qml.qnode(dev, interface='torch')
def q_net(q_in, q_weights_flat):
# Reshape weights
q_weights = q_weights_flat.reshape(max_layers, n_qubits)
# Start from state |+> , unbiased w.r.t. |0> and |1>
H_layer(n_qubits)
# Embed features in the quantum node
RY_layer(q_in)
# Sequence of trainable variational layers
for k in range(q_depth):
entangling_layer(n_qubits)
RY_layer(q_weights[k+1])
# Expectation values in the Z basis
return [qml.expval(qml.PauliZ(j)) for j in range(n_qubits)]
class Quantumnet(nn.Module):
def __init__(self):
super().__init__()
self.pre_net = nn.Linear(512, n_qubits)
self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits))
self.post_net = nn.Linear(n_qubits, len(filtered_classes))
def forward(self, input_features):
pre_out = self.pre_net(input_features)
q_in = torch.tanh(pre_out) * np.pi / 2.0
# Apply the quantum circuit to each element of the batch, and append to q_out
q_out = torch.Tensor(0, n_qubits)
q_out = q_out.to(device)
for elem in q_in:
q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0)
q_out = torch.cat((q_out, q_out_elem))
return self.post_net(q_out)
class Quantumnet_Cut(nn.Module):
def __init__(self):
super().__init__()
self.pre_net = nn.Linear(512, n_qubits)
self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits))
def forward(self, input_features):
pre_out = self.pre_net(input_features)
q_in = torch.tanh(pre_out) * np.pi / 2.0
# Apply the quantum circuit to each element of the batch, and append to q_out
q_out = torch.Tensor(0, n_qubits)
q_out = q_out.to(device)
for elem in q_in:
q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0)
q_out = torch.cat((q_out, q_out_elem))
return q_out
class Quantumnet_Classical_Cut(nn.Module):
def __init__(self):
super().__init__()
self.pre_net = nn.Linear(512, n_qubits)
self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits))
def forward(self, input_features):
pre_out = self.pre_net(input_features)
q_in = torch.tanh(pre_out) * np.pi / 2.0
return q_in
model = torchvision.models.resnet18(pretrained=True)
model.fc = Quantumnet()
for param in model.parameters():
param.requires_grad = False
# Use CUDA or CPU according to the "device" object.
model = model.to(device)
model_cut = torchvision.models.resnet18(pretrained=True)
model_cut.fc = Quantumnet_Cut()
for param in model_cut.parameters():
param.requires_grad = False
# Use CUDA or CPU according to the "device" object.
model_cut = model_cut.to(device)
model_classical_cut = torchvision.models.resnet18(pretrained=True)
model_classical_cut.fc = Quantumnet_Classical_Cut()
for param in model_cut.parameters():
param.requires_grad = False
# Use CUDA or CPU according to the "device" object.
model_classical_cut = model_classical_cut.to(device)
# Load model from file
path = 'drive/MyDrive/'
if quantum:
model.load_state_dict(torch.load(
path+'quantum_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt'
)
)
else:
model.load_state_dict(torch.load(
path+'classical_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt'
)
)
model_dict = model.state_dict()
model_cut_dict = model_cut.state_dict()
model_cut_dict = {k: v for k, v in model_dict.items() if k in model_cut_dict}
model_cut.load_state_dict(model_cut_dict)
model_classical_cut_dict = model_classical_cut.state_dict()
model_classical_cut_dict = {k: v for k, v in model_dict.items() if k in model_classical_cut_dict}
model_classical_cut.load_state_dict(model_classical_cut_dict)
import sys
sys.path.append('drive/My Drive/')
from torchvis import util
vis_param_dict, reset_state, remove_handles = util.augment_module(model)
from PIL import Image # so, this woorks better than skimage, as torchvision transforms work best with PIL and Tensor.
from torchvision import transforms
img_to_use = Image.open(path + 'dog.jpg')
print(img_to_use.size)
transform_1 = transforms.Compose([
transforms.Scale(256),
transforms.CenterCrop(224),
])
# since it's 0-255 range.
transform_2 = transforms.Compose([
transforms.ToTensor(),
# convert RGB to BGR
# from <https://github.com/mrzhu-cool/pix2pix-pytorch/blob/master/util.py>
transforms.Lambda(lambda x: torch.index_select(x, 0, torch.LongTensor([2, 1, 0]))),
transforms.Lambda(lambda x: x*255),
transforms.Normalize(mean = [103.939, 116.779, 123.68],
std = [ 1, 1, 1 ]),
])
img_to_use_cropped = transform_1(img_to_use)
img_to_use_cropped_tensor = transform_2(img_to_use_cropped)[np.newaxis] # add first column for batching
img_to_use_cropped_tensor.min(), img_to_use_cropped_tensor.max()
img_to_use_cropped # this is same as Lasagne example.
from torchsummary import summary
summary(model, (3, 224, 224))
from torch.nn import Parameter
input_img = Parameter(img_to_use_cropped_tensor.cuda(), requires_grad=True)
if input_img.grad is not None:
input_img.grad.data.zero_()
model.zero_grad()
# wrap input in Parameter, so that gradients will be computed.
raw_score = model(input_img)
raw_score_numpy = raw_score.data.cpu().numpy()
print(raw_score_numpy.shape, np.argmax(raw_score_numpy.ravel()))
loss = raw_score.sum()
print('loss', loss)
# second time, there's no output anymore, due to lack of hook
# I didn't call it, as maybe zero_grad may have some interaction with it. Not sure. Just for safety.
# _ = alexnet(Variable(img_to_use_cropped_tensor.cuda()))
# so, forward one time, and backward multiple times.
vis_param_dict['layer'] = 'classifier.6'
vis_param_dict['method'] = util.GradType.NAIVE
# which one coresponds
# this is the max one. I assume it's the correct one.
# indeed, it's correct.
# 55 is n01729977, corresponding to "green snake, grass snake".
vis_param_dict['index'] = 55
# alexnet gives 64, which is n01749939, or green mamba. not sure which one is correct.
loss.backward(retain_graph=True)
# adapted from <https://github.com/Lasagne/Recipes/blob/master/examples/Saliency%20Maps%20and%20Guided%20Backpropagation.ipynb>
def show_images(img_original, saliency, title):
# convert from c01 to 01c
print(saliency.min(), saliency.max(), saliency.mean(), saliency.std())
saliency = saliency[::-1] # to BGR
saliency = saliency.transpose(1, 2, 0)
# # put back std fixing.
# saliency = saliency * np.array([ 0.229, 0.224, 0.225 ])
# plot the original image and the three saliency map variants
plt.figure(figsize=(10, 10), facecolor='w')
plt.subplot(2, 2, 1)
plt.title('input')
plt.imshow(np.asarray(img_original))
plt.subplot(2, 2, 2)
plt.title('abs. saliency')
plt.imshow(np.abs(saliency).max(axis=-1), cmap='gray')
plt.subplot(2, 2, 3)
plt.title('pos. saliency')
plt.imshow((np.maximum(0, saliency) / saliency.max()))
plt.subplot(2, 2, 4)
plt.title('neg. saliency')
plt.imshow((np.maximum(0, -saliency) / -saliency.min()))
plt.suptitle(title)
plt.show()
show_images(img_to_use_cropped, input_img.grad.data.cpu().numpy()[0], '')
# so, forward one time, and backward multiple times.
vis_param_dict['method'] = util.GradType.GUIDED
# alexnet gives 64, which is n01749939, or green mamba. not sure which one is correct.
if input_img.grad is not None:
input_img.grad.data.zero_()
model.zero_grad()
loss.backward(retain_graph=True)
show_images(img_to_use_cropped, input_img.grad.data.cpu().numpy()[0], 'guided')
# so, forward one time, and backward multiple times.
vis_param_dict['method'] = util.GradType.DECONV
# alexnet gives 64, which is n01749939, or green mamba. not sure which one is correct.
if input_img.grad is not None:
input_img.grad.data.zero_()
model.zero_grad()
loss.backward(retain_graph=True)
show_images(img_to_use_cropped, input_img.grad.data.cpu().numpy()[0], 'deconv')
def dream(image, model, iterations, lr):
""" Updates the image to maximize outputs for n iterations """
Tensor = torch.cuda.FloatTensor if torch.cuda.is_available else torch.FloatTensor
image = preprocess(image).unsqueeze(0).cpu().data.numpy()
image = Variable(Tensor(image), requires_grad=True)
for i in range(iterations):
model.zero_grad()
out = model(image)
loss = out.norm()
if i % 10 == 0:
print('iter: {}/{}, loss: {}'.format(i+1, iterations, loss.item()))
loss.backward()
avg_grad = np.abs(image.grad.data.cpu().numpy()).mean()
norm_lr = lr / avg_grad
image.data += norm_lr * image.grad.data
image.data = clip(image.data)
image.grad.data.zero_()
return image.cpu().data.numpy()
def diff_dream(image, model1, model2, iterations, lr):
""" Updates the image to maximize outputs for n iterations """
Tensor = torch.cuda.FloatTensor if torch.cuda.is_available else torch.FloatTensor
image = preprocess(image).unsqueeze(0).cpu().data.numpy()
image = Variable(Tensor(image), requires_grad=True)
for i in range(iterations):
model1.zero_grad()
model2.zero_grad()
out1 = model1(image)
out2 = model2(image)
loss = out1.norm() / np.sqrt(np.prod(out1.shape)) - out2.norm() / np.sqrt(np.prod(out2.shape))
if i % 10 == 0:
print('iter: {}/{}, loss: {}'.format(i+1, iterations, loss.item()))
loss.backward()
avg_grad = np.abs(image.grad.data.cpu().numpy()).mean()
norm_lr = lr / avg_grad
image.data += norm_lr * image.grad.data
image.data = clip(image.data)
image.grad.data.zero_()
return image.cpu().data.numpy()
def deep_dream(image, model, iterations, lr, octave_scale, num_octaves):
""" Main deep dream method """
image = preprocess(image).unsqueeze(0).cpu().data.numpy()
# Extract image representations for each octave
octaves = [image]
for _ in range(num_octaves - 1):
octaves.append(nd.zoom(octaves[-1], (1, 1, 1 / octave_scale, 1 / octave_scale), order=1))
detail = np.zeros_like(octaves[-1])
for octave, octave_base in enumerate(tqdm.tqdm(octaves[::-1], desc="Dreaming")):
if octave > 0:
# Upsample detail to new octave dimension
detail = nd.zoom(detail, np.array(octave_base.shape) / np.array(detail.shape), order=1)
# Add deep dream detail from previous octave to new base
input_image = octave_base + detail
# Get new deep dream image
dreamed_image = dream(input_image, model, iterations, lr)
# Extract deep dream details
detail = dreamed_image - octave_base
return deprocess(dreamed_image)
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
#preprocess = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean, std)])
preprocess = transforms.Compose([transforms.ToTensor()])
def deprocess(image_np):
image_np = image_np.squeeze().transpose(1, 2, 0)
image_np = image_np * std.reshape((1, 1, 3)) + mean.reshape((1, 1, 3))
image_np = np.clip(image_np, 0.0, 255.0)
return image_np
def clip(image_tensor):
for c in range(3):
m, s = mean[c], std[c]
image_tensor[0, c] = torch.clamp(image_tensor[0, c], -m / s, (1 - m) / s)
return image_tensor
from PIL import Image
import scipy.ndimage as nd
from torch.autograd import Variable
import tqdm, os
# Load image
image = Image.open("/content/drive/MyDrive/Qiskit-Hackathon-Korea/qnn-visualization/images/dog.jpg")
# Set Models
#network = model
#layers = list(network.children())
#classical_model = nn.Sequential(*layers[: 9]) #Max: 9
classical_model = model_classical_cut
quantum_model = model
# Extract deep dream image
dreamed_image = dream(
image,
quantum_model,
iterations=1000,
lr=0.01
)
dreamed_image = np.transpose(dreamed_image, (0,2,3,1))
dreamed_image = dreamed_image[0]
# Save and plot image
#os.makedirs("outputs", exist_ok=True)
#filename = 'test'
plt.figure(figsize=(20, 20))
plt.imshow(dreamed_image)
#plt.imsave(f"outputs/output_{filename}", dreamed_image)
plt.show()
quantum_dreamed_image = diff_dream(
image,
quantum_model,
classical_model,
iterations=500,
lr=0.01
)
dreamed_image = quantum_dreamed_image
dreamed_image = np.transpose(dreamed_image, (0,2,3,1))
dreamed_image = dreamed_image[0]
# Save and plot image
#os.makedirs("outputs", exist_ok=True)
#filename = 'test'
plt.figure(figsize=(20, 20))
plt.imshow(dreamed_image)
#plt.imsave(f"outputs/output_{filename}", dreamed_image)
plt.show()
classical_dreamed_image = diff_dream(
image,
classical_model,
quantum_model,
iterations=500,
lr=0.01
)
dreamed_image = classical_dreamed_image
dreamed_image = np.transpose(dreamed_image, (0,2,3,1))
dreamed_image = dreamed_image[0]
# Save and plot image
#os.makedirs("outputs", exist_ok=True)
#filename = 'test'
plt.figure(figsize=(20, 20))
plt.imshow(dreamed_image)
#plt.imsave(f"outputs/output_{filename}", dreamed_image)
plt.show()
|
https://github.com/LauraGentini/QRL
|
LauraGentini
|
"""
Python script containing functions definitions for the Quantum Deep-Q Learning approach,
used in the DQN-analysis Jupyter Notebook.
Prepared for Qiskit Hackathon Europe by:
Stefano, Paolo, Jani & Laura, 2021.
"""
# General imports
import numpy as np
import matplotlib.pyplot as plt
# Qiskit Circuit imports
from qiskit.circuit import QuantumCircuit, QuantumRegister, Parameter, ParameterVector, ParameterExpression
from qiskit.circuit.library import TwoLocal
# Qiskit imports
import qiskit as qk
from qiskit.utils import QuantumInstance
# Qiskit Machine Learning imports
import qiskit_machine_learning as qkml
from qiskit_machine_learning.neural_networks import CircuitQNN
from qiskit_machine_learning.connectors import TorchConnector
# PyTorch imports
import torch
from torch import Tensor
from torch.nn import MSELoss
from torch.optim import LBFGS, SGD, Adam, RMSprop
def encoding_circuit(inputs, num_qubits=4, *args):
"""
Encode classical input data (i.e. the state of the enironment) on a quantum circuit.
To be used inside the `parametrized_circuit` function.
Args
-------
inputs (list): a list containing the classical inputs.
num_qubits (int): number of qubits in the quantum circuit.
Return
-------
qc (QuantumCircuit): quantum circuit with encoding gates.
"""
qc = qk.QuantumCircuit(num_qubits)
# Encode data with a RX rotation
for i, data in enumerate(inputs):
qc.rx(inputs[i], i)
return qc
def parametrized_circuit(num_qubits=4, reuploading=False, reps=2, insert_barriers=True, meas=False):
"""
Create the Parameterized Quantum Circuit (PQC) for estimating Q-values.
It implements the architecure proposed in Skolik et al. arXiv:2104.15084.
Args
-------
num_qubit (int): number of qubits in the quantum circuit.
reuploading (bool): True if want to use data reuploading technique.
reps (int): number of repetitions (layers) in the variational circuit.
insert_barrirerd (bool): True to add barriers in between gates, for better drawing of the circuit.
meas (bool): True to add final measurements on the qubits.
Return
-------
qc (QuantumCircuit): the full parametrized quantum circuit.
"""
qr = qk.QuantumRegister(num_qubits, 'qr')
qc = qk.QuantumCircuit(qr)
if meas:
qr = qk.QuantumRegister(num_qubits, 'qr')
cr = qk.ClassicalRegister(num_qubits, 'cr')
qc = qk.QuantumCircuit(qr, cr)
if not reuploading:
# Define a vector containg Inputs as parameters (*not* to be optimized)
inputs = qk.circuit.ParameterVector('x', num_qubits)
# Encode classical input data
qc.compose(encoding_circuit(
inputs, num_qubits=num_qubits), inplace=True)
if insert_barriers:
qc.barrier()
# Variational circuit
qc.compose(TwoLocal(num_qubits, ['ry', 'rz'], 'cz', 'circular',
reps=reps, insert_barriers=insert_barriers,
skip_final_rotation_layer=True), inplace=True)
if insert_barriers:
qc.barrier()
# Add final measurements
if meas:
qc.measure(qr, cr)
elif reuploading:
# Define a vector containg Inputs as parameters (*not* to be optimized)
inputs = qk.circuit.ParameterVector('x', num_qubits)
# Define a vector containng variational parameters
ΞΈ = qk.circuit.ParameterVector('ΞΈ', 2 * num_qubits * reps)
# Iterate for a number of repetitions
for rep in range(reps):
# Encode classical input data
qc.compose(encoding_circuit(
inputs, num_qubits=num_qubits), inplace=True)
if insert_barriers:
qc.barrier()
# Variational circuit (does the same as TwoLocal from Qiskit)
for qubit in range(num_qubits):
qc.ry(ΞΈ[qubit + 2*num_qubits*(rep)], qubit)
qc.rz(ΞΈ[qubit + 2*num_qubits*(rep) + num_qubits], qubit)
if insert_barriers:
qc.barrier()
# Add entanglers (this code is for a circular entangler)
qc.cz(qr[-1], qr[0])
for qubit in range(num_qubits-1):
qc.cz(qr[qubit], qr[qubit+1])
if insert_barriers:
qc.barrier()
# (Optional) Add final measurements
if meas:
qc.measure(qr, cr)
return qc
################
# PyTorch Code #
################
class encoding_layer(torch.nn.Module):
def __init__(self, num_qubits=4):
super().__init__()
# Define weights for the layer
weights = torch.Tensor(num_qubits)
self.weights = torch.nn.Parameter(weights)
# Initialization strategy
torch.nn.init.uniform_(self.weights, -1, 1)
def forward(self, x):
"""Forward step, as explained above."""
if not isinstance(x, Tensor):
x = Tensor(x)
# if len(x.shape) == 1: # Not needed, may cause problems
# x = torch.unsqueeze(x, 0)
x = self.weights * x
x = torch.atan(x)
return x
class exp_val_layer(torch.nn.Module):
def __init__(self, action_space=2):
super().__init__()
# Define the weights for the layer
weights = torch.Tensor(action_space)
self.weights = torch.nn.Parameter(weights)
# <-- Initialization strategy (heuristic choice)
torch.nn.init.uniform_(self.weights, 35, 40)
# Check that these masks take the vector of probabilities to <Z_0*Z_1> and <Z_2*Z_3>
self.mask_ZZ_12 = torch.tensor(
[1., -1., -1., 1., 1., -1., -1., 1., 1., -1., -1., 1., 1., -1., -1., 1.], requires_grad=False)
self.mask_ZZ_34 = torch.tensor(
[-1., -1., -1., -1., 1., 1., 1., 1., -1., -1., -1., -1., 1., 1., 1., 1.], requires_grad=False)
def forward(self, x):
"""Forward step, as described above."""
expval_ZZ_12 = self.mask_ZZ_12 * x
expval_ZZ_34 = self.mask_ZZ_34 * x
if len(x.shape) == 1:
# , dim = 1, keepdim = True)
expval_ZZ_12 = torch.sum(expval_ZZ_12)
# , dim = 1, keepdim = True)
expval_ZZ_34 = torch.sum(expval_ZZ_34)
out = torch.cat((expval_ZZ_12.unsqueeze(0),
expval_ZZ_34.unsqueeze(0)))
else:
expval_ZZ_12 = torch.sum(expval_ZZ_12, dim=1, keepdim=True)
expval_ZZ_34 = torch.sum(expval_ZZ_34, dim=1, keepdim=True)
out = torch.cat((expval_ZZ_12, expval_ZZ_34), 1)
return self.weights * ((out + 1.) / 2.)
#################
# Training code #
#################
def epsilon_greedy_policy(state, epsilon=0):
"""Manages the transition from the *exploration* to *exploitation* phase"""
if np.random.rand() < epsilon:
return np.random.randint(n_outputs)
else:
with torch.no_grad():
Q_values = model(Tensor(state[np.newaxis])).numpy()
return np.argmax(Q_values[0])
def sample_experiences(batch_size):
"""Sample some past experiences from the replay memory"""
indices = np.random.randint(len(replay_memory), size=batch_size)
batch = [replay_memory[index] for index in indices]
states, actions, rewards, next_states, dones = [
np.array([experience[field_index] for experience in batch])
for field_index in range(5)]
return states, actions, rewards, next_states, dones
def play_one_step(env, state, epsilon):
"""Perform one action in the environment and register the state of the system"""
action = epsilon_greedy_policy(state, epsilon)
next_state, reward, done, info = env.step(action)
replay_memory.append((state, action, reward, next_state, done))
return next_state, reward, done, info
def sequential_training_step(batch_size):
"""
Actual training routine. Implements the Deep Q-Learning algorithm.
This implementation evaluates individual losses sequentially instead of using batches.
This is due to an issue in the TorchConnector, which yields vanishing gradients if it
is called with a batch of data (see https://github.com/Qiskit/qiskit-machine-learning/issues/100).
Use this training for the quantum model. If using the classical model, you can use indifferently
this implementation or the batched one below.
"""
# Sample past experiences
experiences = sample_experiences(batch_size)
states, actions, rewards, next_states, dones = experiences
# Evaluates the Target Q-values
with torch.no_grad():
next_Q_values = model(Tensor(next_states)).numpy()
max_next_Q_values = np.max(next_Q_values, axis=1)
target_Q_values = (rewards + (1 - dones) *
discount_rate * max_next_Q_values)
# Accumulate Loss (this is the only way it works. If batching data, gradients are vanishing)
loss = 0.
for j, state in enumerate(states):
single_Q_value = model(Tensor(state))
Q_value = single_Q_value[actions[j]]
loss += (target_Q_values[j] - Q_value)**2
# Evaluate the gradients and update the parameters
optimizer.zero_grad()
loss.backward()
optimizer.step()
def training_step(batch_size):
"""
This is exactly the same function as sequential_training_step, except that it
evaluates loss with batch of data, instead of using a for loop.
Can use this if training the classical model.
"""
# Sample past experiences
experiences = sample_experiences(batch_size)
states, actions, rewards, next_states, dones = experiences
# Evaluate Target Q-values
with torch.no_grad():
next_Q_values = model(Tensor(next_states)).numpy()
max_next_Q_values = np.max(next_Q_values, axis=1)
target_Q_values = (rewards +
(1 - dones) * discount_rate * max_next_Q_values)
target_Q_values = target_Q_values.reshape(-1, 1)
mask = torch.nn.functional.one_hot(Tensor(actions).long(), n_outputs)
# Evaluate the loss
all_Q_values = model(Tensor(states))
Q_values = torch.sum(all_Q_values * mask, dim=1, keepdims=True)
loss = loss_fn(Tensor(target_Q_values), Q_values)
# Evaluate the gradients and update the parameters
optimizer.zero_grad()
loss.backward()
optimizer.step()
|
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/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
import qiskit
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from tsp_qaoa import marina_solution
G=nx.Graph()
i=1
G.add_node(i,pos=(i,i))
G.add_node(2,pos=(2,2))
G.add_node(3,pos=(1,0))
G.add_edge(1,2,weight=20.5)
G.add_edge(1,3,weight=9.8)
pos=nx.get_node_attributes(G,'pos')
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
def append_zz_term(qc,q1,q2,gamma):
qc.cx(q1,q2)
qc.rz(2*gamma,q2)
qc.cx(q1,q2)
def get_cost_circuit(G,gamma):
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
for i,j in G.edges():
append_zz_term(qc,i,j,gamma)
return qc
#print(get_cost_circuit(G,0.5))
def append_x_term(qc,q1,beta):
qc.rx(2*beta,q1)
def get_mixer_operator(G,beta):
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
for n in G.nodes():
append_x_term(qc,n,beta)
return qc
#print(get_mixer_operator(G,0.5))
def get_QAOA_circuit(G,beta,gamma):
assert(len(beta)==len(gamma))
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
qc.h(range(N))
p=len(beta)
#aplicamos las p rotaciones
for i in range(p):
qc=qc.compose(get_cost_circuit(G,gamma[i]))
qc=qc.compose(get_mixer_operator(G,beta[i]))
qc.barrier(range(N))
qc.measure(range(N),range(N))
return qc
print(get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6]))
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
qc=get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6])
backend=Aer.get_backend('qasm_simulator')
job=execute(qc,backend)
result=job.result()
print(invert_counts(result.get_counts()))
def maxcut_obj(x,G):
cut=0
for i,j in G.edges():
if x[i]!=x[j]:
cut = cut-1
return cut
print(maxcut_obj("00011",G))
def compute_maxcut_energy(counts,G):
energy=0
get_counts=0
total_counts=0
for meas, meas_count in counts.items():
obj_for_meas=maxcut_obj(meas,G)
energy+=obj_for_meas*meas_count
total_counts+=meas_count
return energy/total_counts
def get_black_box_objective(G,p):
backend=Aer.get_backend('qasm_simulator')
def f(theta):
beta=theta[:p]
gamma=theta[p:]
qc=get_QAOA_circuit(G,beta,gamma)
counts=execute(qc,backend,seed_simulator=10).result().get_counts()
return compute_maxcut_energy(invert_counts(counts),G)
return f
p=5
obj=get_black_box_objective(G,p)
init_point=np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1])#([2,2,1,1,1,1,1,1,1,1])
res_sample=minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
res_sample
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
cantidad_ciudades = 4
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
pos=nx.spring_layout(G)
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
G
pos=nx.get_node_attributes(G,'weight')
pos
labels = nx.get_edge_attributes(G,'weight')
labels
def funcion_costo(multiplicador_lagrange, cantidad_ciudades, pesos, conexiones ):
N = G.number_of_nodes()
N_square = N^2
# restriccion 1
for i in range(cantidad_ciudades):
cur = sI(N_square)
for j in range(num_cities):
cur -= D(i, j)
ret += cur**2
# retorna el indice de qubit por conversion al problema
def quibit_indice(i, l, N):
return i * N + l
from qiskit.quantum_info.operators import Operator, Pauli
# Create an operator
XX = Operator(Pauli(label='XX'))
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(XX, [0, 1])
circ.measure([0,1], [0,1])
circ.draw('mpl')
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(a, [0])
#circ.measure([0,1], [0,1])
circ.draw('mpl')
a = I - ( 0.5*(I+ Z))**2
a = Operator(a)
a.is_unitary()
print(I @ Z)
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError
from qiskit import available_backends, execute, register, get_backend
from qiskit.tools.visualization import circuit_drawer
from qiskit.tools.qi.qi import state_fidelity
# Useful additional packages
import matplotlib.pyplot as plt
#matplotlib inline
import numpy as np
from math import pi
q = QuantumRegister(1)
qc = QuantumCircuit(q)
# 1. u/unitary gate
'''qc.u1(pi/2,q) #u0, u1, u2, u3
#circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
# 2. identity gate
qc.iden(q) #or u0(1)
job = execute(qc, backend='local_unitary_simulator')
print(np.round(job.result().get_data(qc)['unitary'], 3))
#Pauli Gates
# 3. X (bit-flip) gate
qc.x(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 4. Y (bit- and phase-flip) gate
qc.y(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 5. Z (phase-flip) gate
qc.z(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
#Clifford Gates
# 6. hadamard gate
qc.h(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 7. S (or sqrt(Z) phase) gate
qc.s(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 8. Sdg (or conjugate of sqrt(Z) phase) gate
qc.sdg(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
#C3 Gates
# 9. T (or sqrt(S) phase) gate
qc.t(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 10. Tdg (or sqrt(S) phase) gate
qc.tdg(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
#Standard Rotations
# 11. Rotation around X-axis
qc.rx(pi/2,q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 12. Rotation around Y-axis
qc.ry(pi/2,q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
'''
# 13. Rotation around Z-axis
qc.rz(pi/2,q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import Aer, QuantumCircuit, transpile
from qiskit.circuit.library import PhaseEstimation
qc= QuantumCircuit(3,3)
# dummy unitary circuit
unitary_circuit = QuantumCircuit(1)
unitary_circuit.h(0)
# QPE
qc.append(PhaseEstimation(2, unitary_circuit), list(range(3)))
qc.measure(list(range(3)), list(range(3)))
backend = Aer.get_backend('qasm_simulator')
qc_transpiled = transpile(qc, backend)
result = backend.run(qc, shots = 8192).result()
|
https://github.com/iamr0b0tx/qiskit_practice
|
iamr0b0tx
|
import numpy as np
# import qiskit libs
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
from qiskit.tools.jupyter import *
API_KEY = 'c6f6569ab6b6f9ec1a437d4d1187b7c7ea2ac4bd91679613e204e7bb9728efd9639af14a86f840cbb05e60b6a249e532e3168c7dbff07edc4c37de9c4bb3e0b3'
try:
provider = IBMQ.enable_account(API_KEY)
except Exception as e:
print(e)
# qiskit plot tool
from qiskit.visualization import plot_histogram
def dj_oracle(case, n, draw=False):
oracle_qc = QuantumCircuit(n+1)
if case == "balanced":
for qubit in range(n):
oracle_qc.cx(qubit, n)
if case == "constant":
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
if draw:
print(oracle_qc.draw())
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle"
return oracle_gate
dj_oracle("balanced", 4, True)
dj_oracle("constant", 4, True)
dj_oracle("constant", 4, True)
def dj_algorithm(n, case="random"):
dj_circuit = QuantumCircuit(n+1, n)
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.x(n)
dj_circuit.h(n)
if case=="random":
random_case = np.random.randint(2)
if random_case == 0:
case = "constant"
else:
case="balanced"
oracle = dj_oracle(case, n)
dj_circuit.append(oracle, range(n+1))
for i in range(n):
dj_circuit.h(i)
dj_circuit.measure(i, i)
return dj_circuit
n = 4
dj_circuit = dj_algorithm(n)
dj_circuit.draw()
# using local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
dj_circuit = dj_algorithm(n, 'constant')
results = execute(dj_circuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate
from qiskit.converters import dag_to_circuit
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
circuit = dag_to_circuit(dag)
circuit.draw('mpl')
|
https://github.com/kazawai/shor_qiskit
|
kazawai
|
from numpy import pi, random
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit_aer import AerSimulator
backend = AerSimulator()
def bell_state():
q = QuantumRegister(2)
c = ClassicalRegister(2)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.cx(q[0], q[1])
return circuit
def algorithm(value1, value2, circuit):
theta1, theta2 = 0, pi / 8
if value1 == 1:
theta1 = pi / 4
if value2 == 1:
theta2 = -theta2
circuit.ry(theta1, 0)
circuit.ry(theta2, 1)
return circuit
def quantum_strategy(x, y):
circuit = bell_state()
circuit = algorithm(x, y, circuit)
circuit.measure([0, 1], [0, 1])
result = backend.run(circuit).result()
counts = result.get_counts(circuit)
counts = dict(counts)
return int(list(counts.keys())[0][0]), int(list(counts.keys())[0][1])
def bell_inequality_game(nb_tries):
wins = 0
for _ in range(nb_tries):
x = random.randint(2)
y = random.randint(2)
a, b = quantum_strategy(x, y)
wins += x * y == (a and b)
print(f"Quantum strategy wins {wins}/{nb_tries} times")
if __name__ == "__main__":
bell_inequality_game(1000)
|
https://github.com/nahumsa/volta
|
nahumsa
|
import sys
sys.path.append('../../')
# Python imports
import numpy as np
import matplotlib.pyplot as plt
# Qiskit
from qiskit import BasicAer, Aer
from qiskit.aqua import QuantumInstance
from qiskit.aqua.components.optimizers import COBYLA, SPSA
from qiskit.circuit.library import TwoLocal
# VOLTA
from volta.vqd import VQD
from volta.utils import classical_solver
from volta.hamiltonians import BCS_hamiltonian
%load_ext autoreload
%autoreload 2
EPSILONS = [3, 3]
V = -2.
hamiltonian = BCS_hamiltonian(EPSILONS, V)
print(hamiltonian)
eigenvalues, eigenvectors = classical_solver(hamiltonian)
print(f"Eigenvalues: {eigenvalues}")
from tqdm import tqdm
def hamiltonian_varying_V(min_V, max_V, points, epsilons, n_trials):
solution_VQD = {}
energies_Classical = []
V = np.linspace(min_V, max_V, points)
backend = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'),
shots=10000)
optimizer = SPSA(maxiter=250, c1=.7, last_avg=25)
#optimizer = COBYLA()
for v in tqdm(V):
hamiltonian = BCS_hamiltonian(epsilons, v)
ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=3)
es_1 = []
es_2 = []
for _ in tqdm(range(n_trials), desc=f"V= {v}"):
# Run algorithm
Algo = VQD(hamiltonian=hamiltonian,
ansatz=ansatz,
n_excited_states=2,
beta=10.,
optimizer=optimizer,
backend=backend)
Algo.run(0)
vqd_energies = Algo.energies
es_1.append(vqd_energies[1])
es_2.append(vqd_energies[2])
es_1 = np.array(es_1)
es_2 = np.array(es_2)
solution_VQD[v] = {'mean':np.mean(es_2 - es_1), 'std':np.std(es_2 - es_1)}
classical, _ = classical_solver(hamiltonian)
energies_Classical.append(classical[2]- classical[1])
return solution_VQD, np.array(energies_Classical), V
min_V = -0.
max_V = -2.
points = 5
epsilons = [3,3]
n_trials = 50
solution_VQD, energy_classical, V = hamiltonian_varying_V(min_V, max_V, points, epsilons, n_trials)
solution_VQD
import seaborn as sns
sns.set()
mean = []
std = []
for _, sol in solution_VQD.items():
mean.append(sol['mean'])
std.append(sol['std'])
plt.errorbar(V,
np.array(mean)/2,
yerr=np.array(std)/2,
fmt='ro', ecolor='green',
label='VQD')
plt.plot(V, energy_classical/2, 'b-', label="Exact")
plt.xlabel('V')
plt.ylabel('Gap')
plt.legend()
plt.savefig('Var_V.png')
plt.show()
V
spsa_dict = {-0.0: {'mean': 2.2544600000000004, 'std': 3.6059371187529052},
-0.5: {'mean': 2.201132, 'std': 3.5924339523749076},
-1.0: {'mean': 2.3685160000000005, 'std': 3.2362400972956262},
-1.5: {'mean': 2.262069, 'std': 3.6215824729514305},
-2.0: {'mean': 2.151896, 'std': 3.285247713884601}}
cobyla_dict = {-0.0: {'mean': 0.2738039999999999, 'std': 0.5017597014348602},
-0.5: {'mean': 1.1608589999999999, 'std': 0.7228235554884747},
-1.0: {'mean': 2.0350799999999993, 'std': 0.8327042377699295},
-1.5: {'mean': 3.137112, 'std': 0.6724548732487554},
-2.0: {'mean': 4.314758, 'std': 0.5284894406097439}}
mean_spsa = []
std_spsa = []
mean_cobyla = []
std_cobyla = []
x_axis = np.array([-0. , -0.5, -1. , -1.5, -2. ])
for sol in x_axis:
mean_spsa.append(spsa_dict[sol]['mean'])
std_spsa.append(spsa_dict[sol]['std'])
mean_cobyla.append(cobyla_dict[sol]['mean'])
std_cobyla.append(cobyla_dict[sol]['std'])
from matplotlib.ticker import MaxNLocator
x_axis = np.array([-0. , -0.5, -1. , -1.5, -2. ])
energy_classical = np.array([0., 1., 2., 3., 4.])
plt.errorbar(x_axis,
np.array(mean_spsa)/2,
yerr=np.array(std_spsa)/2,
fmt='o', color='black',
ecolor='gray', elinewidth=2,
label='SPSA')
plt.errorbar(x_axis,
np.array(mean_cobyla)/2,
yerr=np.array(std_cobyla)/2,
fmt='o', color='red',
ecolor='green', elinewidth=2,
label='COBYLA')
plt.plot(V, energy_classical/2, 'b-', label="Exact")
plt.xlabel('V')
plt.ylabel('Gap')
plt.legend()
plt.savefig('Var_V_optimizers.png')
plt.show()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""The EfficientSU2 2-local circuit."""
from __future__ import annotations
import typing
from collections.abc import Callable
from numpy import pi
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library.standard_gates import RYGate, RZGate, CXGate
from .two_local import TwoLocal
if typing.TYPE_CHECKING:
import qiskit # pylint: disable=cyclic-import
class EfficientSU2(TwoLocal):
r"""The hardware efficient SU(2) 2-local circuit.
The ``EfficientSU2`` circuit consists of layers of single qubit operations spanned by SU(2)
and :math:`CX` entanglements. This is a heuristic pattern that can be used to prepare trial wave
functions for variational quantum algorithms or classification circuit for machine learning.
SU(2) stands for special unitary group of degree 2, its elements are :math:`2 \times 2`
unitary matrices with determinant 1, such as the Pauli rotation gates.
On 3 qubits and using the Pauli :math:`Y` and :math:`Z` su2_gates as single qubit gates, the
hardware efficient SU(2) circuit is represented by:
.. parsed-literal::
ββββββββββββββββββββββββ β β β ββββββββββββββββββββββββββ
β€ RY(ΞΈ[0]) ββ€ RZ(ΞΈ[3]) ββββββββββββ βββββ ... ββββ€ RY(ΞΈ[12]) ββ€ RZ(ΞΈ[15]) β
ββββββββββββ€ββββββββββββ€ β βββ΄ββ β β βββββββββββββ€βββββββββββββ€
β€ RY(ΞΈ[1]) ββ€ RZ(ΞΈ[4]) βββββββ βββ€ X ββββ ... ββββ€ RY(ΞΈ[13]) ββ€ RZ(ΞΈ[16]) β
ββββββββββββ€ββββββββββββ€ β βββ΄βββββββ β β βββββββββββββ€βββββββββββββ€
β€ RY(ΞΈ[2]) ββ€ RZ(ΞΈ[5]) βββββ€ X βββββββββ ... ββββ€ RY(ΞΈ[14]) ββ€ RZ(ΞΈ[17]) β
ββββββββββββββββββββββββ β βββββ β β ββββββββββββββββββββββββββ
See :class:`~qiskit.circuit.library.RealAmplitudes` for more detail on the possible arguments
and options such as skipping unentanglement qubits, which apply here too.
Examples:
>>> circuit = EfficientSU2(3, reps=1)
>>> print(circuit)
ββββββββββββββββββββββββ ββββββββββββββββββββββββ
q_0: β€ RY(ΞΈ[0]) ββ€ RZ(ΞΈ[3]) ββββ βββββ βββ€ RY(ΞΈ[6]) ββ€ RZ(ΞΈ[9]) ββββββββββββββ
ββββββββββββ€ββββββββββββ€βββ΄ββ β ββββββββββββββββββββββββ€βββββββββββββ
q_1: β€ RY(ΞΈ[1]) ββ€ RZ(ΞΈ[4]) ββ€ X ββββΌββββββββ βββββββ€ RY(ΞΈ[7]) ββ€ RZ(ΞΈ[10]) β
ββββββββββββ€ββββββββββββ€ββββββββ΄ββ βββ΄ββ ββββββββββββ€βββββββββββββ€
q_2: β€ RY(ΞΈ[2]) ββ€ RZ(ΞΈ[5]) βββββββ€ X βββββ€ X ββββββ€ RY(ΞΈ[8]) ββ€ RZ(ΞΈ[11]) β
ββββββββββββββββββββββββ βββββ βββββ βββββββββββββββββββββββββ
>>> ansatz = EfficientSU2(4, su2_gates=['rx', 'y'], entanglement='circular', reps=1)
>>> qc = QuantumCircuit(4) # create a circuit and append the RY variational form
>>> qc.compose(ansatz, inplace=True)
>>> qc.draw()
ββββββββββββββββββββββ ββββββββββββ βββββ
q_0: β€ RX(ΞΈ[0]) ββ€ Y ββ€ X ββββ βββ€ RX(ΞΈ[4]) βββββ€ Y ββββββββββββββββββββββ
ββββββββββββ€βββββ€βββ¬βββββ΄ββββββββββββββββββ΄ββββ΄ββββ βββββ
q_1: β€ RX(ΞΈ[1]) ββ€ Y ββββΌβββ€ X βββββββ βββββββ€ RX(ΞΈ[5]) βββββ€ Y ββββββββββ
ββββββββββββ€βββββ€ β βββββ βββ΄ββ ββββββββββββββββ΄ββββ΄βββββββββ
q_2: β€ RX(ΞΈ[2]) ββ€ Y ββββΌβββββββββββ€ X βββββββββββ βββββββ€ RX(ΞΈ[6]) ββ€ Y β
ββββββββββββ€βββββ€ β βββββ βββ΄ββ ββββββββββββ€βββββ€
q_3: β€ RX(ΞΈ[3]) ββ€ Y ββββ βββββββββββββββββββββββ€ X ββββββ€ RX(ΞΈ[7]) ββ€ Y β
βββββββββββββββββ βββββ βββββββββββββββββ
"""
def __init__(
self,
num_qubits: int | None = None,
su2_gates: str
| type
| qiskit.circuit.Instruction
| QuantumCircuit
| list[str | type | qiskit.circuit.Instruction | QuantumCircuit]
| None = None,
entanglement: str | list[list[int]] | Callable[[int], list[int]] = "reverse_linear",
reps: int = 3,
skip_unentangled_qubits: bool = False,
skip_final_rotation_layer: bool = False,
parameter_prefix: str = "ΞΈ",
insert_barriers: bool = False,
initial_state: QuantumCircuit | None = None,
name: str = "EfficientSU2",
flatten: bool | None = None,
) -> None:
"""
Args:
num_qubits: The number of qubits of the EfficientSU2 circuit.
reps: Specifies how often the structure of a rotation layer followed by an entanglement
layer is repeated.
su2_gates: The SU(2) single qubit gates to apply in single qubit gate layers.
If only one gate is provided, the same gate is applied to each qubit.
If a list of gates is provided, all gates are applied to each qubit in the provided
order.
entanglement: Specifies the entanglement structure. Can be a string ('full', 'linear'
, 'reverse_linear', 'circular' or 'sca'), a list of integer-pairs specifying the indices
of qubits entangled with one another, or a callable returning such a list provided with
the index of the entanglement layer.
Default to 'reverse_linear' entanglement.
Note that 'reverse_linear' entanglement provides the same unitary as 'full'
with fewer entangling gates.
See the Examples section of :class:`~qiskit.circuit.library.TwoLocal` for more
detail.
initial_state: A `QuantumCircuit` object to prepend to the circuit.
skip_unentangled_qubits: If True, the single qubit gates are only applied to qubits
that are entangled with another qubit. If False, the single qubit gates are applied
to each qubit in the Ansatz. Defaults to False.
skip_final_rotation_layer: If False, a rotation layer is added at the end of the
ansatz. If True, no rotation layer is added.
parameter_prefix: The parameterized gates require a parameter to be defined, for which
we use :class:`~qiskit.circuit.ParameterVector`.
insert_barriers: If True, barriers are inserted in between each layer. If False,
no barriers are inserted.
flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple
layers of gate objects. By default currently the contents of
the output circuit will be wrapped in nested objects for
cleaner visualization. However, if you're using this circuit
for anything besides visualization its **strongly** recommended
to set this flag to ``True`` to avoid a large performance
overhead for parameter binding.
"""
if su2_gates is None:
su2_gates = [RYGate, RZGate]
super().__init__(
num_qubits=num_qubits,
rotation_blocks=su2_gates,
entanglement_blocks=CXGate,
entanglement=entanglement,
reps=reps,
skip_unentangled_qubits=skip_unentangled_qubits,
skip_final_rotation_layer=skip_final_rotation_layer,
parameter_prefix=parameter_prefix,
insert_barriers=insert_barriers,
initial_state=initial_state,
name=name,
flatten=flatten,
)
@property
def parameter_bounds(self) -> list[tuple[float, float]]:
"""Return the parameter bounds.
Returns:
The parameter bounds.
"""
return self.num_parameters * [(-pi, pi)]
|
https://github.com/kaelynj/Qiskit-HubbardModel
|
kaelynj
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister
from qiskit.compiler import transpile, assemble
from qiskit.quantum_info import Operator
from qiskit.tools.monitor import job_monitor
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import random as rand
import scipy.linalg as la
provider = IBMQ.load_account()
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from matplotlib import rcParams
rcParams['text.usetex'] = True
def reverse_list(s):
temp_list = list(s)
temp_list.reverse()
return ''.join(temp_list)
#Useful tool for converting an integer to a binary bit string
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters: x (int), n (int, number of digits)"""
binry = format(x, 'b').zfill(n)
sup = list( reversed( binry[0:int(len(binry)/2)] ) )
sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) )
return format(x, 'b').zfill(n)
#return ''.join(sup)+''.join(sdn)
'''The task here is now to define a function which will either update a given circuit with a time-step
or return a single gate which contains all the necessary components of a time-step'''
#==========Set Parameters of the System=============#
dt = 0.2 #Delta t
t = 1.0 #Hopping parameter
U = 2. #On-Site repulsion
time_steps = 30
nsite = 3
trotter_slices = 5
#==========Needed Functions=============#
#Function to apply a full set of time evolution gates to a given circuit
def qc_evolve(qc, numsite, dt, t, U, num_steps):
#Compute angles for the onsite and hopping gates
# based on the model parameters t, U, and dt
theta = t*dt/(2*trotter_slices)
phi = U*dt/(trotter_slices)
numq = 2*numsite
y_hop = Operator([[np.cos(theta), 0, 0, -1j*np.sin(theta)],
[0, np.cos(theta), 1j*np.sin(theta), 0],
[0, 1j*np.sin(theta), np.cos(theta), 0],
[-1j*np.sin(theta), 0, 0, np.cos(theta)]])
x_hop = Operator([[np.cos(theta), 0, 0, 1j*np.sin(theta)],
[0, np.cos(theta), 1j*np.sin(theta), 0],
[0, 1j*np.sin(theta), np.cos(theta), 0],
[1j*np.sin(theta), 0, 0, np.cos(theta)]])
z_onsite = Operator([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, np.exp(1j*phi)]])
#Loop over each time step needed and apply onsite and hopping gates
for step in range(num_steps):
for trot in range(trotter_slices):
#Onsite Terms
for i in range(0, numsite):
qc.unitary(z_onsite, [i,i+numsite], label="Z_Onsite")
#Add barrier to separate onsite from hopping terms
qc.barrier()
#Hopping terms
for i in range(0,numsite-1):
#Spin-up chain
qc.unitary(y_hop, [i,i+1], label="YHop")
qc.unitary(x_hop, [i,i+1], label="Xhop")
#Spin-down chain
qc.unitary(y_hop, [i+numsite, i+1+numsite], label="Xhop")
qc.unitary(x_hop, [i+numsite, i+1+numsite], label="Xhop")
#Add barrier after finishing the time step
qc.barrier()
#Measure the circuit
for i in range(numq):
qc.measure(i, i)
#Function to run the circuit and store the counts for an evolution with
# num_steps number of time steps.
def sys_evolve(nsites, dt, t, U, num_steps):
numq = 2*nsites
data = np.zeros((2**numq, num_steps))
for t_step in range(0, num_steps):
#Create circuit with t_step number of steps
q = QuantumRegister(numq)
c = ClassicalRegister(numq)
qcirc = QuantumCircuit(q,c)
#Initialize circuit by setting the occupation to
# a spin up and down electron in the middle site
#=========I TURNED THIS OFF FOR A SPECIFIC CASE==============
#qcirc.x(int(nsites/2))
#qcirc.x(nsites+int(nsites/2))
# if nsites==3:
#Half-filling
# qcirc.x(1)
# qcirc.x(4)
# qcirc.x(0)
#1 electron
qcirc.x(1)
#=======USE THE REGION ABOVE TO SET YOUR INITIAL STATE=======
qcirc.barrier()
#Append circuit with Trotter steps needed
qc_evolve(qcirc, nsites, dt, t, U, t_step)
#Choose provider and backend
provider = IBMQ.get_provider()
#backend = Aer.get_backend('statevector_simulator')
backend = Aer.get_backend('qasm_simulator')
#backend = provider.get_backend('ibmq_qasm_simulator')
#backend = provider.get_backend('ibmqx4')
#backend = provider.get_backend('ibmqx2')
#backend = provider.get_backend('ibmq_16_melbourne')
shots = 8192
max_credits = 10 #Max number of credits to spend on execution
job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(job_exp)
result = job_exp.result()
counts = result.get_counts(qcirc)
print(result.get_counts(qcirc))
print("Job: ",t_step+1, " of ", time_steps," complete.")
#Store results in data array and normalize them
for i in range(2**numq):
if counts.get(get_bin(i,numq)) is None:
dat = 0
else:
dat = counts.get(get_bin(i,numq))
data[i,t_step] = dat/shots
return data
#Run simulation
run_results = sys_evolve(nsite, dt, t, U, time_steps)
#Process and plot data
'''The procedure here is, for each fermionic mode, add the probability of every state containing
that mode (at a given time step), and renormalize the data based on the total occupation of each mode.
Afterwards, plot the data as a function of time step for each mode.'''
proc_data = np.zeros((2*nsite, time_steps))
timesq = np.arange(0.,time_steps*dt, dt)
#Sum over time steps
for t in range(time_steps):
#Sum over all possible states of computer
for i in range(2**(2*nsite)):
#num = get_bin(i, 2*nsite)
num = ''.join( list( reversed(get_bin(i,2*nsite)) ) )
#For each state, check which mode(s) it contains and add them
for mode in range(len(num)):
if num[mode]=='1':
proc_data[mode,t] += run_results[i,t]
#Renormalize these sums so that the total occupation of the modes is 1
norm = 0.0
for mode in range(len(num)):
norm += proc_data[mode,t]
proc_data[:,t] = proc_data[:,t] / norm
'''
At this point, proc_data is a 2d array containing the occupation
of each mode, for every time step
'''
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
for i in range(nsite):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(timesq, proc_data[i,:], marker="^", color=str(colors[i]), label=strup)
ax2.plot(timesq, proc_data[i+nsite,:], marker="v", color=str(colors[i]), label=strdwn)
#ax2.set_ylim(0, 0.55)
ax2.set_xlim(0, time_steps*dt+dt/2.)
#ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2))
#ax2.set_yticks(np.arange(0,0.55, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax2.legend(fontsize=20)
#Plot the raw data as a colormap
xticks = np.arange(2**(nsite*2))
xlabels=[]
print("Time Steps: ",time_steps, " Step Size: ",dt)
for i in range(2**(nsite*2)):
xlabels.append(get_bin(i,6))
fig, ax = plt.subplots(figsize=(10,20))
c = ax.pcolor(run_results, cmap='binary')
ax.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
plt.yticks(xticks, xlabels, size=18)
ax.set_xlabel('Time Step', fontsize=22)
ax.set_ylabel('State', fontsize=26)
plt.show()
#Try by constructing the matrix and finding the eigenvalues
N = 3
Nup = 2
Ndwn = N - Nup
t = 1.0
U = 2.
#Check if two states are different by a single hop
def hop(psii, psij):
#Check spin down
hopp = 0
if psii[0]==psij[0]:
#Create array of indices with nonzero values
indi = np.nonzero(psii[1])[0]
indj = np.nonzero(psij[1])[0]
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -t
return hopp
#Check spin up
if psii[1]==psij[1]:
indi = np.nonzero(psii[0])[0]
indj = np.nonzero(psij[0])[0]
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -t
return hopp
return hopp
#On-site terms
def repel(l,state):
if state[0][l]==1 and state[1][l]==1:
return state
else:
return []
#States for 3 electrons with net spin up
'''
states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]],
[[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]],
[[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ]
#States for 2 electrons in singlet state
'''
states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]],
[[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]],
[[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ]
#'''
#States for a single electron
#states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ]
#'''
H = np.zeros((len(states),len(states)) )
#Construct Hamiltonian matrix
for i in range(len(states)):
psi_i = states[i]
for j in range(len(states)):
psi_j = states[j]
if j==i:
for l in range(0,N):
if psi_i == repel(l,psi_j):
H[i,j] = U
break
else:
H[i,j] = hop(psi_i, psi_j)
print(H)
results = la.eig(H)
print()
for i in range(len(results[0])):
print('Eigenvalue: ',results[0][i])
print('Eigenvector: \n',results[1][i])
print()
dens_ops = []
eigs = []
for vec in results[1]:
dens_ops.append(np.outer(results[1][i],results[1][i]))
eigs.append(results[0][i])
print(dens_ops)
dt = 0.1
tsteps = 50
times = np.arange(0., tsteps*dt, dt)
t_op = la.expm(-1j*H*dt)
#print(np.subtract(np.identity(len(H)), dt*H*1j))
#print(t_op)
wfk = [0., 1., 0., 0., .0, 0., 0., 0., 0.] #Half-filling initial state
#wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state
#wfk = [0., 1., 0.] #1 electron initial state
evolve = np.zeros([tsteps, len(wfk)])
mode_evolve = np.zeros([tsteps, 6])
evolve[0] = wfk
#Figure out how to generalize this later
#'''
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2.
mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2.
mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2.
'''
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3.
mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3.
'''
print(mode_evolve[0])
#Define density matrices
for t in range(1, tsteps):
#t_op = la.expm(-1j*H*t)
wfk = np.dot(t_op, wfk)
evolve[t] = np.multiply(np.conj(wfk), wfk)
norm = np.sum(evolve[t])
#print(evolve[t])
#Store data in modes rather than basis defined in 'states' variable
#''' #Procedure for two electrons
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2)
mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2)
mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2)
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2)
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2)
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2)
''' #Procedure for half-filling
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3.
mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3.
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3.
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3.
#'''
print(mode_evolve[t])
#print(np.linalg.norm(evolve[t]))
#print(len(evolve[:,0]) )
#print(len(times))
#print(evolve[:,0])
#print(min(evolve[:,0]))
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
sit1 = "Exact Site "+str(1)+r'$\uparrow$'
sit2 = "Exact Site "+str(2)+r'$\uparrow$'
sit3 = "Exact Site "+str(3)+r'$\uparrow$'
#ax2.plot(times, evolve[:,0], linestyle='--', color=colors[0], linewidth=2.5, label=sit1)
#ax2.plot(times, evolve[:,1], linestyle='--', color=str(colors[1]), linewidth=2.5, label=sit2)
#ax2.plot(times, evolve[:,2], linestyle='--', color=str(colors[2]), linewidth=2., label=sit3)
#ax2.plot(times, np.zeros(len(times)))
for i in range(nsite):
#Create string label
strupq = "Quantum Site "+str(i+1)+r'$\uparrow$'
strdwnq = "Quantum Site "+str(i+1)+r'$\downarrow$'
strup = "Numerical Site "+str(i+1)+r'$\uparrow$'
strdwn = "Numerical Site "+str(i+1)+r'$\downarrow$'
#ax2.plot(timesq, proc_data[i,:], marker="*", color=str(colors[i]), markersize=5, label=strupq)
#ax2.plot(timesq, proc_data[i+nsite,:], marker="v", color=str(colors[i]), markersize=5, label=strdwnq)
ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
#ax2.plot(times, evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
#ax2.plot(times, evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
ax2.set_ylim(0, .5)
ax2.set_xlim(0, tsteps*dt+dt/2.)
ax2.set_xticks(np.arange(0,tsteps*dt+dt, 2*dt))
ax2.set_yticks(np.arange(0,0.5, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 2 Electrons in 3 Site Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax2.legend(fontsize=20)
|
https://github.com/Quantum-Ducks/QuBayes
|
Quantum-Ducks
|
from itertools import product
import numpy as np
from network_setup_temp import *
def generate_cond_keys(child, ps):
##############################################
#THIS FUNCTION WILL GENERATE A LIST OF STRINGS TO USE AS KEYS FOR CONDITIONAL PROBABILITIES
### INPUT ###
# s_0 int number of states of the child node
# s_i list number of states for each parent node, from most to least significant
### OUTPUT ###
# list of strings to use as keys for conditional probabilities (included commas in case there is ever an >11-state node!)
##############################################
cname = child.name
cstates = child.states
ranges = [[child.name], child.states.keys()]
for p in ps:
ranges.append([str(p.name)])
ranges.append(p.states.keys())
enumed = product(*ranges)
add = [",","_"]
cond_keys = []
for enum in enumed:
suff = 0
enum = list(enum)
parent_str = ''
for i in range(2,len(enum)-1):
suff = (suff + 1)%2
parent_str += str(enum[i]) + add[suff]
parent_str += str(enum[len(enum)-1])
cond_keys.append("%s_%s|%s"%(str(enum[0]), str(enum[1]), parent_str))
return cond_keys
def generate_parent_str(ps):
##############################################
#THIS FUNCTION WILL GENERATE A LIST OF STRINGS TO USE AS KEYS FOR CONDITIONAL PROBABILITIES
### INPUT ###
# s_0 int number of states of the child node
# s_i list number of states for each parent node, from most to least significant
### OUTPUT ###
# list of strings to use as keys for conditional probabilities (included commas in case there is ever an >11-state node!)
##############################################
ranges = []
for p in ps:
ranges.append([str(p.name)])
ranges.append(p.states.keys())
enumed = product(*ranges)
add = [",","_"]
cond_keys = []
for enum in enumed:
suff = 0
enum = list(enum)
parent_str = ''
for i in range(len(enum)-1):
suff = (suff + 1)%2
parent_str += str(enum[i]) + add[suff]
parent_str += str(enum[len(enum)-1])
cond_keys.append("%s"%(parent_str))
return cond_keys
class Node:
# A single variable in the Bayesian network
def __init__(self, name, data, states=None, parents=[]):
### INPUTS ###
# name: str name of variable
# data: array state data for the node
# states: dict keys are state names, values are the int each takes on in the data
# parents: list strings of names of parent nodes to this node
##############
if states == None:
states = {}
for i in range(max(data) + 1):
states.update({str(i) : i})
self.name = name
self.data = data
self.states = states
self.parents = parents
C,B,A = get_lesser_model_nodes()
generate_parent_str([C,B,A])
|
https://github.com/unif2/Quantum-Computing-Mentorship-Task-4-Code
|
unif2
|
import numpy as np
from numpy import kron
import qiskit as qk
def decomposition(H):
"""Decompose any 4x4 Hermitian matrix into a sum of tensor products of two Pauli matrices
"""
identity = np.array([[1, 0],[ 0, 1]], dtype=np.complex128)
x = np.array([[0, 1], [ 1, 0]], dtype=np.complex128)
y = np.array([[0, -1j],[1j, 0]], dtype=np.complex128)
z = np.array([[1, 0], [0, -1]], dtype=np.complex128)
S = [identity, x, y, z]
labels = ['I', 'sigma_x', 'sigma_y', 'sigma_z']
d = {'00': 'I product I', '01': 'I product sigma_x', '02': 'I product sigma_y', '03': 'I product sigma_z',
'10': 'sigma_x product I', '11': 'sigma_x product sigma_x', '12': 'sigma_x product sigma_y',
'13': 'sigma_x product sigma_z', '20': 'sigma_y product I', '21': 'sigma_y product sigma_x',
'22': 'sigma_y product sigma_y', '23': 'sigma_y product sigma_z', '30': 'sigma_z product I',
'31': 'sigma_z product sigma_x', '32': 'sigma_z product sigma_y', '33': 'sigma_z product sigma_z'}
for i in range(4):
for j in range(4):
a_ij = 0.25 * np.dot(kron(S[i], S[j]), H).trace()
if a_ij != 0.0:
print(str(a_ij) + ' * ' + d[str(i)+str(j)])
H = np.array([[0,0,0,0],[0,-1,1,0],[0,1,-1,0],[0,0,0,0]])
decomposition(H)
def prepare_state(theta, n=3):
"""
Prepare three 2-qubit states with 3 associated quantum registers, 3 associated classical registers,
and 3 quantum circuits. We will prepare the state with the ansatz mentioned in the notes in which we act on
the first qubit with the Hadamard operator, then with the R_z operator, then we act on the 2-qubit state
with the CNOT gate, and then on the second qubit in each terms of the superposition with the sigma_x operator.
After that, we will take the first circuit and act on each qubit with the R_y(pi/2) operator, and take the second
circuit and act on each qubit with the R_x(-pi/2) operator as explained in the notes. We do this so that those
qubits will be in the basis of eigenvectors of sigma_x and sigma_y as explained in the notes. We can measure
the qubits in the other circuit as-is because we need the expectation value of sigma_z and the qubits are already
in the computational basis.
"""
qr0 = qk.QuantumRegister(2)
cr0 = qk.ClassicalRegister(2)
qc0 = qk.QuantumCircuit(qr0,cr0)
qr1 = qk.QuantumRegister(2)
cr1 = qk.ClassicalRegister(2)
qc1 = qk.QuantumCircuit(qr1,cr1)
qr2 = qk.QuantumRegister(2)
cr2 = qk.ClassicalRegister(2)
qc2 = qk.QuantumCircuit(qr2,cr2)
qregisters = [qr0,qr1,qr2]
cregisters = [cr0,cr1,cr2]
qcircuits = [qc0,qc1,qc2]
for i in range(n):
qcircuits[i].h(qregisters[i][0])
for i in range(n):
qcircuits[i].rz(theta, qregisters[i][0])
for i in range(n):
qcircuits[i].cx(qregisters[i][0], qregisters[i][1])
for i in range(n):
qcircuits[i].x(qregisters[i][1])
qcircuits[0].ry((np.pi)/2, qregisters[0][0])
qcircuits[0].ry((np.pi)/2, qregisters[0][1])
qcircuits[1].rx(-(np.pi)/2, qregisters[1][0])
qcircuits[1].rx(-(np.pi)/2, qregisters[1][1])
return qregisters, cregisters, qcircuits
qregisters, cregisters, qcircuits = prepare_state(np.pi, n=3)
qcircuits[0].draw(output='mpl')
qcircuits[1].draw(output='mpl')
qcircuits[2].draw(output='mpl')
def expectation(qcircuits, cregisters, qregisters, n_shots, n=3):
"""
For each circuit, execute and measure it using the classical simulator 5000 times as explained above. Multiply
each of the three expectation values by 0.5, add them up, and subtract -0.5. Return the result.
"""
expect = -0.5
for i in range(n):
qcircuits[i].measure(qregisters[i],cregisters[i])
qk.Aer.backends()
sim = qk.Aer.get_backend('qasm_simulator')
res = qk.execute(qcircuits[i], sim, shots=n_shots).result()
counts = res.get_counts()
sum = 0
for k,v in counts.items():
if k=='01' or k=='10':
sum += (-1)*v/n_shots
elif k=='00' or k=='11':
sum += v/n_shots
sum = 0.5*sum
expect += sum
return expect
# Consider 100 values of theta, between 0 and Pi. This theta is the one used in state preparation.
thetas = np.linspace(0, np.pi, 100)
# For each theta, store the resulting expectation value in results
results = []
# For each theta, find the expectation value
for theta in thetas:
qregisters, cregisters, qcircuits = prepare_state(theta, n=3)
expect = expectation(qcircuits, cregisters, qregisters, 5000, n=3)
results.append(expect)
# Sort the results in ascending order. The first one is your minimum eigenvalue.
results.sort()
print("The minimum eigenvalue is: {}.".format(results[0]))
from qiskit import IBMQ
#IBMQ.delete_account()
IBMQ.save_account('my IBM token', overwrite=True)
IBMQ.load_account()
provider = IBMQ.get_provider()
procs=provider.backends(operational=True, simulator=False)
from qiskit.tools.jupyter import *
%qiskit_backend_overview
from qiskit.tools import monitor
backend = qk.providers.ibmq.least_busy([p for p in procs if len(p.properties().qubits) >= 2])
from qiskit.tools.monitor import backend_overview, backend_monitor
backend_monitor(backend)
def q_expectation(qcircuits, cregisters, qregisters, n_shots, n=3):
"""
For each circuit, execute and measure it using the classical simulator 5000 times as explained above. Multiply
each of the three expectation values by 0.5, add them up, and subtract -0.5. Return the result.
"""
expect = -0.5
for i in range(n):
qcircuits[i].measure(qregisters[i],cregisters[i])
qk.Aer.backends()
sim = qk.Aer.get_backend('qasm_simulator')
res = qk.execute(qcircuits[i], backend=backend, shots=n_shots).result()
#mon = monitor.job_monitor(res)
counts = res.get_counts()
sum = 0
for k,v in counts.items():
if k=='01' or k=='10':
sum += (-1)*v/n_shots
elif k=='00' or k=='11':
sum += v/n_shots
sum = 0.5*sum
expect += sum
return expect
# Consider 10 values of theta, between 0 and Pi. This theta is the one used in state preparation.
thetas = np.linspace(0, np.pi, 10)
# Use n_shots = 100
results = []
# For each theta, find the expectation value
for theta in thetas:
qregisters, cregisters, qcircuits = prepare_state(theta, n=3)
expect = q_expectation(qcircuits, cregisters, qregisters, 100, n=3)
results.append(expect)
# Sort the results in ascending order. The first one is your minimum eigenvalue.
results.sort()
print("The minimum eigenvalue is: {}.".format(results[0]))
# Use n_shots = 1000
results = []
# For each theta, find the expectation value
for theta in thetas:
qregisters, cregisters, qcircuits = prepare_state(theta, n=3)
expect = q_expectation(qcircuits, cregisters, qregisters, 1000, n=3)
results.append(expect)
# Sort the results in ascending order. The first one is your minimum eigenvalue.
results.sort()
print("The minimum eigenvalue is: {}.".format(results[0]))
# Use n_shots = 5000
results = []
# For each theta, find the expectation value
for theta in thetas:
qregisters, cregisters, qcircuits = prepare_state(theta, n=3)
expect = q_expectation(qcircuits, cregisters, qregisters, 5000, n=3)
results.append(expect)
# Sort the results in ascending order. The first one is your minimum eigenvalue.
results.sort()
print("The minimum eigenvalue is: {}.".format(results[0]))
# Use n_shots = 8192 = max allowed
results = []
thetas = [np.pi]
# For each theta, find the expectation value
for theta in thetas:
qregisters, cregisters, qcircuits = prepare_state(theta, n=3)
expect = q_expectation(qcircuits, cregisters, qregisters, 8192, n=3)
results.append(expect)
# Sort the results in ascending order. The first one is your minimum eigenvalue.
results.sort()
print("The minimum eigenvalue is: {}.".format(results[0]))
def decomposition(H):
"""Decompose any 4x4 Hermitian matrix into a sum of tensor products of two Pauli matrices
"""
A_ij = []
identity = np.array([[1, 0],[ 0, 1]], dtype=np.complex128)
x = np.array([[0, 1], [ 1, 0]], dtype=np.complex128)
y = np.array([[0, -1j],[1j, 0]], dtype=np.complex128)
z = np.array([[1, 0], [0, -1]], dtype=np.complex128)
S = [identity, x, y, z]
labels = ['I', 'sigma_x', 'sigma_y', 'sigma_z']
d = {'00': 'I product I', '01': 'I product sigma_x', '02': 'I product sigma_y', '03': 'I product sigma_z',
'10': 'sigma_x product I', '11': 'sigma_x product sigma_x', '12': 'sigma_x product sigma_y', '13': 'sigma_x product sigma_z',
'20': 'sigma_y product I', '21': 'sigma_y product sigma_x', '22': 'sigma_y product sigma_y', '23': 'sigma_y product sigma_z',
'30': 'sigma_z product I', '31': 'sigma_z product sigma_x', '32': 'sigma_z product sigma_y', '33': 'sigma_z product sigma_z'}
for i in range(4):
for j in range(4):
a_ij = 0.25 * np.dot(kron(S[i], S[j]), H).trace()
A_ij.append(a_ij)
if a_ij != 0.0:
print(str(a_ij) + ' * ' + d[str(i)+str(j)])
return np.asarray(A_ij).reshape(4,4)
def prepare_state2(A, theta):
qregisters = []
cregisters = []
qcircuits = []
identity = np.array([[1, 0],[ 0, 1]], dtype=np.complex128)
x = np.array([[0, 1], [ 1, 0]], dtype=np.complex128)
y = np.array([[0, -1j],[1j, 0]], dtype=np.complex128)
z = np.array([[1, 0], [0, -1]], dtype=np.complex128)
d = {}
for i in range(4):
for j in range(4):
if A[i,j] != 0:
if i !=0 and j!=0:
qr = qk.QuantumRegister(2)
cr = qk.ClassicalRegister(2)
qc = qk.QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.rz(theta, qr[0])
qc.cx(qr[0], qr[1])
qc.x(qr[1])
if i==1:
qc.ry((np.pi)/2, qr[0])
if i==2:
qc.rx(-(np.pi)/2, qr[0])
if j==1:
qc.ry((np.pi)/2, qr[1])
if j==2:
qc.rx(-(np.pi)/2, qr[1])
qregisters.append(qr)
cregisters.append(cr)
qcircuits.append(qc)
d[(i,j)] = [qregisters, cregisters, qcircuits]
if i == 0 and j != 0:
qr = qk.QuantumRegister(2)
cr = qk.ClassicalRegister(2)
qc = qk.QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.rz(theta, qr[0])
qc.cx(qr[0], qr[1])
qc.x(qr[1])
if j==1:
qc.ry((np.pi)/2, qr[1])
if j==2:
qc.rx(-(np.pi)/2, qr[1])
qregisters.append(qr)
cregisters.append(cr)
qcircuits.append(qc)
d[(i,j)] = [qregisters, cregisters, qcircuits]
if i != 0 and j == 0:
qr = qk.QuantumRegister(2)
cr = qk.ClassicalRegister(2)
qc = qk.QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.rz(theta, qr[0])
qc.cx(qr[0], qr[1])
qc.x(qr[1])
if i==1:
qc.ry((np.pi)/2, qr[0])
if i==2:
qc.rx(-(np.pi)/2, qr[0])
qregisters.append(qr)
cregisters.append(cr)
qcircuits.append(qc)
d[(i,j)] = [qregisters, cregisters, qcircuits]
return d, A
def expectation2(d, A, n_shots):
"""
For each circuit, execute and measure it using the classical simulator 5000 times as explained above.
Return the result.
"""
expect = A[0,0]
qk.Aer.backends()
sim = qk.Aer.get_backend('qasm_simulator')
for k,v in d.items():
for i in range(len(v[2])):
v[2][i].measure(v[0][i],v[1][i])
res = qk.execute(v[2][i], sim, shots=n_shots).result()
counts = res.get_counts()
sum = 0
for m,n in counts.items():
if m=='01' or m=='10':
sum += (-1)*n/n_shots
elif m=='00' or m=='11':
sum += n/n_shots
sum = A[k[0],k[1]]*sum
expect += sum
return expect
thetas = np.linspace(0, np.pi, 100)
H = np.array([[0,0,0,0],[0,-1,1,0],[0,1,-1,0],[0,0,0,0]])
A = decomposition(H)
# For each theta, store the resulting expectation value in results
results = []
# For each theta, find the expectation value
for theta in thetas:
d, A = prepare_state2(A, theta)
expect = expectation2(d, A, 5000)
results.append(expect)
# Sort the results in ascending order. The first one is your minimum eigenvalue.
results.sort()
print("The minimum eigenvalue is: {}.".format(results[0]))
# -5??!! Maybe I missed something in my logic. Will continue to look into this. :-)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.