repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
---|---|---|
https://github.com/intrinsicvardhan/QuantumComputingAlgos
|
intrinsicvardhan
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from numpy.random import randint
import numpy as np
from qiskit_aer import AerSimulator
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 = AerSimulator()
job = aer_sim.run(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 = AerSimulator()
job = aer_sim.run(qc)
plot_histogram(job.result().get_counts())
np.random.seed(seed=0)
n = 100
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
print(alice_bits)
np.random.seed(seed=0)
n = 100
## Step 1
#Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
print(alice_bases)
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
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
print('bit = %i' % alice_bits[0])
print('basis = %i' % alice_bases[0])
message[0].draw()
print('bit = %i' % alice_bits[4])
print('basis = %i' % alice_bases[4])
message[4].draw()
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
print(bob_bases)
def measure_message(message, bases):
backend = AerSimulator()
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 = AerSimulator()
result = aer_sim.run(message[q], shots=1, memory=True).result()
measured_bit = int(result.get_memory()[0])
measurements.append(measured_bit)
return measurements
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
message[0].draw()
message[6].draw()
print(bob_results)
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
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
print(alice_key)
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
print(bob_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
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
## Step 5
sample_size = 15
bit_selection = randint(n, size=sample_size)
bob_sample = sample_bits(bob_key, bit_selection)
print(" bob_sample = " + str(bob_sample))
alice_sample = sample_bits(alice_key, bit_selection)
print("alice_sample = "+ str(alice_sample))
bob_sample == alice_sample
print(bob_key)
print(alice_key)
print("key length = %i" % len(alice_key))
np.random.seed(seed=3)
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
print(alice_bits)
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
print(alice_bases)
message[0].draw()
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
print(intercepted_message)
message[0].draw()
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
message[0].draw()
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = 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)
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = 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)
## Step 5
sample_size = 15
bit_selection = randint(n, size=sample_size)
bob_sample = sample_bits(bob_key, bit_selection)
print(" bob_sample = " + str(bob_sample))
alice_sample = sample_bits(alice_key, bit_selection)
print("alice_sample = "+ str(alice_sample))
bob_sample == alice_sample
n = 100
# Step 1
alice_bits = randint(2, size=n)
alice_bases = randint(2, size=n)
# Step 2
message = encode_message(alice_bits, alice_bases)
# Interception!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
# Step 3
bob_bases = 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)
# Step 5
sample_size = 15 # Change this to something lower and see if
# Eve can intercept the message without Alice
# and Bob finding out
bit_selection = randint(n, size=sample_size)
bob_sample = sample_bits(bob_key, bit_selection)
alice_sample = sample_bits(alice_key, bit_selection)
if bob_sample != alice_sample:
print("Eve's interference was detected.")
else:
print("Eve went undetected!")
# import qiskit.tools.jupyter
# %qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
ghz.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
# Create a circuit with a register of three qubits
circ = QuantumCircuit(3)
# H gate on qubit 0, putting this qubit in a superposition of |0> + |1>.
circ.h(0)
# A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state.
circ.cx(0, 1)
# CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state.
circ.cx(0, 2)
# Draw the circuit
circ.draw('mpl')
|
https://github.com/arthurfaria/Qiskit_certificate_prep
|
arthurfaria
|
# General tools
import numpy as np
import matplotlib.pyplot as plt
import math
# Importing standard Qiskit libraries
from qiskit import execute,QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
QuantumCircuit(4, 4)
qc = QuantumCircuit(1)
qc.ry(3 * math.pi/4, 0)
# draw the circuit
qc.draw()
# et's plot the histogram and see the probability :)
qc.measure_all()
qasm_sim = Aer.get_backend('qasm_simulator') #this time we call the qasm simulator
result = execute(qc, qasm_sim).result() # NOTICE: we can skip some steps by doing .result() directly, we could go further!
counts = result.get_counts() #this time, we are not getting the state, but the counts!
plot_histogram(counts) #a new plotting method! this works for counts obviously!
inp_reg = QuantumRegister(2, name='inp')
ancilla = QuantumRegister(1, name='anc')
qc = QuantumCircuit(inp_reg, ancilla)
# Insert code here
qc.h(inp_reg[0:2])
qc.x(ancilla[0])
qc.draw()
bell = QuantumCircuit(2)
bell.h(0)
bell.x(1)
bell.cx(0, 1)
bell.draw()
qc = QuantumCircuit(1,1)
# Insert code fragment here
qc.ry(math.pi / 2,0)
simulator = Aer.get_backend('statevector_simulator')
job = execute(qc, simulator)
result = job.result()
outputstate = result.get_statevector(qc)
plot_bloch_multivector(outputstate)
from qiskit import QuantumCircuit, Aer, execute
from math import sqrt
qc = QuantumCircuit(2)
# Insert fragment here
v = [1/sqrt(2), 0, 0, 1/sqrt(2)]
qc.initialize(v,[0,1])
simulator = Aer.get_backend('statevector_simulator')
result = execute(qc, simulator).result()
statevector = result.get_statevector()
print(statevector)
qc = QuantumCircuit(3,3)
qc.barrier() # B. qc.barrier([0,1,2])
qc.draw()
qc = QuantumCircuit(1,1)
qc.h(0)
qc.s(0)
qc.h(0)
qc.measure(0,0)
qc.draw()
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.barrier(0)
qc.cx(0,1)
qc.barrier([0,1])
qc.draw()
qc.depth()
# Use Aer's qasm_simulator
qasm_sim = Aer.get_backend('qasm_simulator')
#use a coupling map that connects three qubits linearly
couple_map = [[0, 1], [1, 2]]
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job = execute(qc, backend=qasm_sim, shots=1024, coupling_map=couple_map)
from qiskit import QuantumCircuit, execute, BasicAer
backend = BasicAer.get_backend('qasm_simulator')
qc = QuantumCircuit(3)
# insert code here
execute(qc, backend, shots=1024, coupling_map=[[0,1], [1,2]])
qc = QuantumCircuit(2, 2)
qc.x(0)
qc.measure([0,1], [0,1])
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, simulator, shots=1000).result()
counts = result.get_counts(qc)
print(counts)
|
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.
"""
Example showing how to draw a quantum circuit using Qiskit.
"""
from qiskit import QuantumCircuit
def build_bell_circuit():
"""Returns a circuit putting 2 qubits in the Bell state."""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
return qc
# Create the circuit
bell_circuit = build_bell_circuit()
# Use the internal .draw() to print the circuit
print(bell_circuit)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=unused-import
"""
A convenient way to track reusable subschedules by name and qubit.
This can be used for scheduling circuits with custom definitions, for instance::
inst_map = InstructionScheduleMap()
inst_map.add('new_inst', 0, qubit_0_new_inst_schedule)
sched = schedule(quantum_circuit, backend, inst_map)
An instance of this class is instantiated by Pulse-enabled backends and populated with defaults
(if available)::
inst_map = backend.defaults().instruction_schedule_map
"""
from __future__ import annotations
import functools
import warnings
from collections import defaultdict
from collections.abc import Iterable, Callable
from qiskit import circuit
from qiskit.circuit.parameterexpression import ParameterExpression
from qiskit.pulse.calibration_entries import (
CalibrationEntry,
ScheduleDef,
CallableDef,
# for backward compatibility
PulseQobjDef,
CalibrationPublisher,
)
from qiskit.pulse.exceptions import PulseError
from qiskit.pulse.schedule import Schedule, ScheduleBlock
class InstructionScheduleMap:
"""Mapping from :py:class:`~qiskit.circuit.QuantumCircuit`
:py:class:`qiskit.circuit.Instruction` names and qubits to
:py:class:`~qiskit.pulse.Schedule` s. In particular, the mapping is formatted as type::
Dict[str, Dict[Tuple[int], Schedule]]
where the first key is the name of a circuit instruction (e.g. ``'u1'``, ``'measure'``), the
second key is a tuple of qubit indices, and the final value is a Schedule implementing the
requested instruction.
These can usually be seen as gate calibrations.
"""
def __init__(self):
"""Initialize a circuit instruction to schedule mapper instance."""
# The processed and reformatted circuit instruction definitions
# Do not use lambda function for nested defaultdict, i.e. lambda: defaultdict(CalibrationEntry).
# This crashes qiskit parallel. Note that parallel framework passes args as
# pickled object, however lambda function cannot be pickled.
self._map: dict[str | circuit.instruction.Instruction, dict[tuple, CalibrationEntry]] = (
defaultdict(functools.partial(defaultdict, CalibrationEntry))
)
# A backwards mapping from qubit to supported instructions
self._qubit_instructions: dict[tuple[int, ...], set] = defaultdict(set)
def has_custom_gate(self) -> bool:
"""Return ``True`` if the map has user provided instruction."""
for qubit_inst in self._map.values():
for entry in qubit_inst.values():
if entry.user_provided:
return True
return False
@property
def instructions(self) -> list[str]:
"""Return all instructions which have definitions.
By default, these are typically the basis gates along with other instructions such as
measure and reset.
Returns:
The names of all the circuit instructions which have Schedule definitions in this.
"""
return list(self._map.keys())
def qubits_with_instruction(
self, instruction: str | circuit.instruction.Instruction
) -> list[int | tuple[int, ...]]:
"""Return a list of the qubits for which the given instruction is defined. Single qubit
instructions return a flat list, and multiqubit instructions return a list of ordered
tuples.
Args:
instruction: The name of the circuit instruction.
Returns:
Qubit indices which have the given instruction defined. This is a list of tuples if the
instruction has an arity greater than 1, or a flat list of ints otherwise.
Raises:
PulseError: If the instruction is not found.
"""
instruction = _get_instruction_string(instruction)
if instruction not in self._map:
return []
return [
qubits[0] if len(qubits) == 1 else qubits
for qubits in sorted(self._map[instruction].keys())
]
def qubit_instructions(self, qubits: int | Iterable[int]) -> list[str]:
"""Return a list of the instruction names that are defined by the backend for the given
qubit or qubits.
Args:
qubits: A qubit index, or a list or tuple of indices.
Returns:
All the instructions which are defined on the qubits.
For 1 qubit, all the 1Q instructions defined. For multiple qubits, all the instructions
which apply to that whole set of qubits (e.g. ``qubits=[0, 1]`` may return ``['cx']``).
"""
if _to_tuple(qubits) in self._qubit_instructions:
return list(self._qubit_instructions[_to_tuple(qubits)])
return []
def has(
self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int]
) -> bool:
"""Is the instruction defined for the given qubits?
Args:
instruction: The instruction for which to look.
qubits: The specific qubits for the instruction.
Returns:
True iff the instruction is defined.
"""
instruction = _get_instruction_string(instruction)
return instruction in self._map and _to_tuple(qubits) in self._map[instruction]
def assert_has(
self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int]
) -> None:
"""Error if the given instruction is not defined.
Args:
instruction: The instruction for which to look.
qubits: The specific qubits for the instruction.
Raises:
PulseError: If the instruction is not defined on the qubits.
"""
instruction = _get_instruction_string(instruction)
if not self.has(instruction, _to_tuple(qubits)):
if instruction in self._map:
raise PulseError(
"Operation '{inst}' exists, but is only defined for qubits "
"{qubits}.".format(
inst=instruction, qubits=self.qubits_with_instruction(instruction)
)
)
raise PulseError(f"Operation '{instruction}' is not defined for this system.")
def get(
self,
instruction: str | circuit.instruction.Instruction,
qubits: int | Iterable[int],
*params: complex | ParameterExpression,
**kwparams: complex | ParameterExpression,
) -> Schedule | ScheduleBlock:
"""Return the defined :py:class:`~qiskit.pulse.Schedule` or
:py:class:`~qiskit.pulse.ScheduleBlock` for the given instruction on the given qubits.
If all keys are not specified this method returns schedule with unbound parameters.
Args:
instruction: Name of the instruction or the instruction itself.
qubits: The qubits for the instruction.
*params: Command parameters for generating the output schedule.
**kwparams: Keyworded command parameters for generating the schedule.
Returns:
The Schedule defined for the input.
"""
return self._get_calibration_entry(instruction, qubits).get_schedule(*params, **kwparams)
def _get_calibration_entry(
self,
instruction: str | circuit.instruction.Instruction,
qubits: int | Iterable[int],
) -> CalibrationEntry:
"""Return the :class:`.CalibrationEntry` without generating schedule.
When calibration entry is un-parsed Pulse Qobj, this returns calibration
without parsing it. :meth:`CalibrationEntry.get_schedule` method
must be manually called with assigned parameters to get corresponding pulse schedule.
This method is expected be directly used internally by the V2 backend converter
for faster loading of the backend calibrations.
Args:
instruction: Name of the instruction or the instruction itself.
qubits: The qubits for the instruction.
Returns:
The calibration entry.
"""
instruction = _get_instruction_string(instruction)
self.assert_has(instruction, qubits)
return self._map[instruction][_to_tuple(qubits)]
def add(
self,
instruction: str | circuit.instruction.Instruction,
qubits: int | Iterable[int],
schedule: Schedule | ScheduleBlock | Callable[..., Schedule | ScheduleBlock],
arguments: list[str] | None = None,
) -> None:
"""Add a new known instruction for the given qubits and its mapping to a pulse schedule.
Args:
instruction: The name of the instruction to add.
qubits: The qubits which the instruction applies to.
schedule: The Schedule that implements the given instruction.
arguments: List of parameter names to create a parameter-bound schedule from the
associated gate instruction. If :py:meth:`get` is called with arguments rather
than keyword arguments, this parameter list is used to map the input arguments to
parameter objects stored in the target schedule.
Raises:
PulseError: If the qubits are provided as an empty iterable.
"""
instruction = _get_instruction_string(instruction)
# validation of target qubit
qubits = _to_tuple(qubits)
if not qubits:
raise PulseError(f"Cannot add definition {instruction} with no target qubits.")
# generate signature
if isinstance(schedule, (Schedule, ScheduleBlock)):
entry: CalibrationEntry = ScheduleDef(arguments)
elif callable(schedule):
if arguments:
warnings.warn(
"Arguments are overruled by the callback function signature. "
"Input `arguments` are ignored.",
UserWarning,
)
entry = CallableDef()
else:
raise PulseError(
"Supplied schedule must be one of the Schedule, ScheduleBlock or a "
"callable that outputs a schedule."
)
entry.define(schedule, user_provided=True)
self._add(instruction, qubits, entry)
def _add(
self,
instruction_name: str,
qubits: tuple[int, ...],
entry: CalibrationEntry,
):
"""A method to resister calibration entry.
.. note::
This is internal fast-path function, and caller must ensure
the entry is properly formatted. This function may be used by other programs
that load backend calibrations to create Qiskit representation of it.
Args:
instruction_name: Name of instruction.
qubits: List of qubits that this calibration is applied.
entry: Calibration entry to register.
:meta public:
"""
self._map[instruction_name][qubits] = entry
self._qubit_instructions[qubits].add(instruction_name)
def remove(
self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int]
) -> None:
"""Remove the given instruction from the listing of instructions defined in self.
Args:
instruction: The name of the instruction to add.
qubits: The qubits which the instruction applies to.
"""
instruction = _get_instruction_string(instruction)
qubits = _to_tuple(qubits)
self.assert_has(instruction, qubits)
del self._map[instruction][qubits]
if not self._map[instruction]:
del self._map[instruction]
self._qubit_instructions[qubits].remove(instruction)
if not self._qubit_instructions[qubits]:
del self._qubit_instructions[qubits]
def pop(
self,
instruction: str | circuit.instruction.Instruction,
qubits: int | Iterable[int],
*params: complex | ParameterExpression,
**kwparams: complex | ParameterExpression,
) -> Schedule | ScheduleBlock:
"""Remove and return the defined schedule for the given instruction on the given
qubits.
Args:
instruction: Name of the instruction.
qubits: The qubits for the instruction.
*params: Command parameters for generating the output schedule.
**kwparams: Keyworded command parameters for generating the schedule.
Returns:
The Schedule defined for the input.
"""
instruction = _get_instruction_string(instruction)
schedule = self.get(instruction, qubits, *params, **kwparams)
self.remove(instruction, qubits)
return schedule
def get_parameters(
self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int]
) -> tuple[str, ...]:
"""Return the list of parameters taken by the given instruction on the given qubits.
Args:
instruction: Name of the instruction.
qubits: The qubits for the instruction.
Returns:
The names of the parameters required by the instruction.
"""
instruction = _get_instruction_string(instruction)
self.assert_has(instruction, qubits)
signature = self._map[instruction][_to_tuple(qubits)].get_signature()
return tuple(signature.parameters.keys())
def __str__(self):
single_q_insts = "1Q instructions:\n"
multi_q_insts = "Multi qubit instructions:\n"
for qubits, insts in self._qubit_instructions.items():
if len(qubits) == 1:
single_q_insts += f" q{qubits[0]}: {insts}\n"
else:
multi_q_insts += f" {qubits}: {insts}\n"
instructions = single_q_insts + multi_q_insts
return f"<{self.__class__.__name__}({instructions})>"
def __eq__(self, other):
if not isinstance(other, InstructionScheduleMap):
return False
for inst in self.instructions:
for qinds in self.qubits_with_instruction(inst):
try:
if self._map[inst][_to_tuple(qinds)] != other._map[inst][_to_tuple(qinds)]:
return False
except KeyError:
return False
return True
def _to_tuple(values: int | Iterable[int]) -> tuple[int, ...]:
"""Return the input as a tuple.
Args:
values: An integer, or iterable of integers.
Returns:
The input values as a sorted tuple.
"""
try:
return tuple(values)
except TypeError:
return (values,)
def _get_instruction_string(inst: str | circuit.instruction.Instruction) -> str:
if isinstance(inst, str):
return inst
else:
try:
return inst.name
except AttributeError as ex:
raise PulseError(
'Input "inst" has no attribute "name". This should be a circuit "Instruction".'
) from ex
|
https://github.com/lockwo/Paper-Review
|
lockwo
|
import numpy as np
from qiskit import Aer, IBMQ
from qiskit.utils import QuantumInstance
from qiskit.circuit import QuantumCircuit, ParameterVector
from qiskit.opflow import StateFn, Z, I, CircuitSampler, Gradient, Hessian
from qiskit.algorithms.optimizers import GradientDescent
import matplotlib.pyplot as plt
# Code to generate a circuit as present in the paper
def paper_circuit():
circuit = QuantumCircuit(5)
params = ParameterVector("theta", length=5)
for i in range(5):
circuit.rx(params[i], i)
circuit.cx(0, 1)
circuit.cx(2, 1)
circuit.cx(3, 1)
circuit.cx(4, 3)
hamiltonian = I
for i in range(1, 5):
if i == 3:
hamiltonian = hamiltonian ^ Z
else:
hamiltonian = hamiltonian ^ I
readout_operator = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit)
return circuit, readout_operator
print(paper_circuit()[0])
def evaluate_expectation(x):
value_dict = dict(zip(circuit.parameters, x))
result = sampler.convert(op, params=value_dict).eval()
return np.real(result)
def evaluate_gradient(x):
value_dict = dict(zip(circuit.parameters, x))
result = sampler.convert(gradient, params=value_dict).eval()
return np.real(result)
def gd_callback(nfevs, x, fx, stepsize):
#if nfevs % 10 == 0:
# print(nfevs, fx)
#print(nfevs, fx)
gd_loss.append(fx)
x_values.append([x[0], x[1]])
simulate = True
provider = IBMQ.load_account()
if simulate:
backend = Aer.get_backend('aer_simulator')
else:
backend = provider.backends(name='ibmq_belem')[0]
initial_point = np.random.uniform(0, 2 * np.pi, 5)
shots = [10, 100, 1000]
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.tight_layout()
for s in shots:
# Create circuit
circuit, op = paper_circuit()
# Specify backend information
q_instance = QuantumInstance(backend, shots=s)
sampler = CircuitSampler(q_instance)
gradient = Gradient(grad_method='param_shift').convert(op)
gd_loss, x_values = [], []
# Create optimizer
gd = GradientDescent(maxiter=100, learning_rate=0.1, tol=1e-4, callback=gd_callback)
# Minimize function
gd.optimize(initial_point.size, evaluate_expectation, gradient_function=evaluate_gradient, initial_point=initial_point)
# Plotting information
cir_evals = np.array([i for i in range(len(gd_loss))])
cir_evals *= (2 * circuit.num_parameters * s)
ax1.plot(cir_evals, gd_loss, label='Shots %d'%s)
x_values.clear()
# Keeping track of just theta_0 and theta_1
gd.optimize(initial_point.size, evaluate_expectation, gradient_function=evaluate_gradient, \
initial_point=[0.1, 0.15, 0, 0, 0])
x_values = np.array(x_values)
ax2.plot(x_values[:,0], x_values[:,1], label='Shots %d'%s)
# Make the graph look nice
ax1.axhline(-1, ls='--', c='tab:red', label='Target')
ax1.set_ylabel('Cost')
ax1.set_xlabel('Circuit Evaluations')
ax1.set_xscale('log')
ax1.legend()
ax2.set_ylim(0, np.pi + 0.2)
ax2.set_xlim(-np.pi/2, np.pi/2)
ax2.set_ylabel('Theta 2')
ax2.set_xlabel('Theta 1')
#ax2.legend()
plt.show()
class NewtonOpt(object):
def __init__(self, hess, grad, num_param, circuit, sampler, op, init, lr=0.1, s=1000, maxiter=100):
self.lr = lr
self.shots = s
self.hess = hess
self.grad = grad
self.max_iter = maxiter
self.num_params = num_param
self.circuit = circuit
self.sampler = sampler
self.op = op
self.values = []
self.circuit_evals = []
self.init = init
def optimize(self):
x = self.init
for i in range(self.max_iter):
value_dict = dict(zip(self.circuit.parameters, x))
result = np.real(self.sampler.convert(self.op, params=value_dict).eval())
self.values.append(result)
value_dict = dict(zip(self.circuit.parameters, x))
hessian = np.real(self.sampler.convert(self.hess, params=value_dict).eval())
gradient = np.real(self.sampler.convert(self.grad, params=value_dict).eval())
x = x - self.lr * np.linalg.inv(hessian + np.eye(self.num_params)) @ gradient
#if i % 10 == 0:
# print(i, result)
return self.values, np.array([i for i in range(len(self.values))]) * \
((4 * self.num_params**2 - 3 * self.num_params) * self.shots)
# Generate circuit with only two parameters
def paper_circuit_two_param():
circuit = QuantumCircuit(5) # 5 qubit circuit
params = ParameterVector("theta", length=2)
for i in range(2):
circuit.rx(params[i], i)
circuit.cx(0, 1)
circuit.cx(2, 1)
circuit.cx(3, 1)
circuit.cx(4, 3)
hamiltonian = I
for i in range(1, 5):
if i == 3:
hamiltonian = hamiltonian ^ Z
else:
hamiltonian = hamiltonian ^ I
readout_operator = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit)
return circuit, readout_operator
initial_point = np.array([0.1, 0.15])
s = 1000
circuit, op = paper_circuit_two_param()
q_instance = QuantumInstance(backend, shots=s)
sampler = CircuitSampler(q_instance)
gradient = Gradient(grad_method='param_shift').convert(op)
hessian = Hessian(hess_method='param_shift').convert(op)
gd_loss = []
x_values = []
# GD minimization
gd = GradientDescent(maxiter=80, learning_rate=0.1, tol=1e-4, callback=gd_callback)
x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, evaluate_expectation, gradient_function=evaluate_gradient, \
initial_point=initial_point)
cir_evals = np.array([i for i in range(len(gd_loss))])
cir_evals *= (2 * circuit.num_parameters * s)
# 2nd order mimization
newton = NewtonOpt(hessian, gradient, circuit.num_parameters, circuit, sampler, op, initial_point, maxiter=80)
loss, evals = newton.optimize()
plt.plot(evals, loss, label='Newton')
plt.plot(cir_evals, gd_loss, label='GD')
plt.axhline(-1, ls='--', c='tab:red', label='Target')
plt.ylabel('Cost')
plt.xlabel('Circuit Evaluations')
plt.legend()
plt.show()
#initial_point = np.random.uniform(0, 2 * np.pi, 5)
initial_point = np.array([0.1, 0.15, 0, 0, 0])
s = 1000
circuit, op = paper_circuit()
q_instance = QuantumInstance(backend, shots=s)
sampler = CircuitSampler(q_instance)
gradient = Gradient().convert(op)
hessian = Hessian(hess_method='param_shift').convert(op)
gd_loss = []
x_values = []
# GD minimization
gd = GradientDescent(maxiter=100, learning_rate=0.1, tol=1e-4, callback=gd_callback)
x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, evaluate_expectation, gradient_function=evaluate_gradient, \
initial_point=initial_point)
cir_evals = np.array([i for i in range(len(gd_loss))])
cir_evals *= (2 * circuit.num_parameters * s)
# 2nd order mimization
newton = NewtonOpt(hessian, gradient, circuit.num_parameters, circuit, sampler, op, initial_point)
loss, evals = newton.optimize()
plt.plot(evals, loss, label='Newton')
plt.plot(cir_evals, gd_loss, label='GD')
plt.axhline(-1, ls='--', c='tab:red', label='Target')
plt.ylabel('Cost')
plt.xlabel('Circuit Evaluations')
plt.xscale('log')
plt.legend()
plt.show()
|
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.
""" A utility for caching and reparameterizing circuits, rather than compiling from scratch
with each iteration. Note that if the circuit is transpiled aggressively such that rotation parameters
cannot be easily mapped from the uncompiled to compiled circuit, caching will fail gracefully to
standard compilation. This will be noted by multiple cache misses in the DEBUG log. It is generally safer to
skip the transpiler (aqua_dict['backend']['skip_transpiler'] = True) when using caching.
Caching is controlled via the aqua_dict['problem']['circuit_caching'] parameter. Setting skip_qobj_deepcopy = True
reuses the same qobj object over and over to avoid deepcopying. It is controlled via the aqua_dict['problem'][
'skip_qobj_deepcopy'] parameter.
You may also specify a filename into which to store the cache as a pickle file, for circuits which
are expensive to compile even the first time. The filename is set in aqua_dict['problem']['circuit_cache_file'].
If a filename is present, the system will attempt to load from the file.
In the event of an error, the system will fail gracefully, compile from scratch, and cache the new
compiled qobj and mapping in the file location in pickled form. It will fail over 5 times before deciding
that caching should be disabled."""
import numpy as np
import copy
import pickle
import logging
from qiskit import QuantumRegister
from qiskit.circuit import CompositeGate
from qiskit.assembler.run_config import RunConfig
from qiskit.qobj import Qobj, QasmQobjConfig
from qiskit.aqua.aqua_error import AquaError
logger = logging.getLogger(__name__)
class CircuitCache:
def __init__(self,
skip_qobj_deepcopy=False,
cache_file=None,
allowed_misses=3):
self.skip_qobj_deepcopy = skip_qobj_deepcopy
self.cache_file = cache_file
self.misses = 0
self.qobjs = []
self.mappings = []
self.cache_transpiled_circuits = False
self.try_reusing_qobjs = True
self.allowed_misses = allowed_misses
try:
self.try_loading_cache_from_file()
except(EOFError, FileNotFoundError) as e:
logger.warning("Error loading cache from file {0}: {1}".format(self.cache_file, repr(e)))
def cache_circuit(self, qobj, circuits, chunk):
"""
A method for caching compiled qobjs by storing the compiled qobj
and constructing a mapping array from the uncompiled operations in the circuit
to the instructions in the qobj. Note that the "qobjs" list in the cache dict is a
list of the cached chunks, each element of which contains a single qobj with as
many experiments as is allowed by the execution backend. E.g. if the backend allows
300 experiments per job and the user wants to run 500 circuits,
len(circuit_cache['qobjs']) == 2,
len(circuit_cache['qobjs'][0].experiments) == 300, and
len(circuit_cache['qobjs'][1].experiments) == 200.
This feature is only applied if 'circuit_caching' is True in the 'problem' Aqua
dictionary section.
Args:
qobj (Qobj): A compiled qobj to be saved
circuits (list): The original uncompiled QuantumCircuits
chunk (int): If a larger list of circuits was broken into chunks by run_algorithm for separate runs,
which chunk number `circuits` represents
"""
self.qobjs.insert(chunk, copy.deepcopy(qobj))
self.mappings.insert(chunk, [{} for i in range(len(circuits))])
for circ_num, input_circuit in enumerate(circuits):
qreg_sizes = [reg.size for reg in input_circuit.qregs if isinstance(reg, QuantumRegister)]
qreg_indeces = {reg.name: sum(qreg_sizes[0:i]) for i, reg in enumerate(input_circuit.qregs)}
op_graph = {}
# Unroll circuit in case of composite gates
raw_gates = []
for gate in input_circuit.data:
if isinstance(gate, CompositeGate): raw_gates += gate.instruction_list()
else: raw_gates += [gate]
for i, (uncompiled_gate, regs, _) in enumerate(raw_gates):
if not hasattr(uncompiled_gate, 'params') or len(uncompiled_gate.params) < 1: continue
if uncompiled_gate.name == 'snapshot': continue
qubits = [qubit+qreg_indeces[reg.name] for reg, qubit in regs if isinstance(reg, QuantumRegister)]
gate_type = uncompiled_gate.name
type_and_qubits = gate_type + qubits.__str__()
op_graph[type_and_qubits] = \
op_graph.get(type_and_qubits, []) + [i]
mapping = {}
for compiled_gate_index, compiled_gate in enumerate(qobj.experiments[circ_num].instructions):
if not hasattr(compiled_gate, 'params') or len(compiled_gate.params) < 1: continue
if compiled_gate.name == 'snapshot': continue
type_and_qubits = compiled_gate.name + compiled_gate.qubits.__str__()
if len(op_graph[type_and_qubits]) > 0:
uncompiled_gate_index = op_graph[type_and_qubits].pop(0)
(uncompiled_gate, regs, _) = raw_gates[uncompiled_gate_index]
qubits = [qubit + qreg_indeces[reg.name] for reg, qubit in regs if isinstance(reg, QuantumRegister)]
if (compiled_gate.name == uncompiled_gate.name) and (compiled_gate.qubits.__str__() ==
qubits.__str__()):
mapping[compiled_gate_index] = uncompiled_gate_index
else: raise AquaError("Circuit shape does not match qobj, found extra {} instruction in qobj".format(
type_and_qubits))
self.mappings[chunk][circ_num] = mapping
for type_and_qubits, ops in op_graph.items():
if len(ops) > 0:
raise AquaError("Circuit shape does not match qobj, found extra {} in circuit".format(type_and_qubits))
if self.cache_file is not None and len(self.cache_file) > 0:
with open(self.cache_file, 'wb') as cache_handler:
qobj_dicts = [qob.to_dict() for qob in self.qobjs]
pickle.dump({'qobjs': qobj_dicts,
'mappings': self.mappings,
'transpile': self.cache_transpiled_circuits},
cache_handler,
protocol=pickle.HIGHEST_PROTOCOL)
logger.debug("Circuit cache saved to file: {}".format(self.cache_file))
def try_loading_cache_from_file(self):
if len(self.qobjs) == 0 and self.cache_file is not None and len(self.cache_file) > 0:
with open(self.cache_file, "rb") as cache_handler:
try:
cache = pickle.load(cache_handler, encoding="ASCII")
except (EOFError) as e:
logger.debug("No cache found in file: {}".format(self.cache_file))
return
self.qobjs = [Qobj.from_dict(qob) for qob in cache['qobjs']]
self.mappings = cache['mappings']
self.cache_transpiled_circuits = cache['transpile']
logger.debug("Circuit cache loaded from file: {}".format(self.cache_file))
# Note that this function overwrites the previous cached qobj for speed
def load_qobj_from_cache(self, circuits, chunk, run_config=None):
self.try_loading_cache_from_file()
if self.try_reusing_qobjs and self.qobjs is not None and len(self.qobjs) > 0 and len(self.qobjs) <= chunk:
self.mappings.insert(chunk, self.mappings[0])
self.qobjs.insert(chunk, copy.deepcopy(self.qobjs[0]))
for circ_num, input_circuit in enumerate(circuits):
# If there are too few experiments in the cache, try reusing the first experiment.
# Only do this for the first chunk. Subsequent chunks should rely on these copies
# through the deepcopy above.
if self.try_reusing_qobjs and chunk == 0 and circ_num > 0 and len(self.qobjs[chunk].experiments) <= \
circ_num:
self.qobjs[0].experiments.insert(circ_num, copy.deepcopy(self.qobjs[0].experiments[0]))
self.mappings[0].insert(circ_num, self.mappings[0][0])
# Unroll circuit in case of composite gates
raw_gates = []
for gate in input_circuit.data:
if isinstance(gate, CompositeGate): raw_gates += gate.instruction_list()
else: raw_gates += [gate]
self.qobjs[chunk].experiments[circ_num].header.name = input_circuit.name
for gate_num, compiled_gate in enumerate(self.qobjs[chunk].experiments[circ_num].instructions):
if not hasattr(compiled_gate, 'params') or len(compiled_gate.params) < 1: continue
if compiled_gate.name == 'snapshot': continue
cache_index = self.mappings[chunk][circ_num][gate_num]
(uncompiled_gate, regs, _) = raw_gates[cache_index]
# Need the 'getattr' wrapper because measure has no 'params' field and breaks this.
if not len(getattr(compiled_gate, 'params', [])) == len(getattr(uncompiled_gate, 'params', [])) or \
not compiled_gate.name == uncompiled_gate.name:
raise AquaError('Gate mismatch at gate {0} ({1}, {2} params) of circuit against gate {3} ({4}, '
'{5} params) of cached qobj'.format(cache_index,
uncompiled_gate.name,
len(uncompiled_gate.params),
gate_num,
compiled_gate.name,
len(compiled_gate.params)))
compiled_gate.params = np.array(uncompiled_gate.params, dtype=float).tolist()
exec_qobj = copy.copy(self.qobjs[chunk])
if self.skip_qobj_deepcopy: exec_qobj.experiments = self.qobjs[chunk].experiments[0:len(circuits)]
else: exec_qobj.experiments = copy.deepcopy(self.qobjs[chunk].experiments[0:len(circuits)])
if run_config is None:
run_config = RunConfig(shots=1024, max_credits=10, memory=False)
exec_qobj.config = QasmQobjConfig(**run_config.to_dict())
exec_qobj.config.memory_slots = max(experiment.config.memory_slots for experiment in exec_qobj.experiments)
exec_qobj.config.n_qubits = max(experiment.config.n_qubits for experiment in exec_qobj.experiments)
return exec_qobj
def clear_cache(self):
self.qobjs = []
self.mappings = []
self.try_reusing_qobjs = True
|
https://github.com/PabloAMC/Qiskit_meetup_2021
|
PabloAMC
|
%matplotlib inline
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
#from iqx import *
from qiskit.aqua.circuits import PhaseEstimationCircuit
from qiskit.chemistry.components.initial_states import HartreeFock
from qiskit.chemistry.core import Hamiltonian
from qiskit.circuit.library import PhaseEstimation
from qiskit import QuantumCircuit, execute, Aer
from qiskit.circuit import QuantumRegister, Qubit, Gate, ClassicalRegister
from qiskit.quantum_info import Statevector
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
from qiskit.chemistry.drivers import PySCFDriver, UnitsType, Molecule, PSI4Driver
molecule = Molecule(geometry=[['H', [0., 0., 0.]],
['H', [0., 0., 0.735]]],
charge=0, multiplicity=1)
driver = PySCFDriver(molecule = molecule, unit=UnitsType.ANGSTROM, basis='sto3g')
qmol = driver.run()
print(qmol.one_body_integrals)
print(qmol.two_body_integrals)
from qiskit.chemistry.transformations import (FermionicTransformation,
FermionicTransformationType,
FermionicQubitMappingType)
fermionic_transformation = FermionicTransformation(
transformation=FermionicTransformationType.FULL,
qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER,
two_qubit_reduction=False,
freeze_core=False)
qubit_op, _ = fermionic_transformation.transform(driver)
print('Qubit operator is', qubit_op)
num_orbitals = fermionic_transformation.molecule_info['num_orbitals']
num_particles = fermionic_transformation.molecule_info['num_particles']
qubit_mapping = fermionic_transformation.qubit_mapping
two_qubit_reduction = fermionic_transformation.molecule_info['two_qubit_reduction']
z2_symmetries = fermionic_transformation.molecule_info['z2_symmetries']
initial_state = HartreeFock(num_orbitals, num_particles, qubit_mapping,
two_qubit_reduction, z2_symmetries.sq_list)
initial_circ = initial_state.construct_circuit()
print(initial_state.bitstr)
initial_circ.draw()
qubit_op, _ = fermionic_transformation.transform(driver)
print(qubit_op)
num_evaluation_qubits = 5
normalization_factor = 1/2 # Since the min energy will be -1.8... we need to normalize it so that it is smaller than 1
unitary = (normalization_factor*qubit_op).exp_i().to_circuit()
phase_estimation = PhaseEstimation(num_evaluation_qubits = num_evaluation_qubits, unitary = unitary)
type(qubit_op.exp_i().to_circuit())
print(phase_estimation.qubits)
dir(phase_estimation)
phase_estimation.draw()
circ = initial_circ.combine(phase_estimation)
classical_eval = ClassicalRegister(num_evaluation_qubits, name = 'class_eval')
circ = circ + QuantumCircuit(classical_eval)
#circ.measure_all()
print(circ.qregs)
circ.measure(circ.qregs[1], classical_eval)
circ.draw()
# Use Aer's qasm_simulator
backend_sim = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = execute(circ, backend_sim, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
print(counts)
maxkey = '0'*num_evaluation_qubits
maxvalue = 0
for key, value in counts.items():
if value > maxvalue:
maxvalue = value
maxkey = key
energy = 0
for i,s in zip(range(num_evaluation_qubits), maxkey[::-1]):
energy -= (int(s)/2**(i))/normalization_factor
print('The energy is', energy, 'Hartrees')
36/32
26/16
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator
from qiskit.transpiler.passes import UnitarySynthesis
circuit = QuantumCircuit(1)
circuit.rx(0.8, 0)
unitary = Operator(circuit).data
unitary_circ = QuantumCircuit(1)
unitary_circ.unitary(unitary, [0])
synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk")
out = synth(unitary_circ)
out.draw('mpl')
|
https://github.com/Marduk-42/Quantum-Algorithm-Tutorials
|
Marduk-42
|
from qiskit import Aer, execute, QuantumCircuit, visualization
import matplotlib.pyplot as plt
qc = QuantumCircuit.from_qasm_file('Bell test.qasm')
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=2048)
result = job.result()
ax1 = qc.draw("mpl")
ax1.suptitle("Bell test circuit")
ax2 = visualization.plot_histogram(result.get_counts(qc))
ax2.suptitle("Results")
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import execute, pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), d0)
pulse_prog.draw()
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
s = '11'
# Creating registers
# qubits for querying the oracle and finding the hidden period s
qr = QuantumRegister(2*len(str(s)))
# classical registers for recording the measurement from qr
cr = ClassicalRegister(2*len(str(s)))
simonCircuit = QuantumCircuit(qr, cr)
barriers = True
# Apply Hadamard gates before querying the oracle
for i in range(len(str(s))):
simonCircuit.h(qr[i])
# Apply barrier
if barriers:
simonCircuit.barrier()
# Apply the query function
## 2-qubit oracle for s = 11
simonCircuit.cx(qr[0], qr[len(str(s)) + 0])
simonCircuit.cx(qr[0], qr[len(str(s)) + 1])
simonCircuit.cx(qr[1], qr[len(str(s)) + 0])
simonCircuit.cx(qr[1], qr[len(str(s)) + 1])
# Apply barrier
if barriers:
simonCircuit.barrier()
# Measure ancilla qubits
for i in range(len(str(s)), 2*len(str(s))):
simonCircuit.measure(qr[i], cr[i])
# Apply barrier
if barriers:
simonCircuit.barrier()
# Apply Hadamard gates to the input register
for i in range(len(str(s))):
simonCircuit.h(qr[i])
# Apply barrier
if barriers:
simonCircuit.barrier()
# Measure input register
for i in range(len(str(s))):
simonCircuit.measure(qr[i], cr[i])
simonCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(simonCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
# Categorize measurements by input register values
answer_plot = {}
for measresult in answer.keys():
measresult_input = measresult[len(str(s)):]
if measresult_input in answer_plot:
answer_plot[measresult_input] += answer[measresult]
else:
answer_plot[measresult_input] = answer[measresult]
# Plot the categorized results
print( answer_plot )
plot_histogram(answer_plot)
# Calculate the dot product of the results
def sdotz(a, b):
accum = 0
for i in range(len(a)):
accum += int(a[i]) * int(b[i])
return (accum % 2)
print('s, z, s.z (mod 2)')
for z_rev in answer_plot:
z = z_rev[::-1]
print( '{}, {}, {}.{}={}'.format(s, z, s,z,sdotz(s,z)) )
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
IBMQ.load_account()
IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(simonCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Categorize measurements by input register values
answer_plot = {}
for measresult in answer.keys():
measresult_input = measresult[len(str(s)):]
if measresult_input in answer_plot:
answer_plot[measresult_input] += answer[measresult]
else:
answer_plot[measresult_input] = answer[measresult]
# Plot the categorized results
print( answer_plot )
plot_histogram(answer_plot)
# Calculate the dot product of the most significant results
print('s, z, s.z (mod 2)')
for z_rev in answer_plot:
if answer_plot[z_rev] >= 0.1*shots:
z = z_rev[::-1]
print( '{}, {}, {}.{}={}'.format(s, z, s,z,sdotz(s,z)) )
import qiskit
qiskit.__qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
# Create a circuit with a register of three qubits
circ = QuantumCircuit(3)
# H gate on qubit 0, putting this qubit in a superposition of |0> + |1>.
circ.h(0)
# A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state.
circ.cx(0, 1)
# CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state.
circ.cx(0, 2)
# Draw the circuit
circ.draw('mpl')
|
https://github.com/ka-us-tubh/quantum-computing-qiskit-
|
ka-us-tubh
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit import assemble
import numpy as np
import matplotlib.pyplot as plt
n=4
grover_ckt=QuantumCircuit(n+1,n)
marked=[1,0,1,1]#1101 marked =13
def apply_oracle(n,marked,ckt):
controlO=[i for i in range(n) if not marked[i]]
ckt.x(controlO)
ckt.mct(list(range(n)),n)
ckt.x(controlO)
ckt.draw()
def reflect_uniform(ckt,n):
ckt.h(list(range(n)))
ckt.x(list(range(n)))
ckt.mct(list(range(n)),n)
ckt.x(list(range(n+1)))
ckt.h(list(range(n)))
grover_ckt.x(n)
grover_ckt.barrier()
grover_ckt.h(list(range(n+1)))
grover_ckt.draw()
svsim= Aer.get_backend('statevector_simulator')
qobj=assemble(grover_ckt)
result=svsim.run(qobj).result()
#statevector=result.data()["statevector"]
statevector=result.get_statevector()
statevector=np.array(statevector)
#statevector.dtype
statevector.shape
print(statevector)
statevector=statevector[:2**n]
statevector.shape
#print(np.array([i for i in range(2**n)]))
#statevector = statevector(dims=[i for i in range(2**n)])
marked=[1,0,1,1]
ket_a=np.zeros(2**n)
ket_a[13]=1
ket_e=(np.ones(2**n)-ket_a)/np.sqrt(2**n-1)
ket_a
ket_e
def get_projection(psi,e,a):
proj=[np.real(np.vdot(e,psi)),np.real(np.vdot(a,psi))]
return proj
def plt_vector(proj,axes=[0.0,1.0,0.0,1.0]):
x_pos=0
y_pos=0
x_direct=proj[0]
y_direct=proj[1]
fig,ax =plt.subplots()
ax.quiver(x_pos,y_pos,x_direct,y_direct,scale=1.0)
ax.axis(axes)
plt.show()
proj =get_projection(statevector,ket_e,ket_a)
plt_vector(proj)
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
grover_ckt.draw()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
grover_ckt.draw()
svsim= Aer.get_backend('statevector_simulator')
qobj=assemble(grover_ckt)
result=svsim.run(qobj).result()
#statevector=result.data()["statevector"]
statevector=result.get_statevector()
statevector=np.array(statevector)
statevector=statevector[:2**n]
proj =get_projection(statevector,ket_e,ket_a)
plt_vector(proj)
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
grover_ckt.draw()
svsim= Aer.get_backend('statevector_simulator')
qobj=assemble(grover_ckt)
result=svsim.run(qobj).result()
#statevector=result.data()["statevector"]
statevector=result.get_statevector()
statevector=np.array(statevector)
statevector=statevector[:2**n]
proj =get_projection(statevector,ket_e,ket_a)
plt_vector(proj)
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
grover_ckt.draw()
svsim= Aer.get_backend('statevector_simulator')
qobj=assemble(grover_ckt)
result=svsim.run(qobj).result()
#statevector=result.data()["statevector"]
statevector=result.get_statevector()
statevector=np.array(statevector)
statevector=statevector[:2**n]
proj =get_projection(statevector,ket_e,ket_a)
plt_vector(proj,axes=[-1.0,1.0,-1.0,1.0])
import math
thetaO=math.asin(1/math.sqrt(2**n))
print(thetaO)
T=0
angle=thetaO
print(angle)
while(angle+(2*thetaO)<=(math.pi/2)and angle>=0):
T+=1
angle=angle+(2*thetaO)
print(angle)
#print(T)
n=4
grover_ckt=QuantumCircuit(n+1,n)
marked=[1,0,1,1]#1101 marked =13
grover_ckt.x(n)
grover_ckt.barrier()
grover_ckt.h(list(range(n+1)))
grover_ckt.barrier()
for _ in range(int(np.floor(T))):
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
for j in range(n):
grover_ckt.measure(j,j)
grover_ckt.draw()
sim=Aer.get_backend("qasm_simulator")
qobj=assemble(grover_ckt)
result=sim.run(qobj).result()
result
counts=result.get_counts(grover_ckt)
plot_histogram(counts)
|
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.
"""
Tests for the bergholm state preparation
"""
from unittest import TestCase
import numpy as np
from qiskit import QuantumCircuit
from qclib.state_preparation import UCGInitialize
from qclib.util import get_state
class TestUCGInitialize(TestCase):
"""Test UCGInitialize"""
def _test_ucg(self, n_qubits):
state = np.random.rand(2 ** n_qubits) + np.random.rand(2 ** n_qubits) * 1j
state = state / np.linalg.norm(state)
for target_state in range(2 ** n_qubits):
gate = UCGInitialize(state.tolist(),
opt_params={
"target_state": target_state
}
).definition
circuit = QuantumCircuit(n_qubits)
for j, bit in enumerate(f'{target_state:0{n_qubits}b}'[::-1]):
if bit == '1':
circuit.x(j)
circuit.append(gate, circuit.qubits)
output_state = get_state(circuit)
self.assertTrue(np.allclose(state, output_state))
def _test_ucg_preserve(self, n_qubits):
state = np.random.rand(2 ** n_qubits) + np.random.rand(2 ** n_qubits) * 1j
for target_state in range(1, 2 ** n_qubits):
state[target_state - 1] = 0
state = state / np.linalg.norm(state)
gate = UCGInitialize(state.tolist(),
opt_params={
"target_state": target_state,
"preserve_previous": True
}
).definition
circuit = QuantumCircuit(n_qubits)
for j, bit in enumerate(f'{target_state:0{n_qubits}b}'[::-1]):
if bit == '1':
circuit.x(j)
circuit.append(gate, circuit.qubits)
output_state = get_state(circuit)
self.assertTrue(np.allclose(output_state, state))
def test_ucg(self):
"""Test UCGInitialize"""
for n_qubits in range(3, 5):
self._test_ucg(n_qubits)
def test_ucg_preserve(self):
"""Test UCGInitialize with `preserve_previous`"""
for n_qubits in range(3, 5):
self._test_ucg_preserve(n_qubits)
def test_real(self):
"""Test UCGInitialize with four qubits and index 10"""
n_qubits = 4
state = np.random.rand(2 ** n_qubits)
state[0] = 0
state[1] = 0
state = state / np.linalg.norm(state)
initialize = UCGInitialize.initialize
circuit = QuantumCircuit(n_qubits)
circuit.x(1)
circuit.x(3)
initialize(circuit, state.tolist(), opt_params={"target_state": 10})
output_state = get_state(circuit)
self.assertTrue(np.allclose(output_state, state))
|
https://github.com/ionq-samples/Ion-Q-Thruster
|
ionq-samples
|
%%capture
%pip install qiskit
%pip install qiskit_ibm_provider
%pip install qiskit-aer
# Importing standard Qiskit libraries
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer
from qiskit_ibm_provider import IBMProvider
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.circuit.library import C3XGate
# Importing matplotlib
import matplotlib.pyplot as plt
# Importing Numpy, Cmath and math
import numpy as np
import os, math, cmath
from numpy import pi
# Other imports
from IPython.display import display, Math, Latex
# Specify the path to your env file
env_file_path = 'config.env'
# Load environment variables from the file
os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#'))
# Load IBM Provider API KEY
IBMP_API_KEY = os.environ.get('IBMP_API_KEY')
# Loading your IBM Quantum account(s)
IBMProvider.save_account(IBMP_API_KEY, overwrite=True)
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
qc_b1 = QuantumCircuit(2, 2)
qc_b1.h(0)
qc_b1.cx(0, 1)
qc_b1.draw(output='mpl', style="iqp")
sv = backend.run(qc_b1).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.x(0)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.z(0)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.x(1)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.x(0)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.x(0)
qc_b4.h(0)
qc_b4.x(1)
qc_b4.cx(0, 1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.h(0)
qc_b4.cx(0, 1)
qc_b4.x(0)
qc_b4.z(1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
def sv_latex_from_qc(qc, backend):
sv = backend.run(qc).result().get_statevector()
return sv.draw(output='latex')
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(3)
sv_latex_from_qc(qc_ej2, backend)
def circuit_adder (num):
if num<1 or num>8:
raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricción sería directo.
# Definición del circuito base que vamos a construir
qreg_q = QuantumRegister(4, 'q')
creg_c = ClassicalRegister(1, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
qbit_position = 0
for element in reversed(np.binary_repr(num)):
if (element=='1'):
circuit.barrier()
match qbit_position:
case 0: # +1
circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]])
circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
circuit.x(qreg_q[0])
case 1: # +2
circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.x(qreg_q[1])
case 2: # +4
circuit.cx(qreg_q[2], qreg_q[3])
circuit.x(qreg_q[2])
case 3: # +8
circuit.x(qreg_q[3])
qbit_position+=1
return circuit
add_3 = circuit_adder(3)
add_3.draw(output='mpl', style="iqp")
qc_test_2 = QuantumCircuit(4, 4)
qc_test_2.x(1)
qc_test_2_plus_3 = qc_test_2.compose(add_3)
qc_test_2_plus_3.draw(output='mpl', style="iqp")
sv_latex_from_qc(qc_test_2_plus_3, backend)
qc_test_7 = QuantumCircuit(4, 4)
qc_test_7.x(0)
qc_test_7.x(1)
qc_test_7.x(2)
qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8))
sv_latex_from_qc(qc_test_7_plus_8, backend)
#qc_test_7_plus_8.draw()
theta = 6.544985
phi = 2.338741
lmbda = 0
alice_1 = 0
alice_2 = 1
bob_1 = 2
qr_alice = QuantumRegister(2, 'Alice')
qr_bob = QuantumRegister(1, 'Bob')
cr = ClassicalRegister(3, 'c')
qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr)
qc_ej3.barrier(label='1')
qc_ej3.u(theta, phi, lmbda, alice_1);
qc_ej3.barrier(label='2')
qc_ej3.h(alice_2)
qc_ej3.cx(alice_2, bob_1);
qc_ej3.barrier(label='3')
qc_ej3.cx(alice_1, alice_2)
qc_ej3.h(alice_1);
qc_ej3.barrier(label='4')
qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]);
qc_ej3.barrier(label='5')
qc_ej3.x(bob_1).c_if(alice_2, 1)
qc_ej3.z(bob_1).c_if(alice_1, 1)
qc_ej3.measure(bob_1, bob_1);
qc_ej3.draw(output='mpl', style="iqp")
result = backend.run(qc_ej3, shots=1024).result()
counts = result.get_counts()
plot_histogram(counts)
sv_0 = np.array([1, 0])
sv_1 = np.array([0, 1])
def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/√2'}, tolerance=1e-10):
"""
Check if the given numerical value corresponds to a symbolic constant within a specified tolerance.
Parameters:
- value (float): The numerical value to check.
- symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations.
Defaults to {1/np.sqrt(2): '1/√2'}.
- tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10.
Returns:
str or float: If a match is found, returns the symbolic representation as a string
(prefixed with '-' if the value is negative); otherwise, returns the original value.
"""
for constant, symbol in symbolic_constants.items():
if np.isclose(abs(value), constant, atol=tolerance):
return symbol if value >= 0 else '-' + symbol
return value
def array_to_dirac_notation(array, tolerance=1e-10):
"""
Convert a complex-valued array representing a quantum state in superposition
to Dirac notation.
Parameters:
- array (numpy.ndarray): The complex-valued array representing
the quantum state in superposition.
- tolerance (float): Tolerance for considering amplitudes as negligible.
Returns:
str: The Dirac notation representation of the quantum state.
"""
# Ensure the statevector is normalized
array = array / np.linalg.norm(array)
# Get the number of qubits
num_qubits = int(np.log2(len(array)))
# Find indices where amplitude is not negligible
non_zero_indices = np.where(np.abs(array) > tolerance)[0]
# Generate Dirac notation terms
terms = [
(find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b"))
for i in non_zero_indices
]
# Format Dirac notation
dirac_notation = " + ".join([f"{amplitude}|{binary_rep}⟩" for amplitude, binary_rep in terms])
return dirac_notation
def array_to_matrix_representation(array):
"""
Convert a one-dimensional array to a column matrix representation.
Parameters:
- array (numpy.ndarray): The one-dimensional array to be converted.
Returns:
numpy.ndarray: The column matrix representation of the input array.
"""
# Replace symbolic constants with their representations
matrix_representation = np.array([find_symbolic_representation(value) or value for value in array])
# Return the column matrix representation
return matrix_representation.reshape((len(matrix_representation), 1))
def array_to_dirac_and_matrix_latex(array):
"""
Generate LaTeX code for displaying both the matrix representation and Dirac notation
of a quantum state.
Parameters:
- array (numpy.ndarray): The complex-valued array representing the quantum state.
Returns:
Latex: A Latex object containing LaTeX code for displaying both representations.
"""
matrix_representation = array_to_matrix_representation(array)
latex = "Matrix representation\n\\begin{bmatrix}\n" + \
"\\\\\n".join(map(str, matrix_representation.flatten())) + \
"\n\\end{bmatrix}\n"
latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}'
return Latex(latex)
sv_b1 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b2 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b3 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b4 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
|
https://github.com/harshagarine/QISKIT_INDIA_CHALLENGE
|
harshagarine
|
### WRITE YOUR CODE BETWEEN THESE LINES - START
# import libraries that are used in the functions below.
from qiskit import QuantumCircuit
import numpy as np
### WRITE YOUR CODE BETWEEN THESE LINES - END
def init_circuit():
# create a quantum circuit on two qubits
qc = QuantumCircuit(2)
# initializing the circuit
qc.h(0)
qc.x(1)
return qc
# The initial state has been defined above.
# You'll now have to apply necessary gates in the build_state() function to convert the state as asked in the question.
def build_state():
### WRITE YOUR CODE BETWEEN THESE LINES - START
# the initialized circuit
circuit = init_circuit()
# apply a single cu3 gate
circuit.cu3(0, -np.pi/2, 0, 0, 1)
### WRITE YOUR CODE BETWEEN THESE LINES - END
return circuit
|
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/quantumyatra/quantum_computing
|
quantumyatra
|
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibmq_armonk')
backend_config = backend.configuration()
assert backend_config.open_pulse, "Backend doesn't support Pulse"
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
backend_defaults = backend.defaults()
import numpy as np
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
# We will find the qubit frequency for the following qubit.
qubit = 0
# The sweep will be centered around the estimated qubit frequency.
# The default frequency is given in Hz
# warning: this will change in a future release
center_frequency_Hz = backend_defaults.qubit_freq_est[qubit]
print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.")
# scale factor to remove factors of 10 from the data
scale_factor = 1e-14
# We will sweep 40 MHz around the estimated frequency
frequency_span_Hz = 40 * MHz
# in steps of 1 MHz.
frequency_step_Hz = 1 * MHz
# We will sweep 20 MHz above and 20 MHz below the estimated frequency
frequency_min = center_frequency_Hz - frequency_span_Hz / 2
frequency_max = center_frequency_Hz + frequency_span_Hz / 2
# Construct an np array of the frequencies for our experiment
frequencies_GHz = np.arange(frequency_min / GHz,
frequency_max / GHz,
frequency_step_Hz / GHz)
print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz \
in steps of {frequency_step_Hz / MHz} MHz.")
# samples need to be multiples of 16
def get_closest_multiple_of_16(num):
return int(num + 8 ) - (int(num + 8 ) % 16)
from qiskit import pulse
from qiskit.pulse import pulse_lib
#from qiskit.pulse import library as pulse_lib
from qiskit import pulse # This is where we access all of our Pulse features!
#from qiskit.pulse import Play
# This Pulse module helps us build sampled pulses for common pulse shapes
#from qiskit.pulse import library as pulse_lib
from qiskit.pulse import pulse_lib
# Drive pulse parameters (us = microseconds)
drive_sigma_us = 0.075 # This determines the actual width of the gaussian
drive_samples_us = drive_sigma_us*8 # This is a truncating parameter, because gaussians don't have
# a natural finite length
drive_sigma = get_closest_multiple_of_16(drive_sigma_us * us /dt) # The width of the gaussian in units of dt
drive_samples = get_closest_multiple_of_16(drive_samples_us * us /dt) # The truncating parameter in units of dt
drive_amp = 0.05
# Drive pulse samples
drive_pulse = pulse_lib.gaussian(duration=drive_samples,
sigma=drive_sigma,
amp=drive_amp,
name='freq_sweep_excitation_pulse')
# Find out which group of qubits need to be acquired with this qubit
meas_map_idx = None
for i, measure_group in enumerate(backend_config.meas_map):
if qubit in measure_group:
meas_map_idx = i
break
assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!"
inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure', qubits=backend_config.meas_map[meas_map_idx])
measure
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Create the base schedule
# Start with drive pulse acting on the drive channel
schedule = pulse.Schedule(name='Frequency sweep')
schedule += Play(drive_pulse, drive_chan)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
schedule += measure << schedule.duration
# Create the frequency settings for the sweep (MUST BE IN HZ)
frequencies_Hz = frequencies_GHz*GHz
schedule_frequencies = [{drive_chan: freq} for freq in frequencies_Hz]
schedule.draw(label=True)
from qiskit import assemble
num_shots_per_frequency = 1024
frequency_sweep_program = assemble(schedule,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_frequency,
schedule_los=schedule_frequencies)
job = backend.run(frequency_sweep_program)
# print(job.job_id())
from qiskit.tools.monitor import job_monitor
job_monitor(job)
frequency_sweep_results = job.result(timeout=120) # timeout parameter set to 120 seconds
import matplotlib.pyplot as plt
sweep_values = []
for i in range(len(frequency_sweep_results.results)):
# Get the results from the ith experiment
res = frequency_sweep_results.get_memory(i)*scale_factor
# Get the results for `qubit` from this experiment
sweep_values.append(res[qubit])
plt.scatter(frequencies_GHz, np.real(sweep_values), color='black') # plot real part of sweep values
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured signal [a.u.]")
plt.show()
from scipy.optimize import curve_fit
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
fit_params, y_fit = fit_function(frequencies_GHz,
np.real(sweep_values),
lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C,
[-5, 4.975, 1, 5] # initial parameters for curve_fit
)
plt.scatter(frequencies_GHz, np.real(sweep_values), color='black')
plt.plot(frequencies_GHz, y_fit, color='red')
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_circuit_layout
from qiskit.tools.monitor import job_monitor
from qiskit.providers.fake_provider import FakeVigoV2
import matplotlib.pyplot as plt
ghz = QuantumCircuit(3, 3)
ghz.h(0)
for idx in range(1,3):
ghz.cx(0,idx)
ghz.measure(range(3), range(3))
backend = FakeVigoV2()
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/abbarreto/qiskit3
|
abbarreto
|
import sympy
from sympy import *
import numpy as np
from numpy import random
import math
import scipy
init_printing(use_unicode=True)
from matplotlib import pyplot as plt
%matplotlib inline
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum import TensorProduct as tp
from mpmath import factorial as fact
import io
import base64
#from IPython.core.display import display, HTML, clear_output
from IPython import *
from ipywidgets import interactive, interact, fixed, interact_manual, widgets
import csv
import importlib
import scipy.interpolate
from mpl_toolkits.mplot3d import Axes3D, proj3d
from itertools import product, combinations
from matplotlib.patches import FancyArrowPatch
from matplotlib import cm, colors
from sympy.functions.special.tensor_functions import KroneckerDelta
from scipy.linalg import polar, lapack
import mpmath
# constantes físicas
e = 1.60217662*10**-19 # C (carga elementar)
k = 8.9875517923*10**9 # Nm^2/C^2 (constante de Coulomb)
eps0 = 8.8541878128*10**-12 #F/m (permissividade do vácuo)
mu0 = 1.25663706212*10**-6 # N/A^2 (permeabilidade do vácuo)
h = 6.626069*10**-34 # Js (constante de Planck)
heV = h/e # em eV
hb = h/(2*math.pi) # hbar
hbeV = hb/e # em eV
c = 2.99792458*10**8 # m/s (velocidade da luz no vácuo)
G = 6.6742*10**-11 # Nm^2/kg^2 (constante gravitacional)
kB = 1.38065*10**-23 # J/K (constante de Boltzmann)
me = 9.109382*10**-31 # kg (massa do elétron)
mp = 1.6726219*10**-27 # kg (massa do próton)
mn = 1.67492749804*10**-27 # kg (massa do nêutron)
mT = 5.9722*10**24 # kg (massa da Terra)
mS = 1.98847*10**30 # kg (massa do Sol)
u = 1.660538921*10**-27 # kg (unidade de massa atômica)
dTS = 1.496*10**11 # m (distância Terra-Sol)
rT = 6.3781*10**6 # m (raio da Terra)
sSB = 5.670374419*10**-8 # W⋅m−2⋅K−4 (constante de Stefan-Boltzmann)
Ri = 10973734.848575922 # m^-1 (constante de Rydberg)
al = (k*e**2)/(hb*c) # ~1/137.035999084 (constante de estrutura fina)
a0=(hb**2)/(me*k*e**2) # ~ 0.52917710^-10 m (raio de Bohr)
ge = 2 # (fator giromagnetico do eletron)
gp = 5.58 # (fator giromagnetico do proton)
def id(n):
'''retorna a matriz identidade nxn'''
id = zeros(n,n)
for j in range(0,n):
id[j,j] = 1
return id
#id(2)
def pauli(j):
'''retorna as matrizes de Pauli'''
if j == 1:
return Matrix([[0,1],[1,0]])
elif j == 2:
return Matrix([[0,-1j],[1j,0]])
elif j == 3:
return Matrix([[1,0],[0,-1]])
#pauli(1), pauli(2), pauli(3)
def tr(A):
'''retorna o traço de uma matriz'''
d = A.shape[0]
tr = 0
for j in range(0,d):
tr += A[j,j]
return tr
#tr(pauli(1))
def comm(A,B):
'''retorna a função comutador'''
return A*B-B*A
#comm(pauli(1),pauli(2))
def acomm(A,B):
'''retorna a função anti-comutador'''
return A*B+B*A
#acomm(pauli(1),pauli(2))
def cb(n,j):
'''retorna um vetor da base padrão de C^n'''
vec = zeros(n,1)
vec[j] = 1
return vec
#cb(2,0)
def proj(psi):
'''retorna o projeto no vetor psi'''
d = psi.shape[0]
P = zeros(d,d)
for j in range(0,d):
for k in range(0,d):
P[j,k] = psi[j]*conjugate(psi[k])
return P
#proj(cb(2,0))
def bell(j,k):
if j == 0 and k == 0:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))+tp(cb(2,1),cb(2,1)))
elif j == 0 and k == 1:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))+tp(cb(2,1),cb(2,0)))
elif j == 1 and k == 0:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))-tp(cb(2,1),cb(2,0)))
elif j == 1 and k == 1:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))-tp(cb(2,1),cb(2,1)))
#bell(0,0), bell(0,1), bell(1,0), bell(1,1)
def inner_product(v,w):
d = len(v); ip = 0
for j in range(0,d):
ip += conjugate(v[j])*w[j]
return ip
#a,b,c,d = symbols("a b c d"); v = [b,a]; w = [c,d]; inner_product(v,w)
def norm(v):
d = len(v)
return sqrt(inner_product(v,v))
#v = [2,2]; norm(v)
def tp(x,y):
return tensorproduct(x,y)
A = tp(pauli(3),pauli(1)); A
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123456
from sklearn.datasets import make_blobs
features, labels = make_blobs(
n_samples=20,
centers=2,
center_box=(-1, 1),
cluster_std=0.1,
random_state=algorithm_globals.random_seed,
)
from qiskit import BasicAer
from qiskit.utils import QuantumInstance
sv_qi = QuantumInstance(
BasicAer.get_backend("statevector_simulator"),
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed,
)
from qiskit.circuit.library import ZZFeatureMap
from qiskit_machine_learning.kernels import QuantumKernel
feature_map = ZZFeatureMap(2)
previous_kernel = QuantumKernel(feature_map=feature_map, quantum_instance=sv_qi)
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=previous_kernel)
qsvc.fit(features, labels)
qsvc.score(features, labels)
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit.primitives import Sampler
fidelity = ComputeUncompute(sampler=Sampler())
from qiskit_machine_learning.kernels import FidelityQuantumKernel
feature_map = ZZFeatureMap(2)
new_kernel = FidelityQuantumKernel(feature_map=feature_map, fidelity=fidelity)
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=new_kernel)
qsvc.fit(features, labels)
qsvc.score(features, labels)
from qiskit import QuantumCircuit
from qiskit.circuit.library import RealAmplitudes
num_inputs = 2
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs, reps=1)
circuit = QuantumCircuit(num_inputs)
circuit.compose(feature_map, inplace=True)
circuit.compose(ansatz, inplace=True)
def parity(x):
return "{:b}".format(x).count("1") % 2
initial_point = algorithm_globals.random.random(ansatz.num_parameters)
from qiskit_machine_learning.neural_networks import CircuitQNN
circuit_qnn = CircuitQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=2,
quantum_instance=sv_qi,
)
from qiskit.algorithms.optimizers import COBYLA
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
classifier = NeuralNetworkClassifier(
neural_network=circuit_qnn,
loss="cross_entropy",
one_hot=True,
optimizer=COBYLA(maxiter=40),
initial_point=initial_point,
)
classifier.fit(features, labels)
classifier.score(features, labels)
from qiskit.primitives import Sampler
sampler = Sampler()
from qiskit_machine_learning.neural_networks import SamplerQNN
sampler_qnn = SamplerQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=2,
sampler=sampler,
)
classifier = NeuralNetworkClassifier(
neural_network=sampler_qnn,
loss="cross_entropy",
one_hot=True,
optimizer=COBYLA(maxiter=40),
initial_point=initial_point,
)
classifier.fit(features, labels)
classifier.score(features, labels)
import numpy as np
num_samples = 20
eps = 0.2
lb, ub = -np.pi, np.pi
features = (ub - lb) * np.random.rand(num_samples, 1) + lb
labels = np.sin(features[:, 0]) + eps * (2 * np.random.rand(num_samples) - 1)
from qiskit.circuit import Parameter
num_inputs = 1
feature_map = QuantumCircuit(1)
feature_map.ry(Parameter("input"), 0)
ansatz = QuantumCircuit(1)
ansatz.ry(Parameter("weight"), 0)
circuit = QuantumCircuit(num_inputs)
circuit.compose(feature_map, inplace=True)
circuit.compose(ansatz, inplace=True)
initial_point = algorithm_globals.random.random(ansatz.num_parameters)
from qiskit.opflow import PauliSumOp, StateFn
from qiskit_machine_learning.neural_networks import OpflowQNN
observable = PauliSumOp.from_list([("Z", 1)])
operator = StateFn(observable, is_measurement=True) @ StateFn(circuit)
opflow_qnn = OpflowQNN(
operator=operator,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
quantum_instance=sv_qi,
)
from qiskit.algorithms.optimizers import L_BFGS_B
from qiskit_machine_learning.algorithms import NeuralNetworkRegressor
regressor = NeuralNetworkRegressor(
neural_network=opflow_qnn,
optimizer=L_BFGS_B(maxiter=5),
initial_point=initial_point,
)
regressor.fit(features, labels)
regressor.score(features, labels)
from qiskit.primitives import Estimator
estimator = Estimator()
from qiskit_machine_learning.neural_networks import EstimatorQNN
estimator_qnn = EstimatorQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
estimator=estimator,
)
from qiskit.algorithms.optimizers import L_BFGS_B
from qiskit_machine_learning.algorithms import VQR
regressor = NeuralNetworkRegressor(
neural_network=estimator_qnn,
optimizer=L_BFGS_B(maxiter=5),
initial_point=initial_point,
)
regressor.fit(features, labels)
regressor.score(features, labels)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# import common packages
import numpy as np
from qiskit import Aer
# lib from Qiskit Aqua
from qiskit_aqua import Operator, QuantumInstance
from qiskit_aqua.algorithms import VQE, ExactEigensolver
from qiskit_aqua.components.optimizers import COBYLA
# lib from Qiskit Aqua Chemistry
from qiskit_chemistry import FermionicOperator
from qiskit_chemistry.drivers import PySCFDriver, UnitsType
from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock
# using driver to get fermionic Hamiltonian
# PySCF example
driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
molecule = driver.run()
# please be aware that the idx here with respective to original idx
freeze_list = [0]
remove_list = [-3, -2] # negative number denotes the reverse order
map_type = 'parity'
h1 = molecule.one_body_integrals
h2 = molecule.two_body_integrals
nuclear_repulsion_energy = molecule.nuclear_repulsion_energy
num_particles = molecule.num_alpha + molecule.num_beta
num_spin_orbitals = molecule.num_orbitals * 2
print("HF energy: {}".format(molecule.hf_energy - molecule.nuclear_repulsion_energy))
print("# of electrons: {}".format(num_particles))
print("# of spin orbitals: {}".format(num_spin_orbitals))
# prepare full idx of freeze_list and remove_list
# convert all negative idx to positive
remove_list = [x % molecule.num_orbitals for x in remove_list]
freeze_list = [x % molecule.num_orbitals for x in freeze_list]
# update the idx in remove_list of the idx after frozen, since the idx of orbitals are changed after freezing
remove_list = [x - len(freeze_list) for x in remove_list]
remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list]
freeze_list += [x + molecule.num_orbitals for x in freeze_list]
# prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian
# and if PARITY mapping is selected, reduction qubits
energy_shift = 0.0
qubit_reduction = True if map_type == 'parity' else False
ferOp = FermionicOperator(h1=h1, h2=h2)
if len(freeze_list) > 0:
ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list)
num_spin_orbitals -= len(freeze_list)
num_particles -= len(freeze_list)
if len(remove_list) > 0:
ferOp = ferOp.fermion_mode_elimination(remove_list)
num_spin_orbitals -= len(remove_list)
qubitOp = ferOp.mapping(map_type=map_type, threshold=0.00000001)
qubitOp = qubitOp.two_qubit_reduced_operator(num_particles) if qubit_reduction else qubitOp
qubitOp.chop(10**-10)
print(qubitOp.print_operators())
print(qubitOp)
# Using exact eigensolver to get the smallest eigenvalue
exact_eigensolver = ExactEigensolver(qubitOp, k=1)
ret = exact_eigensolver.run()
print('The computed energy is: {:.12f}'.format(ret['eigvals'][0].real))
print('The total ground state energy is: {:.12f}'.format(ret['eigvals'][0].real + energy_shift + nuclear_repulsion_energy))
# from qiskit import IBMQ
# IBMQ.load_accounts()
backend = Aer.get_backend('statevector_simulator')
# setup COBYLA optimizer
max_eval = 200
cobyla = COBYLA(maxiter=max_eval)
# setup HartreeFock state
HF_state = HartreeFock(qubitOp.num_qubits, num_spin_orbitals, num_particles, map_type,
qubit_reduction)
# setup UCCSD variational form
var_form = UCCSD(qubitOp.num_qubits, depth=1,
num_orbitals=num_spin_orbitals, num_particles=num_particles,
active_occupied=[0], active_unoccupied=[0, 1],
initial_state=HF_state, qubit_mapping=map_type,
two_qubit_reduction=qubit_reduction, num_time_slices=1)
# setup VQE
vqe = VQE(qubitOp, var_form, cobyla, 'matrix')
quantum_instance = QuantumInstance(backend=backend)
results = vqe.run(quantum_instance)
print('The computed ground state energy is: {:.12f}'.format(results['eigvals'][0]))
print('The total ground state energy is: {:.12f}'.format(results['eigvals'][0] + energy_shift + nuclear_repulsion_energy))
print("Parameters: {}".format(results['opt_params']))
|
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
|
gustavomirapalheta
|
# Setup básico
!pip install qiskit -q
!pip install qiskit[visualization] -q
import qiskit as qk
!pip install qiskit-aer -q
import qiskit_aer as qk_aer
import numpy as np
np.set_printoptions(precision=3, suppress=True)
from matplotlib import pyplot as plt
%matplotlib inline
import pandas as pd
import sklearn as sk
import qiskit as qk
qc = qk.QuantumCircuit(3,3)
qc.initialize(1,[0])
qc.barrier()
qc.h(1)
qc.cx(1,2)
qc.barrier()
qc.cx(0,1)
qc.h(0)
qc.barrier()
qc.measure([0,1],[0,1])
display(qc.draw('mpl', style='clifford', scale=1))
import sympy as sp
a, b = sp.symbols('a b')
q0 = sp.Matrix([[a, b]]); display(q0); print(" ")
q1 = sp.Matrix([[1, 0]]); display(q1); print(" ")
q2 = sp.Matrix([[1, 0]]); display(q2);
from sympy import kronecker_product as kron
e0 = kron(q0, kron(q1,q2)); e0
I1 = sp.Matrix([[1,0],
[0,1]])
H1 = sp.Matrix([[1, 1],
[1,-1]])
IHI = kron(I1,kron(H1,I1))
CNOT12 = sp.Matrix([[1,0,0,0],
[0,1,0,0],
[0,0,0,1],
[0,0,1,0]])
IC12 = kron(I1,CNOT12)
e1 = e0*IHI*IC12; e1
e2 = e1*kron(CNOT12,I1)*kron(H1,kron(I1,I1)); e2
|
https://github.com/HQSquantumsimulations/qoqo-qiskit
|
HQSquantumsimulations
|
# Copyright 2022-2023 Ohad Lev.
# 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,
# or in the root directory of this package("LICENSE.txt").
# 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.
"""
`SATInterface` class.
"""
import os
import json
from typing import List, Tuple, Union, Optional, Dict, Any
from sys import stdout
from datetime import datetime
from hashlib import sha256
from qiskit import transpile, QuantumCircuit, qpy
from qiskit.result.counts import Counts
from qiskit.visualization.circuit.text import TextDrawing
from qiskit.providers.backend import Backend
from qiskit.transpiler.passes import RemoveBarriers
from IPython import display
from matplotlib.figure import Figure
from sat_circuits_engine.util import timer_dec, timestamp, flatten_circuit
from sat_circuits_engine.util.settings import DATA_PATH, TRANSPILE_KWARGS
from sat_circuits_engine.circuit import GroverConstraintsOperator, SATCircuit
from sat_circuits_engine.constraints_parse import ParsedConstraints
from sat_circuits_engine.interface.circuit_decomposition import decompose_operator
from sat_circuits_engine.interface.counts_visualization import plot_histogram
from sat_circuits_engine.interface.translator import ConstraintsTranslator
from sat_circuits_engine.classical_processing import (
find_iterations_unknown,
calc_iterations,
ClassicalVerifier,
)
from sat_circuits_engine.interface.interactive_inputs import (
interactive_operator_inputs,
interactive_solutions_num_input,
interactive_run_input,
interactive_backend_input,
interactive_shots_input,
)
# Local globlas for visualization of charts and diagrams
IFRAME_WIDTH = "100%"
IFRAME_HEIGHT = "700"
class SATInterface:
"""
An interface for building, running and mining data from n-SAT problems quantum circuits.
There are 2 options to use this class:
(1) Using an interactive interface (intuitive but somewhat limited) - for this
just initiate a bare instance of this class: `SATInterface()`.
(2) Using the API defined by this class, that includes the following methods:
* The following descriptions are partial, for full annotations see the methods' docstrings.
- `__init__`: an instance of `SATInterface must be initiated with exactly 1 combination:
(a) (high_level_constraints_string + high_level_vars) - for constraints
in a high-level format.
(b) (num_input_qubits + constraints_string) - for constraints
in a low-level foramt.
* For formats annotations see `constriants_format.ipynb` in the main directory.
- `obtain_grover_operator`: obtains the suitable grover operator for the constraints.
- `save_display_grover_operator`: saves and displays data generated
by the `obtain_grover_operator` method.
- `obtain_overall_circuit`: obtains the suitable overall SAT circuit.
- `save_display_overall_circuit: saves and displays data generated
by the `obtain_overall_circuit` method.
- `run_overall_circuit`: executes the overall SAT circuit.
- `save_display_results`: saves and displays data generated
by the `run_overall_circuit` method.
It is very recommended to go through `demos.ipynb` that demonstrates the various optional uses
of this class, in addition to reading `constraints_format.ipynb`, which is a must for using
this package properly. Both notebooks are in ther main directory.
"""
def __init__(
self,
num_input_qubits: Optional[int] = None,
constraints_string: Optional[str] = None,
high_level_constraints_string: Optional[str] = None,
high_level_vars: Optional[Dict[str, int]] = None,
name: Optional[str] = None,
save_data: Optional[bool] = True,
) -> None:
"""
Accepts the combination of paramters:
(high_level_constraints_string + high_level_vars) or (num_input_qubits + constraints_string).
Exactly one combination is accepted.
In other cases either an iteractive user interface will be called to take user's inputs,
or an exception will be raised due to misuse of the API.
Args:
num_input_qubits (Optional[int] = None): number of input qubits.
constraints_string (Optional[str] = None): a string of constraints in a low-level format.
high_level_constraints_string (Optional[str] = None): a string of constraints in a
high-level format.
high_level_vars (Optional[Dict[str, int]] = None): a dictionary that configures
the high-level variables - keys are names and values are bits-lengths.
name (Optional[str] = None): a name for this object, if None than the
generic name "SAT" is given automatically.
save_data (Optional[bool] = True): if True, saves all data and metadata generated by this
class to a unique data folder (by using the `save_XXX` methods of this class).
Raises:
SyntaxError - if a forbidden combination of arguments has been provided.
"""
if name is None:
name = "SAT"
self.name = name
# Creating a directory for data to be saved
if save_data:
self.time_created = timestamp(datetime.now())
self.dir_path = f"{DATA_PATH}{self.time_created}_{self.name}/"
os.mkdir(self.dir_path)
print(f"Data will be saved into '{self.dir_path}'.")
# Initial metadata, more to be added by this class' `save_XXX` methods
self.metadata = {
"name": self.name,
"datetime": self.time_created,
"num_input_qubits": num_input_qubits,
"constraints_string": constraints_string,
"high_level_constraints_string": high_level_constraints_string,
"high_level_vars": high_level_vars,
}
self.update_metadata()
# Identifying user's platform, for visualization purposes
self.identify_platform()
# In the case of low-level constraints format, that is the default value
self.high_to_low_map = None
# Case A - interactive interface
if (num_input_qubits is None or constraints_string is None) and (
high_level_constraints_string is None or high_level_vars is None
):
self.interactive_interface()
# Case B - API
else:
self.high_level_constraints_string = high_level_constraints_string
self.high_level_vars = high_level_vars
# Case B.1 - high-level format constraints inputs
if num_input_qubits is None or constraints_string is None:
self.num_input_qubits = sum(self.high_level_vars.values())
self.high_to_low_map, self.constraints_string = ConstraintsTranslator(
self.high_level_constraints_string, self.high_level_vars
).translate()
# Case B.2 - low-level format constraints inputs
elif num_input_qubits is not None and constraints_string is not None:
self.num_input_qubits = num_input_qubits
self.constraints_string = constraints_string
# Misuse
else:
raise SyntaxError(
"SATInterface accepts the combination of paramters:"
"(high_level_constraints_string + high_level_vars) or "
"(num_input_qubits + constraints_string). "
"Exactly one combination is accepted, not both."
)
self.parsed_constraints = ParsedConstraints(
self.constraints_string, self.high_level_constraints_string
)
def update_metadata(self, update_metadata: Optional[Dict[str, Any]] = None) -> None:
"""
Updates the metadata file (in the unique data folder of a given `SATInterface` instance).
Args:
update_metadata (Optional[Dict[str, Any]] = None):
- If None - just dumps `self.metadata` into the metadata JSON file.
- If defined - updates the `self.metadata` attribute and then dumps it.
"""
if update_metadata is not None:
self.metadata.update(update_metadata)
with open(f"{self.dir_path}metadata.json", "w") as metadata_file:
json.dump(self.metadata, metadata_file, indent=4)
def identify_platform(self) -> None:
"""
Identifies user's platform.
Writes True to `self.jupyter` for Jupyter notebook, False for terminal.
"""
# If True then the platform is a terminal/command line/shell
if stdout.isatty():
self.jupyter = False
# If False, we assume the platform is a Jupyter notebook
else:
self.jupyter = True
def output_to_platform(
self,
*,
title: str,
output_terminal: Union[TextDrawing, str],
output_jupyter: Union[Figure, str],
display_both_on_jupyter: Optional[bool] = False,
) -> None:
"""
Displays output to user's platform.
Args:
title (str): a title for the output.
output_terminal (Union[TextDrawing, str]): text to print for a terminal platform.
output_jupyter: (Union[Figure, str]): objects to display for a Jupyter notebook platform.
can handle `Figure` matplotlib objects or strings of paths to IFrame displayable file,
e.g PDF files.
display_both_on_jupyter (Optional[bool] = False): if True, displays both
`output_terminal` and `output_jupyter` in a Jupyter notebook platform.
Raises:
TypeError - in the case of misusing the `output_jupyter` argument.
"""
print()
print(title)
if self.jupyter:
if isinstance(output_jupyter, str):
display.display(display.IFrame(output_jupyter, width=IFRAME_WIDTH, height=IFRAME_HEIGHT))
elif isinstance(output_jupyter, Figure):
display.display(output_jupyter)
else:
raise TypeError("output_jupyter must be an str (path to image file) or a Figure object.")
if display_both_on_jupyter:
print(output_terminal)
else:
print(output_terminal)
def interactive_interface(self) -> None:
"""
An interactive CLI that allows exploiting most (but not all) of the package's features.
Uses functions of the form `interactive_XXX_inputs` from the `interactive_inputs.py` module.
Divided into 3 main stages:
1. Obtaining Grover's operator for the SAT problem.
2. Obtaining the overall SAT cirucit.
3. Executing the circuit and parsing the results.
The interface is built in a modular manner such that a user can halt at any stage.
The defualt settings for the interactive user intreface are:
1. `name = "SAT"`.
2. `save_data = True`.
3. `display = True`.
4. `transpile_kwargs = {'basis_gates': ['u', 'cx'], 'optimization_level': 3}`.
5. Backends are limited to those defined in the global-constant-like function `BACKENDS`:
- Those are the local `aer_simulator` and the remote `ibmq_qasm_simulator` for now.
Due to these default settings the interactive CLI is somewhat restrictive,
for full flexibility a user should use the API and not the CLI.
"""
# Handling operator part
operator_inputs = interactive_operator_inputs()
self.num_input_qubits = operator_inputs["num_input_qubits"]
self.high_to_low_map = operator_inputs["high_to_low_map"]
self.constraints_string = operator_inputs["constraints_string"]
self.high_level_constraints_string = operator_inputs["high_level_constraints_string"]
self.high_level_vars = operator_inputs["high_level_vars"]
self.parsed_constraints = ParsedConstraints(
self.constraints_string, self.high_level_constraints_string
)
self.update_metadata(
{
"num_input_qubits": self.num_input_qubits,
"constraints_string": self.constraints_string,
"high_level_constraints_string": self.high_level_constraints_string,
"high_level_vars": self.high_level_vars,
}
)
obtain_grover_operator_output = self.obtain_grover_operator()
self.save_display_grover_operator(obtain_grover_operator_output)
# Handling overall circuit part
solutions_num = interactive_solutions_num_input()
if solutions_num is not None:
backend = None
if solutions_num == -1:
backend = interactive_backend_input()
overall_circuit_data = self.obtain_overall_sat_circuit(
obtain_grover_operator_output["operator"], solutions_num, backend
)
self.save_display_overall_circuit(overall_circuit_data)
# Handling circuit execution part
if interactive_run_input():
if backend is None:
backend = interactive_backend_input()
shots = interactive_shots_input()
counts_parsed = self.run_overall_sat_circuit(
overall_circuit_data["circuit"], backend, shots
)
self.save_display_results(counts_parsed)
print()
print(f"Done saving data into '{self.dir_path}'.")
def obtain_grover_operator(
self, transpile_kwargs: Optional[Dict[str, Any]] = None
) -> Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]:
"""
Obtains the suitable `GroverConstraintsOperator` object for the constraints,
decomposes it using the `circuit_decomposition.py` module and transpiles it
according to `transpile_kwargs`.
Args:
transpile_kwargs (Optional[Dict[str, Any]]): kwargs for Qiskit's transpile function.
The defualt is set to the global constant `TRANSPILE_KWARGS`.
Returns:
(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit, Dict[str, List[int]]]]):
- 'operator' (GroverConstraintsOperator):the high-level blocks operator.
- 'decomposed_operator' (QuantumCircuit): decomposed to building-blocks operator.
* For annotations regarding the decomposition method see the
`circuit_decomposition` module.
- 'transpiled_operator' (QuantumCircuit): the transpiled operator.
*** The high-level operator and the decomposed operator are generated with barriers
between constraints as default for visualizations purposes. The barriers are stripped
off before transpiling so the the transpiled operator object contains no barriers. ***
- 'high_level_to_bit_indexes_map' (Optional[Dict[str, List[int]]] = None):
A map of high-level variables with their allocated bit-indexes in the input register.
"""
print()
print(
"The system synthesizes and transpiles a Grover's "
"operator for the given constraints. Please wait.."
)
if transpile_kwargs is None:
transpile_kwargs = TRANSPILE_KWARGS
self.transpile_kwargs = transpile_kwargs
operator = GroverConstraintsOperator(
self.parsed_constraints, self.num_input_qubits, insert_barriers=True
)
decomposed_operator = decompose_operator(operator)
no_baerriers_operator = RemoveBarriers()(operator)
transpiled_operator = transpile(no_baerriers_operator, **transpile_kwargs)
print("Done.")
return {
"operator": operator,
"decomposed_operator": decomposed_operator,
"transpiled_operator": transpiled_operator,
"high_level_to_bit_indexes_map": self.high_to_low_map,
}
def save_display_grover_operator(
self,
obtain_grover_operator_output: Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]],
display: Optional[bool] = True,
) -> None:
"""
Handles saving and displaying data generated by the `self.obtain_grover_operator` method.
Args:
obtain_grover_operator_output(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]):
the dictionary returned upon calling the `self.obtain_grover_operator` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
# Creating a directory to save operator's data
operator_dir_path = f"{self.dir_path}grover_operator/"
os.mkdir(operator_dir_path)
# Titles for displaying objects, by order of `obtain_grover_operator_output`
titles = [
"The operator diagram - high level blocks:",
"The operator diagram - decomposed:",
f"The transpiled operator diagram saved into '{operator_dir_path}'.\n"
f"It's not presented here due to its complexity.\n"
f"Please note that barriers appear in the high-level diagrams above only for convenient\n"
f"visual separation between constraints.\n"
f"Before transpilation all barriers are removed to avoid redundant inefficiencies.",
]
for index, (op_name, op_obj) in enumerate(obtain_grover_operator_output.items()):
# Generic path and name for files to be saved
files_path = f"{operator_dir_path}{op_name}"
# Generating a circuit diagrams figure
figure_path = f"{files_path}.pdf"
op_obj.draw("mpl", filename=figure_path, fold=-1)
# Generating a QPY serialization file for the circuit object
qpy_file_path = f"{files_path}.qpy"
with open(qpy_file_path, "wb") as qpy_file:
qpy.dump(op_obj, qpy_file)
# Original high-level operator and decomposed operator
if index < 2 and display:
# Displaying to user
self.output_to_platform(
title=titles[index], output_terminal=op_obj.draw("text"), output_jupyter=figure_path
)
# Transpiled operator
elif index == 2:
# Output to user, not including the circuit diagram
print()
print(titles[index])
print()
print(f"The transpilation kwargs are: {self.transpile_kwargs}.")
transpiled_operator_depth = op_obj.depth()
transpiled_operator_gates_count = op_obj.count_ops()
print(f"Transpiled operator depth: {transpiled_operator_depth}.")
print(f"Transpiled operator gates count: {transpiled_operator_gates_count}.")
print(f"Total number of qubits: {op_obj.num_qubits}.")
# Generating QASM 2.0 file only for the (flattened = no registers) tranpsiled operator
qasm_file_path = f"{files_path}.qasm"
flatten_circuit(op_obj).qasm(filename=qasm_file_path)
# Index 3 is 'high_level_to_bit_indexes_map' so it's time to break from the loop
break
# Mapping from high-level variables to bit-indexes will be displayed as well
mapping = obtain_grover_operator_output["high_level_to_bit_indexes_map"]
if mapping:
print()
print(f"The high-level variables mapping to bit-indexes:\n{mapping}")
print()
print(
f"Saved into '{operator_dir_path}':\n",
" Circuit diagrams for all levels.\n",
" QPY serialization exports for all levels.\n",
" QASM 2.0 export only for the transpiled level.",
)
with open(f"{operator_dir_path}operator.qpy", "rb") as qpy_file:
operator_qpy_sha256 = sha256(qpy_file.read()).hexdigest()
self.update_metadata(
{
"high_level_to_bit_indexes_map": self.high_to_low_map,
"transpile_kwargs": self.transpile_kwargs,
"transpiled_operator_depth": transpiled_operator_depth,
"transpiled_operator_gates_count": transpiled_operator_gates_count,
"operator_qpy_sha256": operator_qpy_sha256,
}
)
def obtain_overall_sat_circuit(
self,
grover_operator: GroverConstraintsOperator,
solutions_num: int,
backend: Optional[Backend] = None,
) -> Dict[str, SATCircuit]:
"""
Obtains the suitable `SATCircuit` object (= the overall SAT circuit) for the SAT problem.
Args:
grover_operator (GroverConstraintsOperator): Grover's operator for the SAT problem.
solutions_num (int): number of solutions for the SAT problem. In the case the number
of solutions is unknown, specific negative values are accepted:
* '-1' - for launching a classical iterative stochastic process that finds an adequate
number of iterations - by calling the `find_iterations_unknown` function (see its
docstrings for more information).
* '-2' - for generating a dynamic circuit that iterates over Grover's iterator until
a solution is obtained, using weak measurements. TODO - this feature isn't ready yet.
backend (Optional[Backend] = None): in the case of a '-1' value given to `solutions_num`,
a backend object to execute the depicted iterative prcess upon should be provided.
Returns:
(Dict[str, SATCircuit]):
- 'circuit' key for the overall SAT circuit.
- 'concise_circuit' key for the overall SAT circuit, with only 1 iteration over Grover's
iterator (operator + diffuser). Useful for visualization purposes.
*** The concise circuit is generated with barriers between segments as default
for visualizations purposes. In the actual circuit there no barriers. ***
"""
# -1 = Unknown number of solutions - iterative stochastic process
print()
if solutions_num == -1:
assert backend is not None, "Need to specify a backend if `solutions_num == -1`."
print("Please wait while the system checks various solutions..")
circuit, iterations = find_iterations_unknown(
self.num_input_qubits,
grover_operator,
self.parsed_constraints,
precision=10,
backend=backend,
)
print()
print(f"An adequate number of iterations found = {iterations}.")
# -2 = Unknown number of solutions - implement a dynamic circuit
# TODO this feature isn't fully implemented yet
elif solutions_num == -2:
print("The system builds a dynamic circuit..")
circuit = SATCircuit(self.num_input_qubits, grover_operator, iterations=None)
circuit.add_input_reg_measurement()
iterations = None
# Known number of solutions
else:
print("The system builds the overall circuit..")
iterations = calc_iterations(self.num_input_qubits, solutions_num)
print(f"\nFor {solutions_num} solutions, {iterations} iterations needed.")
circuit = SATCircuit(
self.num_input_qubits, grover_operator, iterations, insert_barriers=False
)
circuit.add_input_reg_measurement()
self.iterations = iterations
# Obtaining a SATCircuit object with one iteration for concise representation
concise_circuit = SATCircuit(
self.num_input_qubits, grover_operator, iterations=1, insert_barriers=True
)
concise_circuit.add_input_reg_measurement()
return {"circuit": circuit, "concise_circuit": concise_circuit}
def save_display_overall_circuit(
self, obtain_overall_sat_circuit_output: Dict[str, SATCircuit], display: Optional[bool] = True
) -> None:
"""
Handles saving and displaying data generated by the `self.obtain_overall_sat_circuit` method.
Args:
obtain_overall_sat_circuit_output(Dict[str, SATCircuit]):
the dictionary returned upon calling the `self.obtain_overall_sat_circuit` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
circuit = obtain_overall_sat_circuit_output["circuit"]
concise_circuit = obtain_overall_sat_circuit_output["concise_circuit"]
# Creating a directory to save overall circuit's data
overall_circuit_dir_path = f"{self.dir_path}overall_circuit/"
os.mkdir(overall_circuit_dir_path)
# Generating a figure of the overall SAT circuit with just 1 iteration (i.e "concise")
concise_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_1_iteration.pdf"
concise_circuit.draw("mpl", filename=concise_circuit_fig_path, fold=-1)
# Displaying the concise circuit to user
if display:
if self.iterations:
self.output_to_platform(
title=(
f"The high level circuit contains {self.iterations}"
f" iterations of the following form:"
),
output_terminal=concise_circuit.draw("text"),
output_jupyter=concise_circuit_fig_path,
)
# Dynamic circuit case - TODO NOT FULLY IMPLEMENTED YET
else:
dynamic_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_dynamic.pdf"
circuit.draw("mpl", filename=dynamic_circuit_fig_path, fold=-1)
self.output_to_platform(
title="The dynamic circuit diagram:",
output_terminal=circuit.draw("text"),
output_jupyter=dynamic_circuit_fig_path,
)
if self.iterations:
transpiled_overall_circuit = transpile(flatten_circuit(circuit), **self.transpile_kwargs)
print()
print(f"The transpilation kwargs are: {self.transpile_kwargs}.")
transpiled_overall_circuit_depth = transpiled_overall_circuit.depth()
transpiled_overall_circuit_gates_count = transpiled_overall_circuit.count_ops()
print(f"Transpiled overall-circuit depth: {transpiled_overall_circuit_depth}.")
print(f"Transpiled overall-circuit gates count: {transpiled_overall_circuit_gates_count}.")
print(f"Total number of qubits: {transpiled_overall_circuit.num_qubits}.")
print()
print("Exporting the full overall SAT circuit object..")
export_files_path = f"{overall_circuit_dir_path}overall_circuit"
with open(f"{export_files_path}.qpy", "wb") as qpy_file:
qpy.dump(circuit, qpy_file)
if self.iterations:
transpiled_overall_circuit.qasm(filename=f"{export_files_path}.qasm")
print()
print(
f"Saved into '{overall_circuit_dir_path}':\n",
" A concised (1 iteration) circuit diagram of the high-level overall SAT circuit.\n",
" QPY serialization export for the full overall SAT circuit object.",
)
if self.iterations:
print(" QASM 2.0 export for the transpiled full overall SAT circuit object.")
metadata_update = {
"num_total_qubits": circuit.num_qubits,
"num_iterations": circuit.iterations,
}
if self.iterations:
metadata_update["transpiled_overall_circuit_depth"] = (transpiled_overall_circuit_depth,)
metadata_update[
"transpiled_overall_circuit_gates_count"
] = transpiled_overall_circuit_gates_count
self.update_metadata(metadata_update)
@timer_dec("Circuit simulation execution time = ")
def run_overall_sat_circuit(
self, circuit: QuantumCircuit, backend: Backend, shots: int
) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]:
"""
Executes a `circuit` on `backend` transpiled w.r.t backend, `shots` times.
Args:
circuit (QuantumCircuit): `QuantumCircuit` object or child-object (a.k.a `SATCircuit`)
to execute.
backend (Backend): backend to execute `circuit` upon.
shots (int): number of execution shots.
Returns:
(Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]):
dict object returned by `self.parse_counts` - see this method's docstrings for annotations.
"""
# Defines also instance attributes to use in other methods
self.backend = backend
self.shots = shots
print()
print(f"The system is running the circuit {shots} times on {backend}, please wait..")
print("This process might take a while.")
job = backend.run(transpile(circuit, backend), shots=shots)
counts = job.result().get_counts()
print("Done.")
parsed_counts = self.parse_counts(counts)
return parsed_counts
def parse_counts(
self, counts: Counts
) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]:
"""
Parses a `Counts` object into several desired datas (see 'Returns' section).
Args:
counts (Counts): the `Counts` object to parse.
Returns:
(Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]):
'counts' (Counts) - the original `Counts` object.
'counts_sorted' (List[Tuple[Union[str, int]]]) - results sorted in a descending order.
'distilled_solutions' (List[str]): list of solutions (bitstrings).
'high_level_vars_values' (List[Dict[str, int]]): list of solutions (each solution is a
dictionary with variable-names as keys and their integer values as values).
"""
# Sorting results in an a descending order
counts_sorted = sorted(counts.items(), key=lambda x: x[1], reverse=True)
# Generating a set of distilled verified-only solutions
verifier = ClassicalVerifier(self.parsed_constraints)
distilled_solutions = set()
for count_item in counts_sorted:
if not verifier.verify(count_item[0]):
break
distilled_solutions.add(count_item[0])
# In the case of high-level format in use, translating `distilled_solutions` into integer values
high_level_vars_values = None
if self.high_level_constraints_string and self.high_level_vars:
# Container for dictionaries with variables integer values
high_level_vars_values = []
for solution in distilled_solutions:
# Keys are variable-names and values are their integer values
solution_vars = {}
for var, bits_bundle in self.high_to_low_map.items():
reversed_solution = solution[::-1]
var_bitstring = ""
for bit_index in bits_bundle:
var_bitstring += reversed_solution[bit_index]
# Translating to integer value
solution_vars[var] = int(var_bitstring, 2)
high_level_vars_values.append(solution_vars)
return {
"counts": counts,
"counts_sorted": counts_sorted,
"distilled_solutions": distilled_solutions,
"high_level_vars_values": high_level_vars_values,
}
def save_display_results(
self,
run_overall_sat_circuit_output: Dict[
str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]
],
display: Optional[bool] = True,
) -> None:
"""
Handles saving and displaying data generated by the `self.run_overall_sat_circuit` method.
Args:
run_overall_sat_circuit_output (Dict[str, Union[Counts, List[Tuple[Union[str, int]]],
List[str], List[Dict[str, int]]]]): the dictionary returned upon calling
the `self.run_overall_sat_circuit` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
counts = run_overall_sat_circuit_output["counts"]
counts_sorted = run_overall_sat_circuit_output["counts_sorted"]
distilled_solutions = run_overall_sat_circuit_output["distilled_solutions"]
high_level_vars_values = run_overall_sat_circuit_output["high_level_vars_values"]
# Creating a directory to save results data
results_dir_path = f"{self.dir_path}results/"
os.mkdir(results_dir_path)
# Defining custom dimensions for the custom `plot_histogram` of this package
histogram_fig_width = max((len(counts) * self.num_input_qubits * (10 / 72)), 7)
histogram_fig_height = 5
histogram_figsize = (histogram_fig_width, histogram_fig_height)
histogram_path = f"{results_dir_path}histogram.pdf"
plot_histogram(counts, figsize=histogram_figsize, sort="value_desc", filename=histogram_path)
if display:
# Basic output text
output_text = (
f"All counts:\n{counts_sorted}\n"
f"\nDistilled solutions ({len(distilled_solutions)} total):\n"
f"{distilled_solutions}"
)
# Additional outputs for a high-level constraints format
if high_level_vars_values:
# Mapping from high-level variables to bit-indexes will be displayed as well
output_text += (
f"\n\nThe high-level variables mapping to bit-indexes:" f"\n{self.high_to_low_map}"
)
# Actual integer solutions will be displayed as well
additional_text = ""
for solution_index, solution in enumerate(high_level_vars_values):
additional_text += f"Solution {solution_index + 1}: "
for var_index, (var, value) in enumerate(solution.items()):
additional_text += f"{var} = {value}"
if var_index != len(solution) - 1:
additional_text += ", "
else:
additional_text += "\n"
output_text += f"\n\nHigh-level format solutions: \n{additional_text}"
self.output_to_platform(
title=f"The results for {self.shots} shots are:",
output_terminal=output_text,
output_jupyter=histogram_path,
display_both_on_jupyter=True,
)
results_dict = {
"high_level_to_bit_indexes_map": self.high_to_low_map,
"solutions": list(distilled_solutions),
"high_level_solutions": high_level_vars_values,
"counts": counts_sorted,
}
with open(f"{results_dir_path}results.json", "w") as results_file:
json.dump(results_dict, results_file, indent=4)
self.update_metadata(
{
"num_solutions": len(distilled_solutions),
"backend": str(self.backend),
"shots": self.shots,
}
)
|
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/MonitSharma/Learn-Quantum-Computing-with-Qiskit
|
MonitSharma
|
# Importing standard Qiskit libraries:
from qiskit import *
from qiskit.providers.ibmq import least_busy
from qiskit.tools.jupyter import *
from qiskit.visualization import *
%matplotlib inline
circuit = QuantumCircuit(7+1,7)
circuit.draw("mpl")
circuit.h([0,1,2,3,4,5,6])
circuit.x(7)
circuit.h(7)
circuit.barrier()
circuit.draw("mpl")
circuit.cx(6,7)
circuit.cx(3,7)
circuit.cx(2,7)
circuit.cx(0,7)
circuit.barrier()
circuit.draw("mpl")
circuit.h([0,1,2,3,4,5,6])
circuit.barrier()
circuit.measure([0,1,2,3,4,5,6],[0,1,2,3,4,5,6])
circuit.draw("mpl")
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend = simulator, shots = 1).result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
secret_number = input("Input a Binary String of your choice ")
## Not more than 4 bits if you want to run on a real quantum device later on
bv_circ = QuantumCircuit(len(secret_number)+1,len(secret_number))
bv_circ.h(range(len(secret_number)))
bv_circ.x(len(secret_number))
bv_circ.h(len(secret_number))
bv_circ.barrier()
bv_circ.draw("mpl")
for digit, query in enumerate(reversed(secret_number)):
if query == "1":
bv_circ.cx(digit, len(secret_number))
bv_circ.barrier()
bv_circ.draw("mpl")
bv_circ.h(range(len(secret_number)))
bv_circ.barrier()
bv_circ.measure(range(len(secret_number)),range(len(secret_number)))
bv_circ.draw("mpl")
simulator = Aer.get_backend("qasm_simulator")
result = execute(bv_circ, backend = simulator, shots = 1).result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
# Enabling our IBMQ accounts to get the least busy backend device with less than or equal to 5 qubits
IBMQ.enable_account('IBM Q API Token')
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
x.configuration().n_qubits >= 2 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
exp = execute(bv_circ, backend, shots = 1024)
result_exp = exp.result()
counts_exp = result_exp.get_counts()
plot_histogram([counts_exp,counts])
|
https://github.com/hrahman12/IBM-Variational-Algorithm-Design-Challenge
|
hrahman12
|
from qiskit.circuit.library import TwoLocal
from qc_grader.challenges.algorithm_design import grade_problem_2a
# Create a TwoLocal circuit with 3 qubits, using Y-rotations ("ry") and controlled-Z gates ("cz")
reference_operator = TwoLocal(3, "ry", "cz", entanglement="linear", reps=1)
# Define specific parameter values for the reference operator
# We can choose any values we want, for example, [0.1, 0.2, 0.3, 0.4, 0.5, 0.6] for the parameter list
parameters = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
# Assign the specific parameter values to the reference_operator
reference_operator = reference_operator.assign_parameters(parameters)
# Grade the answer
grade_problem_2a(reference_operator)
from qiskit.circuit.library import TwoLocal
from qc_grader.challenges.algorithm_design import grade_problem_2b
# Use the reference operator from Problem 2a
# Make sure you have defined and assigned the reference_operator as done in Problem 2a
# Create a TwoLocal circuit with 3 qubits, using Y-rotations ("ry") and controlled-Z gates ("cz")
reference_operator = TwoLocal(3, "ry", "cz", entanglement="linear", reps=1)
# Define specific parameter values for the reference operator
# We can choose any values we want, for example, [0.1, 0.2, 0.3, 0.4, 0.5, 0.6] for the parameter list
parameters = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
# Assign the specific parameter values to the reference_operator
reference_operator = reference_operator.assign_parameters(parameters)
# Define the provided variational_form
variational_form = TwoLocal(3, rotation_blocks=["rx", "rz"], entanglement_blocks="cx")
# Create the ansatz by composing the reference_operator with the variational_form
ansatz = reference_operator.compose(variational_form)
# Grade the answer
grade_problem_2b(reference_operator, variational_form, ansatz)
|
https://github.com/alexandrepdumont/Quantum-Random-Number-Generator
|
alexandrepdumont
|
#!/usr/bin/env python
# coding: utf-8
import numpy as np
from qiskit import *
get_ipython().run_line_magic('matplotlib', 'inline')
num_of_bits = 64
recorded_response = np.zeros(num_of_bits)
for i in range(num_of_bits):
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.measure(q, c)
backend = BasicAer.get_backend('statevector_simulator')
job_sim = execute(qc, backend, shots=1)
sim_result = job_sim.result()
outputstate = sim_result.get_statevector(qc)
recorded_response[i] = int(outputstate[0].real)
print((recorded_response))
res = int("".join(str(int(x)) for x in recorded_response), 2)
print(res)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
qc.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
def udd10_pos(j):
return np.sin(np.pi*j/(2*10 + 2))**2
with pulse.build() as udd_sched:
pulse.play(x90, d0)
with pulse.align_func(duration=300, func=udd10_pos):
for _ in range(10):
pulse.play(x180, d0)
pulse.play(x90, d0)
udd_sched.draw()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for the converters."""
import math
import unittest
import numpy as np
from qiskit.converters import circuit_to_instruction
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit, Instruction
from qiskit.circuit import Parameter
from qiskit.quantum_info import Operator
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
class TestCircuitToInstruction(QiskitTestCase):
"""Test Circuit to Instruction."""
def test_flatten_circuit_registers(self):
"""Check correct flattening"""
qr1 = QuantumRegister(4, "qr1")
qr2 = QuantumRegister(3, "qr2")
qr3 = QuantumRegister(3, "qr3")
cr1 = ClassicalRegister(4, "cr1")
cr2 = ClassicalRegister(1, "cr2")
circ = QuantumCircuit(qr1, qr2, qr3, cr1, cr2)
circ.cx(qr1[1], qr2[2])
circ.measure(qr3[0], cr2[0])
inst = circuit_to_instruction(circ)
q = QuantumRegister(10, "q")
c = ClassicalRegister(5, "c")
self.assertEqual(inst.definition[0].qubits, (q[1], q[6]))
self.assertEqual(inst.definition[1].qubits, (q[7],))
self.assertEqual(inst.definition[1].clbits, (c[4],))
def test_flatten_registers_of_circuit_single_bit_cond(self):
"""Check correct mapping of registers gates conditioned on single classical bits."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(3, "qr2")
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
circ = QuantumCircuit(qr1, qr2, cr1, cr2)
circ.h(qr1[0]).c_if(cr1[1], True)
circ.h(qr2[1]).c_if(cr2[0], False)
circ.cx(qr1[1], qr2[2]).c_if(cr2[2], True)
circ.measure(qr2[2], cr2[0])
inst = circuit_to_instruction(circ)
q = QuantumRegister(5, "q")
c = ClassicalRegister(6, "c")
self.assertEqual(inst.definition[0].qubits, (q[0],))
self.assertEqual(inst.definition[1].qubits, (q[3],))
self.assertEqual(inst.definition[2].qubits, (q[1], q[4]))
self.assertEqual(inst.definition[0].operation.condition, (c[1], True))
self.assertEqual(inst.definition[1].operation.condition, (c[3], False))
self.assertEqual(inst.definition[2].operation.condition, (c[5], True))
def test_flatten_circuit_registerless(self):
"""Test that the conversion works when the given circuit has bits that are not contained in
any register."""
qr1 = QuantumRegister(2)
qubits = [Qubit(), Qubit(), Qubit()]
qr2 = QuantumRegister(3)
cr1 = ClassicalRegister(2)
clbits = [Clbit(), Clbit(), Clbit()]
cr2 = ClassicalRegister(3)
circ = QuantumCircuit(qr1, qubits, qr2, cr1, clbits, cr2)
circ.cx(3, 5)
circ.measure(4, 4)
inst = circuit_to_instruction(circ)
self.assertEqual(inst.num_qubits, len(qr1) + len(qubits) + len(qr2))
self.assertEqual(inst.num_clbits, len(cr1) + len(clbits) + len(cr2))
inst_definition = inst.definition
cx = inst_definition.data[0]
measure = inst_definition.data[1]
self.assertEqual(cx.qubits, (inst_definition.qubits[3], inst_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
self.assertEqual(measure.qubits, (inst_definition.qubits[4],))
self.assertEqual(measure.clbits, (inst_definition.clbits[4],))
def test_flatten_circuit_overlapping_registers(self):
"""Test that the conversion works when the given circuit has bits that are contained in more
than one register."""
qubits = [Qubit() for _ in [None] * 10]
qr1 = QuantumRegister(bits=qubits[:6])
qr2 = QuantumRegister(bits=qubits[4:])
clbits = [Clbit() for _ in [None] * 10]
cr1 = ClassicalRegister(bits=clbits[:6])
cr2 = ClassicalRegister(bits=clbits[4:])
circ = QuantumCircuit(qubits, clbits, qr1, qr2, cr1, cr2)
circ.cx(3, 5)
circ.measure(4, 4)
inst = circuit_to_instruction(circ)
self.assertEqual(inst.num_qubits, len(qubits))
self.assertEqual(inst.num_clbits, len(clbits))
inst_definition = inst.definition
cx = inst_definition.data[0]
measure = inst_definition.data[1]
self.assertEqual(cx.qubits, (inst_definition.qubits[3], inst_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
self.assertEqual(measure.qubits, (inst_definition.qubits[4],))
self.assertEqual(measure.clbits, (inst_definition.clbits[4],))
def test_flatten_parameters(self):
"""Verify parameters from circuit are moved to instruction.params"""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
qc.rz(theta, qr[0])
qc.rz(phi, qr[1])
qc.u(theta, phi, 0, qr[2])
qc.rz(sum_, qr[0])
inst = circuit_to_instruction(qc)
self.assertEqual(inst.params, [phi, theta])
self.assertEqual(inst.definition[0].operation.params, [theta])
self.assertEqual(inst.definition[1].operation.params, [phi])
self.assertEqual(inst.definition[2].operation.params, [theta, phi, 0])
self.assertEqual(str(inst.definition[3].operation.params[0]), "phi + theta")
def test_underspecified_parameter_map_raises(self):
"""Verify we raise if not all circuit parameters are present in parameter_map."""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
gamma = Parameter("gamma")
qc.rz(theta, qr[0])
qc.rz(phi, qr[1])
qc.u(theta, phi, 0, qr[2])
qc.rz(sum_, qr[0])
self.assertRaises(QiskitError, circuit_to_instruction, qc, {theta: gamma})
# Raise if provided more parameters than present in the circuit
delta = Parameter("delta")
self.assertRaises(
QiskitError, circuit_to_instruction, qc, {theta: gamma, phi: phi, delta: delta}
)
def test_parameter_map(self):
"""Verify alternate parameter specification"""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
gamma = Parameter("gamma")
qc.rz(theta, qr[0])
qc.rz(phi, qr[1])
qc.u(theta, phi, 0, qr[2])
qc.rz(sum_, qr[0])
inst = circuit_to_instruction(qc, {theta: gamma, phi: phi})
self.assertEqual(inst.params, [gamma, phi])
self.assertEqual(inst.definition[0].operation.params, [gamma])
self.assertEqual(inst.definition[1].operation.params, [phi])
self.assertEqual(inst.definition[2].operation.params, [gamma, phi, 0])
self.assertEqual(str(inst.definition[3].operation.params[0]), "gamma + phi")
def test_registerless_classical_bits(self):
"""Test that conditions on registerless classical bits can be handled during the conversion.
Regression test of gh-7394."""
expected = QuantumCircuit([Qubit(), Clbit()])
expected.h(0).c_if(expected.clbits[0], 0)
test = circuit_to_instruction(expected)
self.assertIsInstance(test, Instruction)
self.assertIsInstance(test.definition, QuantumCircuit)
self.assertEqual(len(test.definition.data), 1)
test_instruction = test.definition.data[0]
expected_instruction = expected.data[0]
self.assertIs(type(test_instruction.operation), type(expected_instruction.operation))
self.assertEqual(test_instruction.operation.condition, (test.definition.clbits[0], 0))
def test_zero_operands(self):
"""Test that an instruction can be created, even if it has zero operands."""
base = QuantumCircuit(global_phase=math.pi)
instruction = base.to_instruction()
self.assertEqual(instruction.num_qubits, 0)
self.assertEqual(instruction.num_clbits, 0)
self.assertEqual(instruction.definition, base)
compound = QuantumCircuit(1)
compound.append(instruction, [], [])
np.testing.assert_allclose(-np.eye(2), Operator(compound), atol=1e-16)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/sebasmos/QuantumVE
|
sebasmos
|
!pwd
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from torch.utils.data import random_split
from torch.utils.data import Subset, DataLoader, random_split
from torchvision import datasets, transforms
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
import matplotlib.pyplot as plt
import os
import numpy as np
from sklearn.metrics import confusion_matrix, classification_report
import pandas as pd
# from MAE code
from util.datasets import build_dataset
import argparse
import util.misc as misc
import argparse
import datetime
import json
import numpy as np
import os
import time
from pathlib import Path
import torch
import torch.backends.cudnn as cudnn
from torch.utils.tensorboard import SummaryWriter
import timm
assert timm.__version__ == "0.3.2" # version check
from timm.models.layers import trunc_normal_
from timm.data.mixup import Mixup
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
import util.lr_decay as lrd
import util.misc as misc
from util.datasets import build_dataset
from util.pos_embed import interpolate_pos_embed
from util.misc import NativeScalerWithGradNormCount as NativeScaler
import models_vit
import sys
import os
import torch
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import models_mae
import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}')
from engine_finetune import train_one_epoch, evaluate
from timm.data import Mixup
from timm.utils import accuracy
from sklearn.metrics import confusion_matrix, classification_report
import seaborn as sns
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
from itertools import cycle
import numpy as np
from sklearn.metrics import precision_score, recall_score, f1_score
imagenet_mean = np.array([0.485, 0.456, 0.406])
imagenet_std = np.array([0.229, 0.224, 0.225])
def show_image(image, title=''):
# image is [H, W, 3]
assert image.shape[2] == 3
plt.imshow(torch.clip((image * imagenet_std + imagenet_mean) * 255, 0, 255).int())
plt.title(title, fontsize=16)
plt.axis('off')
return
def prepare_model(chkpt_dir, arch='mae_vit_large_patch16'):
# build model
model = getattr(models_mae, arch)()
# load model
checkpoint = torch.load(chkpt_dir, map_location='cpu')
msg = model.load_state_dict(checkpoint['model'], strict=False)
print(msg)
return model
def run_one_image(img, model):
x = torch.tensor(img)
# make it a batch-like
x = x.unsqueeze(dim=0)
x = torch.einsum('nhwc->nchw', x)
# run MAE
loss, y, mask = model(x.float(), mask_ratio=0.75)
y = model.unpatchify(y)
y = torch.einsum('nchw->nhwc', y).detach().cpu()
# visualize the mask
mask = mask.detach()
mask = mask.unsqueeze(-1).repeat(1, 1, model.patch_embed.patch_size[0]**2 *3) # (N, H*W, p*p*3)
mask = model.unpatchify(mask) # 1 is removing, 0 is keeping
mask = torch.einsum('nchw->nhwc', mask).detach().cpu()
x = torch.einsum('nchw->nhwc', x)
# masked image
im_masked = x * (1 - mask)
# MAE reconstruction pasted with visible patches
im_paste = x * (1 - mask) + y * mask
# make the plt figure larger
plt.rcParams['figure.figsize'] = [24, 24]
plt.subplot(1, 4, 1)
show_image(x[0], "original")
plt.subplot(1, 4, 2)
show_image(im_masked[0], "masked")
plt.subplot(1, 4, 3)
show_image(y[0], "reconstruction")
plt.subplot(1, 4, 4)
show_image(im_paste[0], "reconstruction + visible")
plt.show()
# Set the seed for PyTorch
torch.manual_seed(42)
parser = argparse.ArgumentParser('MAE fine-tuning for image classification', add_help=False)
parser.add_argument('--batch_size', default=1, type=int,
help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus')
parser.add_argument('--epochs', default=2, type=int)
parser.add_argument('--accum_iter', default=4, type=int,
help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)')
# Model parameters
parser.add_argument('--model', default='vit_base_patch16', type=str, metavar='MODEL',
help='Name of model to train')
parser.add_argument('--input_size', default=224, type=int,
help='images input size')
parser.add_argument('--drop_path', type=float, default=0.1, metavar='PCT',
help='Drop path rate (default: 0.1)')
# Optimizer parameters
parser.add_argument('--clip_grad', type=float, default=None, metavar='NORM',
help='Clip gradient norm (default: None, no clipping)')
parser.add_argument('--weight_decay', type=float, default=0.05,
help='weight decay (default: 0.05)')
parser.add_argument('--lr', type=float, default=None, metavar='LR',
help='learning rate (absolute lr)')
parser.add_argument('--blr', type=float, default=5e-4, metavar='LR',
help='base learning rate: absolute_lr = base_lr * total_batch_size / 256')
parser.add_argument('--layer_decay', type=float, default=0.65,
help='layer-wise lr decay from ELECTRA/BEiT')
parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR',
help='lower lr bound for cyclic schedulers that hit 0')
parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N',
help='epochs to warmup LR')
# Augmentation parameters
parser.add_argument('--color_jitter', type=float, default=None, metavar='PCT',
help='Color jitter factor (enabled only when not using Auto/RandAug)')
parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME',
help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)'),
parser.add_argument('--smoothing', type=float, default=0.1,
help='Label smoothing (default: 0.1)')
# * Random Erase params
parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT',
help='Random erase prob (default: 0.25)')
parser.add_argument('--remode', type=str, default='pixel',
help='Random erase mode (default: "pixel")')
parser.add_argument('--recount', type=int, default=1,
help='Random erase count (default: 1)')
parser.add_argument('--resplit', action='store_true', default=False,
help='Do not random erase first (clean) augmentation split')
# * Mixup params
parser.add_argument('--mixup', type=float, default=0.8,
help='mixup alpha, mixup enabled if > 0.')
parser.add_argument('--cutmix', type=float, default=1.0,
help='cutmix alpha, cutmix enabled if > 0.')
parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None,
help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)')
parser.add_argument('--mixup_prob', type=float, default=1.0,
help='Probability of performing mixup or cutmix when either/both is enabled')
parser.add_argument('--mixup_switch_prob', type=float, default=0.5,
help='Probability of switching to cutmix when both mixup and cutmix enabled')
parser.add_argument('--mixup_mode', type=str, default='batch',
help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"')
# * Finetuning params
parser.add_argument('--finetune', default='mae_pretrain_vit_base.pth',
help='finetune from checkpoint')
parser.add_argument('--global_pool', action='store_true')
parser.set_defaults(global_pool=True)
parser.add_argument('--cls_token', action='store_false', dest='global_pool',
help='Use class token instead of global pool for classification')
# Dataset parameters
parser.add_argument('--data_path', default='/media/enc/vera1/sebastian/data/Datos_Entrenamiento/', type=str,
help='dataset path')
parser.add_argument('--nb_classes', default=7, type=int,
help='number of the classification types')
parser.add_argument('--output_dir', default='EXP_base_biggest_dataset',
help='path where to save, empty for no saving')
parser.add_argument('--log_dir', default='./output_dir',
help='path where to tensorboard log')
parser.add_argument('--device', default='cuda',
help='device to use for training / testing')
parser.add_argument('--seed', default=0, type=int)
parser.add_argument('--resume', default='',
help='resume from checkpoint')
parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
help='start epoch')
parser.add_argument('--eval',default=True, action='store_true',
help='Perform evaluation only')
parser.add_argument('--dist_eval', action='store_true', default=False,
help='Enabling distributed evaluation (recommended during training for faster monitor')
parser.add_argument('--num_workers', default=10, type=int)
parser.add_argument('--pin_mem', action='store_true',
help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.')
parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem')
parser.set_defaults(pin_mem=True)
# distributed training parameters
parser.add_argument('--world_size', default=1, type=int,
help='number of distributed processes')
parser.add_argument('--local_rank', default=-1, type=int)
parser.add_argument('--dist_on_itp', action='store_true')
parser.add_argument('--dist_url', default='env://',
help='url used to set up distributed training')
args, unknown = parser.parse_known_args()
misc.init_distributed_mode(args)
print("{}".format(args).replace(', ', ',\n'))
device = torch.device(args.device)
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# --------------------------------------------------------
# References:
# DeiT: https://github.com/facebookresearch/deit
# --------------------------------------------------------
import os
import PIL
from torchvision import datasets, transforms
from sklearn.model_selection import KFold
from torch.utils.data import Subset
from timm.data import create_transform
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
def build_transform(is_train, args):
mean = IMAGENET_DEFAULT_MEAN
std = IMAGENET_DEFAULT_STD
# train transform
if is_train:
# this should always dispatch to transforms_imagenet_train
transform = create_transform(
input_size=args.input_size,
is_training=True,
color_jitter=args.color_jitter,
auto_augment=args.aa,
interpolation='bicubic',
re_prob=args.reprob,
re_mode=args.remode,
re_count=args.recount,
mean=mean,
std=std,
)
return transform
# eval transform
t = []
if args.input_size <= 224:
crop_pct = 224 / 256
else:
crop_pct = 1.0
size = int(args.input_size / crop_pct)
t.append(
transforms.Resize(size, interpolation=PIL.Image.BICUBIC), # to maintain same ratio w.r.t. 224 images
)
t.append(transforms.CenterCrop(args.input_size))
t.append(transforms.ToTensor())
t.append(transforms.Normalize(mean, std))
return transforms.Compose(t)
def build_dataset_full_dataset(is_train, args):
transform = build_transform(is_train, args)
# root = os.path.join(args.data_path, 'train' if is_train else 'val')
root = args.data_path
dataset = datasets.ImageFolder(root, transform=transform)
print(dataset)
return dataset
misc.init_distributed_mode(args)
# print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__))))
print("{}".format(args).replace(', ', ',\n'))
device = torch.device(args.device)
# fix the seed for reproducibility
seed = args.seed + misc.get_rank()
torch.manual_seed(seed)
np.random.seed(seed)
cudnn.benchmark = True
# create dataset with all folders possible withoput splits
training = False# false because we will resplit this
dataset = build_dataset_full_dataset(training,args=args)
num_splits = 2
train = True
kf = KFold(n_splits=num_splits, shuffle=True, random_state=42)
# Iterate over each fold
for fold, (train_index, val_index) in enumerate(kf.split(dataset)):
print(f"\nTraining on Fold {fold + 1}/{num_splits}:".center(60,"-"))
# Create train and validation sets for this fold
train_dataset_fold = Subset(dataset, train_index)
val_dataset_fold = Subset(dataset, val_index)
if True: # args.distributed:
num_tasks = misc.get_world_size()
global_rank = misc.get_rank()
sampler_train = torch.utils.data.DistributedSampler(
dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True
)
print("Sampler_train = %s" % str(sampler_train))
if args.dist_eval:
if len(dataset_val) % num_tasks != 0:
print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. '
'This will slightly alter validation results as extra duplicate entries are added to achieve '
'equal num of samples per-process.')
sampler_val = torch.utils.data.DistributedSampler(
dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True) # shuffle=True to reduce monitor bias
else:
sampler_val = torch.utils.data.SequentialSampler(dataset_val)
else:
sampler_train = torch.utils.data.RandomSampler(dataset_train)
sampler_val = torch.utils.data.SequentialSampler(dataset_val)
if global_rank == 0 and args.log_dir is not None and not args.eval:
os.makedirs(args.log_dir, exist_ok=True)
log_writer = SummaryWriter(log_dir=args.log_dir)
else:
log_writer = None
data_loader_train = torch.utils.data.DataLoader(
dataset_train, sampler=sampler_train,
batch_size=args.batch_size,
num_workers=args.num_workers,
pin_memory=args.pin_mem,
drop_last=True,
)
data_loader_val = torch.utils.data.DataLoader(
dataset_val, sampler=sampler_val,
batch_size=args.batch_size,
num_workers=args.num_workers,
pin_memory=args.pin_mem,
drop_last=False
)
mixup_fn = None
mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None
if mixup_active:
print("Mixup is activated!")
mixup_fn = Mixup(
mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax,
prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode,
label_smoothing=args.smoothing, num_classes=args.nb_classes)
model = models_vit.__dict__[args.model](
num_classes=args.nb_classes,
drop_path_rate=args.drop_path,
global_pool=args.global_pool,
)
if args.finetune and not args.eval:
checkpoint = torch.load(args.finetune, map_location='cpu')
print("Load pre-trained checkpoint from: %s" % args.finetune)
checkpoint_model = checkpoint['model']
state_dict = model.state_dict()
for k in ['head.weight', 'head.bias']:
if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape:
print(f"Removing key {k} from pretrained checkpoint")
del checkpoint_model[k]
# interpolate position embedding
interpolate_pos_embed(model, checkpoint_model)
# load pre-trained model
msg = model.load_state_dict(checkpoint_model, strict=False)
print(msg)
if args.global_pool:
assert set(msg.missing_keys) == {'head.weight', 'head.bias', 'fc_norm.weight', 'fc_norm.bias'}
else:
assert set(msg.missing_keys) == {'head.weight', 'head.bias'}
# manually initialize fc layer
trunc_normal_(model.head.weight, std=2e-5)
model.to(device)
model_without_ddp = model
n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
print("Model = %s" % str(model_without_ddp))
print('number of params (M): %.2f' % (n_parameters / 1.e6))
eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size()
if args.lr is None: # only base_lr is specified
args.lr = args.blr * eff_batch_size / 256
print("base lr: %.2e" % (args.lr * 256 / eff_batch_size))
print("actual lr: %.2e" % args.lr)
print("accumulate grad iterations: %d" % args.accum_iter)
print("effective batch size: %d" % eff_batch_size)
if args.distributed:
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
model_without_ddp = model.module
# build optimizer with layer-wise lr decay (lrd)
param_groups = lrd.param_groups_lrd(model_without_ddp, args.weight_decay,
no_weight_decay_list=model_without_ddp.no_weight_decay(),
layer_decay=args.layer_decay
)
optimizer = torch.optim.AdamW(param_groups, lr=args.lr)
loss_scaler = NativeScaler()
if mixup_fn is not None:
# smoothing is handled with mixup label transform
criterion = SoftTargetCrossEntropy()
elif args.smoothing > 0.:
criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing)
else:
criterion = torch.nn.CrossEntropyLoss()
print("criterion = %s" % str(criterion))
misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler)
if args.eval:
test_stats = evaluate(data_loader_val, model, device)
print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%")
if train:
print(f"Start training for {args.epochs} epochs")
start_time = time.time()
max_accuracy = 0.0
for epoch in range(args.start_epoch, args.epochs):
if args.distributed:
data_loader_train.sampler.set_epoch(epoch)
train_stats = train_one_epoch(
model, criterion, data_loader_train,
optimizer, device, epoch, loss_scaler,
args.clip_grad, mixup_fn,
log_writer=log_writer,
args=args
)
if args.output_dir:
misc.save_model(
args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer,
loss_scaler=loss_scaler, epoch=epoch)
test_stats = evaluate(data_loader_val, model, device)
print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%")
max_accuracy = max(max_accuracy, test_stats["acc1"])
print(f'Max accuracy: {max_accuracy:.2f}%')
if log_writer is not None:
log_writer.add_scalar('perf/test_acc1', test_stats['acc1'], epoch)
log_writer.add_scalar('perf/test_acc5', test_stats['acc5'], epoch)
log_writer.add_scalar('perf/test_loss', test_stats['loss'], epoch)
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},
**{f'test_{k}': v for k, v in test_stats.items()},
'epoch': epoch,
'n_parameters': n_parameters}
if args.output_dir and misc.is_main_process():
if log_writer is not None:
log_writer.flush()
with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f:
f.write(json.dumps(log_stats) + "\n")
total_time = time.time() - start_time
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
print('Training time {}'.format(total_time_str))
evaluation_metrics = {
"Acc1": test_stats['acc1'], # Add acc1 metric
"Acc5": test_stats['acc5'], # Add acc5 metric
"loss": test_stats['loss'], # Add acc5 metric
}
print(evaluation_metrics)
break
# if True: # args.distributed:
# num_tasks = misc.get_world_size()
# global_rank = misc.get_rank()
# sampler_train = torch.utils.data.DistributedSampler(
# dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True
# )
# print("Sampler_train = %s" % str(sampler_train))
# if args.dist_eval:
# if len(dataset_val) % num_tasks != 0:
# print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. '
# 'This will slightly alter validation results as extra duplicate entries are added to achieve '
# 'equal num of samples per-process.')
# sampler_val = torch.utils.data.DistributedSampler(
# dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True) # shuffle=True to reduce monitor bias
# else:
# sampler_val = torch.utils.data.SequentialSampler(dataset_val)
# else:
# sampler_train = torch.utils.data.RandomSampler(dataset_train)
# sampler_val = torch.utils.data.SequentialSampler(dataset_val)
# if global_rank == 0 and args.log_dir is not None and not args.eval:
# os.makedirs(args.log_dir, exist_ok=True)
# log_writer = SummaryWriter(log_dir=args.log_dir)
# else:
# log_writer = None
# data_loader_train = torch.utils.data.DataLoader(
# dataset_train, sampler=sampler_train,
# batch_size=args.batch_size,
# num_workers=args.num_workers,
# pin_memory=args.pin_mem,
# drop_last=True,
# )
# data_loader_val = torch.utils.data.DataLoader(
# dataset_val, sampler=sampler_val,
# batch_size=args.batch_size,
# num_workers=args.num_workers,
# pin_memory=args.pin_mem,
# drop_last=False
# )
# #Liberia Validacion cruzada
# from sklearn.model_selection import KFold
# # K-fold cross-validation
# num_splits = 5 # ajusta el número de splits según tus necesidades
# kf = KFold(n_splits=num_splits, shuffle=True, random_state=42)
# for fold, (train_index, val_index) in enumerate(kf.split(dataset_train)):
# print(f"\nTraining on Fold {fold + 1}/{num_splits}:")
# # create train and validation sets for this fold
# train_dataset_fold = Subset(dataset_train, train_index)
# val_dataset_fold = Subset(dataset_train, val_index)
# data_loader_train = torch.utils.data.DataLoader(
# train_dataset_fold, sampler=torch.utils.data.RandomSampler(train_dataset_fold),
# batch_size=args.batch_size,
# num_workers=args.num_workers,
# pin_memory=args.pin_mem,
# drop_last=True,
# )
# data_loader_val = torch.utils.data.DataLoader(
# val_dataset_fold, sampler=torch.utils.data.SequentialSampler(val_dataset_fold),
# batch_size=args.batch_size,
# num_workers=args.num_workers,
# pin_memory=args.pin_mem,
# drop_last=False
# )
# mixup_fn = None
# mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None
# if mixup_active:
# print("Mixup is activated!")
# mixup_fn = Mixup(
# mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax,
# prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode,
# label_smoothing=args.smoothing, num_classes=args.nb_classes)
# model = models_vit.__dict__[args.model](
# num_classes=args.nb_classes,
# drop_path_rate=args.drop_path,
# global_pool=args.global_pool,
# )
# if args.finetune and not args.eval:
# checkpoint = torch.load(args.finetune, map_location='cpu')
# print("Load pre-trained checkpoint from: %s" % args.finetune)
# checkpoint_model = checkpoint['model']
# state_dict = model.state_dict()
# for k in ['head.weight', 'head.bias']:
# if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape:
# print(f"Removing key {k} from pretrained checkpoint")
# del checkpoint_model[k]
# # interpolate position embedding
# interpolate_pos_embed(model, checkpoint_model)
# # load pre-trained model
# msg = model.load_state_dict(checkpoint_model, strict=False)
# print(msg)
# if args.global_pool:
# assert set(msg.missing_keys) == {'head.weight', 'head.bias', 'fc_norm.weight', 'fc_norm.bias'}
# else:
# assert set(msg.missing_keys) == {'head.weight', 'head.bias'}
# # manually initialize fc layer
# trunc_normal_(model.head.weight, std=2e-5)
# model.to(device)
# model_without_ddp = model
# n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
# print("Model = %s" % str(model_without_ddp))
# print('number of params (M): %.2f' % (n_parameters / 1.e6))
# eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size()
# if args.lr is None: # only base_lr is specified
# args.lr = args.blr * eff_batch_size / 256
# print("base lr: %.2e" % (args.lr * 256 / eff_batch_size))
# print("actual lr: %.2e" % args.lr)
# print("accumulate grad iterations: %d" % args.accum_iter)
# print("effective batch size: %d" % eff_batch_size)
# if args.distributed:
# model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
# model_without_ddp = model.module
# # build optimizer with layer-wise lr decay (lrd)
# param_groups = lrd.param_groups_lrd(model_without_ddp, args.weight_decay,
# no_weight_decay_list=model_without_ddp.no_weight_decay(),
# layer_decay=args.layer_decay
# )
# optimizer = torch.optim.AdamW(param_groups, lr=args.lr)
# loss_scaler = NativeScaler()
# if mixup_fn is not None:
# # smoothing is handled with mixup label transform
# criterion = SoftTargetCrossEntropy()
# elif args.smoothing > 0.:
# criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing)
# else:
# criterion = torch.nn.CrossEntropyLoss()
# print("criterion = %s" % str(criterion))
# misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler)
# if args.eval:
# test_stats = evaluate(data_loader_val, model, device)
# print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%")
# # exit(0)
train = True
if train:
print(f"Start training for {args.epochs} epochs")
start_time = time.time()
max_accuracy = 0.0
for epoch in range(args.start_epoch, args.epochs):
if args.distributed:
data_loader_train.sampler.set_epoch(epoch)
train_stats = train_one_epoch(
model, criterion, data_loader_train,
optimizer, device, epoch, loss_scaler,
args.clip_grad, mixup_fn,
log_writer=log_writer,
args=args
)
if args.output_dir:
misc.save_model(
args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer,
loss_scaler=loss_scaler, epoch=epoch)
test_stats = evaluate(data_loader_val, model, device)
print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%")
max_accuracy = max(max_accuracy, test_stats["acc1"])
print(f'Max accuracy: {max_accuracy:.2f}%')
if log_writer is not None:
log_writer.add_scalar('perf/test_acc1', test_stats['acc1'], epoch)
log_writer.add_scalar('perf/test_acc5', test_stats['acc5'], epoch)
log_writer.add_scalar('perf/test_loss', test_stats['loss'], epoch)
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},
**{f'test_{k}': v for k, v in test_stats.items()},
'epoch': epoch,
'n_parameters': n_parameters}
if args.output_dir and misc.is_main_process():
if log_writer is not None:
log_writer.flush()
with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f:
f.write(json.dumps(log_stats) + "\n")
total_time = time.time() - start_time
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
print('Training time {}'.format(total_time_str))
EXPERIMENT_NAME = "eval_vit_base"
saving_model = f"{EXPERIMENT_NAME}/models"
os.makedirs(saving_model, exist_ok = True)
os.makedirs(EXPERIMENT_NAME, exist_ok=True)
if args.eval:
test_stats = evaluate(data_loader_val, model, device)
print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%")
@torch.no_grad()
def evaluate_test(data_loader, model, device):
criterion = torch.nn.CrossEntropyLoss()
metric_logger = misc.MetricLogger(delimiter=" ")
header = 'Test:'
# switch to evaluation mode
model.eval()
all_predictions = []
all_labels = []
for batch in metric_logger.log_every(data_loader, 10, header):
images = batch[0]
target = batch[-1]
images = images.to(device, non_blocking=True)
target = target.to(device, non_blocking=True)
# compute output
with torch.cuda.amp.autocast():
output = model(images)
loss = criterion(output, target)#
pred = output.argmax(dim=1)
all_predictions.append(pred.cpu().numpy())# ADDED
all_labels.append(target.cpu().numpy())# ADDED
acc1, acc5 = accuracy(output, target, topk=(1, 5))
batch_size = images.shape[0]
metric_logger.update(loss=loss.item())
metric_logger.meters['acc1'].update(acc1.item(), n=batch_size)
metric_logger.meters['acc5'].update(acc5.item(), n=batch_size)
all_predictions = np.array(all_predictions)#.squeeze(0)
all_labels = np.array(all_labels)#.squeeze(0)
# gather the stats from all processes
metric_logger.synchronize_between_processes()
print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}'
.format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss))
# return
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}, np.concatenate(all_predictions, axis=0), np.concatenate(all_labels, axis=0)
metrics, all_predictions, all_labels = evaluate_test(data_loader_val, model, device)
# print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%")
metrics
all_predictions
unique_classes = np.unique(np.concatenate((all_labels, all_predictions)))
unique_classes
confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes)
conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes)
conf_matrix
unique_classes = np.unique(np.concatenate((all_labels, all_predictions)))
confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes)
conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes)
# Plot the confusion matrix using seaborn
plt.figure(figsize=(5, 4))
ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True)
# Set labels and ticks
ax.set_xlabel('Predicted Labels')
ax.set_ylabel('True Labels')
# Set x and y ticks using the unique classes
ax.set_xticks(range(len(unique_classes)))
ax.set_yticks(range(len(unique_classes)))
# Set x and y ticks at the center of the cells
ax.set_xticks([i + 0.5 for i in range(len(unique_classes))])
ax.set_yticks([i + 0.5 for i in range(len(unique_classes))])
plt.show()
def plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME="."):
# Step 1: Label Binarization
label_binarizer = LabelBinarizer()
y_onehot = label_binarizer.fit_transform(all_labels)
all_predictions_hot = label_binarizer.transform(all_predictions)
# Step 2: Calculate ROC curves
fpr = dict()
tpr = dict()
roc_auc = dict()
unique_classes = range(y_onehot.shape[1])
for i in unique_classes:
fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# Step 3: Plot ROC curves
fig, ax = plt.subplots(figsize=(8, 8))
# Micro-average ROC curve
fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel())
roc_auc_micro = auc(fpr_micro, tpr_micro)
plt.plot(
fpr_micro,
tpr_micro,
label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})",
color="deeppink",
linestyle=":",
linewidth=4,
)
# Macro-average ROC curve
all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes]))
mean_tpr = np.zeros_like(all_fpr)
for i in unique_classes:
mean_tpr += np.interp(all_fpr, fpr[i], tpr[i])
mean_tpr /= len(unique_classes)
fpr_macro = all_fpr
tpr_macro = mean_tpr
roc_auc_macro = auc(fpr_macro, tpr_macro)
plt.plot(
fpr_macro,
tpr_macro,
label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})",
color="navy",
linestyle=":",
linewidth=4,
)
# Individual class ROC curves with unique colors
colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes)))
for class_id, color in zip(unique_classes, colors):
plt.plot(
fpr[class_id],
tpr[class_id],
color=color,
label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})",
linewidth=2,
)
plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference
plt.axis("equal")
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass")
plt.legend()
plt.savefig(f'{EXPERIMENT_NAME}/roc_curve.png')
plt.show()
# Example usage:
plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME)
# def visualize_predictions(model, val_loader, device, type_label=None, dataset_type=1, unique_classes=np.array([0, 1, 2, 3, 4, 5, 6])):
# criterion = torch.nn.CrossEntropyLoss()
# metric_logger = misc.MetricLogger(delimiter=" ")
# header = 'Test:'
# # switch to evaluation mode
# model.eval()
# all_predictions = []
# all_labels = []
# for batch in metric_logger.log_every(val_loader, 10, header):
# images = batch[0]
# target = batch[-1]
# images = images.to(device, non_blocking=True)
# target = target.to(device, non_blocking=True)
# # compute output
# with torch.cuda.amp.autocast():
# output = model(images)
# loss = criterion(output, target)#
# pred = output.argmax(dim=1)
# all_predictions.append(pred.cpu().numpy())# ADDED
# all_labels.append(target.cpu().numpy())# ADDED
# acc1, acc5 = accuracy(output, target, topk=(1, 5))
# batch_size = images.shape[0]
# metric_logger.update(loss=loss.item())
# metric_logger.meters['acc1'].update(acc1.item(), n=batch_size)
# metric_logger.meters['acc5'].update(acc5.item(), n=batch_size)
# all_predictions = np.array(all_predictions)#.squeeze(0)
# all_labels = np.array(all_labels)#.squeeze(0)
# if type_label is None:
# type_label = unique_classes
# # Create a 4x4 grid for visualization
# num_rows = 4
# num_cols = 4
# plt.figure(figsize=(12, 12))
# for i in range(num_rows * num_cols):
# plt.subplot(num_rows, num_cols, i + 1)
# idx = np.random.randint(len(all_labels))
# import pdb;pdb.set_trace()
# plt.imshow(images[idx].cpu().numpy().squeeze(), cmap='gray')
# # Use the class names instead of numeric labels for Fashion MNIST
# if dataset_type == 1:
# class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# predicted_class = class_names[all_predictions[idx]]
# actual_class = class_names[all_labels[idx]]
# else:
# predicted_class = all_predictions[idx]
# actual_class = all_labels[idx]
# plt.title(f'Pred: {predicted_class}\nActual: {actual_class}')
# plt.axis('off')
# plt.tight_layout()
# plt.show()
# visualize_predictions(model, data_loader_val, device, dataset_type=2, unique_classes=unique_classes)
unique_classes
report = classification_report(all_labels, all_predictions, target_names=unique_classes,output_dict=True)# Mostrar el informe de
df = pd.DataFrame(report).transpose()
df.to_csv(os.path.join(EXPERIMENT_NAME, "confusion_matrix.csv"))
print(df)
# Calculate precision, recall, and specificity (micro-averaged)
precision = precision_score(all_labels, all_predictions, average='micro')
recall = recall_score(all_labels, all_predictions, average='micro')
# Calculate true negatives, false positives, and specificity (micro-averaged)
tn = np.sum((all_labels != 1) & (all_predictions != 1))
fp = np.sum((all_labels != 1) & (all_predictions == 1))
specificity = tn / (tn + fp)
# Calculate F1 score (weighted average)
f1 = f1_score(all_labels, all_predictions, average='weighted')
evaluation_metrics = {
"Acc1": metrics['acc1'], # Add acc1 metric
"Acc5": metrics['acc5'], # Add acc5 metric
"loss": metrics['loss'], # Add acc5 metric
"F1 Score": [f1],
"Precision": [precision],
"Recall": [recall],
"Specificity": [specificity]
}
evaluation_metrics
# Create a DataFrame from the dictionary
df = pd.DataFrame(evaluation_metrics)
# Save the DataFrame to a CSV file
df.to_csv(f'{EXPERIMENT_NAME}/evaluation_metrics_for_table.csv', index=False)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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.
# pylint: disable=invalid-name
"""Tests for generator of timeline drawer."""
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import generators, types, stylesheet
from qiskit.circuit import library, Delay
class TestGates(QiskitTestCase):
"""Tests for generator.gates."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubit = list(qiskit.QuantumRegister(1))[0]
self.u1 = types.ScheduledGate(
t0=100, operand=library.U1Gate(0), duration=0, bits=[self.qubit], bit_position=0
)
self.u3 = types.ScheduledGate(
t0=100, operand=library.U3Gate(0, 0, 0), duration=20, bits=[self.qubit], bit_position=0
)
self.delay = types.ScheduledGate(
t0=100, operand=Delay(20), duration=20, bits=[self.qubit], bit_position=0
)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_sched_gate_with_finite_duration(self):
"""Test test_gen_sched_gate generator with finite duration gate."""
drawing_obj = generators.gen_sched_gate(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.SCHED_GATE.value))
self.assertListEqual(list(drawing_obj.xvals), [100, 120])
self.assertListEqual(
list(drawing_obj.yvals),
[-0.5 * self.formatter["box_height.gate"], 0.5 * self.formatter["box_height.gate"]],
)
self.assertListEqual(drawing_obj.bits, [self.qubit])
ref_meta = {
"name": "u3",
"label": "n/a",
"bits": str(self.qubit.register.name),
"t0": 100,
"duration": 20,
"unitary": "[[1.+0.j 0.-0.j]\n [0.+0.j 1.+0.j]]",
"parameters": "0, 0, 0",
}
self.assertDictEqual(ref_meta, drawing_obj.meta)
ref_styles = {
"zorder": self.formatter["layer.gate"],
"facecolor": self.formatter["color.gates"]["u3"],
"alpha": self.formatter["alpha.gate"],
"linewidth": self.formatter["line_width.gate"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_sched_gate_with_zero_duration(self):
"""Test test_gen_sched_gate generator with zero duration gate."""
drawing_obj = generators.gen_sched_gate(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.SymbolType.FRAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, self.formatter["unicode_symbol.frame_change"])
self.assertEqual(drawing_obj.latex, self.formatter["latex_symbol.frame_change"])
ref_styles = {
"zorder": self.formatter["layer.frame_change"],
"color": self.formatter["color.gates"]["u1"],
"size": self.formatter["text_size.frame_change"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_sched_gate_with_delay(self):
"""Test test_gen_sched_gate generator with delay."""
drawing_obj = generators.gen_sched_gate(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.DELAY.value))
def test_gen_full_gate_name_with_finite_duration(self):
"""Test gen_full_gate_name generator with finite duration gate."""
drawing_obj = generators.gen_full_gate_name(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [110.0])
self.assertListEqual(list(drawing_obj.yvals), [0.0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u3(0.00, 0.00, 0.00)[20]")
ref_latex = "{name}(0.00, 0.00, 0.00)[20]".format(
name=self.formatter["latex_symbol.gates"]["u3"]
)
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_full_gate_name_with_zero_duration(self):
"""Test gen_full_gate_name generator with zero duration gate."""
drawing_obj = generators.gen_full_gate_name(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100.0])
self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u1(0.00)")
ref_latex = "{name}(0.00)".format(name=self.formatter["latex_symbol.gates"]["u1"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "bottom",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_full_gate_name_with_delay(self):
"""Test gen_full_gate_name generator with delay."""
drawing_obj = generators.gen_full_gate_name(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value))
def test_gen_short_gate_name_with_finite_duration(self):
"""Test gen_short_gate_name generator with finite duration gate."""
drawing_obj = generators.gen_short_gate_name(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [110.0])
self.assertListEqual(list(drawing_obj.yvals), [0.0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u3")
ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u3"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_short_gate_name_with_zero_duration(self):
"""Test gen_short_gate_name generator with zero duration gate."""
drawing_obj = generators.gen_short_gate_name(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100.0])
self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u1")
ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u1"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "bottom",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_short_gate_name_with_delay(self):
"""Test gen_short_gate_name generator with delay."""
drawing_obj = generators.gen_short_gate_name(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value))
class TestTimeslot(QiskitTestCase):
"""Tests for generator.bits."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubit = list(qiskit.QuantumRegister(1))[0]
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_timeslot(self):
"""Test gen_timeslot generator."""
drawing_obj = generators.gen_timeslot(self.qubit, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.TIMELINE.value))
self.assertListEqual(
list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
)
self.assertListEqual(
list(drawing_obj.yvals),
[
-0.5 * self.formatter["box_height.timeslot"],
0.5 * self.formatter["box_height.timeslot"],
],
)
self.assertListEqual(drawing_obj.bits, [self.qubit])
ref_styles = {
"zorder": self.formatter["layer.timeslot"],
"alpha": self.formatter["alpha.timeslot"],
"linewidth": self.formatter["line_width.timeslot"],
"facecolor": self.formatter["color.timeslot"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_bit_name(self):
"""Test gen_bit_name generator."""
drawing_obj = generators.gen_bit_name(self.qubit, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.BIT_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, str(self.qubit.register.name))
ref_latex = r"{{\rm {register}}}_{{{index}}}".format(
register=self.qubit.register.prefix, index=self.qubit.index
)
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.bit_name"],
"color": self.formatter["color.bit_name"],
"size": self.formatter["text_size.bit_name"],
"va": "center",
"ha": "right",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
class TestBarrier(QiskitTestCase):
"""Tests for generator.barriers."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubits = list(qiskit.QuantumRegister(3))
self.barrier = types.Barrier(t0=100, bits=self.qubits, bit_position=1)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_barrier(self):
"""Test gen_barrier generator."""
drawing_obj = generators.gen_barrier(self.barrier, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LineType.BARRIER.value))
self.assertListEqual(list(drawing_obj.xvals), [100, 100])
self.assertListEqual(list(drawing_obj.yvals), [-0.5, 0.5])
self.assertListEqual(drawing_obj.bits, [self.qubits[1]])
ref_styles = {
"alpha": self.formatter["alpha.barrier"],
"zorder": self.formatter["layer.barrier"],
"linewidth": self.formatter["line_width.barrier"],
"linestyle": self.formatter["line_style.barrier"],
"color": self.formatter["color.barrier"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
class TestGateLink(QiskitTestCase):
"""Tests for generator.gate_links."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubits = list(qiskit.QuantumRegister(2))
self.gate_link = types.GateLink(t0=100, opname="cx", bits=self.qubits)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def gen_bit_link(self):
"""Test gen_bit_link generator."""
drawing_obj = generators.gen_gate_link(self.gate_link, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LineType.GATE_LINK.value))
self.assertListEqual(list(drawing_obj.xvals), [100])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, self.qubits)
ref_styles = {
"alpha": self.formatter["alpha.bit_link"],
"zorder": self.formatter["layer.bit_link"],
"linewidth": self.formatter["line_width.bit_link"],
"linestyle": self.formatter["line_style.bit_link"],
"color": self.formatter["color.gates"]["cx"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
|
https://github.com/matteoacrossi/oqs-jupyterbook
|
matteoacrossi
|
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Parameter
#############################
# Pauli channel on IBMQX2 #
#############################
# Quantum register
q = QuantumRegister(3, name="q")
# Quantum circuit
pauli = QuantumCircuit(q)
# Pauli channel acting on q_2
## Qubit identification
system = 0
a_0 = 1
a_1 = 2
# ## Define rotation angles
theta_1 = Parameter('θ1')
theta_2 = Parameter('θ2')
theta_3 = Parameter('θ3')
## Construct circuit
pauli.ry(theta_1, q[a_0])
pauli.cx(q[a_0], q[a_1])
pauli.ry(theta_2, q[a_0])
pauli.ry(theta_3, q[a_1])
pauli.cx(q[a_0], q[system])
pauli.cy(q[a_1], q[system])
# Draw circuit
pauli.draw(output='mpl')
def pauli_channel(q, p, system, pauli_ancillae):
"""
Apply the Pauli channel to system with probabilities p
Args:
q (QuantumRegister): the quantum register for the circuit
system (int): index of the system qubit
pauli_ancillae (list): list of indices of the ancillary qubits
p (list): list of probabilities [p_1, p_2, p_3] for the Pauli channel
Returns:
A QuantumCircuit implementing the Pauli channel
"""
# Write code
# Suggested imports...
from qiskit.tools.qi.qi import entropy, partial_trace
def conditional_entropy(state, qubit_a, qubit_b):
"""Conditional entropy S(A|B) = S(AB) - S(B)
Args:
state: a vector or density operator
qubit_a: 0-based index of the qubit A
qubit_b: 0-based index of the qubit B
Returns:
int: the conditional entropy
"""
# Write code here
def extractable_work(state, system_qubit, memory_qubit):
"""Extractable work from a two-qubit state
=
Cfr. Eq. (4) Bylicka et al., Sci. Rep. 6, 27989 (2016)
Args:
qubit_a: 0-based index of the system qubit S
qubit_b: 0-based index of the memory qubit M
"""
# Write code here
|
https://github.com/jayeshparashar/Bloch-sphere-
|
jayeshparashar
|
# in this step, we will generate a 2 dim random statevector using quantum_info random_statevector method
from qiskit.quantum_info import random_statevector, Statevector
rand_sv = random_statevector(2).data
print(rand_sv) # print the vector components (complex amplitudes) associated with bais |0> and |1> from rand_sv
#Lets plot the rand_sv using plot_bloch_multivector, before that import plot_bloch vector from qiskit.visualization
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(rand_sv)
# once we will have the cartesian cordinates calculated we can use plot_bloch_vector from visualization as shown below
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([1,0,0])
# break down complex amplitudes α and β in real and imaginary parts to express same in polar form.
import math
import numpy as np
print('The random statevector', rand_sv)
alpha_real = rand_sv[0].real
alpha_imag = rand_sv[0].imag
alpha_theta = math.atan(alpha_imag/alpha_real)
if alpha_real < 0 and alpha_imag > 0 :
alpha_theta = math.atan(alpha_imag/alpha_real) + math.pi
if alpha_real < 0 and alpha_imag < 0 :
alpha_theta = math.atan(alpha_imag/alpha_real) + math.pi
print ('alpha and alpha_theta ', np.around(alpha_real,8), np.around(alpha_imag,8), math.degrees(alpha_theta))
r_alpha = math.sqrt((alpha_real**2) + (alpha_imag**2))
beta_real = rand_sv[1].real
beta_imag = rand_sv[1].imag
beta_theta = math.atan(beta_imag/beta_real)
if beta_real < 0 and beta_imag > 0 :
beta_theta = math.atan(beta_imag/beta_real) + math.pi
if beta_real < 0 and beta_imag < 0 :
beta_theta = math.atan(beta_imag/beta_real) + math.pi
print ('beta and beta_theta ', np.around(beta_real,8), np.around(beta_imag,8), math.degrees(beta_theta))
r_beta = math.sqrt((beta_real**2) + (beta_imag**2))
# use global phase to get a real only value for amplitude associated with state |0> on bloch sphere
phi = beta_theta - alpha_theta
print('r_alpha, r_beta, Phase differnce phi: ',phi)
theta = 2 * np.arccos(r_alpha)
print('Spherical Coordinates of Blochsphere are theta and phi : 1, ', theta, beta_theta - alpha_theta)
x = math.sin(theta)*math.cos(phi)
y = math.sin(theta)*math.sin(phi)
z = math.cos(theta)
print(x,y,z)
plot_bloch_vector([x,y,z])
#plot_bloch_vector([1, theta, phi], coord_type='spherical') # also try it out with spherical coordinates
#once agian we plot rand_sv state to check if that is same as what we have calculated above
plot_bloch_multivector(rand_sv)
|
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.
"""Multicontrolled gate decompositions for unitaries in U(2) and SU(2)"""
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit import Gate
from .ldmcu import Ldmcu
from .ldmcsu import Ldmcsu
from .util import check_u2, check_su2, u2_to_su2
# pylint: disable=maybe-no-member
# pylint: disable=protected-access
class Mcg(Gate):
"""
Selects the most cost-effective multicontrolled gate decomposition.
"""
def __init__(
self,
unitary,
num_controls,
ctrl_state: str=None,
up_to_diagonal: bool=False
):
check_u2(unitary)
self.unitary = unitary
self.controls = QuantumRegister(num_controls)
self.target = QuantumRegister(1)
self.num_qubits = num_controls + 1
self.ctrl_state = ctrl_state
self.up_to_diagonal = up_to_diagonal
super().__init__("mcg", self.num_qubits, [], "mcg")
def _define(self):
self.definition = QuantumCircuit(self.controls, self.target)
num_ctrl = len(self.controls)
if num_ctrl == 0:
self.definition.unitary(self.unitary, [self.target])
elif num_ctrl == 1:
u_gate = QuantumCircuit(1)
u_gate.unitary(self.unitary, 0)
self.definition.append(
u_gate.control(num_ctrl, ctrl_state=self.ctrl_state),
[*self.controls, self.target]
)
else:
if check_su2(self.unitary):
Ldmcsu.ldmcsu(
self.definition,
self.unitary,
self.controls,
self.target,
ctrl_state=self.ctrl_state
)
else:
if self.up_to_diagonal:
su_2, _ = u2_to_su2(self.unitary)
self.mcg(su_2, self.controls, self.target, self.ctrl_state)
else:
Ldmcu.ldmcu(self.definition, self.unitary, self.controls[:], self.target[0], self.ctrl_state)
@staticmethod
def mcg(
circuit,
unitary,
controls,
target,
ctrl_state: str = None
):
circuit.append(
Mcg(unitary, len(controls), ctrl_state=ctrl_state),
[*controls, target]
)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for SparsePauliOp class."""
import itertools as it
import unittest
from test import combine
import numpy as np
from ddt import ddt
from qiskit import QiskitError
from qiskit.circuit import ParameterExpression, Parameter, ParameterVector
from qiskit.circuit.parametertable import ParameterView
from qiskit.quantum_info.operators import Operator, Pauli, PauliList, PauliTable, SparsePauliOp
from qiskit.test import QiskitTestCase
def pauli_mat(label):
"""Return Pauli matrix from a Pauli label"""
mat = np.eye(1, dtype=complex)
for i in label:
if i == "I":
mat = np.kron(mat, np.eye(2, dtype=complex))
elif i == "X":
mat = np.kron(mat, np.array([[0, 1], [1, 0]], dtype=complex))
elif i == "Y":
mat = np.kron(mat, np.array([[0, -1j], [1j, 0]], dtype=complex))
elif i == "Z":
mat = np.kron(mat, np.array([[1, 0], [0, -1]], dtype=complex))
else:
raise QiskitError(f"Invalid Pauli string {i}")
return mat
class TestSparsePauliOpInit(QiskitTestCase):
"""Tests for SparsePauliOp initialization."""
def test_pauli_table_init(self):
"""Test PauliTable initialization."""
labels = ["I", "X", "Y", "Z"]
table = PauliTable.from_labels(labels)
paulis = PauliList(labels)
with self.subTest(msg="no coeffs"):
spp_op = SparsePauliOp(table)
np.testing.assert_array_equal(spp_op.coeffs, np.ones(len(labels)))
self.assertEqual(spp_op.paulis, paulis)
with self.subTest(msg="no coeffs"):
coeffs = [1, 2, 3, 4]
spp_op = SparsePauliOp(table, coeffs)
np.testing.assert_array_equal(spp_op.coeffs, coeffs)
self.assertEqual(spp_op.paulis, paulis)
def test_str_init(self):
"""Test str initialization."""
for label in ["IZ", "XI", "YX", "ZZ"]:
pauli_list = PauliList(label)
spp_op = SparsePauliOp(label)
self.assertEqual(spp_op.paulis, pauli_list)
np.testing.assert_array_equal(spp_op.coeffs, [1])
def test_pauli_list_init(self):
"""Test PauliList initialization."""
labels = ["I", "X", "Y", "-Z", "iZ", "-iX"]
paulis = PauliList(labels)
with self.subTest(msg="no coeffs"):
spp_op = SparsePauliOp(paulis)
np.testing.assert_array_equal(spp_op.coeffs, [1, 1, 1, -1, 1j, -1j])
paulis.phase = 0
self.assertEqual(spp_op.paulis, paulis)
paulis = PauliList(labels)
with self.subTest(msg="with coeffs"):
coeffs = [1, 2, 3, 4, 5, 6]
spp_op = SparsePauliOp(paulis, coeffs)
np.testing.assert_array_equal(spp_op.coeffs, [1, 2, 3, -4, 5j, -6j])
paulis.phase = 0
self.assertEqual(spp_op.paulis, paulis)
paulis = PauliList(labels)
with self.subTest(msg="with Parameterized coeffs"):
params = ParameterVector("params", 6)
coeffs = np.array(params)
spp_op = SparsePauliOp(paulis, coeffs)
target = coeffs.copy()
target[3] *= -1
target[4] *= 1j
target[5] *= -1j
np.testing.assert_array_equal(spp_op.coeffs, target)
paulis.phase = 0
self.assertEqual(spp_op.paulis, paulis)
def test_sparse_pauli_op_init(self):
"""Test SparsePauliOp initialization."""
labels = ["I", "X", "Y", "-Z", "iZ", "-iX"]
with self.subTest(msg="make SparsePauliOp from SparsePauliOp"):
op = SparsePauliOp(labels)
ref_op = op.copy()
spp_op = SparsePauliOp(op)
self.assertEqual(spp_op, ref_op)
np.testing.assert_array_equal(ref_op.paulis.phase, np.zeros(ref_op.size))
np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size))
# make sure the changes of `op` do not propagate through to `spp_op`
op.paulis.z[:] = False
op.coeffs *= 2
self.assertNotEqual(spp_op, op)
self.assertEqual(spp_op, ref_op)
with self.subTest(msg="make SparsePauliOp from SparsePauliOp and ndarray"):
op = SparsePauliOp(labels)
coeffs = np.array([1, 2, 3, 4, 5, 6])
spp_op = SparsePauliOp(op, coeffs)
ref_op = SparsePauliOp(op.paulis.copy(), coeffs.copy())
self.assertEqual(spp_op, ref_op)
np.testing.assert_array_equal(ref_op.paulis.phase, np.zeros(ref_op.size))
np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size))
# make sure the changes of `op` and `coeffs` do not propagate through to `spp_op`
op.paulis.z[:] = False
coeffs *= 2
self.assertNotEqual(spp_op, op)
self.assertEqual(spp_op, ref_op)
with self.subTest(msg="make SparsePauliOp from PauliList"):
paulis = PauliList(labels)
spp_op = SparsePauliOp(paulis)
ref_op = SparsePauliOp(labels)
self.assertEqual(spp_op, ref_op)
np.testing.assert_array_equal(ref_op.paulis.phase, np.zeros(ref_op.size))
np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size))
# make sure the change of `paulis` does not propagate through to `spp_op`
paulis.z[:] = False
self.assertEqual(spp_op, ref_op)
with self.subTest(msg="make SparsePauliOp from PauliList and ndarray"):
paulis = PauliList(labels)
coeffs = np.array([1, 2, 3, 4, 5, 6])
spp_op = SparsePauliOp(paulis, coeffs)
ref_op = SparsePauliOp(labels, coeffs.copy())
self.assertEqual(spp_op, ref_op)
np.testing.assert_array_equal(ref_op.paulis.phase, np.zeros(ref_op.size))
np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size))
# make sure the changes of `paulis` and `coeffs` do not propagate through to `spp_op`
paulis.z[:] = False
coeffs[:] = 0
self.assertEqual(spp_op, ref_op)
class TestSparsePauliOpConversions(QiskitTestCase):
"""Tests SparsePauliOp representation conversions."""
def test_from_operator(self):
"""Test from_operator methods."""
for tup in it.product(["I", "X", "Y", "Z"], repeat=2):
label = "".join(tup)
with self.subTest(msg=label):
spp_op = SparsePauliOp.from_operator(Operator(pauli_mat(label)))
np.testing.assert_array_equal(spp_op.coeffs, [1])
self.assertEqual(spp_op.paulis, PauliList(label))
def test_from_list(self):
"""Test from_list method."""
labels = ["XXZ", "IXI", "YZZ", "III"]
coeffs = [3.0, 5.5, -1j, 23.3333]
spp_op = SparsePauliOp.from_list(zip(labels, coeffs))
np.testing.assert_array_equal(spp_op.coeffs, coeffs)
self.assertEqual(spp_op.paulis, PauliList(labels))
def test_from_list_parameters(self):
"""Test from_list method with parameters."""
labels = ["XXZ", "IXI", "YZZ", "III"]
coeffs = ParameterVector("a", 4)
spp_op = SparsePauliOp.from_list(zip(labels, coeffs), dtype=object)
np.testing.assert_array_equal(spp_op.coeffs, coeffs)
self.assertEqual(spp_op.paulis, PauliList(labels))
def test_from_index_list(self):
"""Test from_list method specifying the Paulis via indices."""
expected_labels = ["XXZ", "IXI", "YIZ", "III"]
paulis = ["XXZ", "X", "YZ", ""]
indices = [[2, 1, 0], [1], [2, 0], []]
coeffs = [3.0, 5.5, -1j, 23.3333]
spp_op = SparsePauliOp.from_sparse_list(zip(paulis, indices, coeffs), num_qubits=3)
np.testing.assert_array_equal(spp_op.coeffs, coeffs)
self.assertEqual(spp_op.paulis, PauliList(expected_labels))
def test_from_index_list_parameters(self):
"""Test from_list method specifying the Paulis via indices with paramteres."""
expected_labels = ["XXZ", "IXI", "YIZ", "III"]
paulis = ["XXZ", "X", "YZ", ""]
indices = [[2, 1, 0], [1], [2, 0], []]
coeffs = ParameterVector("a", 4)
spp_op = SparsePauliOp.from_sparse_list(
zip(paulis, indices, coeffs), num_qubits=3, dtype=object
)
np.testing.assert_array_equal(spp_op.coeffs, coeffs)
self.assertEqual(spp_op.paulis, PauliList(expected_labels))
def test_from_index_list_endianness(self):
"""Test the construction from index list has the right endianness."""
spp_op = SparsePauliOp.from_sparse_list([("ZX", [1, 4], 1)], num_qubits=5)
expected = Pauli("XIIZI")
self.assertEqual(spp_op.paulis[0], expected)
def test_from_index_list_raises(self):
"""Test from_list via Pauli + indices raises correctly, if number of qubits invalid."""
with self.assertRaises(QiskitError):
_ = SparsePauliOp.from_sparse_list([("Z", [2], 1)], 1)
def test_from_index_list_same_index(self):
"""Test from_list via Pauli + number of qubits raises correctly, if indices duplicate."""
with self.assertRaises(QiskitError):
_ = SparsePauliOp.from_sparse_list([("ZZ", [0, 0], 1)], 2)
with self.assertRaises(QiskitError):
_ = SparsePauliOp.from_sparse_list([("ZI", [0, 0], 1)], 2)
with self.assertRaises(QiskitError):
_ = SparsePauliOp.from_sparse_list([("IZ", [0, 0], 1)], 2)
def test_from_zip(self):
"""Test from_list method for zipped input."""
labels = ["XXZ", "IXI", "YZZ", "III"]
coeffs = [3.0, 5.5, -1j, 23.3333]
spp_op = SparsePauliOp.from_list(zip(labels, coeffs))
np.testing.assert_array_equal(spp_op.coeffs, coeffs)
self.assertEqual(spp_op.paulis, PauliList(labels))
def test_to_matrix(self):
"""Test to_matrix method."""
labels = ["XI", "YZ", "YY", "ZZ"]
coeffs = [-3, 4.4j, 0.2 - 0.1j, 66.12]
spp_op = SparsePauliOp(labels, coeffs)
target = np.zeros((4, 4), dtype=complex)
for coeff, label in zip(coeffs, labels):
target += coeff * pauli_mat(label)
np.testing.assert_array_equal(spp_op.to_matrix(), target)
np.testing.assert_array_equal(spp_op.to_matrix(sparse=True).toarray(), target)
def test_to_matrix_large(self):
"""Test to_matrix method with a large number of qubits."""
reps = 5
labels = ["XI" * reps, "YZ" * reps, "YY" * reps, "ZZ" * reps]
coeffs = [-3, 4.4j, 0.2 - 0.1j, 66.12]
spp_op = SparsePauliOp(labels, coeffs)
size = 1 << 2 * reps
target = np.zeros((size, size), dtype=complex)
for coeff, label in zip(coeffs, labels):
target += coeff * pauli_mat(label)
np.testing.assert_array_equal(spp_op.to_matrix(), target)
np.testing.assert_array_equal(spp_op.to_matrix(sparse=True).toarray(), target)
def test_to_matrix_parameters(self):
"""Test to_matrix method for parameterized SparsePauliOp."""
labels = ["XI", "YZ", "YY", "ZZ"]
coeffs = np.array(ParameterVector("a", 4))
spp_op = SparsePauliOp(labels, coeffs)
target = np.zeros((4, 4), dtype=object)
for coeff, label in zip(coeffs, labels):
target += coeff * pauli_mat(label)
np.testing.assert_array_equal(spp_op.to_matrix(), target)
def test_to_operator(self):
"""Test to_operator method."""
labels = ["XI", "YZ", "YY", "ZZ"]
coeffs = [-3, 4.4j, 0.2 - 0.1j, 66.12]
spp_op = SparsePauliOp(labels, coeffs)
target = Operator(np.zeros((4, 4), dtype=complex))
for coeff, label in zip(coeffs, labels):
target = target + Operator(coeff * pauli_mat(label))
self.assertEqual(spp_op.to_operator(), target)
def test_to_list(self):
"""Test to_operator method."""
labels = ["XI", "YZ", "YY", "ZZ"]
coeffs = [-3, 4.4j, 0.2 - 0.1j, 66.12]
op = SparsePauliOp(labels, coeffs)
target = list(zip(labels, coeffs))
self.assertEqual(op.to_list(), target)
def test_to_list_parameters(self):
"""Test to_operator method with paramters."""
labels = ["XI", "YZ", "YY", "ZZ"]
coeffs = np.array(ParameterVector("a", 4))
op = SparsePauliOp(labels, coeffs)
target = list(zip(labels, coeffs))
self.assertEqual(op.to_list(), target)
class TestSparsePauliOpIteration(QiskitTestCase):
"""Tests for SparsePauliOp iterators class."""
def test_enumerate(self):
"""Test enumerate with SparsePauliOp."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array([1, 2, 3, 4, 5, 6])
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(op):
self.assertEqual(i, SparsePauliOp(labels[idx], coeffs[[idx]]))
def test_enumerate_parameters(self):
"""Test enumerate with SparsePauliOp with parameters."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array(ParameterVector("a", 6))
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(op):
self.assertEqual(i, SparsePauliOp(labels[idx], coeffs[[idx]]))
def test_iter(self):
"""Test iter with SparsePauliOp."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array([1, 2, 3, 4, 5, 6])
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(iter(op)):
self.assertEqual(i, SparsePauliOp(labels[idx], coeffs[[idx]]))
def test_iter_parameters(self):
"""Test iter with SparsePauliOp with parameters."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array(ParameterVector("a", 6))
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(iter(op)):
self.assertEqual(i, SparsePauliOp(labels[idx], coeffs[[idx]]))
def test_label_iter(self):
"""Test SparsePauliOp label_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array([1, 2, 3, 4, 5, 6])
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(op.label_iter()):
self.assertEqual(i, (labels[idx], coeffs[idx]))
def test_label_iter_parameters(self):
"""Test SparsePauliOp label_iter method with parameters."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array(ParameterVector("a", 6))
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(op.label_iter()):
self.assertEqual(i, (labels[idx], coeffs[idx]))
def test_matrix_iter(self):
"""Test SparsePauliOp dense matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array([1, 2, 3, 4, 5, 6])
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(op.matrix_iter()):
np.testing.assert_array_equal(i, coeffs[idx] * pauli_mat(labels[idx]))
def test_matrix_iter_parameters(self):
"""Test SparsePauliOp dense matrix_iter method. with parameters"""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array(ParameterVector("a", 6))
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(op.matrix_iter()):
np.testing.assert_array_equal(i, coeffs[idx] * pauli_mat(labels[idx]))
def test_matrix_iter_sparse(self):
"""Test SparsePauliOp sparse matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array([1, 2, 3, 4, 5, 6])
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(op.matrix_iter(sparse=True)):
np.testing.assert_array_equal(i.toarray(), coeffs[idx] * pauli_mat(labels[idx]))
def bind_parameters_to_one(array):
"""Bind parameters to one. The purpose of using this method is to bind some value and
use ``assert_allclose``, since it is impossible to verify equivalence in the case of
numerical errors with parameters existing.
"""
def bind_one(a):
parameters = a.parameters
return complex(a.bind(dict(zip(parameters, [1] * len(parameters)))))
return np.vectorize(bind_one, otypes=[complex])(array)
@ddt
class TestSparsePauliOpMethods(QiskitTestCase):
"""Tests for SparsePauliOp operator methods."""
RNG = np.random.default_rng(1994)
def setUp(self):
super().setUp()
self.parameter_names = (f"param_{x}" for x in it.count())
def random_spp_op(self, num_qubits, num_terms, use_parameters=False):
"""Generate a pseudo-random SparsePauliOp"""
if use_parameters:
coeffs = np.array(ParameterVector(next(self.parameter_names), num_terms))
else:
coeffs = self.RNG.uniform(-1, 1, size=num_terms) + 1j * self.RNG.uniform(
-1, 1, size=num_terms
)
labels = [
"".join(self.RNG.choice(["I", "X", "Y", "Z"], size=num_qubits))
for _ in range(num_terms)
]
return SparsePauliOp(labels, coeffs)
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_conjugate(self, num_qubits, use_parameters):
"""Test conjugate method for {num_qubits}-qubits."""
spp_op = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
target = spp_op.to_matrix().conjugate()
op = spp_op.conjugate()
value = op.to_matrix()
np.testing.assert_array_equal(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_transpose(self, num_qubits, use_parameters):
"""Test transpose method for {num_qubits}-qubits."""
spp_op = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
target = spp_op.to_matrix().transpose()
op = spp_op.transpose()
value = op.to_matrix()
np.testing.assert_array_equal(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_adjoint(self, num_qubits, use_parameters):
"""Test adjoint method for {num_qubits}-qubits."""
spp_op = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
target = spp_op.to_matrix().transpose().conjugate()
op = spp_op.adjoint()
value = op.to_matrix()
np.testing.assert_array_equal(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_compose(self, num_qubits, use_parameters):
"""Test {num_qubits}-qubit compose methods."""
spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
target = spp_op2.to_matrix() @ spp_op1.to_matrix()
op = spp_op1.compose(spp_op2)
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
target = bind_parameters_to_one(target)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
op = spp_op1 & spp_op2
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_dot(self, num_qubits, use_parameters):
"""Test {num_qubits}-qubit dot methods."""
spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
target = spp_op1.to_matrix() @ spp_op2.to_matrix()
op = spp_op1.dot(spp_op2)
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
target = bind_parameters_to_one(target)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
op = spp_op1 @ spp_op2
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3])
def test_qargs_compose(self, num_qubits):
"""Test 3-qubit compose method with {num_qubits}-qubit qargs."""
spp_op1 = self.random_spp_op(3, 2**3)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits)
qargs = self.RNG.choice(3, size=num_qubits, replace=False).tolist()
target = Operator(spp_op1).compose(Operator(spp_op2), qargs=qargs)
op = spp_op1.compose(spp_op2, qargs=qargs)
value = op.to_operator()
self.assertEqual(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
op = spp_op1 & spp_op2(qargs)
value = op.to_operator()
self.assertEqual(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3])
def test_qargs_dot(self, num_qubits):
"""Test 3-qubit dot method with {num_qubits}-qubit qargs."""
spp_op1 = self.random_spp_op(3, 2**3)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits)
qargs = self.RNG.choice(3, size=num_qubits, replace=False).tolist()
target = Operator(spp_op1).dot(Operator(spp_op2), qargs=qargs)
op = spp_op1.dot(spp_op2, qargs=qargs)
value = op.to_operator()
self.assertEqual(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits1=[1, 2, 3], num_qubits2=[1, 2, 3], use_parameters=[True, False])
def test_tensor(self, num_qubits1, num_qubits2, use_parameters):
"""Test tensor method for {num_qubits1} and {num_qubits2} qubits."""
spp_op1 = self.random_spp_op(num_qubits1, 2**num_qubits1, use_parameters)
spp_op2 = self.random_spp_op(num_qubits2, 2**num_qubits2, use_parameters)
target = np.kron(spp_op1.to_matrix(), spp_op2.to_matrix())
op = spp_op1.tensor(spp_op2)
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
target = bind_parameters_to_one(target)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits1=[1, 2, 3], num_qubits2=[1, 2, 3], use_parameters=[True, False])
def test_expand(self, num_qubits1, num_qubits2, use_parameters):
"""Test expand method for {num_qubits1} and {num_qubits2} qubits."""
spp_op1 = self.random_spp_op(num_qubits1, 2**num_qubits1, use_parameters)
spp_op2 = self.random_spp_op(num_qubits2, 2**num_qubits2, use_parameters)
target = np.kron(spp_op2.to_matrix(), spp_op1.to_matrix())
op = spp_op1.expand(spp_op2)
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
target = bind_parameters_to_one(target)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_add(self, num_qubits, use_parameters):
"""Test + method for {num_qubits} qubits."""
spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
target = spp_op1.to_matrix() + spp_op2.to_matrix()
op = spp_op1 + spp_op2
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
target = bind_parameters_to_one(target)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_sub(self, num_qubits, use_parameters):
"""Test + method for {num_qubits} qubits."""
spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
target = spp_op1.to_matrix() - spp_op2.to_matrix()
op = spp_op1 - spp_op2
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
target = bind_parameters_to_one(target)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3])
def test_add_qargs(self, num_qubits):
"""Test + method for 3 qubits with {num_qubits} qubit qargs."""
spp_op1 = self.random_spp_op(3, 2**3)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits)
qargs = self.RNG.choice(3, size=num_qubits, replace=False).tolist()
target = Operator(spp_op1) + Operator(spp_op2)(qargs)
op = spp_op1 + spp_op2(qargs)
value = op.to_operator()
self.assertEqual(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3])
def test_sub_qargs(self, num_qubits):
"""Test - method for 3 qubits with {num_qubits} qubit qargs."""
spp_op1 = self.random_spp_op(3, 2**3)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits)
qargs = self.RNG.choice(3, size=num_qubits, replace=False).tolist()
target = Operator(spp_op1) - Operator(spp_op2)(qargs)
op = spp_op1 - spp_op2(qargs)
value = op.to_operator()
self.assertEqual(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(
num_qubits=[1, 2, 3],
value=[
0,
1,
1j,
-3 + 4.4j,
np.int64(2),
Parameter("x"),
0 * Parameter("x"),
(-2 + 1.7j) * Parameter("x"),
],
param=[None, "a"],
)
def test_mul(self, num_qubits, value, param):
"""Test * method for {num_qubits} qubits and value {value}."""
spp_op = self.random_spp_op(num_qubits, 2**num_qubits, param)
target = value * spp_op.to_matrix()
op = value * spp_op
value_mat = op.to_matrix()
has_parameters = isinstance(value, ParameterExpression) or param is not None
if value != 0 and has_parameters:
value_mat = bind_parameters_to_one(value_mat)
target = bind_parameters_to_one(target)
if value == 0:
np.testing.assert_array_equal(value_mat, target.astype(complex))
else:
np.testing.assert_allclose(value_mat, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
target = spp_op.to_matrix() * value
op = spp_op * value
value_mat = op.to_matrix()
if value != 0 and has_parameters:
value_mat = bind_parameters_to_one(value_mat)
target = bind_parameters_to_one(target)
if value == 0:
np.testing.assert_array_equal(value_mat, target.astype(complex))
else:
np.testing.assert_allclose(value_mat, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3], value=[1, 1j, -3 + 4.4j], param=[None, "a"])
def test_div(self, num_qubits, value, param):
"""Test / method for {num_qubits} qubits and value {value}."""
spp_op = self.random_spp_op(num_qubits, 2**num_qubits, param)
target = spp_op.to_matrix() / value
op = spp_op / value
value_mat = op.to_matrix()
if param is not None:
value_mat = bind_parameters_to_one(value_mat)
target = bind_parameters_to_one(target)
np.testing.assert_allclose(value_mat, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
def test_simplify(self):
"""Test simplify method"""
coeffs = [3 + 1j, -3 - 1j, 0, 4, -5, 2.2, -1.1j]
labels = ["IXI", "IXI", "ZZZ", "III", "III", "XXX", "XXX"]
spp_op = SparsePauliOp.from_list(zip(labels, coeffs))
simplified_op = spp_op.simplify()
target_coeffs = [-1, 2.2 - 1.1j]
target_labels = ["III", "XXX"]
target_op = SparsePauliOp.from_list(zip(target_labels, target_coeffs))
self.assertEqual(simplified_op, target_op)
np.testing.assert_array_equal(simplified_op.paulis.phase, np.zeros(simplified_op.size))
@combine(num_qubits=[1, 2, 3, 4], num_adds=[0, 1, 2, 3])
def test_simplify2(self, num_qubits, num_adds):
"""Test simplify method for {num_qubits} qubits with {num_adds} `add` calls."""
spp_op = self.random_spp_op(num_qubits, 2**num_qubits)
for _ in range(num_adds):
spp_op += spp_op
simplified_op = spp_op.simplify()
value = Operator(simplified_op)
target = Operator(spp_op)
self.assertEqual(value, target)
np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size))
np.testing.assert_array_equal(simplified_op.paulis.phase, np.zeros(simplified_op.size))
@combine(num_qubits=[1, 2, 3, 4])
def test_simplify_zero(self, num_qubits):
"""Test simplify method for {num_qubits} qubits with zero operators."""
spp_op = self.random_spp_op(num_qubits, 2**num_qubits)
zero_op = spp_op - spp_op
simplified_op = zero_op.simplify()
value = Operator(simplified_op)
target = Operator(zero_op)
self.assertEqual(value, target)
np.testing.assert_array_equal(simplified_op.coeffs, [0])
np.testing.assert_array_equal(zero_op.paulis.phase, np.zeros(zero_op.size))
np.testing.assert_array_equal(simplified_op.paulis.phase, np.zeros(simplified_op.size))
def test_simplify_parameters(self):
"""Test simplify methods for parameterized SparsePauliOp."""
a = Parameter("a")
coeffs = np.array([a, -a, 0, a, a, a, 2 * a])
labels = ["IXI", "IXI", "ZZZ", "III", "III", "XXX", "XXX"]
spp_op = SparsePauliOp(labels, coeffs)
simplified_op = spp_op.simplify()
target_coeffs = np.array([2 * a, 3 * a])
target_labels = ["III", "XXX"]
target_op = SparsePauliOp(target_labels, target_coeffs)
self.assertEqual(simplified_op, target_op)
np.testing.assert_array_equal(simplified_op.paulis.phase, np.zeros(simplified_op.size))
def test_sort(self):
"""Test sort method."""
with self.assertRaises(QiskitError):
target = SparsePauliOp([], [])
with self.subTest(msg="1 qubit real number"):
target = SparsePauliOp(
["I", "I", "I", "I"], [-3.0 + 0.0j, 1.0 + 0.0j, 2.0 + 0.0j, 4.0 + 0.0j]
)
value = SparsePauliOp(["I", "I", "I", "I"], [1, 2, -3, 4]).sort()
self.assertEqual(target, value)
with self.subTest(msg="1 qubit complex"):
target = SparsePauliOp(
["I", "I", "I", "I"], [-1.0 + 0.0j, 0.0 - 1.0j, 0.0 + 1.0j, 1.0 + 0.0j]
)
value = SparsePauliOp(
["I", "I", "I", "I"], [1.0 + 0.0j, 0.0 + 1.0j, 0.0 - 1.0j, -1.0 + 0.0j]
).sort()
self.assertEqual(target, value)
with self.subTest(msg="1 qubit Pauli I, X, Y, Z"):
target = SparsePauliOp(
["I", "X", "Y", "Z"], [-1.0 + 2.0j, 1.0 + 0.0j, 2.0 + 0.0j, 3.0 - 4.0j]
)
value = SparsePauliOp(
["Y", "X", "Z", "I"], [2.0 + 0.0j, 1.0 + 0.0j, 3.0 - 4.0j, -1.0 + 2.0j]
).sort()
self.assertEqual(target, value)
with self.subTest(msg="1 qubit weight order"):
target = SparsePauliOp(
["I", "X", "Y", "Z"], [-1.0 + 2.0j, 1.0 + 0.0j, 2.0 + 0.0j, 3.0 - 4.0j]
)
value = SparsePauliOp(
["Y", "X", "Z", "I"], [2.0 + 0.0j, 1.0 + 0.0j, 3.0 - 4.0j, -1.0 + 2.0j]
).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="1 qubit multi Pauli"):
target = SparsePauliOp(
["I", "I", "I", "I", "X", "X", "Y", "Z"],
[
-1.0 + 2.0j,
1.0 + 0.0j,
2.0 + 0.0j,
3.0 - 4.0j,
-1.0 + 4.0j,
-1.0 + 5.0j,
-1.0 + 3.0j,
-1.0 + 2.0j,
],
)
value = SparsePauliOp(
["I", "I", "I", "I", "X", "Z", "Y", "X"],
[
2.0 + 0.0j,
1.0 + 0.0j,
3.0 - 4.0j,
-1.0 + 2.0j,
-1.0 + 5.0j,
-1.0 + 2.0j,
-1.0 + 3.0j,
-1.0 + 4.0j,
],
).sort()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit standard order"):
target = SparsePauliOp(
["II", "XI", "XX", "XX", "XX", "XY", "XZ", "YI"],
[
4.0 + 0.0j,
7.0 + 0.0j,
2.0 + 1.0j,
2.0 + 2.0j,
3.0 + 0.0j,
6.0 + 0.0j,
5.0 + 0.0j,
3.0 + 0.0j,
],
)
value = SparsePauliOp(
["XX", "XX", "XX", "YI", "II", "XZ", "XY", "XI"],
[
2.0 + 1.0j,
2.0 + 2.0j,
3.0 + 0.0j,
3.0 + 0.0j,
4.0 + 0.0j,
5.0 + 0.0j,
6.0 + 0.0j,
7.0 + 0.0j,
],
).sort()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit weight order"):
target = SparsePauliOp(
["II", "XI", "YI", "XX", "XX", "XX", "XY", "XZ"],
[
4.0 + 0.0j,
7.0 + 0.0j,
3.0 + 0.0j,
2.0 + 1.0j,
2.0 + 2.0j,
3.0 + 0.0j,
6.0 + 0.0j,
5.0 + 0.0j,
],
)
value = SparsePauliOp(
["XX", "XX", "XX", "YI", "II", "XZ", "XY", "XI"],
[
2.0 + 1.0j,
2.0 + 2.0j,
3.0 + 0.0j,
3.0 + 0.0j,
4.0 + 0.0j,
5.0 + 0.0j,
6.0 + 0.0j,
7.0 + 0.0j,
],
).sort(weight=True)
self.assertEqual(target, value)
def test_chop(self):
"""Test chop, which individually truncates real and imaginary parts of the coeffs."""
eps = 1e-10
op = SparsePauliOp(
["XYZ", "ZII", "ZII", "YZY"], coeffs=[eps + 1j * eps, 1 + 1j * eps, eps + 1j, 1 + 1j]
)
simplified = op.chop(tol=eps)
expected_coeffs = [1, 1j, 1 + 1j]
expected_paulis = ["ZII", "ZII", "YZY"]
self.assertListEqual(simplified.coeffs.tolist(), expected_coeffs)
self.assertListEqual(simplified.paulis.to_labels(), expected_paulis)
def test_chop_all(self):
"""Test that chop returns an identity operator with coeff 0 if all coeffs are chopped."""
eps = 1e-10
op = SparsePauliOp(["X", "Z"], coeffs=[eps, eps])
simplified = op.chop(tol=eps)
expected = SparsePauliOp(["I"], coeffs=[0.0])
self.assertEqual(simplified, expected)
@combine(num_qubits=[1, 2, 3, 4], num_ops=[1, 2, 3, 4], param=[None, "a"])
def test_sum(self, num_qubits, num_ops, param):
"""Test sum method for {num_qubits} qubits with {num_ops} operators."""
ops = [
self.random_spp_op(
num_qubits, 2**num_qubits, param if param is None else f"{param}_{i}"
)
for i in range(num_ops)
]
sum_op = SparsePauliOp.sum(ops)
value = sum_op.to_matrix()
target_operator = sum((op.to_matrix() for op in ops[1:]), ops[0].to_matrix())
if param is not None:
value = bind_parameters_to_one(value)
target_operator = bind_parameters_to_one(target_operator)
np.testing.assert_allclose(value, target_operator, atol=1e-8)
target_spp_op = sum((op for op in ops[1:]), ops[0])
self.assertEqual(sum_op, target_spp_op)
np.testing.assert_array_equal(sum_op.paulis.phase, np.zeros(sum_op.size))
def test_sum_error(self):
"""Test sum method with invalid cases."""
with self.assertRaises(QiskitError):
SparsePauliOp.sum([])
with self.assertRaises(QiskitError):
ops = [self.random_spp_op(num_qubits, 2**num_qubits) for num_qubits in [1, 2]]
SparsePauliOp.sum(ops)
with self.assertRaises(QiskitError):
SparsePauliOp.sum([1, 2])
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_eq(self, num_qubits, use_parameters):
"""Test __eq__ method for {num_qubits} qubits."""
spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
spp_op3 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
zero = spp_op3 - spp_op3
self.assertEqual(spp_op1, spp_op1)
self.assertEqual(spp_op2, spp_op2)
self.assertNotEqual(spp_op1, spp_op1 + zero)
self.assertNotEqual(spp_op2, spp_op2 + zero)
if spp_op1 != spp_op2:
self.assertNotEqual(spp_op1 + spp_op2, spp_op2 + spp_op1)
@combine(num_qubits=[1, 2, 3, 4])
def test_equiv(self, num_qubits):
"""Test equiv method for {num_qubits} qubits."""
spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits)
spp_op3 = self.random_spp_op(num_qubits, 2**num_qubits)
spp_op4 = self.random_spp_op(num_qubits, 2**num_qubits)
zero = spp_op3 - spp_op3
zero2 = spp_op4 - spp_op4
self.assertTrue(spp_op1.equiv(spp_op1))
self.assertTrue(spp_op1.equiv(spp_op1 + zero))
self.assertTrue(spp_op2.equiv(spp_op2))
self.assertTrue(spp_op2.equiv(spp_op2 + zero))
self.assertTrue(zero.equiv(zero2))
self.assertTrue((zero + zero2).equiv(zero2 + zero))
self.assertTrue((zero2 + zero).equiv(zero + zero2))
self.assertTrue((spp_op1 + spp_op2).equiv(spp_op2 + spp_op1))
self.assertTrue((spp_op2 + spp_op1).equiv(spp_op1 + spp_op2))
self.assertTrue((spp_op1 - spp_op1).equiv(spp_op2 - spp_op2))
self.assertTrue((2 * spp_op1).equiv(spp_op1 + spp_op1))
self.assertTrue((2 * spp_op2).equiv(spp_op2 + spp_op2))
if not spp_op1.equiv(zero):
self.assertFalse(spp_op1.equiv(spp_op1 + spp_op1))
if not spp_op2.equiv(zero):
self.assertFalse(spp_op2.equiv(spp_op2 + spp_op2))
def test_equiv_atol(self):
"""Test equiv method with atol."""
op1 = SparsePauliOp.from_list([("X", 1), ("Y", 2)])
op2 = op1 + 1e-7 * SparsePauliOp.from_list([("I", 1)])
self.assertFalse(op1.equiv(op2))
self.assertTrue(op1.equiv(op2, atol=1e-7))
def test_eq_equiv(self):
"""Test __eq__ and equiv methods with some specific cases."""
with self.subTest("shuffled"):
spp_op1 = SparsePauliOp.from_list([("X", 1), ("Y", 2)])
spp_op2 = SparsePauliOp.from_list([("Y", 2), ("X", 1)])
self.assertNotEqual(spp_op1, spp_op2)
self.assertTrue(spp_op1.equiv(spp_op2))
with self.subTest("w/ zero"):
spp_op1 = SparsePauliOp.from_list([("X", 1), ("Y", 1)])
spp_op2 = SparsePauliOp.from_list([("X", 1), ("Y", 1), ("Z", 0)])
self.assertNotEqual(spp_op1, spp_op2)
self.assertTrue(spp_op1.equiv(spp_op2))
@combine(parameterized=[True, False], qubit_wise=[True, False])
def test_group_commuting(self, parameterized, qubit_wise):
"""Test general grouping commuting operators"""
def commutes(left: Pauli, right: Pauli, qubit_wise: bool) -> bool:
if len(left) != len(right):
return False
if not qubit_wise:
return left.commutes(right)
else:
# qubit-wise commuting check
vec_l = left.z + 2 * left.x
vec_r = right.z + 2 * right.x
qubit_wise_comparison = (vec_l * vec_r) * (vec_l - vec_r)
return np.all(qubit_wise_comparison == 0)
input_labels = ["IX", "IY", "IZ", "XX", "YY", "ZZ", "XY", "YX", "ZX", "ZY", "XZ", "YZ"]
np.random.shuffle(input_labels)
if parameterized:
coeffs = np.array(ParameterVector("a", len(input_labels)))
else:
coeffs = np.random.random(len(input_labels)) + np.random.random(len(input_labels)) * 1j
sparse_pauli_list = SparsePauliOp(input_labels, coeffs)
groups = sparse_pauli_list.group_commuting(qubit_wise)
# checking that every input Pauli in sparse_pauli_list is in a group in the ouput
output_labels = [pauli.to_label() for group in groups for pauli in group.paulis]
self.assertListEqual(sorted(output_labels), sorted(input_labels))
# checking that every coeffs are grouped according to sparse_pauli_list group
paulis_coeff_dict = dict(
sum([list(zip(group.paulis.to_labels(), group.coeffs)) for group in groups], [])
)
self.assertDictEqual(dict(zip(input_labels, coeffs)), paulis_coeff_dict)
# Within each group, every operator commutes with every other operator.
for group in groups:
self.assertTrue(
all(
commutes(pauli1, pauli2, qubit_wise)
for pauli1, pauli2 in it.combinations(group.paulis, 2)
)
)
# For every pair of groups, at least one element from one group does not commute with
# at least one element of the other.
for group1, group2 in it.combinations(groups, 2):
self.assertFalse(
all(
commutes(group1_pauli, group2_pauli, qubit_wise)
for group1_pauli, group2_pauli in it.product(group1.paulis, group2.paulis)
)
)
def test_dot_real(self):
"""Test dot for real coefficiets."""
x = SparsePauliOp("X", np.array([1]))
y = SparsePauliOp("Y", np.array([1]))
iz = SparsePauliOp("Z", 1j)
self.assertEqual(x.dot(y), iz)
def test_get_parameters(self):
"""Test getting the parameters."""
x, y = Parameter("x"), Parameter("y")
op = SparsePauliOp(["X", "Y", "Z"], coeffs=[1, x, x * y])
with self.subTest(msg="all parameters"):
self.assertEqual(ParameterView([x, y]), op.parameters)
op.assign_parameters({y: 2}, inplace=True)
with self.subTest(msg="after partial binding"):
self.assertEqual(ParameterView([x]), op.parameters)
def test_assign_parameters(self):
"""Test assign parameters."""
x, y = Parameter("x"), Parameter("y")
op = SparsePauliOp(["X", "Y", "Z"], coeffs=[1, x, x * y])
# partial binding inplace
op.assign_parameters({y: 2}, inplace=True)
with self.subTest(msg="partial binding"):
self.assertListEqual(op.coeffs.tolist(), [1, x, 2 * x])
# bind via array
bound = op.assign_parameters([3])
with self.subTest(msg="fully bound"):
self.assertTrue(np.allclose(bound.coeffs.astype(complex), [1, 3, 6]))
def test_paulis_setter_rejects_bad_inputs(self):
"""Test that the setter for `paulis` rejects different-sized inputs."""
op = SparsePauliOp(["XY", "ZX"], coeffs=[1, 1j])
with self.assertRaisesRegex(ValueError, "incorrect number of qubits"):
op.paulis = PauliList([Pauli("X"), Pauli("Y")])
with self.assertRaisesRegex(ValueError, "incorrect number of operators"):
op.paulis = PauliList([Pauli("XY"), Pauli("ZX"), Pauli("YZ")])
if __name__ == "__main__":
unittest.main()
|
https://github.com/soultanis/Quantum-SAT-Solver
|
soultanis
|
import grover_test as gt
# Simulator-Backend
# output = gt.build_and_run(3, [1])
# IBMQ-Backend
output = gt.build_and_run(2, [1], real=True, online=True)
print(output)
|
https://github.com/qiskit-community/qiskit-dell-runtime
|
qiskit-community
|
from dell_runtime import DellRuntimeProvider
RUNTIME_PROGRAM = """
import random
from qiskit import transpile
from qiskit.circuit.random import random_circuit
def prepare_circuits(backend):
circuit = random_circuit(num_qubits=5, depth=4, measure=True,
seed=random.randint(0, 1000))
return transpile(circuit, backend)
def main(backend, user_messenger, **kwargs):
iterations = kwargs['iterations']
interim_results = kwargs.pop('interim_results', {})
final_result = kwargs.pop("final_result", {})
for it in range(iterations):
qc = prepare_circuits(backend)
user_messenger.publish({"iteration": it, "interim_results": interim_results})
backend.run(qc).result()
user_messenger.publish(final_result, final=True)
"""
RUNTIME_PROGRAM_METADATA = {
"max_execution_time": 600,
"description": "Qiskit test program"
}
PROGRAM_PREFIX = 'qiskit-test'
provider = DellRuntimeProvider()
provider.runtime.programs()
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
provider.runtime.pprint_programs()
runtime_program = provider.runtime.program(program_id)
program_inputs = {
"iterations": 10
}
job = provider.runtime.run(program_id, options=None, inputs=program_inputs)
job.status()
|
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
|
Qiskit-Extensions
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit_aer.primitives import EstimatorV2, SamplerV2
from circuit_knitting.cutting import (
partition_problem,
generate_cutting_experiments,
reconstruct_expectation_values,
)
from circuit_knitting.cutting.instructions import CutWire
from circuit_knitting.cutting import cut_wires, expand_observables
qc_0 = QuantumCircuit(7)
for i in range(7):
qc_0.rx(np.pi / 4, i)
qc_0.cx(0, 3)
qc_0.cx(1, 3)
qc_0.cx(2, 3)
qc_0.append(CutWire(), [3])
qc_0.cx(3, 4)
qc_0.cx(3, 5)
qc_0.cx(3, 6)
qc_0.append(CutWire(), [3])
qc_0.cx(0, 3)
qc_0.cx(1, 3)
qc_0.cx(2, 3)
qc_0.draw("mpl")
qc_0.decompose("cut_wire").draw("mpl")
observable = SparsePauliOp(["ZIIIIII", "IIIZIII", "IIIIIIZ"])
qc_1 = cut_wires(qc_0)
qc_1.draw("mpl")
observable_expanded_paulis = expand_observables(observable.paulis, qc_0, qc_1)
observable_expanded_paulis
partitioned_problem = partition_problem(
circuit=qc_1, observables=observable_expanded_paulis
)
subcircuits = partitioned_problem.subcircuits
subobservables = partitioned_problem.subobservables
subobservables
subcircuits[0].draw("mpl")
subcircuits[1].draw("mpl")
subexperiments, coefficients = generate_cutting_experiments(
circuits=subcircuits,
observables=subobservables,
num_samples=np.inf,
)
sampler = SamplerV2()
results = {
label: sampler.run(subexperiment, shots=2**12).result()
for label, subexperiment in subexperiments.items()
}
reconstructed_expvals = reconstruct_expectation_values(
results,
coefficients,
subobservables,
)
final_expval = np.dot(reconstructed_expvals, observable.coeffs)
estimator = EstimatorV2()
exact_expval = (
estimator.run([(qc_0.decompose("cut_wire"), observable)]).result()[0].data.evs
)
print(f"Reconstructed expectation value: {np.real(np.round(final_expval, 8))}")
print(f"Exact expectation value: {np.round(exact_expval, 8)}")
print(f"Error in estimation: {np.real(np.round(final_expval-exact_expval, 8))}")
print(
f"Relative error in estimation: {np.real(np.round((final_expval-exact_expval) / exact_expval, 8))}"
)
|
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/Glebegor/Quantum-programming-algorithms
|
Glebegor
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
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 qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
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)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
circ.draw('mpl')
from qiskit.quantum_info import Statevector
# Set the intial state of the simulator to the ground state using from_int
state = Statevector.from_int(0, 2**3)
# Evolve the state by the quantum circuit
state = state.evolve(circ)
#draw using latex
state.draw('latex')
from qiskit.visualization import array_to_latex
#Alternative way of representing in latex
array_to_latex(state)
state.draw('qsphere')
state.draw('hinton')
from qiskit.quantum_info import Operator
U = Operator(circ)
# Show the results
U.data
# Create a Quantum Circuit
meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
# map the quantum measurement to the classical bits
meas.measure(range(3), range(3))
# The Qiskit circuit object supports composition.
# Here the meas has to be first and front=True (putting it before)
# as compose must put a smaller circuit into a larger one.
qc = meas.compose(circ, range(3), front=True)
#drawing the circuit
qc.draw('mpl')
# Adding the transpiler to reduce the circuit to QASM instructions
# supported by the backend
from qiskit import transpile
# Use AerSimulator
from qiskit_aer import AerSimulator
backend = AerSimulator()
# First we have to transpile the quantum circuit
# to the low-level QASM instructions used by the
# backend
qc_compiled = transpile(qc, backend)
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = backend.run(qc_compiled, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc_compiled)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import pylab
from qiskit_chemistry import QiskitChemistry
# Input dictionary to configure Qiskit Chemistry for the chemistry problem.
qiskit_chemistry_dict = {
'problem': {'random_seed': 50},
'driver': {'name': 'PYSCF'},
'PYSCF': {'atom': 'H .0 .0 -0.3625; H .0 .0 0.3625', 'basis': 'sto3g'},
'operator': {'name': 'hamiltonian', 'qubit_mapping': 'jordan_wigner',
'two_qubit_reduction': False},
'algorithm': {'name': 'ExactEigensolver'},
'optimizer': {'name': 'COBYLA', 'maxiter': 10000 },
'variational_form': {'name': 'RYRZ', 'depth': 3, 'entanglement': 'full'},
'initial_state': {'name': 'ZERO'}
}
var_forms = ['RYRZ', 'RY']
entanglements = ['full', 'linear']
depths = [x for x in range(3, 11)]
energies = np.empty([len(var_forms), len(entanglements), len(depths)])
hf_energy = None
energy = None
eval_counts = np.empty([len(var_forms), len(entanglements), len(depths)])
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict)
hf_energy = result['hf_energy']
energy = result['energy']
print('Hartree-Fock energy:', hf_energy)
print('FCI energy:', energy)
qiskit_chemistry_dict['algorithm']['name'] = 'VQE'
print('Processing step __', end='')
for i, d in enumerate(depths):
print('\b\b{:2d}'.format(i), end='', flush=True)
qiskit_chemistry_dict['variational_form']['depth'] = d
for j in range(len(entanglements)):
qiskit_chemistry_dict['variational_form']['entanglement'] = entanglements[j]
for k in range(len(var_forms)):
qiskit_chemistry_dict['variational_form']['name'] = var_forms[k]
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict)
energies[k][j][i] = result['energy']
eval_counts[k][j][i] = result['algorithm_retvals']['eval_count']
print(' --- complete')
print('Depths: ', depths)
print('Energies:', energies)
print('Num evaluations:', eval_counts)
for k in range(len(var_forms)):
for j in range(len(entanglements)):
pylab.plot(depths, energies[k][j]-energy, label=var_forms[k]+' + '+entanglements[j])
pylab.xlabel('Variational form depth')
pylab.ylabel('Energy difference')
pylab.yscale('log')
pylab.title('H2 Ground State Energy Difference from Reference')
pylab.legend(loc='upper right')
for k in range(len(var_forms)):
for j in range(len(entanglements)):
pylab.plot(depths, eval_counts[k][j], '-o', label=var_forms[k]+' + '+entanglements[j])
pylab.xlabel('Variational form depth')
pylab.ylabel('Evaluations')
pylab.title('VQE number of evaluations')
pylab.legend(loc='upper right')
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
import qiskit
from qiskit import QuantumCircuit
# creating a quantum circuit
qc = QuantumCircuit(3)
qc.z(0)
qc.s(1)
qc.t(2)
qc.cx(0,1)
qc.h(2)
qc.ccx(0, 1, 2)
qc.draw()
# inverse of the quantum circuit
inverse_qc = qc.inverse()
# to draw the quantum circuit
inverse_qc.draw()
# If we measure the quantum circuit's each qubit's states
qc.measure()
# to draw the quantum circuit
qc.draw()
# inverse of the measured quantum circuit's qubit is not possible
inverse_qc = qc.inverse()
qc.measure()
# to draw the quantum circuit
inverse_qc.draw()
# creating a quantum circuit
m_circuit = QuantumCircuit(3)
m_circuit.h(2)
m_circuit.ccx(0, 1, 2)
m_circuit.cz(2, 1)
# draw the circuit
m_circuit.draw()
m_gate = m_circuit.to_gate()
type(m_gate)
new_circuit = QuantumCircuit(5)
new_circuit.append(m_gate, [1, 2, 4])
new_circuit.draw()
#decompose the circuit
new_circuit.decompose().draw()
from qiskit import QuantumCircuit, transpile, Aer
my_circuit = QuantumCircuit(3)
my_circuit.t(1)
my_circuit.h(0)
my_circuit.ccx(2,1,0)
my_circuit.s(2)
my_circuit.t(0)
my_circuit.draw()
my_gate = my_circuit.to_gate()
my_gate
my_inv_gate = my_gate.inverse()
my_inv_gate
my_inv_gate.name = 'My Inverse Gate'
new_circuit = QuantumCircuit(3)
new_circuit.append(my_inv_gate, [0,1,2])
new_circuit.draw()
new_circuit.decompose().draw()
my_circuit = QuantumCircuit(2)
my_circuit.cx(1,0)
my_circuit.cx(0,1)
my_circuit.cx(1,0)
my_circuit.draw()
my_gate = my_circuit.to_gate()
my_gate.name = "My Gate"
my_controlled_gate = my_gate.control()
new_circuit = QuantumCircuit(3)
new_circuit.append(my_controlled_gate, [0, 1, 2])
new_circuit.draw()
new_circuit.decompose().draw()
## What is the qsphere ?
## What is the unitary simulator ?
## How can i convert a Unitary Matrix to a set of One and Two Qubit gates ?
## How can i change qiskit's defoult behaviour ?
## How do i use parameterization circuit in Qiskit ?
## Why does qiskit order it's qubit the way it does ?
## How i combine two quantum circuits ?
## What is the difference between gates and instructions ?
## How can i use a specific version of qiskit ?
## How can i implement a multi controlled Toffoli Gate ?
## How can i monitor a job send to IBM Quantum ?
## How can i convert a quantum circuit to QASM ?
my_circuit = QuantumCircuit(3)
my_circuit.t(1)
my_circuit.h(0)
my_circuit.ccx(2,1,0)
my_circuit.s(2)
my_circuit.t(0)
my_circuit.draw('latex')
my_circuit.draw('latex_source')
print(my_circuit.draw('latex_source'))
## How can i bundle several circuit into a single job ?
## How can i save circuit Drawings to Different File Types ?
## How can i contruct a quantum volume circuit ?
## What trick can i do with draw methods ?
## How i can find reduced quantum states using qiskit ?
## In What different ways can i draw a quantum circuit ?
## How can i use a classical register for quantum compuation ?
## What is circuit depth and how can i calculate it ?
## How can i choose initial layout for the traspiler ?
## What are the Ancillary Qubits and how are they usefull ?
## What are registers ?
## How can i create a custom gate from matrix ?
## How can i find expectation value for an operator ?
## How can i measure the qubit midway through a quantum circuit ?
## How can i transpile a quantum circuit ?
## How can i make a noise model with qiskit ?
## How can i create a custome controlled gate ?
## How can i choose the best backend from a provider ?
## How can i perform state tomography ?
## How can i reset a qubit in a quantum circuit
## How do i perform a unitary projection in a quantum circuit ?
## How do i debuge an issue in transpiler ?
## How can i estimate Pi using a quantum computer ?
## How do i initialize a mixed states ?
## What is gate fidelity and how do i canculate it ?
## How do i check the state fedility with noisy simulator ?
## How do i change the fitter algorithm in a state tomography experiment ?
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit.providers.aer import AerProvider
from qiskit import Aer
from qiskit import QuantumCircuit
from qiskit.test.mock import FakeVigo
Aer.backends()
type(Aer.backends()[0])
Aer.backends()
for name in (Aer.backends()):
print(name)
Aer.backends()[0].name()
print(Aer.backends()[0])
print(Aer.backends()[-1])
Aer.backends()[0:8]
Aer.backends()[8:-1]
from qiskit.providers.aer import AerSimulator
backend=AerSimulator()
backend
backend.name()
qc=QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.measure_all()
qc.draw(output="mpl")
backend=AerSimulator()
result= backend.run(qc).result()
counts=result.get_counts()
print(counts)
backend=AerSimulator.from_backend(FakeVigo())
result= backend.run(qc).result()
counts=result.get_counts()
print(counts)
provider=AerProvider()
backend=provider.backends(name='aer_simulator')
backend
backend=provider.get_backend(name='aer_simulator')
backend
backend.name()
backend=Aer.backends(name='aer_simulator')
backend
backend=Aer.get_backend(name='aer_simulator')
backend
backend.name()
#from qiskit.providers.aer import AerSimulator
backend=AerSimulator() # creates an object of class AerSimulator
backend
backend.name()
|
https://github.com/anpaschool/quantum-computing
|
anpaschool
|
from qiskit import *
from math import pi
import numpy as np
from qiskit.visualization import *
import matplotlib.pyplot as plt
qc = QuantumCircuit(3)
qc.ccx(0,1,2)
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
qc = QuantumCircuit(3)
qc.cswap(0,1,2)
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# TODO: Remove after 0.7 and the deprecated methods are removed
# pylint: disable=unused-argument
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import errno
import logging
import os
import subprocess
import tempfile
from PIL import Image
from qiskit import user_config
from qiskit.visualization import exceptions
from qiskit.visualization import latex as _latex
from qiskit.visualization import text as _text
from qiskit.visualization import utils
from qiskit.visualization import matplotlib as _matplotlib
logger = logging.getLogger(__name__)
def circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Args:
circuit (QuantumCircuit): the quantum circuit to draw
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (str): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. By
default the 'text' drawer is used unless a user config file has
an alternative backend set as the default. If the output is passed
in that backend will always be used.
interactive (bool): when set true show the circuit in a new window
(for `mpl` this depends on the matplotlib backend being used
supporting this). Note when used with either the `text` or the
`latex_source` output type this has no effect and will be silently
ignored.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). However, if you're running in
jupyter the default line length is set to 80 characters. If you
don't want pagination at all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (string): Options are `left`, `right` or `none`, if anything
else is supplied it defaults to left justified. It refers to where
gates should be placed in the output circuit if there is an option.
`none` results in each gate being placed in its own column. Currently
only supported by text drawer.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
ImportError: when the output methods requieres non-installed libraries.
.. _style-dict-doc:
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'id': 'id',
'u0': 'U_0',
'u1': 'U_1',
'u2': 'U_2',
'u3': 'U_3',
'x': 'X',
'y': 'Y',
'z': 'Z',
'h': 'H',
's': 'S',
'sdg': 'S^\\dagger',
't': 'T',
'tdg': 'T^\\dagger',
'rx': 'R_x',
'ry': 'R_y',
'rz': 'R_z',
'reset': '\\left|0\\right\\rangle'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
"""
image = None
config = user_config.get_config()
# Get default from config file else use text
default_output = 'text'
if config:
default_output = config.get('circuit_drawer', 'text')
if output is None:
output = default_output
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename,
line_length=line_length,
reverse_bits=reverse_bits,
plotbarriers=plot_barriers,
justify=justify)
elif output == 'latex':
image = _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits,
justify=justify)
elif output == 'latex_source':
return _generate_latex_source(circuit,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits,
justify=justify)
elif output == 'mpl':
image = _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits,
justify=justify)
else:
raise exceptions.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if image and interactive:
image.show()
return image
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
"""Return default style for matplotlib_circuit_drawer (IBM QX style)."""
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"id": "id",
"u0": "U_0",
"u1": "U_1",
"u2": "U_2",
"u3": "U_3",
"x": "X",
"y": "Y",
"z": "Z",
"h": "H",
"s": "S",
"sdg": "S^\\dagger",
"t": "T",
"tdg": "T^\\dagger",
"rx": "R_x",
"ry": "R_y",
"rz": "R_z",
"reset": "\\left|0\\right\\rangle"
},
"displaycolor": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None, line_length=None, reverse_bits=False,
plotbarriers=True, justify=None, vertically_compressed=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reverse_bits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
vertically_compressed (bool): Default is `True`. It merges the lines so the
drawing will take less vertical room.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
qregs, cregs, ops = utils._get_layered_instructions(circuit,
reverse_bits=reverse_bits,
justify=justify)
text_drawing = _text.TextDrawing(qregs, cregs, ops)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
text_drawing.vertically_compressed = vertically_compressed
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def _latex_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits, justify=justify)
image = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as ex:
with open('latex_error.log', 'wb') as error_file:
error_file.write(ex.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
image = Image.open(base + '.png')
image = utils._trim(image)
os.remove(base + '.png')
if filename:
image.save(filename, 'PNG')
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return image
def _generate_latex_source(circuit, filename=None,
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True, justify=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
str: Latex string appropriate for writing to file.
"""
qregs, cregs, ops = utils._get_layered_instructions(circuit,
reverse_bits=reverse_bits,
justify=justify)
qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
qregs, cregs, ops = utils._get_layered_instructions(circuit,
reverse_bits=reverse_bits,
justify=justify)
qcd = _matplotlib.MatplotlibDrawer(qregs, cregs, ops, scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
return qcd.draw(filename)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_circuit_layout
from qiskit.tools.monitor import job_monitor
from qiskit.providers.fake_provider import FakeVigoV2
import matplotlib.pyplot as plt
ghz = QuantumCircuit(3, 3)
ghz.h(0)
for idx in range(1,3):
ghz.cx(0,idx)
ghz.measure(range(3), range(3))
backend = FakeVigoV2()
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
with pulse.build() as hahn_echo:
with pulse.align_equispaced(duration=100):
pulse.play(x90, d0)
pulse.play(x180, d0)
pulse.play(x90, d0)
hahn_echo.draw()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2022.
#
# 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 Iterative Quantum Phase Estimation Algorithm."""
from __future__ import annotations
import numpy
import qiskit
from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.circuit.classicalregister import ClassicalRegister
from qiskit.providers import Backend
from qiskit.utils import QuantumInstance
from qiskit.utils.deprecation import deprecate_arg
from qiskit_algorithms.exceptions import AlgorithmError
from .phase_estimator import PhaseEstimator
from .phase_estimator import PhaseEstimatorResult
from ...primitives import BaseSampler
class IterativePhaseEstimation(PhaseEstimator):
"""Run the Iterative quantum phase estimation (QPE) algorithm.
Given a unitary circuit and a circuit preparing an eigenstate, return the phase of the
eigenvalue as a number in :math:`[0,1)` using the iterative phase estimation algorithm.
[1]: Dobsicek et al. (2006), Arbitrary accuracy iterative phase estimation algorithm as a two
qubit benchmark, `arxiv/quant-ph/0610214 <https://arxiv.org/abs/quant-ph/0610214>`_
"""
@deprecate_arg(
"quantum_instance",
additional_msg=(
"Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a "
"migration guide."
),
since="0.24.0",
)
def __init__(
self,
num_iterations: int,
quantum_instance: QuantumInstance | Backend | None = None,
sampler: BaseSampler | None = None,
) -> None:
r"""
Args:
num_iterations: The number of iterations (rounds) of the phase estimation to run.
quantum_instance: Deprecated: The quantum instance on which the
circuit will be run.
sampler: The sampler primitive on which the circuit will be sampled.
Raises:
ValueError: if num_iterations is not greater than zero.
AlgorithmError: If neither sampler nor quantum instance is provided.
"""
if sampler is None and quantum_instance is None:
raise AlgorithmError(
"Neither a sampler nor a quantum instance was provided. Please provide one of them."
)
if isinstance(quantum_instance, Backend):
quantum_instance = QuantumInstance(quantum_instance)
self._quantum_instance = quantum_instance
if num_iterations <= 0:
raise ValueError("`num_iterations` must be greater than zero.")
self._num_iterations = num_iterations
self._sampler = sampler
def construct_circuit(
self,
unitary: QuantumCircuit,
state_preparation: QuantumCircuit,
k: int,
omega: float = 0.0,
measurement: bool = False,
) -> QuantumCircuit:
"""Construct the kth iteration Quantum Phase Estimation circuit.
For details of parameters, see Fig. 2 in https://arxiv.org/pdf/quant-ph/0610214.pdf.
Args:
unitary: The circuit representing the unitary operator whose eigenvalue (via phase)
will be measured.
state_preparation: The circuit that prepares the state whose eigenphase will be
measured. If this parameter is omitted, no preparation circuit
will be run and input state will be the all-zero state in the
computational basis.
k: the iteration idx.
omega: the feedback angle.
measurement: Boolean flag to indicate if measurement should
be included in the circuit.
Returns:
QuantumCircuit: the quantum circuit per iteration
"""
k = self._num_iterations if k is None else k
# The auxiliary (phase measurement) qubit
phase_register = QuantumRegister(1, name="a")
eigenstate_register = QuantumRegister(unitary.num_qubits, name="q")
qc = QuantumCircuit(eigenstate_register)
qc.add_register(phase_register)
if isinstance(state_preparation, QuantumCircuit):
qc.append(state_preparation, eigenstate_register)
elif state_preparation is not None:
qc += state_preparation.construct_circuit("circuit", eigenstate_register)
# hadamard on phase_register[0]
qc.h(phase_register[0])
# controlled-U
# TODO: We may want to allow flexibility in how the power is computed
# For example, it may be desirable to compute the power via Trotterization, if
# we are doing Trotterization anyway.
unitary_power = unitary.power(2 ** (k - 1)).control()
qc = qc.compose(unitary_power, [unitary.num_qubits] + list(range(0, unitary.num_qubits)))
qc.p(omega, phase_register[0])
# hadamard on phase_register[0]
qc.h(phase_register[0])
if measurement:
c = ClassicalRegister(1, name="c")
qc.add_register(c)
qc.measure(phase_register, c)
return qc
def _estimate_phase_iteratively(self, unitary, state_preparation):
"""
Main loop of iterative phase estimation.
"""
omega_coef = 0
# k runs from the number of iterations back to 1
for k in range(self._num_iterations, 0, -1):
omega_coef /= 2
if self._sampler is not None:
qc = self.construct_circuit(
unitary, state_preparation, k, -2 * numpy.pi * omega_coef, True
)
try:
sampler_job = self._sampler.run([qc])
result = sampler_job.result().quasi_dists[0]
except Exception as exc:
raise AlgorithmError("The primitive job failed!") from exc
x = 1 if result.get(1, 0) > result.get(0, 0) else 0
elif self._quantum_instance.is_statevector:
qc = self.construct_circuit(
unitary, state_preparation, k, -2 * numpy.pi * omega_coef, measurement=False
)
result = self._quantum_instance.execute(qc)
complete_state_vec = result.get_statevector(qc)
ancilla_density_mat = qiskit.quantum_info.partial_trace(
complete_state_vec, range(unitary.num_qubits)
)
ancilla_density_mat_diag = numpy.diag(ancilla_density_mat)
max_amplitude = max(
ancilla_density_mat_diag.min(), ancilla_density_mat_diag.max(), key=abs
)
x = numpy.where(ancilla_density_mat_diag == max_amplitude)[0][0]
else:
qc = self.construct_circuit(
unitary, state_preparation, k, -2 * numpy.pi * omega_coef, measurement=True
)
measurements = self._quantum_instance.execute(qc).get_counts(qc)
x = 1 if measurements.get("1", 0) > measurements.get("0", 0) else 0
omega_coef = omega_coef + x / 2
return omega_coef
# pylint: disable=signature-differs
def estimate(
self, unitary: QuantumCircuit, state_preparation: QuantumCircuit
) -> "IterativePhaseEstimationResult":
"""
Estimate the eigenphase of the input unitary and initial-state pair.
Args:
unitary: The circuit representing the unitary operator whose eigenvalue (via phase)
will be measured.
state_preparation: The circuit that prepares the state whose eigenphase will be
measured. If this parameter is omitted, no preparation circuit
will be run and input state will be the all-zero state in the
computational basis.
Returns:
Estimated phase in an IterativePhaseEstimationResult object.
Raises:
AlgorithmError: If neither sampler nor quantum instance is provided.
"""
phase = self._estimate_phase_iteratively(unitary, state_preparation)
return IterativePhaseEstimationResult(self._num_iterations, phase)
class IterativePhaseEstimationResult(PhaseEstimatorResult):
"""Phase Estimation Result."""
def __init__(self, num_iterations: int, phase: float) -> None:
"""
Args:
num_iterations: number of iterations used in the phase estimation.
phase: the estimated phase.
"""
self._num_iterations = num_iterations
self._phase = phase
@property
def phase(self) -> float:
r"""Return the estimated phase as a number in :math:`[0.0, 1.0)`.
1.0 corresponds to a phase of :math:`2\pi`. It is assumed that the input vector is an
eigenvector of the unitary so that the peak of the probability density occurs at the bit
string that most closely approximates the true phase.
"""
return self._phase
@property
def num_iterations(self) -> int:
r"""Return the number of iterations used in the estimation algorithm."""
return self._num_iterations
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_circuit_layout
from qiskit.tools.monitor import job_monitor
from qiskit.providers.fake_provider import FakeVigoV2
import matplotlib.pyplot as plt
ghz = QuantumCircuit(3, 3)
ghz.h(0)
for idx in range(1,3):
ghz.cx(0,idx)
ghz.measure(range(3), range(3))
backend = FakeVigoV2()
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/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/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2024 Qiskit on IQM developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A simple extension of the QuantumCircuit class to allow the MOVE
gate to be applied with a .move(qubit, resonator) shortcut."""
from qiskit import QuantumCircuit
from iqm.qiskit_iqm.move_gate import MoveGate
class IQMCircuit(QuantumCircuit):
"""Extends the QuantumCircuit class, adding a shortcut for applying the MOVE gate."""
def move(self, qubit: int, resonator: int):
"""Applies the MOVE gate to the circuit.
Note: at this point the circuit layout is only guaranteed to work if the order
of the qubit and the resonator is correct (qubit first, resonator second).
Args:
qubit: the logical index of the qubit
resonator: the logical index of the resonator
"""
self.append(MoveGate(), [qubit, resonator])
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#initialization
import sys
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing the QISKit
from qiskit import QuantumProgram
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
except:
qx_config = {
"APItoken":"YOUR_TOKEN_HERE",
"url":"https://quantumexperience.ng.bluemix.net/api"}
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
#set api
from IBMQuantumExperience import IBMQuantumExperience
api = IBMQuantumExperience(token=qx_config['APItoken'], config={'url': qx_config['url']})
#prepare backends
from qiskit.backends import discover_local_backends, discover_remote_backends, get_backend_instance
remote_backends = discover_remote_backends(api) #we have to call this to connect to remote backends
local_backends = discover_local_backends()
# Quantum program setup
Q_program = QuantumProgram()
#for plot with 16qubit
import numpy as np
from functools import reduce
from scipy import linalg as la
from collections import Counter
import matplotlib.pyplot as plt
def plot_histogram5(data, number_to_keep=False):
"""Plot a histogram of data.
data is a dictionary of {'000': 5, '010': 113, ...}
number_to_keep is the number of terms to plot and rest is made into a
single bar called other values
"""
if number_to_keep is not False:
data_temp = dict(Counter(data).most_common(number_to_keep))
data_temp["rest"] = sum(data.values()) - sum(data_temp.values())
data = data_temp
labels = sorted(data)
values = np.array([data[key] for key in labels], dtype=float)
pvalues = values / sum(values)
numelem = len(values)
ind = np.arange(numelem) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects = ax.bar(ind, pvalues, width, color='seagreen')
# add some text for labels, title, and axes ticks
ax.set_ylabel('Probabilities', fontsize=12)
ax.set_xticks(ind)
ax.set_xticklabels(labels, fontsize=12, rotation=70)
ax.set_ylim([0., min([1.2, max([1.2 * val for val in pvalues])])])
# attach some text labels
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height,
'%f' % float(height),
ha='center', va='bottom', fontsize=8)
plt.show()
q1_2 = Q_program.create_quantum_register("q1_2", 3)
c1_2 = Q_program.create_classical_register("c1_2", 3)
qw1_2 = Q_program.create_circuit("qw1_2", [q1_2], [c1_2])
t=8 #time
qw1_2.x(q1_2[2])
qw1_2.u3(t, 0, 0, q1_2[1])
qw1_2.cx(q1_2[2], q1_2[1])
qw1_2.u3(t, 0, 0, q1_2[1])
qw1_2.cx(q1_2[2], q1_2[1])
qw1_2.measure(q1_2[0], c1_2[0])
qw1_2.measure(q1_2[1], c1_2[2])
qw1_2.measure(q1_2[2], c1_2[1])
print(qw1_2.qasm())
result = Q_program.execute(["qw1_2"], backend='local_qiskit_simulator', shots=1000)
plot_histogram5(result.get_counts("qw1_2"))
result = Q_program.execute(["qw1_2"], backend='ibmqx4', shots=1000, max_credits=3, wait=10, timeout=1024)
plot_histogram5(result.get_counts("qw1_2"))
q1 = Q_program.create_quantum_register("q1", 3)
c1 = Q_program.create_classical_register("c1", 3)
qw1 = Q_program.create_circuit("qw1", [q1], [c1])
t=8 #time
qw1.x(q1[1])
qw1.cx(q1[2], q1[1])
qw1.u3(t, 0, 0, q1[2])
qw1.cx(q1[2], q1[0])
qw1.u3(t, 0, 0, q1[2])
qw1.cx(q1[2], q1[0])
qw1.cx(q1[2], q1[1])
qw1.u3(2*t, 0, 0, q1[2])
qw1.measure(q1[0], c1[0])
qw1.measure(q1[1], c1[1])
qw1.measure(q1[2], c1[2])
print(qw1.qasm())
result = Q_program.execute(["qw1"], backend='local_qiskit_simulator')
plot_histogram5(result.get_counts("qw1"))
result = Q_program.execute(["qw1"], backend='ibmqx4', shots=1000, max_credits=3, wait=10, timeout=600)
plot_histogram5(result.get_counts("qw1"))
|
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/matteoacrossi/oqs-jupyterbook
|
matteoacrossi
|
import numpy as np
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource, Slider, CustomJS, TextAnnotation
from bokeh.plotting import Figure, show
from bokeh.io import output_notebook
# Define data
x = [x*0.05 for x in range(0, 500)]
trigonometric_functions = {
'0': np.sin(x),
'1': np.cos(x),
'2': np.tan(x),
'3': np.arctan(x)}
initial_function = '0'
# Wrap the data in two ColumnDataSources
source_visible = ColumnDataSource(data=dict(
x=x, y=trigonometric_functions[initial_function]))
source_available = ColumnDataSource(data=trigonometric_functions)
# Define plot elements
plot = Figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source_visible, line_width=3, line_alpha=0.6)
slider = Slider(title='Trigonometric function',
value=int(initial_function),
start=np.min([int(i) for i in trigonometric_functions.keys()]),
end=np.max([int(i) for i in trigonometric_functions.keys()]),
step=1)
# Define CustomJS callback, which updates the plot based on selected function
# by updating the source_visible ColumnDataSource.
slider.callback = CustomJS(
args=dict(source_visible=source_visible,
source_available=source_available), code="""
var selected_function = cb_obj.value;
// Get the data from the data sources
var data_visible = source_visible.data;
var data_available = source_available.data;
// Change y-axis data according to the selected value
data_visible.y = data_available[selected_function];
// Update the plot
source_visible.change.emit();
""")
layout = row(plot, slider)
output_notebook()
show(layout)
def c1t(t, lam = 1., R = .25, c10 = 1.):
expt = lam * t / 2
if R == .5:
output = c10 * np.exp(-expt) * (1 + expt)
elif R == 0:
output = c10 * np.exp(-expt)
elif R < .5:
sqt = np.sqrt(1-2*R)
output = c10 * np.exp(-expt) * (np.cosh(expt * sqt) + np.sinh(expt*sqt) / sqt)
elif R > .5:
sqt = np.sqrt(-1+2*R)
output = c10 * np.exp(-expt) * (np.cos(expt * sqt) + np.sin(expt*sqt) / sqt)
return output
ts = [t*0.02 for t in range(0, 500)]
Rmin = 0
Rmax = 10
Rstep = .2
Rrange = np.arange(Rmin, Rmax, Rstep)
Rrange_str = [str(i) for i in range(len(Rrange))]
#Rrange_str = ['{:.1f}'.format(i) for i in Rrange] # truncate to two decimals
#Rrange_dict = {Rrange_str[i]:Rrange[i] for i,_ in enumerate(Rrange)}
ys = {r_str:[c1t(t, R = Rrange[int(r_str)])**2 for t in ts] for r_str in Rrange_str}
#ys = {r_str:[c1t(t, R = Rrange_dict[r_str])**2 for t in ts] for r_str in Rrange_str}
initial_y = Rrange_str[1]
# Wrap the data in two ColumnDataSources
source_visible = ColumnDataSource(data=dict(
x = ts, y = ys[initial_y]))
source_available = ColumnDataSource(data=ys)
# Define plot elements
plot = Figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source_visible, line_width=3, line_alpha=0.6)
slider = Slider(value=int(initial_function),
start=np.min([int(i) for i in ys.keys()]),
end=np.max([int(i) for i in ys.keys()]),
step=1,
show_value = False)
#slider = Slider(title='R = ',
# value=float(initial_function),
# start=float(Rrange_str[0]),
# end=float(Rrange_str[-1]),
# step=Rstep)
# Define CustomJS callback, which updates the plot based on selected function
# by updating the source_visible ColumnDataSource.
slider.callback = CustomJS(
args=dict(source_visible=source_visible,
source_available=source_available), code="""
var r_value = cb_obj.value;
// Get the data from the data sources
var data_visible = source_visible.data;
var data_available = source_available.data;
// Change y-axis data according to the selected value
data_visible.y = data_available[r_value];
// Update the plot
source_visible.change.emit();
""")
layout = row(plot, slider)
output_notebook()
show(layout)
|
https://github.com/ShabaniLab/qiskit-hackaton-2019
|
ShabaniLab
|
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from ising_kitaev import initialize_chain, move_chain, rotate_to_measurement_basis, add_measurement
zeeman_ferro = 0.01
zeeman_para = 10
initial_config = np.array([zeeman_ferro, zeeman_ferro, zeeman_ferro, zeeman_para])
final_config = np.array([zeeman_para, zeeman_ferro, zeeman_ferro, zeeman_ferro])
qreg = QuantumRegister(4)
creg = ClassicalRegister(3)
qcirc = QuantumCircuit(qreg, creg)
initialize_chain(qcirc, qreg, initial_config, 'logical_one')
qcirc.draw()
move_chain(qcirc, qreg, initial_config, final_config, 0, 0.25, 0.25, 1, 5, method='single')
qcirc.depth()
rotate_to_measurement_basis(qcirc, qreg, [1, 2, 3])
add_measurement(qcirc, qreg, creg, [1, 2, 3])
from qiskit import Aer, execute
backend = Aer.get_backend('qasm_simulator')
job = execute(qcirc, backend, shots=2000)
job.status()
result = job.result()
print(result.get_counts())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.circuit.library import UCCSD
ansatz = UCCSD()
ansatz.num_spin_orbitals = 10
from qiskit_nature.second_q.circuit.library import UCCSD
ansatz = UCCSD()
ansatz.num_spatial_orbitals = 5
from qiskit_nature.circuit.library import UCC, UVCC
ucc = UCC(qubit_converter=None, num_particles=None, num_spin_orbitals=None, excitations=None)
uvcc = UVCC(qubit_converter=None, num_modals=None, excitations=None)
from qiskit_nature.second_q.circuit.library import UCC, UVCC
ucc = UCC(num_spatial_orbitals=None, num_particles=None, excitations=None, qubit_converter=None)
uvcc = UVCC(num_modals=None, excitations=None, qubit_converter=None)
from qiskit_nature.circuit.library import HartreeFock, VSCF
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import DirectMapper, JordanWignerMapper
hf = HartreeFock(
num_spin_orbitals=4, num_particles=(1, 1), qubit_converter=QubitConverter(JordanWignerMapper())
)
vscf = VSCF(num_modals=[2, 2])
from qiskit_nature.second_q.circuit.library import HartreeFock, VSCF
from qiskit_nature.second_q.mappers import DirectMapper, JordanWignerMapper, QubitConverter
hf = HartreeFock()
hf.num_spatial_orbitals = 2
hf.num_particles = (1, 1)
hf.qubit_converter = QubitConverter(JordanWignerMapper())
vscf = VSCF()
vscf.num_modals = [2, 2]
from qiskit.providers.basicaer import BasicAer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms.ground_state_solvers import VQEUCCFactory
quantum_instance = QuantumInstance(BasicAer.get_backend("statevector_simulator"))
vqe_factory = VQEUCCFactory(quantum_instance=quantum_instance)
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.circuit.library import UCCSD
from qiskit_nature.second_q.algorithms.ground_state_solvers import VQEUCCFactory
estimator = Estimator()
ansatz = UCCSD()
optimizer = SLSQP()
vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer)
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver, VQEUCCFactory
from qiskit_nature.algorithms.excited_states_solvers import QEOM
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
vqe_factory = VQEUCCFactory()
converter = QubitConverter(JordanWignerMapper())
ground_state_solver = GroundStateEigensolver(converter, vqe_factory)
qeom = QEOM(ground_state_solver)
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.circuit.library import UCCSD
from qiskit_nature.second_q.algorithms.ground_state_solvers import (
GroundStateEigensolver,
VQEUCCFactory,
)
from qiskit_nature.second_q.algorithms.excited_states_solvers import QEOM
from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter
estimator = Estimator()
ansatz = UCCSD()
optimizer = SLSQP()
vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer)
converter = QubitConverter(JordanWignerMapper())
ground_state_solver = GroundStateEigensolver(converter, vqe_factory)
qeom = QEOM(ground_state_solver, estimator)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/GabrielPontolillo/QiskitPBT
|
GabrielPontolillo
|
import random
import numpy as np
from qiskit import QuantumCircuit
from QiskitPBT.case_studies.grovers_algorithm.grovers_algorithm import grovers_algorithm
from QiskitPBT.case_studies.grovers_algorithm.grovers_algorithm_helpers import RandomGroversOracleMarkedStatesPairGenerator
from QiskitPBT.property import Property
class GroversAlgorithmMostFrequentMarked(Property):
# specify the inputs that are to be generated
def get_input_generators(self):
return [RandomGroversOracleMarkedStatesPairGenerator(4, 6)]
# specify the preconditions for the test
def preconditions(self, oracle_pair):
oracle, marked_states = oracle_pair
if len(marked_states) == 0 or len(marked_states) > 2**(oracle.num_qubits - 1) - 1:
return False
return True
# specify the operations to be performed on the input
def operations(self, oracle_pair):
oracle, marked_states = oracle_pair
# one qubit is workspace
N = 2**(oracle.num_qubits-1)
# number of marked states is used to identify the number of grover iterations to apply
M = len(marked_states)
binary_states = []
# marked states to binary strings to check
for state in marked_states:
binary = bin(state)[2:]
binary = '0' * (oracle.num_qubits - 1 - len(binary)) + binary
binary = binary[::-1]
binary_states.append(binary)
# src Nielsen and Chuang, quantum computation and quantum information
n_iterations = int(np.floor((np.pi/4) * np.sqrt((N/M))))
circ = grovers_algorithm(oracle, n_iterations)
# TODO: need to implement this assert most frequent, or something like it, all i know about the output state
# is that the most frequent state should be from the list of marked, and (roughly) all should have the same distribution
# but maybe testing that is not easy to implement with what we have
self.statistical_analysis.assert_most_frequent(self, list(range(circ.num_qubits-1)), circ, binary_states, basis=["z"])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import transpile
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc_basis = transpile(qc, backend)
qc_basis.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXSimple
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXSimple(), backend=FakeBoeblingen())
|
https://github.com/qiskit-community/qiskit-dell-runtime
|
qiskit-community
|
# 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.
# Copyright 2021 Dell (www.dell.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from dell_runtime.emulator_runtime_job import EmulatorRuntimeJob
import unittest
from qiskit import QuantumCircuit, execute, transpile
from qiskit.providers import JobStatus
import unittest
from urllib.parse import urljoin
import os, requests
import json
# import pytest_mysql
from server.orchestrator.models import DBService, Job, User, RuntimeProgram, Message, db_service
import pytest
from datetime import datetime
from time import sleep
SERVER_URL = os.getenv('SERVER_URL')
RUNTIME_PROGRAM = """
from qiskit.compiler import transpile, schedule
def main(
backend,
user_messenger,
circuits,
**kwargs,
):
user_messenger.publish({'results': 'intermittently'})
circuits = transpile(
circuits,
)
if not isinstance(circuits, list):
circuits = [circuits]
# Compute raw results
result = backend.run(circuits, **kwargs).result()
user_messenger.publish({'results': 'finally'})
user_messenger.publish(result.to_dict(), final=True)
print("job complete successfully")
"""
RUNTIME_PROGRAM_METADATA = {
"max_execution_time": 600,
"description": "Qiskit test program"
}
# mysql_proc = pytest_mysql.factories.mysql_proc(port=3307)
def test_fetch_program_owner():
db_service = DBService()
rp = RuntimeProgram()
rp.program_id = "12"
rp.user_id = 1
rp.name = "test program"
rp.data = b'test program'
rp.program_metadata = "meta"
rp.status = 'Active'
rp.data_type = "DIR"
db_service.save_runtime_program(rp)
assert(db_service.fetch_program_owner("12") == 1)
def test_fetch_job_owner():
db_service = DBService()
rp = RuntimeProgram()
rp.program_id = "12"
rp.user_id = 1
rp.name = "test program"
rp.data = b'test program'
rp.program_metadata = "meta"
rp.status = 'Active'
rp.data_type = "DIR"
db_service.save_runtime_program(rp)
jb = Job()
jb.job_id = "123"
jb.program_id = "12"
jb.job_status = "Completed"
jb.pod_name = "pod"
jb.pod_status = "Running"
jb.data_token = "USED"
db_service.save_runtime_program(jb)
assert(db_service.fetch_job_owner("123") == 1)
def test_see_programs():
db_service = DBService()
rp = RuntimeProgram()
rp.program_id = "14"
rp.user_id = 1
rp.name = "test program"
rp.data = b'test program'
rp.program_metadata = "meta"
rp.status = 'Active'
rp.data_type = "DIR"
db_service.save_runtime_program(rp)
rp = RuntimeProgram()
rp.program_id = "13"
rp.user_id = 1
rp.name = "test program"
rp.data = b'test program'
rp.program_metadata = "meta"
rp.status = 'Active'
rp.data_type = "DIR"
db_service.save_runtime_program(rp)
rp = RuntimeProgram()
rp.program_id = "12"
rp.user_id = 2
rp.name = "test program"
rp.data = b'test program'
rp.program_metadata = "meta"
rp.status = 'Active'
rp.data_type = "DIR"
db_service.save_runtime_program(rp)
assert(len(db_service.fetch_runtime_programs(1)) == 2)
def test_use_job_token():
db_service = DBService()
jb = Job()
jb.job_id = "123"
jb.program_id = "12"
jb.job_status = "Completed"
jb.pod_name = "pod"
jb.pod_status = "Running"
jb.data_token = "token"
db_service.save_runtime_program(jb)
db_service.use_job_token("123")
assert(db_service.fetch_job_token("123") == "USED")
def test_fetch_messages_timestamp():
db_service = DBService()
db_service.save_message("123", "this message")
msgs = db_service.fetch_messages("123", None)
assert(len(msgs) == 1)
ts = datetime.fromisoformat(msgs[0]["timestamp"])
sleep(2)
db_service.save_message("123", "another message")
newmsgs = db_service.fetch_messages("123", ts)
assert(len(newmsgs) == 1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager
circ = QuantumCircuit(3)
circ.ccx(0, 1, 2)
circ.draw(output='mpl')
from qiskit.transpiler.passes import Unroller
pass_ = Unroller(['u1', 'u2', 'u3', 'cx'])
pm = PassManager(pass_)
new_circ = pm.run(circ)
new_circ.draw(output='mpl')
from qiskit.transpiler import passes
[pass_ for pass_ in dir(passes) if pass_[0].isupper()]
from qiskit.transpiler import CouplingMap, Layout
from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
circuit = QuantumCircuit(7)
circuit.h(3)
circuit.cx(0, 6)
circuit.cx(6, 0)
circuit.cx(0, 1)
circuit.cx(3, 1)
circuit.cx(3, 0)
coupling_map = CouplingMap(couplinglist=coupling)
bs = BasicSwap(coupling_map=coupling_map)
pass_manager = PassManager(bs)
basic_circ = pass_manager.run(circuit)
ls = LookaheadSwap(coupling_map=coupling_map)
pass_manager = PassManager(ls)
lookahead_circ = pass_manager.run(circuit)
ss = StochasticSwap(coupling_map=coupling_map)
pass_manager = PassManager(ss)
stochastic_circ = pass_manager.run(circuit)
circuit.draw(output='mpl')
basic_circ.draw(output='mpl')
lookahead_circ.draw(output='mpl')
stochastic_circ.draw(output='mpl')
import math
from qiskit.providers.fake_provider import FakeTokyo
backend = FakeTokyo() # mimics the tokyo device in terms of coupling map and basis gates
qc = QuantumCircuit(10)
random_state = [
1 / math.sqrt(4) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
0,
0,
0,
0,
0,
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
0,
0,
0,
1 / math.sqrt(4) * complex(1, 0),
1 / math.sqrt(8) * complex(1, 0)]
qc.initialize(random_state, range(4))
qc.draw()
optimized_0 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=0)
print('gates = ', optimized_0.count_ops())
print('depth = ', optimized_0.depth())
optimized_1 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=1)
print('gates = ', optimized_1.count_ops())
print('depth = ', optimized_1.depth())
optimized_2 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=2)
print('gates = ', optimized_2.count_ops())
print('depth = ', optimized_2.depth())
optimized_3 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=3)
print('gates = ', optimized_3.count_ops())
print('depth = ', optimized_3.depth())
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
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)
circ.draw(output='mpl')
from qiskit.converters import circuit_to_dag
from qiskit.tools.visualization import dag_drawer
dag = circuit_to_dag(circ)
dag_drawer(dag)
dag.op_nodes()
node = dag.op_nodes()[3]
print("node name: ", node.name)
print("node op: ", node.op)
print("node qargs: ", node.qargs)
print("node cargs: ", node.cargs)
print("node condition: ", node.op.condition)
from qiskit.circuit.library import HGate
dag.apply_operation_back(HGate(), qargs=[q[0]])
dag_drawer(dag)
from qiskit.circuit.library import CCXGate
dag.apply_operation_front(CCXGate(), qargs=[q[0], q[1], q[2]], cargs=[])
dag_drawer(dag)
from qiskit.circuit.library import CHGate, U2Gate, CXGate
mini_dag = DAGCircuit()
p = QuantumRegister(2, "p")
mini_dag.add_qreg(p)
mini_dag.apply_operation_back(CHGate(), qargs=[p[1], p[0]])
mini_dag.apply_operation_back(U2Gate(0.1, 0.2), qargs=[p[1]])
# substitute the cx node with the above mini-dag
cx_node = dag.op_nodes(op=CXGate).pop()
dag.substitute_node_with_dag(node=cx_node, input_dag=mini_dag, wires=[p[0], p[1]])
dag_drawer(dag)
from qiskit.converters import dag_to_circuit
circuit = dag_to_circuit(dag)
circuit.draw(output='mpl')
from copy import copy
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler import Layout
from qiskit.circuit.library import SwapGate
class BasicSwap(TransformationPass):
"""Maps (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates."""
def __init__(self,
coupling_map,
initial_layout=None):
"""Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
coupling_map (CouplingMap): Directed graph represented a coupling map.
initial_layout (Layout): initial layout of qubits in mapping
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
def run(self, dag):
"""Runs the BasicSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG.
"""
new_dag = DAGCircuit()
for qreg in dag.qregs.values():
new_dag.add_qreg(qreg)
for creg in dag.cregs.values():
new_dag.add_creg(creg)
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.qubits) != len(self.initial_layout):
raise TranspilerError('The layout does not match the amount of qubits in the DAG')
if len(self.coupling_map.physical_qubits) != len(self.initial_layout):
raise TranspilerError(
"Mappers require to have the layout to be the same size as the coupling map")
canonical_register = dag.qregs['q']
trivial_layout = Layout.generate_trivial_layout(canonical_register)
current_layout = trivial_layout.copy()
for layer in dag.serial_layers():
subdag = layer['graph']
for gate in subdag.two_qubit_ops():
physical_q0 = current_layout[gate.qargs[0]]
physical_q1 = current_layout[gate.qargs[1]]
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
# Insert a new layer with the SWAP(s).
swap_layer = DAGCircuit()
swap_layer.add_qreg(canonical_register)
path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1)
for swap in range(len(path) - 2):
connected_wire_1 = path[swap]
connected_wire_2 = path[swap + 1]
qubit_1 = current_layout[connected_wire_1]
qubit_2 = current_layout[connected_wire_2]
# create the swap operation
swap_layer.apply_operation_back(SwapGate(),
qargs=[qubit_1, qubit_2],
cargs=[])
# layer insertion
order = current_layout.reorder_bits(new_dag.qubits)
new_dag.compose(swap_layer, qubits=order)
# update current_layout
for swap in range(len(path) - 2):
current_layout.swap(path[swap], path[swap + 1])
order = current_layout.reorder_bits(new_dag.qubits)
new_dag.compose(subdag, qubits=order)
return new_dag
q = QuantumRegister(7, 'q')
in_circ = QuantumCircuit(q)
in_circ.h(q[0])
in_circ.cx(q[0], q[4])
in_circ.cx(q[2], q[3])
in_circ.cx(q[6], q[1])
in_circ.cx(q[5], q[0])
in_circ.rz(0.1, q[2])
in_circ.cx(q[5], q[0])
from qiskit.transpiler import PassManager
from qiskit.transpiler import CouplingMap
from qiskit import BasicAer
pm = PassManager()
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
coupling_map = CouplingMap(couplinglist=coupling)
pm.append([BasicSwap(coupling_map)])
out_circ = pm.run(in_circ)
in_circ.draw(output='mpl')
out_circ.draw(output='mpl')
import logging
logging.basicConfig(level='DEBUG')
from qiskit.providers.fake_provider import FakeTenerife
log_circ = QuantumCircuit(2, 2)
log_circ.h(0)
log_circ.h(1)
log_circ.h(1)
log_circ.x(1)
log_circ.cx(0, 1)
log_circ.measure([0,1], [0,1])
backend = FakeTenerife()
transpile(log_circ, backend);
logging.getLogger('qiskit.transpiler').setLevel('INFO')
transpile(log_circ, backend);
# Change log level back to DEBUG
logging.getLogger('qiskit.transpiler').setLevel('DEBUG')
# Transpile multiple circuits
circuits = [log_circ, log_circ]
transpile(circuits, backend);
formatter = logging.Formatter('%(name)s - %(processName)-10s - %(levelname)s: %(message)s')
handler = logging.getLogger().handlers[0]
handler.setFormatter(formatter)
transpile(circuits, backend);
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
### removed z gate ###
pass
return qc
def decode_message(qc):
### removed cx gate ###
qc.h(1)
return qc
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
from qiskit import QuantumRegister, ClassicalRegister, BasicAer
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import NormalDistribution,UniformDistribution,LogNormalDistribution
from kaleidoscope import qsphere, probability_distribution
#provider = IBMQ.load_account()
#backend = provider.get_backend('ibmq_qasm_simulator')
backend = BasicAer.get_backend('qasm_simulator')
qubits = 5
q = QuantumRegister(qubits,'q')
c = ClassicalRegister(qubits,'c')
print("\n Normal Distribution")
print("-----------------")
circuit = QuantumCircuit(q,c)
normal = NormalDistribution(num_qubits = qubits, mu=0, sigma=0.1, bounds=([-1,1]))
circuit.append(normal, list(range(qubits)))
circuit.measure(q,c)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
sortedcounts = []
sortedkeys = sorted(counts)
for i in sortedkeys:
for j in counts:
if(i == j):
sortedcounts.append(counts.get(j))
plt.suptitle('Normal Distribution')
plt.plot(sortedcounts)
plt.show()
probability_distribution(counts)
circuit.decompose().decompose().draw('mpl')
print("\n Uniform Distribution")
print("-----------------")
circuit = QuantumCircuit(q,c)
uniform = UniformDistribution(num_qubits = qubits)
circuit.append(uniform, list(range(qubits)))
circuit.measure(q,c)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
sortedcounts = []
sortedkeys = sorted(counts)
for i in sortedkeys:
for j in counts:
if(i == j):
sortedcounts.append(counts.get(j))
plt.suptitle('Uniform Distribution')
plt.plot(sortedcounts)
plt.show()
probability_distribution(counts)
circuit.decompose().draw('mpl')
print("\n Log-Normal Distribution")
print("-----------------")
circuit = QuantumCircuit(q,c)
lognorm = LogNormalDistribution(num_qubits = qubits, mu=0.5, sigma=0.05, bounds=([0,4]))
circuit.append(lognorm, list(range(qubits)))
circuit.measure(q,c)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
sortedcounts = []
sortedkeys = sorted(counts)
for i in sortedkeys:
for j in counts:
if(i == j):
sortedcounts.append(counts.get(j))
plt.suptitle('Log-Normal Distribution')
plt.plot(sortedcounts)
plt.show()
probability_distribution(counts)
from qiskit.finance.applications import GaussianConditionalIndependenceModel as GCI
print("\n Gaussian Conditional Independence Distribution")
print("-----------------")
# set problem parameters
n_z = qubits
z_max = qubits
#p_zeros = [0.15, 0.25, 0.09, 0.05, 0.01]
#rhos = [0.1, 0.05, 0.04, 0.03, 0.01]
p_zeros = [0.15, 0.25]
rhos = [0.1, 0.05]
circuit = GCI(n_z, z_max, p_zeros, rhos)
circuit.measure_all()
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
sortedcounts = []
sortedkeys = sorted(counts)
for i in sortedkeys:
for j in counts:
if(i == j):
sortedcounts.append(counts.get(j))
plt.suptitle('Log-Normal Distribution')
plt.plot(sortedcounts)
plt.show()
probability_distribution(counts)
from qiskit.aqua.algorithms import AmplitudeEstimation
estimation_qubits = 4
ae_lognormal = AmplitudeEstimation(estimation_qubits, state_preparation=lognorm)
ae_uniform = AmplitudeEstimation(estimation_qubits, state_preparation=uniform)
ae_normal = AmplitudeEstimation(estimation_qubits, state_preparation=normal)
result_lognormal = ae_lognormal.run(quantum_instance=BasicAer.get_backend('qasm_simulator'))
result_uniform = ae_uniform.run(quantum_instance=BasicAer.get_backend('qasm_simulator'))
result_normal = ae_normal.run(quantum_instance=BasicAer.get_backend('qasm_simulator'))
# plot estimated values
plt.bar(result_uniform['mapped_a_samples'], result_uniform['probabilities'], width=0.5/len(result_uniform['probabilities']))
plt.bar(result_lognormal['mapped_a_samples'], result_lognormal['probabilities'], width=0.5/len(result_lognormal['probabilities']))
#plt.bar(result_normal['mapped_a_samples'], result_normal['probabilities'], width=0.5/len(result_normal['probabilities']))
plt.xticks([0, 0.25, 0.5, 0.75, 1], 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.ylim((0,1))
plt.grid()
plt.show()
print(result_lognormal)
print(result_uniform)
print(result_normal)
estimation_qubits = 7
ae_lognormal = AmplitudeEstimation(estimation_qubits, state_preparation=lognorm)
result_lognormal = ae_lognormal.run(quantum_instance=BasicAer.get_backend('qasm_simulator'))
plt.bar(result_lognormal['mapped_a_samples'], result_lognormal['probabilities'], width=0.5/len(result_lognormal['probabilities']))
plt.title('Estimated Values', size=15)
plt.ylabel('Probability', size=15)
plt.ylim((0,1))
plt.grid()
|
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
|
mnp-club
|
from qiskit import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import matplotlib.pyplot as plotter
import numpy as np
from IPython.display import display, Math, Latex
%matplotlib inline
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 200000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
# qc1 was already initialised to |1>|1>.
qc1.h(0)
# qc1 => (|0>|1> + |1>|1>)/sqrt(2)
qc1.cx(0,1)
# qc1 => (|0>|1> + |1>|0>)/sqrt(2)
#measure
qc1.measure([0,1],[0,1])
counts = run_circuit(qc1)
print(counts)
plot_histogram(counts)
qc_swap = QuantumCircuit(2,2)
qc_swap.x(0)
#initial state => |1>|0>
# applying swap
qc_swap.cx(0,1)
qc_swap.cx(1,0)
qc_swap.cx(0,1) #Following from the circuit diagram.
# There is also qc_swap.swap(0,1)
# measure
qc_swap.measure([0,1],[0,1])
counts = run_circuit(qc_swap)
print(counts)
plot_histogram(counts)
qc5 = QuantumCircuit(2,2)
qc5.x(1)
# initial state is |0>|1> SO THAT WE KNOW WHAT BOTH |0> AND |1> MAP TO.
# A lot of people did a mistake here in not understanding why we are using |0> and |1>
#apply HZH on both qubits.
qc5.h([0,1])
qc5.z([0,1])
qc5.h([0,1])
# measure
qc5.measure([0,1],[0,1])
counts = run_circuit(qc5)
print(counts)
plot_histogram(counts)
# final state would be |1>|0> = X(|0>|1>)
# Hence they are equal (Actually not. We can only conclude that they agree only upto a global phase. I think now you can appreciate this now.)
qc6 = QuantumCircuit(3,3)
qc6.x(0) # Set any one qubit of the 2 swapping qubits to '1' to see a noticable difference between input and output.
qc6.initialize([1/np.sqrt(2), -complex(1,1)/2],2) # Optional. Initializing the 3rd qubit.
# convert 3rd qubit into |1>
qc6.tdg(2)
qc6.h(2)
# OR
#qc6.t(2)
#qc6.s(2)
#qc6.h(2)
#qc6.x(2)
# You can check that they are equivalent.
# As you know now, it's a Fredkin gate.
qc6.toffoli(2,1,0)
qc6.toffoli(2,0,1)
qc6.toffoli(2,1,0)
#reset the third qubit to its intial state
qc6.h(2)
qc6.t(2)
# Measure
qc6.measure([0,1,2],[0,1,2])
counts = run_circuit(qc6)
print(counts)
plot_histogram(counts)
|
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/Morcu/Qiskit_Hands-on-lab
|
Morcu
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit.circuit.library.standard_gates import XGate, HGate
from operator import *
n = 3
N = 8 #2**n
index_colour_table = {}
colour_hash_map = {}
index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"}
colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'}
def database_oracle(index_colour_table, colour_hash_map):
circ_database = QuantumCircuit(n + n)
for i in range(N):
circ_data = QuantumCircuit(n)
idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
# qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0
# we therefore reverse the index string -> q0, ..., qn
data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour)
circ_database.append(data_gate, list(range(n+n)))
return circ_database
# drawing the database oracle circuit
print("Database Encoding")
database_oracle(index_colour_table, colour_hash_map).draw()
circ_data = QuantumCircuit(n)
m = 4
idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
print("Internal colour encoding for the colour green (as an example)");
circ_data.draw()
def oracle_grover(database, data_entry):
circ_grover = QuantumCircuit(n + n + 1)
circ_grover.append(database, list(range(n+n)))
target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target")
# control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()'
# The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.
circ_grover.append(target_reflection_gate, list(range(n, n+n+1)))
circ_grover.append(database, list(range(n+n)))
return circ_grover
print("Grover Oracle (target example: orange)")
oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw()
def mcz_gate(num_qubits):
num_controls = num_qubits - 1
mcz_gate = QuantumCircuit(num_qubits)
target_mcz = QuantumCircuit(1)
target_mcz.z(0)
target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ")
mcz_gate.append(target_mcz, list(range(num_qubits)))
return mcz_gate.reverse_bits()
print("Multi-controlled Z (MCZ) Gate")
mcz_gate(n).decompose().draw()
def diffusion_operator(num_qubits):
circ_diffusion = QuantumCircuit(num_qubits)
qubits_list = list(range(num_qubits))
# Layer of H^n gates
circ_diffusion.h(qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of Multi-controlled Z (MCZ) Gate
circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of H^n gates
circ_diffusion.h(qubits_list)
return circ_diffusion
print("Diffusion Circuit")
diffusion_operator(n).draw()
# Putting it all together ... !!!
item = "green"
print("Searching for the index of the colour", item)
circuit = QuantumCircuit(n + n + 1, n)
circuit.x(n + n)
circuit.barrier()
circuit.h(list(range(n)))
circuit.h(n+n)
circuit.barrier()
unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator")
unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator")
M = countOf(index_colour_table.values(), item)
Q = int(np.pi * np.sqrt(N/M) / 4)
for i in range(Q):
circuit.append(unitary_oracle, list(range(n + n + 1)))
circuit.append(unitary_diffuser, list(range(n)))
circuit.barrier()
circuit.measure(list(range(n)), list(range(n)))
circuit.draw()
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
if M==1:
print("Index of the colour", item, "is the index with most probable outcome")
else:
print("Indices of the colour", item, "are the indices the most probable outcomes")
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# External imports
from pylab import cm
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
# Qiskit imports
from qiskit import QuantumCircuit
from qiskit.circuit import ParameterVector
from qiskit.visualization import circuit_drawer
from qiskit.algorithms.optimizers import SPSA
from qiskit.circuit.library import ZZFeatureMap
from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel
from qiskit_machine_learning.kernels.algorithms import QuantumKernelTrainer
from qiskit_machine_learning.algorithms import QSVC
from qiskit_machine_learning.datasets import ad_hoc_data
class QKTCallback:
"""Callback wrapper class."""
def __init__(self) -> None:
self._data = [[] for i in range(5)]
def callback(self, x0, x1=None, x2=None, x3=None, x4=None):
"""
Args:
x0: number of function evaluations
x1: the parameters
x2: the function value
x3: the stepsize
x4: whether the step was accepted
"""
self._data[0].append(x0)
self._data[1].append(x1)
self._data[2].append(x2)
self._data[3].append(x3)
self._data[4].append(x4)
def get_callback_data(self):
return self._data
def clear_callback_data(self):
self._data = [[] for i in range(5)]
adhoc_dimension = 2
X_train, y_train, X_test, y_test, adhoc_total = ad_hoc_data(
training_size=20,
test_size=5,
n=adhoc_dimension,
gap=0.3,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
plt.scatter(
X_train[np.where(y_train[:] == 0), 0],
X_train[np.where(y_train[:] == 0), 1],
marker="s",
facecolors="w",
edgecolors="b",
label="A train",
)
plt.scatter(
X_train[np.where(y_train[:] == 1), 0],
X_train[np.where(y_train[:] == 1), 1],
marker="o",
facecolors="w",
edgecolors="r",
label="B train",
)
plt.scatter(
X_test[np.where(y_test[:] == 0), 0],
X_test[np.where(y_test[:] == 0), 1],
marker="s",
facecolors="b",
edgecolors="w",
label="A test",
)
plt.scatter(
X_test[np.where(y_test[:] == 1), 0],
X_test[np.where(y_test[:] == 1), 1],
marker="o",
facecolors="r",
edgecolors="w",
label="B test",
)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for classification")
plt.show()
# Create a rotational layer to train. We will rotate each qubit the same amount.
training_params = ParameterVector("θ", 1)
fm0 = QuantumCircuit(2)
fm0.ry(training_params[0], 0)
fm0.ry(training_params[0], 1)
# Use ZZFeatureMap to represent input data
fm1 = ZZFeatureMap(2)
# Create the feature map, composed of our two circuits
fm = fm0.compose(fm1)
print(circuit_drawer(fm))
print(f"Trainable parameters: {training_params}")
# Instantiate quantum kernel
quant_kernel = TrainableFidelityQuantumKernel(feature_map=fm, training_parameters=training_params)
# Set up the optimizer
cb_qkt = QKTCallback()
spsa_opt = SPSA(maxiter=10, callback=cb_qkt.callback, learning_rate=0.05, perturbation=0.05)
# Instantiate a quantum kernel trainer.
qkt = QuantumKernelTrainer(
quantum_kernel=quant_kernel, loss="svc_loss", optimizer=spsa_opt, initial_point=[np.pi / 2]
)
# Train the kernel using QKT directly
qka_results = qkt.fit(X_train, y_train)
optimized_kernel = qka_results.quantum_kernel
print(qka_results)
# Use QSVC for classification
qsvc = QSVC(quantum_kernel=optimized_kernel)
# Fit the QSVC
qsvc.fit(X_train, y_train)
# Predict the labels
labels_test = qsvc.predict(X_test)
# Evalaute the test accuracy
accuracy_test = metrics.balanced_accuracy_score(y_true=y_test, y_pred=labels_test)
print(f"accuracy test: {accuracy_test}")
plot_data = cb_qkt.get_callback_data() # callback data
K = optimized_kernel.evaluate(X_train) # kernel matrix evaluated on the training samples
plt.rcParams["font.size"] = 20
fig, ax = plt.subplots(1, 2, figsize=(14, 5))
ax[0].plot([i + 1 for i in range(len(plot_data[0]))], np.array(plot_data[2]), c="k", marker="o")
ax[0].set_xlabel("Iterations")
ax[0].set_ylabel("Loss")
ax[1].imshow(K, cmap=cm.get_cmap("bwr", 20))
fig.tight_layout()
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
dc = pulse.DriveChannel
d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4)
with pulse.build(name='pulse_programming_in') as pulse_prog:
pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3)
pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4)
pulse_prog.draw()
|
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
|
Andres8bit
|
#in general we can transform a single CNOT inot a controlled
#version of any rotaion around the Bloch sphere by an angle pi,
#by simply preceding and following it with the correct rotations.
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.circuit import Gate
from math import pi
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
qc = QuantumCircuit(2)
c =0
t =1
#built in controlled-Z
#recall a Z-GATE converts a |+> qubit to a |-> and vive-versa
qc.cz(c,t)
qc.draw()
#converting a CNOT into a CONTROLLED-Z
qc = QuantumCircuit(2)
qc.h(t)
qc.cx(c,t)
qc.h(t)
qc.draw()
#CONTROLLED-Y GATE.
qc = QuantumCircuit(2)
qc.sdg(t)
qc.cx(c,t)
qc.s(t)
qc.draw()
#CONTROLLED-H GATE
qc = QuantumCircuit(2)
qc.ry(pi/4,t)
qc.cx(c,t)
qc.ry(-pi/4,t)
qc.draw()
#SWAPPING QUBITS:
#sometime we need to move information around in a quantum Computer.
#one option is to move the state between two qubits.
a = 0
b = 1
#swaps states oc qubits a and b
qc = QuantumCircuit(2)
qc.swap(a,b)
qc.draw()
# we will now develope a swap gate using he base gate.
#first we will look at the |1> and |0> cases:
#swaps 1 from a to b:
# puts qubits b in state |1> and qubit a in state |0>
qc = QuantumCircuit(2)
qc.cx(a,b) #copies 1 from a to b
qc.cx(b,a) #uses the 1 on b to rotate the state of a to 0
qc.draw()
#swap back to original state
qc.cx(b,a)
qc.cx(a,b)
qc.draw()
#more general swap gate:
# works for |00>,|01>,|10> and |11>
#note you can change the order of the CNOT gates and get the same results
qc = QuantumCircuit(2)
qc.cx(b,a)
qc.cx(a,b)
qc.cx(b,a)
qc.draw()
#controlled Rotations:
#this circuit rotates qubits about the Y-AXIS by theta/2
qc = QuantumCircuit(2)
theta = pi # theta can be any value
qc.ry(theta/2,t)
qc.cx(c,t)
qc.ry(-theta/2,t)
qc.cx(c,t)
qc.draw()
# we can also create a controlled version of any single
#qubit rotation U
# We must first find three rotations A,B,and C,
#and a phase alpha such that
# ABC = I , e^(ialpha)AZBZC =U
A = Gate('A',1,[])
B = Gate('B',1,[])
C = Gate('C',1,[])
alpha = 1 #arbitratily define alpha
qc = QuantumCircuit(2)
qc.append(C,[t])
qc.cz(c,t)
qc.append(B,[t])
qc.cz(c,t)
qc.append(A,[t])
qc.u1(alpha,c)
qc.draw()
#TOFFOLI:
#The Toffoli is a 3-qubit gate with two control and one target.
#It performs an X on the target only if both controls
# are in state |1>.
# the final state of target is then either the AND or NAND of the two controls,
# depending on if the initial state of target was |0> or |1>.
# the Toffoli can be thought of as a controlled-controoled-NOT:
# note the Toffoli requires at least 6 CNOT gates.
# but there are other ways to produce an AND effect using quantum operations.
qc = QuantumCircuit(3)
a = 0
b = 1
t = 2
#Toffoli with control a and b target t:
qc.ccx(a,b,t)
qc.draw()
# before we built a Toffoli from base quibit operations
# we will build a general controlled-controlled-U.
#For any single-qubit rotation U.
qc = QuantumCircuit(3)
qc.cu1(theta,b,t)
qc.cx(a,b)
qc.cu1(-theta,b,t)
qc.cx(a,b)
qc.cu1(theta,a,t)
qc.draw()
#we can built an AND gate using a CONTROLLED-H GATE and CONTROLLED-Z GATES
qc = QuantumCircuit(3)
qc.ch(a,t)
qc.cz(b,t)
qc.ch(a,t)
qc.draw()
|
https://github.com/derek-wang-ibm/coding-with-qiskit
|
derek-wang-ibm
|
from qiskit import QuantumCircuit
from qiskit.circuit.library import YGate, UnitaryGate
import numpy as np
SYGate = UnitaryGate(YGate().power(1/2), label=r"$\sqrt{Y}$")
SYdgGate = UnitaryGate(SYGate.inverse(), label=r"$\sqrt{Y}^\dag$")
def generate_1d_tfim_circuit(num_qubits, num_trotter_steps, rx_angle, num_cl_bits=0, trotter_barriers = False, layer_barriers = False):
if num_cl_bits == 0:
qc = QuantumCircuit(num_qubits)
else:
qc = QuantumCircuit(num_qubits, num_cl_bits)
for trotter_step in range(num_trotter_steps):
add_1d_tfim_trotter_layer(qc, rx_angle, layer_barriers)
if trotter_barriers:
qc.barrier()
return qc
def add_1d_tfim_trotter_layer(qc, rx_angle, layer_barriers = False):
# Adding Rzz in the even layers
for i in range(0, qc.num_qubits-1, 2):
qc.sdg([i, i+1])
qc.append(SYGate, [i+1])
qc.cx(i, i+1)
qc.append(SYdgGate, [i+1])
if layer_barriers:
qc.barrier()
# Adding Rzz in the odd layers
for i in range(1, qc.num_qubits-1, 2):
qc.sdg([i, i+1])
qc.append(SYGate, [i+1])
qc.cx(i, i+1)
qc.append(SYdgGate, [i+1])
if layer_barriers:
qc.barrier()
qc.rx(rx_angle, list(range(qc.num_qubits)))
if layer_barriers:
qc.barrier()
num_qubits = 6
num_trotter_steps = 1
rx_angle = 0.5 * np.pi
qc = generate_1d_tfim_circuit(num_qubits, num_trotter_steps, rx_angle, trotter_barriers=True, layer_barriers=True)
qc.draw(output='mpl', fold=-1)
def append_mirrored_1d_tfim_circuit(qc, num_qubits, num_trotter_steps, rx_angle, trotter_barriers = False, layer_barriers = False):
for trotter_step in range(num_trotter_steps):
add_mirrored_1d_tfim_trotter_layer(qc, rx_angle, layer_barriers)
if trotter_barriers:
qc.barrier()
def add_mirrored_1d_tfim_trotter_layer(qc, rx_angle, layer_barriers = False):
# Note after filming:
# I constructed the inverse by hand here
# But you could also use QuantumCircuit.inverse() to do this more efficiently
qc.rx(-rx_angle, list(range(qc.num_qubits)))
if layer_barriers:
qc.barrier()
# Adding Rzz in the odd layers
for i in range(1, qc.num_qubits-1, 2):
qc.append(SYGate, [i+1])
qc.cx(i, i+1)
qc.append(SYdgGate, [i+1])
qc.s([i, i+1])
if layer_barriers:
qc.barrier()
# Adding Rzz in the even layers
for i in range(0, qc.num_qubits-1, 2):
qc.append(SYGate, [i+1])
qc.cx(i, i+1)
qc.append(SYdgGate, [i+1])
qc.s([i, i+1])
if layer_barriers:
qc.barrier()
append_mirrored_1d_tfim_circuit(qc, num_qubits, num_trotter_steps, rx_angle, trotter_barriers=True, layer_barriers=True)
qc.draw(output='mpl', fold=-1)
max_trotter_steps = 10
num_qubits = 100
measured_qubits = [49, 50]
qc_list = []
for trotter_step in range(max_trotter_steps):
qc = generate_1d_tfim_circuit(num_qubits, trotter_steps, rx_angle, num_cl_bits=len(measured_qubits), trotter_barriers=True, layer_barriers=True)
append_mirrored_1d_tfim_circuit(qc, num_qubits, trotter_steps, rx_angle, trotter_barriers=True, layer_barriers=True)
qc.measure(measured_qubits, list(range(len(measured_qubits))))
qc_list.append(qc)
from qiskit import transpile
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = service.backend(name='ibm_brisbane')
print("Done getting the backend")
# Note after filming:
# `transpile` will be deprecated soon
# so in the future, use `generate_preset_pass_manager` to achieve similar functionality
qc_transpiled_list = transpile(qc_list, backend=backend, optimization_level=1)
from qiskit_ibm_runtime import SamplerV2 as Sampler
sampler = Sampler(backend=backend)
sampler.options.dynamical_decoupling.enable = True
sampler.options.dynamical_decoupling.sequence_type = "XY4"
job = sampler.run(qc_transpiled_list)
print(job.job_id())
job_id = "cqp5rvb417q0008yq3b0"
job = service.job(job_id)
survival_probability_list = []
for trotter_step in range(max_trotter_steps):
try:
data = job.result()[trotter_step].data
survival_probability_list.append(data.c.get_counts()['0' * len(measured_qubits)] / data.c.num_shots)
except:
survival_probability_list.append(0)
import matplotlib.pyplot as plt
plt.plot(list(range(0, 4 * max_trotter_steps, 4)), survival_probability_list, '--o')
plt.xlabel('2Q Gate Depth')
plt.ylabel('Survival Probability of the all-0 bitstring')
plt.xticks(np.arange(0, 44, 4))
plt.show()
from qiskit.circuit import Parameter
rx_angle = Parameter("rx_angle")
trotter_steps = 2
qc = generate_1d_tfim_circuit(num_qubits, trotter_steps, rx_angle)
from qiskit.quantum_info import SparsePauliOp
middle_index = num_qubits // 2
observable = SparsePauliOp("I" * middle_index + "Z" + "I" * (middle_index-1))
from qiskit import transpile
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = service.backend(name='ibm_brisbane')
# Note after filming:
# `transpile` will be deprecated soon
# so in the future, use `generate_preset_pass_manager` to achieve similar functionality
qc_transpiled = transpile(qc, backend=backend, optimization_level=1)
observable = observable.apply_layout(qc_transpiled.layout)
from qiskit_ibm_runtime import EstimatorV2, EstimatorOptions
min_rx_angle = 0
max_rx_angle = np.pi/2
num_rx_angle = 12
rx_angle_list = np.linspace(min_rx_angle, max_rx_angle, num_rx_angle)
options = EstimatorOptions()
options.resilience_level = 1
options.dynamical_decoupling.enable = True
options.dynamical_decoupling.sequence_type = "XY4"
estimator = EstimatorV2(backend=backend, options=options)
job = estimator.run([(qc_transpiled, observable, rx_angle_list)])
print(job.job_id())
job_id = "cqp5xtq417q0008yq43g"
job = service.job(job_id)
exp_val_list = job.result()[0].data.evs
plt.plot(rx_angle_list / np.pi, exp_val_list, '--o')
plt.xlabel(r'Rx angle ($\pi$)')
plt.ylabel(r'$\langle Z \rangle$ in the middle of the chain')
plt.ylim(-0.1, 1.1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, backend=FakeBoeblingen())
|
https://github.com/C2QA/bosonic-qiskit
|
C2QA
|
# The C2QA pacakge is currently not published to PyPI.
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa.
import os
import sys
module_path = os.path.abspath(os.path.join("../.."))
if module_path not in sys.path:
sys.path.append(module_path)
# Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv
module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages"))
if module_path not in sys.path:
sys.path.append(module_path)
import c2qa
import qiskit
from qiskit import QuantumCircuit
qmr0 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=2)
qr0 = qiskit.QuantumRegister(size=1)
circuit0 = c2qa.CVCircuit(qmr0, qr0)
# Initialize qubit
circuit0.initialize([1,0], qr0[0])
# circuit0.initialize([0,1], qr0[0])
# Initialize the qumode to, for example, a Fock sate 1
circuit0.cv_initialize(1, qmr0[0])
# ... Your circuit here ...
state0, _, _ = c2qa.util.simulate(circuit0)
print(state0)
# c2qa.util.trace_out_qumodes() performs a partial trace over the cavities, giving the reduced density matrix of the qubits
print(c2qa.util.trace_out_qumodes(circuit0, state0))
# c2qa.util.trace_out_qubits() performs a partial trace over the qubits, giving the reduced density matrix of the cavities
print(c2qa.util.trace_out_qubits(circuit0, state0))
|
https://github.com/abbarreto/qiskit3
|
abbarreto
| |
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../../')
from composer.qs_circuit import QSCircuit
from qiskit import execute, BasicAer
from math import log2
SIZE_INPUT = 2 ** 1
SIZE_SELECTOR = int(log2(SIZE_INPUT))
for i in range(0, 2 ** SIZE_INPUT):
a = format(i, '0' + str(SIZE_INPUT) + 'b')
for j in range(0, 2 ** SIZE_SELECTOR):
selectors = format(j, '0' + str(SIZE_SELECTOR) + 'b')
a_indexes = list(range(0, SIZE_INPUT))
selectors_indexes = list(range(SIZE_INPUT, SIZE_INPUT + SIZE_SELECTOR))
flipped_selectors_indexes = list(range(SIZE_INPUT + SIZE_SELECTOR, SIZE_INPUT + 2 * SIZE_SELECTOR))
output_index = SIZE_INPUT + 2 * SIZE_SELECTOR
aux_index = SIZE_INPUT + 2 * SIZE_SELECTOR + 1
CIRCUIT_SIZE = SIZE_INPUT + 2 * SIZE_SELECTOR + 2
qc = QSCircuit(CIRCUIT_SIZE)
qc.set_reg(a[::-1], a_indexes)
qc.set_reg(selectors[::-1], selectors_indexes)
qc.multiplexer(a_indexes, selectors_indexes, flipped_selectors_indexes, output_index, aux_index)
qc.measure(output_index, output_index)
print(qc)
backend = BasicAer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1)
counts = job.result().get_counts(qc)
print(a, '-', selectors, '-', list(counts.keys())[0][::-1][output_index])
|
https://github.com/ACDuriez/Ising-VQE
|
ACDuriez
|
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from tqdm import tqdm
from scipy.optimize import minimize
from dataclasses import dataclass
from qiskit.providers.fake_provider import FakeManila,FakeQuito,FakeLima,FakeKolkata,FakeNairobi
from qiskit.transpiler import CouplingMap
from qiskit.circuit import QuantumCircuit,ParameterVector,Parameter
from qiskit.circuit.library import EfficientSU2
from qiskit.quantum_info import SparsePauliOp
#from qiskit.opflow import PauliSumOp
from qiskit.primitives import Estimator,Sampler,BackendEstimator
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import SLSQP,COBYLA,L_BFGS_B,QNSPSA,SPSA
from qiskit_aer.noise import NoiseModel
from qiskit_ibm_runtime import Session,Options,QiskitRuntimeService
from qiskit_ibm_runtime import Estimator as IBM_Estimator
from qiskit_ibm_runtime import Sampler as IBM_Sampler
from qiskit_aer.primitives import Estimator as AerEstimator
J = 1
h = 0.5
n_qubits = 4
def get_line_graph(n_qubits):
"""This function creates a linear lattice with
open boundary conditions for a given number of qubits"""
graph_line = nx.Graph()
graph_line.add_nodes_from(range(n_qubits))
edge_list = []
for i in graph_line.nodes:
if i < n_qubits-1:
edge_list.append((i,i+1))
# Generate graph from the list of edges
graph_line.add_edges_from(edge_list)
return graph_line
graph = get_line_graph(n_qubits)
nx.draw_networkx(graph) #plotting the graph
def get_h_op(graph,J=1.,hx=0.5,hz=0.,ap=0.):
"""Creates a general Ising hamiltonian for
given values of the coupling, transverse field,
longitudinal field and antiparallel field
Args:
graph: networkx graph of the lattice
J: uniform coupling between first neighbors
hx: transverse field parameter
hz: longitudinal field parameter
ap: antiparallel field at the boundaries"""
num_qubits = len(graph.nodes())
sparse_list = []
# Uniform Z and X fields
for qubit in graph.nodes():
# X field
coeff = ('X',[qubit],-1*hx)
sparse_list.append(coeff)
# Z field
coeff = ('Z',[qubit],-1*hz)
sparse_list.append(coeff)
# Anti-paralel field at the borders
coeff = ('Z',[0],ap) #this is the positive field (order reversed)
sparse_list.append(coeff)
coeff = ('Z',[num_qubits-1],-1*ap)
sparse_list.append(coeff)
#Interaction field (ZZ)
for i,j in graph.edges():
coeff = ('ZZ',[i,j],-1*J)
sparse_list.append(coeff)
hamiltonian = SparsePauliOp.from_sparse_list(sparse_list,num_qubits=num_qubits).simplify()
return hamiltonian
def get_kk_op(graph):
"""Creates the number of kinks operator"""
sparse_list = []
for i,j in graph.edges():
coeff = ('II',[i,j],0.5)
sparse_list.append(coeff)
coeff = ('ZZ',[i,j],-0.5)
sparse_list.append(coeff)
kk_op = SparsePauliOp.from_sparse_list(sparse_list,num_qubits=len(graph.nodes))
return kk_op
# We show the Hamiltonian with the crittical boundary field as well as
# the number of kinks
print(get_h_op(graph,J,h,ap=np.sqrt(1-h)))
print(get_kk_op(graph))
exact_steps = 70
g_i = 0.
g_f = 1.6
exact_g_values = np.linspace(g_i,g_f,exact_steps)
def get_numpy_results(graph,J,h,g_values):
"""Returns the exact values of the energy and number of kinks
for a given lattice, coupling, transverse field and values of
the boundary field"""
n_qubits = len(graph.nodes())
numpy_solver = NumPyMinimumEigensolver()
E_values = []
kk_values = []
kk_op = get_kk_op(graph) #getting the (g-independent) number of kinks operator
for g in g_values:
h_op = get_h_op(graph,J,h,ap=g) #getting the hamiltonian operator for each g value
result = numpy_solver.compute_minimum_eigenvalue(operator=h_op,aux_operators=[kk_op])
E_values.append(result.eigenvalue)
kk_values.append(np.real(result.aux_operators_evaluated[0][0]))
return E_values,kk_values
exact_E,exact_kk = get_numpy_results(graph,J,h,exact_g_values) # getting the exact energy and number of kinks
#Plotting
f,ax = plt.subplots()
plt.plot(exact_g_values,exact_E)
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
inset_ax = f.add_axes([0.25, 0.3, 0.27, 0.27])# [left, bottom, width, height]
inset_ax.plot(exact_g_values,exact_kk)
inset_ax.set_ylabel('$<N_k>$')
inset_ax.set_xlabel('boundary field')
inset_ax.axvline(x=np.sqrt(1-h), color='red', linestyle='dashed') #indicating the critical boundary field
plt.show()
#Initialize runtime
service = QiskitRuntimeService(
channel='ibm_quantum',
instance='ibm-q/open/main',
token='your_token'
)
backend = service.backend("ibmq_qasm_simulator")
shots = 2**14 # shots for noisy simulations
def get_ansatz_hva(graph, theta_list):
"""Creates the hamiltonian variaitonal ansatz for a given
lattice graph and list of parameters. The parameters list must have a
lenght of 3*n_layers, and must have a form (coupling_i,transverse_i,boundary_i)
Args:
graph: lattice graph
theta_list: list of parameters
"""
n_qubits = len(graph.nodes())
n_layers = len(theta_list)//3
qc = QuantumCircuit(n_qubits)
even_edges = [edge for edge in graph.edges() if edge[0]%2==0]
odd_edges = [edge for edge in graph.edges() if edge[0]%2!=0]
# initial_state
qc.h(range(n_qubits))
for layer_index in range(n_layers):
# Coupling term
for pair in even_edges:
qc.rzz(2 * theta_list[3*layer_index],pair[0],pair[1])
for pair in odd_edges:
qc.rzz(2 * theta_list[3*layer_index],pair[0],pair[1])
# boundary field term
qc.rz(2 *theta_list[3*layer_index+2],0)
qc.rz(-2 * theta_list[3*layer_index+2], n_qubits-1)
# transverse field term
qc.rx(2 * theta_list[3*layer_index+1], range(n_qubits))
return qc
layers_hva = 4
theta_list_hva = ParameterVector('θ',3*layers_hva)
ansatz_hva = get_ansatz_hva(graph,theta_list_hva)
ansatz_hva.draw('mpl',style='iqx')
def get_ansatz_hea(graph,theta_list):
"""Creates the hardware efficient ansatz for a given
lattice graph and list of parameters. The parameters list must have a
lenght of 2*n_qubits_n_layers
Args:
graph: lattice graph
theta_list: list of parameters
"""
nqubits = len(graph.nodes())
n_layers = len(theta_list)//(2*nqubits)
assert len(theta_list)==2*n_qubits*n_layers, "The list of parameters does not have the correct size"
qc = QuantumCircuit(nqubits)
even_edges = [edge for edge in graph.edges() if edge[0]%2==0]
odd_edges = [edge for edge in graph.edges() if edge[0]%2!=0]
reversed_edges = [edge for edge in graph.edges()][::-1]
for layer_index in range(n_layers):
for qubit in range(nqubits):
qc.ry(theta_list[2*(nqubits)*layer_index+qubit], qubit)
# for pair in reversed_edges:
# qc.cnot(pair[0],pair[1])
for pair in even_edges:
qc.cnot(pair[0],pair[1])
for pair in odd_edges:
qc.cnot(pair[0],pair[1])
for qubit in range(nqubits):
qc.ry(theta_list[nqubits+2*(nqubits)*layer_index+qubit], qubit)
return qc
def get_ansatz_hea_ZNE(graph,theta_list):
"""Creates the folded version of hardware efficient ansatz for a given
lattice graph and list of parameters. The parameters list must have a
lenght of 2*n_qubits_n_layers. Used in the ZNE error mitigation protocol
Args:
graph: lattice graph
theta_list: list of parameters
"""
nqubits = len(graph.nodes())
n_layers = len(theta_list)//(2*nqubits)
assert len(theta_list)==2*n_qubits*n_layers, "The list of parameters does not have the correct size"
qc = QuantumCircuit(nqubits)
even_edges = [edge for edge in graph.edges() if edge[0]%2==0]
odd_edges = [edge for edge in graph.edges() if edge[0]%2!=0]
reversed_edges = [edge for edge in graph.edges()][::-1]
for layer_index in range(n_layers):
for qubit in range(nqubits):
qc.ry(theta_list[2*(nqubits)*layer_index+qubit], qubit)
# for pair in reversed_edges:
# qc.cnot(pair[0],pair[1])
#folding even edges
for pair in even_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for pair in even_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for pair in even_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
#folding odd edges
for pair in odd_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for pair in odd_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for pair in odd_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for qubit in range(nqubits):
qc.ry(theta_list[nqubits+2*(nqubits)*layer_index+qubit], qubit)
return qc
# Here we define and show the circuit for the HEA
layers_hea = 1
theta_list = ParameterVector('t',2*n_qubits*layers_hea) # The list of parameters must
ansatz_hea = get_ansatz_hea(graph,theta_list)
ansatz_hea.draw('mpl', style="iqx")
# Here is the folded version of the HEA ansatz for the ZNE
ansatz_hea = get_ansatz_hea_ZNE(graph,theta_list)
ansatz_hea.draw('mpl', style="iqx")
def get_estimator(session,
server='qasm',
shots=2**14,
device=FakeKolkata(),
options_rtm=Options(),
seed=170):
"""Defines an estimator. Set 'qasm' for noiseless, 'noisy' for
backend estimator and 'rtm' for the runtime estimator"""
if server =='qasm':
estimator = Estimator(options={'shots':shots,'seed':seed})
elif server == 'noisy':
estimator = BackendEstimator(device,options={'shots':shots,'seed':seed})
elif server == 'rtm':
estimator = IBM_Estimator(session=session,options=options_rtm)
return estimator
def get_extrapolation(value_k1,value_k2,extrap='lin'):
"""Returns the exponential extrapolation given the
values for k=1 and k=2 noise factors"""
k_values = [1.,2.]
if extrap =='lin':
y_values = [value_k1,value_k2]
# Fit a linear regression model (polynomial of degree 1)
coefficients = np.polyfit(k_values, y_values, 1)
# The coefficients represent the slope (m) and y-intercept (b) of the line
slope, intercept = coefficients
extrapolation = intercept
if extrap == 'exp':
y_values = [np.abs(value_k1/value_k2),1.]
ln_y = np.log(y_values)
# Fit a linear regression model (polynomial of degree 1)
coefficients_exp = np.polyfit(k_values, ln_y, 1)
# The coefficients represent the slope (m) and y-intercept (b) of the line
slope_exp, intercept_exp = coefficients_exp
extrapolation = np.exp(intercept_exp)*value_k2
return extrapolation
def vqe_opt_scipy(graph,
service,
backend,
g=0.7071067811865476,
h=0.5,
ansatz_str='hea',
layers=1,
optimizer='SLSQP',
maxiter=50,
ftol=0.,
reps=1,
zne=False,
extrap='exp',
shots=None,
server='qasm',
device=FakeNairobi(),
options=Options()):
"""Runs the vqe for the Ising model with boundary fields for
a single value of the boundary field, using the scipy optimization function.
It gives data for the convergence of the optimization, which is the logs for
each sampling, the mean and standart deviation of these samplings, and also the
number of function evaluations
Args:
graph: networkx lattice graph
service: service for runtime
backend: backend for runtime (can include quantum backends)
g: value of the boundary field
h: value of the transverse field
ansatz_str: choice of ansatz, 'hea' for HEA and 'hva' for HVA
layers: number of layers for the ansatz
optimizer: optimization algorithm, as string for scipy
maxiter: maximum iterations for the optimization
ftol: tolerance for convergence, for scipy
reps: (int) number of initial parameters samplings
zne: (bool) zne option
extrap: type of extrapolation
shots: number of shots, set to None for statevector simulations
server: 'qasm' for noiseless, 'noisy' for aer, 'rtm' for runtime
device: noise model for noisy simulations
options: Options() class for runtime
"""
n_qubits = len(graph.nodes())
if ansatz_str == 'hea':
theta_list = ParameterVector('θ',2*n_qubits*layers)
ansatz = get_ansatz_hea(graph,theta_list)
ansatz_k2 = get_ansatz_hea_ZNE(graph,theta_list)
elif ansatz_str == 'hva':
theta_list = ParameterVector('θ',3*layers)
ansatz = get_ansatz_hva(graph,theta_list)
ansatz_k2 = get_ansatz_hva(graph,theta_list)
cost_operator = get_h_op(graph,hx=h,ap=g) #Defining Hamiltonian
# Now we set the cost function, with no mitigation, linear or exp extrapolation
if zne == False:
def cost_function_vqe(theta):
job = estimator.run(ansatz, cost_operator, theta)
values = job.result().values[0]
return values
if zne == True:
def cost_function_vqe(theta):
job = estimator.run([ansatz,ansatz_k2], 2*[cost_operator], 2*[theta])
value_k1 = job.result().values[0]
value_k2 = job.result().values[1]
extrapolation = get_extrapolation(value_k1=value_k1,value_k2=value_k2,extrap=extrap)
return extrapolation
log_list = []
nfev_list = []
with Session(service=service,backend=backend) as session:
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
for i in tqdm(range(reps)):
random_point = np.random.random(ansatz.num_parameters)
iter_list = []
result_sample = minimize(cost_function_vqe,
x0=random_point,
method=optimizer,
callback=lambda xk: iter_list.append(list(xk)),
options={'maxiter':maxiter,'disp':False,'ftol':ftol})
iters = len(iter_list)
energy_list = estimator.run(iters*[ansatz],iters*[cost_operator],iter_list).result().values
nfev_list.append(int(result_sample.nfev))
log_list.append(list(energy_list))
session.close()
max_length = max(len(sublist) for sublist in log_list) # Finding the length of the largest list
for sublist in log_list:
if len(sublist) < max_length:
last_element = sublist[-1] # Extracting the last element
sublist.extend([last_element] * (max_length - len(sublist))) # Filling with the last element
mean_list = []
std_list = []
for i in range(len(log_list[0])):
values_list = [l[i] for l in log_list]
mean_list.append(np.mean(values_list))
std_list.append(np.std(values_list))
return log_list,mean_list,std_list,nfev_list
g_mag = 0.2
g_knk = 1.2
E_mag = NumPyMinimumEigensolver().compute_minimum_eigenvalue(get_h_op(graph,ap=g_mag)).eigenvalue
E_knk = NumPyMinimumEigensolver().compute_minimum_eigenvalue(get_h_op(graph,ap=g_knk)).eigenvalue
reps = 5 # we define the number of initial parameters samplings
logs_hva_mag,avgs_hva_mag,stds_hva_mag,nfevs_hva_mag = vqe_opt_scipy(graph=graph,
service=service,
backend=backend,
server='qasm',
g=g_mag,
layers=layers_hva,
ansatz_str='hva',
reps=reps,
maxiter=300,
shots=None,
ftol=1e-16)
avgs_list = avgs_hva_mag
stds_list = stds_hva_mag
g_value = g_mag
exact_energy = E_mag
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
plt.xlim((0,40))
x_lim = 60
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -10, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
logs_hva_knk,avgs_hva_knk,stds_hva_knk,nfevs_hva_knk = vqe_opt_scipy(graph=graph,
service=service,
backend=backend,
server='qasm',
g=g_knk,
layers=layers_hva,
ansatz_str='hva',
reps=reps,
maxiter=300,
shots=None,
ftol=1e-16)
avgs_list = avgs_hva_knk
stds_list = stds_hva_knk
g_value = g_knk
exact_energy = E_knk
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
plt.xlim((0,40))
x_lim = 60
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -10, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
# Here we define a different callback which is suited for the SPSA implementation of qiskit
intermediate_info = {
'nfev': [],
'parameters': [],
'energy': [],
'step_size': [],
'step_sucesss': []
}
def callback(nfev, parameters, energy, step_size,step_sucess):
intermediate_info['nfev'].append(nfev)
intermediate_info['parameters'].append(parameters)
intermediate_info['energy'].append(energy)
intermediate_info['step_size'].append(step_size)
intermediate_info['step_sucess'].append(step_sucess)
@dataclass
class VQELog:
values: list
parameters: list
def update(self, count, parameters, mean, step_size, step_sucess):
self.values.append(mean)
self.parameters.append(parameters)
print(f"Running circuit {count}", end="\r", flush=True)
# Here is the main function
def vqe_critical_spsa(graph,
service,
backend,
device=FakeKolkata(),
g=0.7071067811865476,
layers=1,
server='qasm',
learning_rate=0.07,
perturbation=0.1,
maxiter=200,
hx=0.5,
options=Options(),
zne=False,
extrap='exp',
reps=1,
shots=2**14,
ansatz_str='hea'):
"""Runs the vqe for the Ising model with boundary fields for
a single value of the boundary field, using the scipy optimization function.
It gives data for the convergence of the optimization, which is the logs for
each sampling, the mean and standart deviation of these samplings, and also the
number of function evaluations
Args:
graph: networkx lattice graph
service: service for runtime
backend: backend for runtime (can include quantum backends)
g: value of the boundary field
h: value of the transverse field
ansatz_str: choice of ansatz, 'hea' for HEA and 'hva' for HVA
layers: number of layers for the ansatz
maxiter: maximum iterations for the optimization
learning_rate: learning rate for the SPSA optimizer
perturbation: perturbation for the SPSA optimizer
reps: (int) number of initial parameters samplings
zne: (bool) zne option
extrap: type of extrapolation
shots: number of shots, set to None for statevector simulations
server: 'qasm' for noiseless, 'noisy' for aer, 'rtm' for runtime
device: noise model for noisy simulations
options: Options() class for runtime
"""
n_qubits = len(graph.nodes())
if ansatz_str == 'hea':
theta_list = ParameterVector('θ',2*n_qubits*layers)
ansatz = get_ansatz_hea(graph,theta_list)
ansatz_k2 = get_ansatz_hea_ZNE(graph,theta_list)
elif ansatz_str == 'hva':
theta_list = ParameterVector('θ',3*layers)
ansatz = get_ansatz_hva(graph,theta_list)
ansatz_k2 = get_ansatz_hva(graph,theta_list)
cost_operator = get_h_op(graph,hx=hx,ap=g) #Defining Hamiltonian
# Now we set the cost function, with no mitigation, linear or exp extrapolation
if zne == False:
def cost_function_vqe(theta):
job = estimator.run(ansatz, cost_operator, theta)
values = job.result().values[0]
return values
if zne == True:
def cost_function_vqe(theta):
job = estimator.run([ansatz,ansatz_k2], 2*[cost_operator], 2*[theta])
value_k1 = job.result().values[0]
value_k2 = job.result().values[1]
return get_extrapolation(value_k1=value_k1,value_k2=value_k2,extrap=extrap)
log_list = []
nfev_list = []
with Session(service=service,backend=backend) as session:
# estimator = BackendEstimator(FakeNairobiV2(),options={'shots':shots})
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
for i in tqdm(range(reps)):
log = VQELog([], [])
spsa = SPSA(maxiter=maxiter,
trust_region=True,
learning_rate=learning_rate,
perturbation=perturbation,
callback=log.update)
random_point = np.random.random(ansatz.num_parameters)
result_sample = spsa.minimize(cost_function_vqe,x0=random_point)
log_list.append(log)
nfev_list.append(result_sample.nfev)
session.close()
max_length = max(len(sublist.values) for sublist in log_list) # Finding the length of the largest list
for sublist in log_list:
if len(sublist.values) < max_length:
last_element = sublist[-1] # Extracting the last element
sublist = list(sublist)[:].extend([last_element] * (max_length - len(sublist))) # Filling with the last element
mean_list = []
std_list = []
for i in range(len(log_list[0].values)):
values_list = [log.values[i] for log in log_list]
mean_list.append(np.mean(values_list))
std_list.append(np.std(values_list))
return log_list,mean_list,std_list,nfev_list
logs_hea_noisy_mag,avgs_hea_noisy_mag,stds_hea_noisy_mag,nfevs_hea_noisy_mag = vqe_critical_spsa(graph=graph,
service=service,
backend=backend,
device=FakeKolkata(),
g=g_mag,
server='noisy',
layers=1,
maxiter=170,
ansatz_str='hea',
reps=5,
zne=False,
shots = shots
)
avgs_list = avgs_hea_noisy_mag
stds_list = stds_hea_noisy_mag
g_value = g_mag
exact_energy = E_mag
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization noisy g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -3, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
reps = 3
logs_hea_zne_mag,avgs_hea_zne_mag,stds_hea_zne_mag,nfevs_hea_zne_mag = vqe_critical_spsa(graph=graph,
service=service,
backend=backend,
device=FakeKolkata(),
g=g_mag,
server='noisy',
layers=1,
maxiter=170,
ansatz_str='hea',
reps=reps,
zne=True,
extrap='exp',
shots=shots
)
avgs_list = avgs_hea_zne_mag
stds_list = stds_hea_zne_mag
g_value = g_mag
exact_energy = E_mag
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
x_lim = 60
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization mitigated g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -3, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
logs_hea_noisy_knk,avgs_hea_noisy_knk,stds_hea_noisy_knk,nfevs_hea_noisy_knk = vqe_critical_spsa(graph=graph,
service=service,
backend=backend,
device=FakeKolkata(),
g=g_knk,
server='noisy',
layers=1,
maxiter=170,
ansatz_str='hea',
reps=reps,
zne=False,
shots=shots
)
avgs_list = avgs_hea_noisy_knk
stds_list = stds_hea_noisy_knk
g_value = g_knk
exact_energy = E_knk
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
x_lim = 60
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization noisy g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -3, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
reps = 3
logs_hea_zne_knk,avgs_hea_zne_knk,stds_hea_zne_knk,nfevs_hea_zne_knk = vqe_critical_spsa(graph=graph,
service=service,
backend=backend,
device=FakeKolkata(),
g=g_knk,
server='noisy',
layers=1,
maxiter=170,
ansatz_str='hea',
reps=reps,
zne=True,
extrap='exp',
shots=shots
)
avgs_list = avgs_hea_zne_knk
stds_list = stds_hea_zne_knk
g_value = g_knk
exact_energy = E_knk
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization mitigated g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -3, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
def vqe_phase_diagram(graph,
g_values,
optimizer,
init_optimizer,
service,
backend,
server='qasm',
device=FakeNairobi(),
angles_dict = {},
layers=1,
hx=0.5,
options=Options(),
zne=False,
extrap='exp',
init_reps=1,
shots=2**14,
ansatz_str='hea'):
"""Runs the vqe to simulate the antiparallel model in
the hardware efficient ansatz for different values of
the antiparallel field. Returns the list of energies as
well as a dictionary with the optimal angles for each
value of the boundary field.
Args:
graph: networkx lattice graph
g_values: list of values for the boundary field
angles_dict: dictionary of angles
optimizer: qiskit optimizer class
init_optimizer: optimizer for the first point
layers: layers for the ansatz
service: service for runtime
backend: backend for runtime (can include quantum backends)
h: value of the transverse field
ansatz_str: choice of ansatz, 'hea' for HEA and 'hva' for HVA
reps: number of initial parameters samplings for the first point
zne: (bool) zne option
extrap: type of extrapolation
shots: number of shots, set to None for statevector simulations
server: 'qasm' for noiseless, 'noisy' for aer, 'rtm' for runtime
device: noise model for noisy simulations
options: Options() class for runtime
"""
n_qubits = len(graph.nodes())
if ansatz_str == 'hea':
theta_list = ParameterVector('θ',2*n_qubits*layers)
ansatz = get_ansatz_hea(graph,theta_list)
ansatz_k2 = get_ansatz_hea_ZNE(graph,theta_list)
elif ansatz_str == 'hva':
theta_list = ParameterVector('θ',3*layers)
ansatz = get_ansatz_hva(graph,theta_list)
ansatz_k2 = get_ansatz_hva(graph,theta_list)
E_values = []
rev_g_values = g_values[::-1]
for i,g in enumerate(tqdm(rev_g_values)):
cost_operator = get_h_op(graph,hx=hx,ap=g) #Defining Hamiltonian
# Now we set the cost function, with no mitigation, linear or exp extrapolation
if zne == False:
def cost_function_vqe(theta):
job = estimator.run(ansatz, cost_operator, theta)
values = job.result().values[0]
return values
if zne == True:
def cost_function_vqe(theta):
job = estimator.run([ansatz,ansatz_k2], 2*[cost_operator], 2*[theta])
value_k1 = job.result().values[0]
value_k2 = job.result().values[1]
return get_extrapolation(value_k1=value_k1,value_k2=value_k2,extrap=extrap)
if i == 0:
sample = 0.
for j in range(init_reps): #Performs sampling of initial parameters for the first point
initial_point = np.random.uniform(0., 2*np.pi, size=ansatz.num_parameters)
with Session(service=service,backend=backend) as session:
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
result_sample = init_optimizer.minimize(fun=cost_function_vqe,
x0=initial_point)
session.close()
if result_sample.fun < sample:
sample = result_sample.fun
result = result_sample
initial_point = result.x
else:
with Session(service=service,backend=backend) as session:
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
result = optimizer.minimize(fun=cost_function_vqe,
x0=initial_point)
session.close()
E_values.append(result.fun)
#optimal angles storage
angles = list(result.x)
angles_dict[str(round(g,5))] = angles
return E_values,angles_dict
def vqe_optimal(graph,
service,
backend,
angles_opt,
server='qasm',
device=FakeNairobi(),
layers=1,
hx=0.5,
options=Options(),
zne=False,
extrap='lin',
shots=2**14,
ansatz_str='hea'):
""" Receives the optimal parameters for each value of
the boundary field and runs the circuits to compute the
energy as well as the number of kinks
Args:
graph: networkx lattice graph
g_values: list of values for the boundary field
angles_opt: dictionary of optimal angles
service: service for runtime
backend: backend for runtime (can include quantum backends)
h: value of the transverse field
ansatz_str: choice of ansatz, 'hea' for HEA and 'hva' for HVA
layers: layers for the ansatz
reps: number of initial parameters samplings for the first point
zne: (bool) zne option
extrap: type of extrapolation
shots: number of shots, set to None for statevector simulations
server: 'qasm' for noiseless, 'noisy' for aer, 'rtm' for runtime
device: noise model for noisy simulations
options: Options() class for runtime
Returns:
The values of the energy, number of kinks, and the associated values
of g to facilitate plotting
"""
n_qubits = len(graph.nodes())
g_values = [float(k) for k in angles_opt.keys()]
n_points = len(g_values)
# Setting the ansatz
if ansatz_str == 'hea':
theta_list = ParameterVector('θ',2*n_qubits*layers)
ansatz = get_ansatz_hea(graph,theta_list)
ansatz_k2 = get_ansatz_hea_ZNE(graph,theta_list)
elif ansatz_str == 'hva':
theta_list = ParameterVector('θ',3*layers)
ansatz = get_ansatz_hva(graph,theta_list)
ansatz_k2 = get_ansatz_hva(graph,theta_list)
# Getting the list of angles and hamiltonians
angles_list = []
h_list = []
g_list = []
kk_op = get_kk_op(graph)
E_values = []
kk_values = []
for g_str,angles in angles_opt.items():
g = float(g_str)
g_list.append(g)
h_list.append(get_h_op(graph,hx=hx,ap=g))
angles_list.append(angles)
with Session(service=service,backend=backend) as session:
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
result_h = estimator.run(n_points*[ansatz],h_list,angles_list).result()
result_kk = estimator.run(n_points*[ansatz],n_points*[kk_op],angles_list).result()
if zne == False:
E_values = list(result_h.values)
kk_values = list(result_kk.values)
else:
result_h_k2 = estimator.run(n_points*[ansatz_k2],h_list,angles_list).result()
result_kk_k2 = estimator.run(n_points*[ansatz_k2],n_points*[kk_op],angles_list).result()
for i in range(n_points):
E_values.append(get_extrapolation(result_h.values[i],result_h_k2.values[i],extrap))
kk_values.append(get_extrapolation(result_kk.values[i],result_kk_k2.values[i],extrap))
session.close()
return E_values,kk_values,g_list
# We define the range of values of g used for the VQE implentation
g_values = np.linspace(g_i,g_f,25)
init_reps = 5
slsqp = SLSQP(150)
init_slsqp = SLSQP(150) # We consider more iterations for the first point
E_hva,angles_hva = vqe_phase_diagram(graph=graph,
g_values=g_values,
ansatz_str='hva',
backend=backend,
layers=layers_hva,
optimizer=slsqp,
init_optimizer=init_slsqp,
service=service,
server='qasm',
shots=None,
init_reps=init_reps)
# Now we run the circuits one last time with the optimal parameters
E_hva,kk_hva,g_hva = vqe_optimal(graph=graph,
service=service,
server='qasm',
angles_opt=angles_hva,
ansatz_str='hva',
layers=layers_hva,
backend=backend)
#Plotting
f,ax = plt.subplots()
#plt.plot(g_values,E_3,'ro')
plt.plot(exact_g_values,exact_E,label='exact')
plt.plot(g_hva,E_hva,'ro',label='VQE')
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
plt.legend()
inset_ax = f.add_axes([0.24, 0.22, 0.3, 0.3]) # [left, bottom, width, height]
plt.plot(exact_g_values,exact_kk)
plt.plot(g_hva,kk_hva,'ro',markersize=4)
inset_ax.set_xlabel('boundary field')
inset_ax.set_ylabel("$<N_k>$")
plt.show()
init_reps = 2
spsa = SPSA(maxiter=300,trust_region=True,learning_rate=0.07,perturbation=0.1)
init_spsa = SPSA(maxiter=300,trust_region=True,learning_rate=0.07,perturbation=0.1) # We consider more iterations for the first point
# To perform the whole optimization using ZNE, just set zne = True
# This step took 207 minutes to run on my machine
E_hea_noisy,angles_hea_noisy = vqe_phase_diagram(graph=graph,
g_values=g_values,
ansatz_str='hea',
backend=backend,
layers=layers_hea,
optimizer=spsa,
init_optimizer=init_spsa,
service=service,
server='noisy',
device=FakeKolkata(),
zne=False,
shots=shots,
init_reps=init_reps)
# Now we run the circuits one last time with the optimal parameters
E_opt_hea_noisy,kk_opt_hea_noisy,g_hea = vqe_optimal(graph=graph,
service=service,
server='noisy',
angles_opt=angles_hea_noisy,
device=FakeKolkata(),
ansatz_str='hea',
layers=layers_hea,
zne=False,
backend=backend,
shots=shots)
#Plotting
f,ax = plt.subplots()
#plt.plot(g_values,E_3,'ro')
plt.plot(exact_g_values,exact_E,label='exact')
plt.plot(g_hea,E_opt_hea_noisy,'o',label='noisy')
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
plt.legend()
inset_ax = f.add_axes([0.24, 0.22, 0.3, 0.3]) # [left, bottom, width, height]
plt.plot(exact_g_values,exact_kk)
plt.plot(g_hea,kk_opt_hea_noisy,'o',markersize=4)
inset_ax.set_xlabel('boundary field')
inset_ax.set_ylabel("$<N_k>$")
plt.show()
# Now we run the circuits now using ZNE
E_opt_hea_mitigated,kk_opt_hea_mitigated,g_hea = vqe_optimal(graph=graph,
service=service,
server='noisy',
angles_opt=angles_hea_noisy,
device=FakeKolkata(),
ansatz_str='hea',
layers=layers_hea,
zne=True,
extrap='exp',
backend=backend,
shots=shots)
#Plotting
f,ax = plt.subplots()
#plt.plot(g_values,E_3,'ro')
plt.plot(exact_g_values,exact_E,label='exact')
plt.plot(g_hea,E_opt_hea_noisy,'o',label='noisy')
plt.plot(g_hea,E_opt_hea_mitigated,'o',label='mitigated')
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
plt.legend()
inset_ax = f.add_axes([0.24, 0.22, 0.3, 0.3]) # [left, bottom, width, height]
plt.plot(exact_g_values,exact_kk)
plt.plot(g_hea,kk_opt_hea_noisy,'o',markersize=4)
plt.plot(g_hea,kk_opt_hea_mitigated,'o',markersize=4)
inset_ax.set_xlabel('boundary field')
inset_ax.set_ylabel("$<N_k>$")
plt.show()
# First we get the optimal parameters with statevector simulations
E_hea_noiseless,angles_hea_noiseless = vqe_phase_diagram(graph=graph,
g_values=g_values,
ansatz_str='hea',
backend=backend,
layers=layers_hea,
optimizer=spsa,
init_optimizer=init_spsa,
service=service,
server='qasm',
shots=None,
init_reps=init_reps)
# Setting options for runtime
# Noisy options
fake_device = FakeKolkata()
noise_model = NoiseModel.from_backend(fake_device)
options_noisy = Options()
options_noisy.execution.shots = shots
options_noisy.simulator = {
"noise_model": noise_model,
"basis_gates": fake_device.configuration().basis_gates,
"coupling_map": fake_device.configuration().coupling_map,
"seed_simulator": 42
}
options_noisy.optimization_level = 3 # no optimization
options_noisy.resilience_level = 0 # M3 for Sampler and T-REx for Estimator
# Mitigated options
options_mitigated = Options()
options_mitigated.execution.shots = shots
options_mitigated.simulator = {
"noise_model": noise_model,
"basis_gates": fake_device.configuration().basis_gates,
"coupling_map": fake_device.configuration().coupling_map
}
# Set number of shots, optimization_level and resilience_level
options_mitigated.optimization_level = 3
options_mitigated.resilience_level = 1 # setting T-REX
# Now we run the circuits in runtime with the optimal parameters
# To run on runtime we set server = 'rtm'
# First we run the unmitigated results
E_opt_hea_noisy_rtm,kk_opt_hea_noisy_rtm,g_hea = vqe_optimal(graph=graph,
service=service,
server='rtm',
options = options_noisy,
angles_opt=angles_hea_noiseless,
ansatz_str='hea',
layers=layers_hea,
zne=False,
extrap='exp',
backend=backend,
shots=shots)
# Now we run using ZNE and ZNE+T-REX
# ZNE
E_opt_hea_mitigated1_rtm,kk_opt_hea_mitigated1_rtm,g_hea = vqe_optimal(graph=graph,
service=service,
server='rtm',
options = options_noisy,
angles_opt=angles_hea_noiseless,
ansatz_str='hea',
layers=layers_hea,
zne=True,
extrap='exp',
backend=backend,
shots=shots)
# ZNE + T-REX
E_opt_hea_mitigated2_rtm,kk_opt_hea_mitigated2_rtm,g_hea = vqe_optimal(graph=graph,
service=service,
server='rtm',
options = options_mitigated,
angles_opt=angles_hea_noiseless,
ansatz_str='hea',
layers=layers_hea,
zne=True,
extrap='exp',
backend=backend,
shots=shots)
#Plotting
f,ax = plt.subplots()
#plt.plot(g_values,E_3,'ro')
plt.plot(exact_g_values,exact_E,label='exact')
plt.plot(g_hea,E_opt_hea_noisy_rtm,'o',label='noisy')
plt.plot(g_hea,E_opt_hea_mitigated1_rtm,'o',label='ZNE')
plt.plot(g_hea,E_opt_hea_mitigated2_rtm,'o',label='ZNE+T-REX')
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
plt.legend()
inset_ax = f.add_axes([0.24, 0.22, 0.3, 0.3]) # [left, bottom, width, height]
plt.plot(exact_g_values,exact_kk)
plt.plot(g_hea,kk_opt_hea_noisy_rtm,'o',markersize=4)
plt.plot(g_hea,kk_opt_hea_mitigated1_rtm,'o',markersize=4)
plt.plot(g_hea,kk_opt_hea_mitigated2_rtm,'o',markersize=4)
inset_ax.set_xlabel('boundary field')
inset_ax.set_ylabel("$<N_k>$")
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can make the bars more transparent to better see the ones that are behind
# if they overlap.
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
state = Statevector(qc)
plot_state_city(state, alpha=0.6)
|
https://github.com/gatchan00/QPlex
|
gatchan00
|
%config IPCompleter.greedy=True
# useful additional packages
import matplotlib.pyplot as plt
import matplotlib.axes as axes
%matplotlib inline
import numpy as np
import networkx as nx
from qiskit import BasicAer
from qiskit.tools.visualization import plot_histogram
from qiskit.aqua import Operator, run_algorithm
from qiskit.aqua.input import EnergyInput
from qiskit.aqua.translators.ising import max_cut, tsp
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua.components.variational_forms import RY
from qiskit.aqua import QuantumInstance
# setup aqua logging
import logging
from qiskit.aqua import set_qiskit_aqua_logging
# set_qiskit_aqua_logging(logging.DEBUG) # choose INFO, DEBUG to see the log
a = -5
b = -3
#xRaw = 4
#yRaw = 5
def getBit(number,precision,posicion):
return int(format(number,'b').rjust(precision,'0')[precision-1-i])
n = 3
from docplex.mp.model import Model
from qiskit.aqua.translators.ising import docplex
# Create an instance of a model and variables.
mdl = Model(name='max_cut')
x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(n)}
y = {i: mdl.binary_var(name='y_{0}'.format(i)) for i in range(n)}
# Object function
precision = 4
max_cut_func = mdl.sum(a*2**i*x[i]+b*2**i*y[i] for i in range(n))
mdl.maximize(max_cut_func)
qubitOp_docplex, offset_docplex = docplex.get_qubitops(mdl)
seed = 10598
spsa = SPSA(max_trials=300)
ry = RY(qubitOp_docplex.num_qubits, depth=4, entanglement='linear')
vqe = VQE(qubitOp_docplex, ry, spsa, 'matrix')
backend = BasicAer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend, seed=seed, seed_transpiler=seed)
result = vqe.run(quantum_instance)
x = max_cut.sample_most_likely(result['eigvecs'][0])
print('solution:', max_cut.get_graph_solution(x))
#print('solution objective:', max_cut.max_cut_value(x, w))
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import copy
# Problem modelling imports
from docplex.mp.model import Model
# Qiskit imports
from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit.utils.algorithm_globals import algorithm_globals
from qiskit_optimization.algorithms import MinimumEigenOptimizer, CplexOptimizer
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.problems.variable import VarType
from qiskit_optimization.converters.quadratic_program_to_qubo import QuadraticProgramToQubo
from qiskit_optimization.translators import from_docplex_mp
def create_problem(mu: np.array, sigma: np.array, total: int = 3) -> QuadraticProgram:
"""Solve the quadratic program using docplex."""
mdl = Model()
x = [mdl.binary_var("x%s" % i) for i in range(len(sigma))]
objective = mdl.sum([mu[i] * x[i] for i in range(len(mu))])
objective -= 2 * mdl.sum(
[sigma[i, j] * x[i] * x[j] for i in range(len(mu)) for j in range(len(mu))]
)
mdl.maximize(objective)
cost = mdl.sum(x)
mdl.add_constraint(cost == total)
qp = from_docplex_mp(mdl)
return qp
def relax_problem(problem) -> QuadraticProgram:
"""Change all variables to continuous."""
relaxed_problem = copy.deepcopy(problem)
for variable in relaxed_problem.variables:
variable.vartype = VarType.CONTINUOUS
return relaxed_problem
mu = np.array([3.418, 2.0913, 6.2415, 4.4436, 10.892, 3.4051])
sigma = np.array(
[
[1.07978412, 0.00768914, 0.11227606, -0.06842969, -0.01016793, -0.00839765],
[0.00768914, 0.10922887, -0.03043424, -0.0020045, 0.00670929, 0.0147937],
[0.11227606, -0.03043424, 0.985353, 0.02307313, -0.05249785, 0.00904119],
[-0.06842969, -0.0020045, 0.02307313, 0.6043817, 0.03740115, -0.00945322],
[-0.01016793, 0.00670929, -0.05249785, 0.03740115, 0.79839634, 0.07616951],
[-0.00839765, 0.0147937, 0.00904119, -0.00945322, 0.07616951, 1.08464544],
]
)
qubo = create_problem(mu, sigma)
print(qubo.prettyprint())
result = CplexOptimizer().solve(qubo)
print(result.prettyprint())
qp = relax_problem(QuadraticProgramToQubo().convert(qubo))
print(qp.prettyprint())
sol = CplexOptimizer().solve(qp)
print(sol.prettyprint())
c_stars = sol.samples[0].x
print(c_stars)
algorithm_globals.random_seed = 12345
qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 1.0])
exact_mes = NumPyMinimumEigensolver()
qaoa = MinimumEigenOptimizer(qaoa_mes)
qaoa_result = qaoa.solve(qubo)
print(qaoa_result.prettyprint())
from qiskit import QuantumCircuit
thetas = [2 * np.arcsin(np.sqrt(c_star)) for c_star in c_stars]
init_qc = QuantumCircuit(len(sigma))
for idx, theta in enumerate(thetas):
init_qc.ry(theta, idx)
init_qc.draw(output="mpl")
from qiskit.circuit import Parameter
beta = Parameter("β")
ws_mixer = QuantumCircuit(len(sigma))
for idx, theta in enumerate(thetas):
ws_mixer.ry(-theta, idx)
ws_mixer.rz(-2 * beta, idx)
ws_mixer.ry(theta, idx)
ws_mixer.draw(output="mpl")
ws_qaoa_mes = QAOA(
sampler=Sampler(),
optimizer=COBYLA(),
initial_state=init_qc,
mixer=ws_mixer,
initial_point=[0.0, 1.0],
)
ws_qaoa = MinimumEigenOptimizer(ws_qaoa_mes)
ws_qaoa_result = ws_qaoa.solve(qubo)
print(ws_qaoa_result.prettyprint())
def format_qaoa_samples(samples, max_len: int = 10):
qaoa_res = []
for s in samples:
if sum(s.x) == 3:
qaoa_res.append(("".join([str(int(_)) for _ in s.x]), s.fval, s.probability))
res = sorted(qaoa_res, key=lambda x: -x[1])[0:max_len]
return [(_[0] + f": value: {_[1]:.3f}, probability: {1e2*_[2]:.1f}%") for _ in res]
format_qaoa_samples(qaoa_result.samples)
format_qaoa_samples(ws_qaoa_result.samples)
from qiskit_optimization.algorithms import WarmStartQAOAOptimizer
qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 1.0])
ws_qaoa = WarmStartQAOAOptimizer(
pre_solver=CplexOptimizer(), relax_for_pre_solver=True, qaoa=qaoa_mes, epsilon=0.0
)
ws_result = ws_qaoa.solve(qubo)
print(ws_result.prettyprint())
format_qaoa_samples(ws_result.samples)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Useful additional packages
import matplotlib.pyplot as plt
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.u(pi/2,pi/4,pi/8,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.p(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.id(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.x(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.y(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.z(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.h(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.s(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.sdg(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.t(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.tdg(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rx(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ry(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rz(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.cx(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cy(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cz(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ch(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.crz(pi/2,q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cp(pi/2,q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cu(pi/2, pi/2, pi/2, 0, q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.swap(q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.ccx(q[0], q[1], q[2])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cswap(q[0], q[1], q[2])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.measure(q, c)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.reset(q[0])
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.reset(q[0])
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.x(q[0]).c_if(c, 0)
qc.measure(q,c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q,c)
qc.x(q[0]).c_if(c, 0)
qc.measure(q,c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
# Initializing a three-qubit quantum state
import math
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0]
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.initialize(desired_vector, [q[0],q[1],q[2]])
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
job = backend.run(transpile(qc, backend))
qc_state = job.result().get_statevector(qc)
qc_state
state_fidelity(desired_vector,qc_state)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0)
plot_circuit_layout(new_circ_lv0, backend)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import QuantumCircuit
# Create a new circuit with a single qubit
qc = QuantumCircuit(1)
# Add a Not gate to qubit 0
qc.x(0)
# Return a drawing of the circuit using MatPlotLib ("mpl"). This is the
# last line of the cell, so the drawing appears in the cell output.
qc.draw("mpl")
### CHECK QISKIT VERSION
import qiskit
qiskit.__version__
### CHECK OTHER DEPENDENCIES
%pip show pylatexenc matplotlib qc_grader
#qc-grader should be 0.18.8 (or higher)
### Imports
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit_ibm_runtime import EstimatorV2 as Estimator
from qiskit_aer import AerSimulator
import matplotlib.pyplot as plt
from qc_grader.challenges.iqc_2024 import grade_lab0_ex1
# Create a new circuit with two qubits
qc = QuantumCircuit(2)
# Add a Hadamard gate to qubit 0
qc.h(0)
# Perform a CNOT gate on qubit 1, controlled by qubit 0
qc.cx(0, 1)
# Return a drawing of the circuit using MatPlotLib ("mpl"). This is the
# last line of the cell, so the drawing appears in the cell output.
qc.draw("mpl")
# The ZZ applies a Z operator on qubit 0, and a Z operator on qubit 1
ZZ = SparsePauliOp('ZZ')
# The ZI applies a Z operator on qubit 0, and an Identity operator on qubit 1
ZI = SparsePauliOp('ZI')
# The IX applies an Identity operator on qubit 0, and an X operator on qubit 1
IX = SparsePauliOp('IX')
### Write your code below here ###
IZ = SparsePauliOp('IZ')
XX = SparsePauliOp('XX')
XI = SparsePauliOp('XI')
### Follow the same naming convention we used above
## Don't change any code past this line, but remember to run the cell.
observables = [IZ, IX, ZI, XI, ZZ, XX]
# Submit your answer using following code
grade_lab0_ex1(observables)
# Set up the Estimator
estimator = Estimator(backend=AerSimulator())
# Submit the circuit to Estimator
pub = (qc, observables)
job = estimator.run(pubs=[pub])
# Collect the data
data = ['IZ', 'IX', 'ZI', 'XI', 'ZZ', 'XX']
values = job.result()[0].data.evs
# Set up our graph
container = plt.plot(data, values, '-o')
# Label each axis
plt.xlabel('Observables')
plt.ylabel('Values')
# Draw the final graph
plt.show()
container = plt.bar(data, values, width=0.8)
plt.xlabel('Observables')
plt.ylabel('Values')
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice
from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel
line = LineLattice(2)
fermi = FermiHubbardModel.uniform_parameters(line, 2.0, 4.0, 3.0)
print(fermi.second_q_ops()) # Note: the trailing `s`
from qiskit_nature.second_q.hamiltonians.lattices import LineLattice
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
line = LineLattice(2)
fermi = FermiHubbardModel(line.uniform_parameters(2.0, 4.0), 3.0)
print(fermi.second_q_op()) # Note: NO trailing `s`
import numpy as np
from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
fermi = FermiHubbardModel.from_parameters(interaction, 3.0)
print(fermi.second_q_ops()) # Note: the trailing `s`
import numpy as np
from qiskit_nature.second_q.hamiltonians.lattices import Lattice
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
lattice = Lattice.from_adjacency_matrix(interaction)
fermi = FermiHubbardModel(lattice, 3.0)
print(fermi.second_q_op()) # Note: NO trailing `s`
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice
from qiskit_nature.problems.second_quantization.lattice.models import IsingModel
line = LineLattice(2)
ising = IsingModel.uniform_parameters(line, 2.0, 4.0)
print(ising.second_q_ops()) # Note: the trailing `s`
from qiskit_nature.second_q.hamiltonians.lattices import LineLattice
from qiskit_nature.second_q.hamiltonians import IsingModel
line = LineLattice(2)
ising = IsingModel(line.uniform_parameters(2.0, 4.0))
print(ising.second_q_op()) # Note: NO trailing `s`
import numpy as np
from qiskit_nature.problems.second_quantization.lattice.models import IsingModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
ising = IsingModel.from_parameters(interaction)
print(ising.second_q_ops()) # Note: the trailing `s`
import numpy as np
from qiskit_nature.second_q.hamiltonians.lattices import Lattice
from qiskit_nature.second_q.hamiltonians import IsingModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
lattice = Lattice.from_adjacency_matrix(interaction)
ising = IsingModel(lattice)
print(ising.second_q_op()) # Note: NO trailing `s`
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
import numpy as np
# Create a quantum register with 2 qubits
q = QuantumRegister(2,'q')
# Form a quantum circuit
# Note that the circuit name is optional
qc = QuantumCircuit(q,name="first_qc")
# Display the quantum circuit
qc.draw()
# Add a Hadamard gate on qubit 0, putting this in superposition.
qc.h(0)
# Add a CX (CNOT) gate on control qubit 0
# and target qubit 1 to create an entangled state.
qc.cx(0, 1)
qc.draw()
# Create a classical register with 2 bits
c = ClassicalRegister(2,'c')
meas = QuantumCircuit(q,c,name="first_m")
meas.barrier(q)
meas.measure(q, c)
meas.draw()
# Quantum circuits can be added with + operations
# Add two pre-defined circuits
qc_all=qc+meas
qc_all.draw()
# Draw the quantum circuit in a different (slightly better) format
qc_all.draw(output='mpl')
# Create the quantum circuit with the measurement in one go.
qc_all = QuantumCircuit(q,c,name="2q_all")
qc_all.h(0)
qc_all.cx(0,1)
qc_all.barrier()
qc_all.measure(0,0)
qc_all.measure(1,1)
qc_all.draw(output='mpl')
# Use Aer's qasm_simulator
backend_q = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
job_sim1 = execute(qc_all, backend_q, shots=4096)
job_sim1.status()
# Grab the results from the job.
result_sim1 = job_sim1.result()
result_sim1
result_sim1.get_counts(qc_all)
plot_histogram(result_sim1.get_counts(qc_all))
# Use Aer's statevector_simulator
backend_sv = Aer.get_backend('statevector_simulator')
# Execute the circuit on the statevector simulator.
# It is important to note that the measurement has been excluded
job_sim2 = execute(qc, backend_sv)
# Grab the results from the job.
result_sim2 = job_sim2.result()
# Output the entire result
result_sim2
# See output state as a vector
outputstate = result_sim2.get_statevector(qc, decimals=5)
print(outputstate)
# Visualize density matrix
plot_state_city(outputstate)
# Create the quantum circuit with the measurement in one go.
qc_3 = QuantumCircuit(3,3,name="qc_bloch")
qc_3.x(1)
qc_3.h(2)
qc_3.barrier()
qc_3.draw(output='mpl')
# Execute the circuit on the statevector simulator.
# It is important to note that the measurement has been excluded
job_sim_bloch = execute(qc_3, backend_sv)
# Grab the results from the job.
result_sim_bloch = job_sim_bloch.result()
# See output state as a vector
output_bloch = result_sim_bloch.get_statevector(qc_3, decimals=5)
# Draw on the Bloch sphere
plot_bloch_multivector(output_bloch)
# Use Aer's unitary_simulator
backend_u = Aer.get_backend('unitary_simulator')
# Execute the circuit on the unitary simulator.
job_usim = execute(qc, backend_u)
# Grab the results from the job.
result_usim = job_usim.result()
result_usim
# Output the unitary matrix
unitary = result_usim.get_unitary(qc)
print('%s\n' % unitary)
# Create the quantum circuit with the measurement in one go.
qc_ex1 = QuantumCircuit(q,c,name="ex1")
# Put the first qubit in equal superposition
qc_ex1.h(0)
# Rest of the circuit
qc_ex1.x(1)
qc_ex1.cx(0,1)
qc_ex1.barrier()
qc_ex1.measure(0,0)
qc_ex1.measure(1,1)
qc_ex1.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_ex1 = execute(qc_ex1, backend_q, shots=4096)
job_ex1.status()
# Grab the results from the job.
result_ex1 = job_ex1.result()
result_ex1.get_counts(qc_ex1)
plot_histogram(result_ex1.get_counts(qc_ex1))
# Or get the histogram in one go
plot_histogram(job_ex1.result().get_counts(qc_ex1))
# Create a quantum register with 3 qubits
q3 = QuantumRegister(3,'q')
# Create a classical register with 3 qubits
c3 = ClassicalRegister(3,'c')
# Create the quantum circuit with the measurement in one go.
qc_ex2 = QuantumCircuit(q3,c3,name="ex1")
qc_ex2.ry(2*np.pi/3,0)
qc_ex2.cx(0,1)
qc_ex2.cx(1,2)
qc_ex2.barrier()
qc_ex2.measure(q3,c3)
qc_ex2.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_ex2 = execute(qc_ex2, backend_q, shots=4096)
# Grab the results from the job.
result_ex2 = job_ex2.result()
plot_histogram(result_ex2.get_counts(qc_ex2))
# Create a quantum register with 3 qubits
q3 = QuantumRegister(3,'q')
# Create a classical register with 3 qubits
c3 = ClassicalRegister(3,'c')
# Create the quantum circuit without a Toffoli gate
qc_toff = QuantumCircuit(q3,c3,name="ex1")
qc_toff.ry(2*np.pi/3,0)
qc_toff.h(1)
qc_toff.h(2)
qc_toff.barrier()
qc_toff.measure(q3,c3)
qc_toff.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_toff = execute(qc_toff, backend_q, shots=4096)
# Grab the results from the job.
result_toff = job_toff.result()
plot_histogram(result_toff.get_counts(qc_toff))
# Now, add a Toffoli gate
qc_toff = QuantumCircuit(q3,c3,name="ex1")
qc_toff.ry(2*np.pi/3,0)
qc_toff.h(1)
qc_toff.h(2)
qc_toff.ccx(1,2,0)
qc_toff.barrier()
qc_toff.measure(q3,c3)
qc_toff.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_toff = execute(qc_toff, backend_q, shots=4096)
# Grab the results from the job.
result_toff = job_toff.result()
plot_histogram(result_toff.get_counts(qc_toff))
from qiskit import IBMQ
# first save your Token to disk
IBMQ.save_account('<Your Token>')
#IBMQ.load_account() # Load account from disk
from qiskit import IBMQ
# first save your Token to disk
# IBMQ.disable_account()
IBMQ.enable_account('<Your Token>')
IBMQ.providers()
open_provider = IBMQ.get_provider(hub='ibm-q', group='open')
#
default_provider = IBMQ.get_provider(hub='ibm-q-kaist', group='internal', project='default')
open_provider.backends()
default_provider.backends()
from qiskit.tools.monitor import backend_overview, backend_monitor
backend_overview()
# Open access
backend = open_provider.get_backend('ibmq_ourense')
# select a number of premium devices
backend_manhattan = default_provider.get_backend('ibmq_manhattan')
backend_toronto = default_provider.get_backend('ibmq_toronto')
backend_casablanca = default_provider.get_backend('ibmq_casablanca')
backend_monitor(default_provider.get_backend('ibmq_ourense'))
from qiskit.tools.jupyter import *
backend
from qiskit import Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, execute
from qiskit.tools.visualization import plot_histogram
# Load account
#IBMQ.load_account()
# Select a backend
backend_local = Aer.get_backend('qasm_simulator')
backend_real = open_provider.get_backend('ibmq_ourense') #Simulator
print(backend_local)
print(backend_real)
# number of qubits
n = 2
# Define the Quantum and Classical Registers
q = QuantumRegister(n)
c = ClassicalRegister(n)
# Build the circuit
generalcircuit = QuantumCircuit(q, c)
generalcircuit.h(q[0])
generalcircuit.cx(q[0],q[1])
generalcircuit.measure(q, c)
generalcircuit.draw(output='mpl')
# Execute the circuit
job_local = execute(generalcircuit, backend_local, shots=8192)
job_local.status()
result=job_local.result()
print(result)
# Print the result
plot_histogram(result.get_counts())
# Execute the circuit
job_real = execute(generalcircuit, backend_real, shots=8192)
job_real.status()
# Print the result
plot_histogram(job_real.result().get_counts())
import numpy as np
from numpy import pi
# importing Qiskit
from qiskit import *
from qiskit.visualization import *
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
from qiskit.tools.visualization import plot_gate_map, plot_error_map
qftc = QuantumCircuit(3)
qftc.h(0)
qftc.draw(output='mpl')
qftc.cu1(2*pi/(2**2), 1, 0) # CROT from qubit 1 to qubit 0
qftc.draw(output='mpl')
qftc.cu1(2*pi/(2**3), 2, 0) # CROT from qubit 1 to qubit 0
qftc.draw(output='mpl')
qftc.h(1)
qftc.cu1(2*pi/(2**2), 2, 1) # CROT from qubit 2 to qubit 1
qftc.h(2)
qftc.draw(output='mpl')
# Complete the QFT circuit by reordering qubits (by exchanging qubit 1 and 3)
qftc.swap(0,2)
qftc.draw(output='mpl')
def qft_rotations(circuit, n):
if n == 0: # Exit function if circuit is empty
print("The number of qubits must be greater than 0")
return circuit
index = 0
circuit.h(index) # Apply the H-gate to the most significant qubit
index += 1
n -= 1
for qubit in range(n): # Apply the controlled rotations conditioned on n-1 qubits
# For each less significant qubit, we need to do a
# smaller-angled controlled rotation:
circuit.cu1(2*pi/2**(2+qubit), index + qubit, 0)
qc = QuantumCircuit(4)
qft_rotations(qc,4)
qc.draw(output = 'mpl')
def qft_rotations(circuit, n, start):
if n == 0: # Exit function if circuit is empty
return circuit
circuit.h(start) # Apply the H-gate to the most significant qubit
if start == n-1:
return circuit
for qubit in range(n-1-start): # Apply the controlled rotations conditioned on n-1 qubits
# For each less significant qubit, we need to do a
# smaller-angled controlled rotation:
circuit.cu1(2*pi/2**(2+qubit), start + 1 + qubit, start)
start += 1
circuit.barrier()
# Apply QFT recursively
qft_rotations(circuit, n, start)
qc = QuantumCircuit(5)
qft_rotations(qc,5,0)
qc.draw(output = 'mpl')
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
from qiskit.circuit import Parameter
# Simple example
# Define two parameters, t1 and t2
theta1 = Parameter('t1')
theta2 = Parameter('t2')
# Build a 1-qubit circuit
qc = QuantumCircuit(1, 1)
# First parameter, t1, is used for a single qubit rotation of a controlled qubit
qc.ry(theta1,0)
qc.rz(theta2,0)
qc.barrier()
qc.measure(0, 0)
qc.draw(output='mpl')
theta1_range = np.linspace(0, 2 * np.pi, 20)
theta2_range = np.linspace(0, np.pi, 2)
circuits = [qc.bind_parameters({theta1: theta_val1, theta2: theta_val2})
for theta_val2 in theta2_range for theta_val1 in theta1_range ]
# Visualize several circuits to check that correct circuits are generated correctly.
display(circuits[0].draw(output='mpl'))
display(circuits[1].draw(output='mpl'))
display(circuits[20].draw(output='mpl'))
# Execute multiple circuits
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots = 8192,
parameter_binds=[{theta1: theta_val1, theta2: theta_val2}
for theta_val2 in theta2_range for theta_val1 in theta1_range])
# Store all counts
counts = [job.result().get_counts(i) for i in range(len(job.result().results))]
# Plot to visualize the result
plt.figure(figsize=(12,6))
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts: (counts.get('0',0)-counts.get('1',1))/8192,counts)))
plt.show()
# IBMQ.disable_account()
provider = IBMQ.enable_account('TOKEN')
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
from qiskit.tools.visualization import plot_gate_map, plot_error_map
# Retrieve IBM Quantum device information
backend_overview()
# Execute multiple circuits
job_exp = execute(qc, backend=provider.get_backend('ibmq_essex'), shots = 8192,
parameter_binds=[{theta1: theta_val1, theta2: theta_val2}
for theta_val2 in theta2_range for theta_val1 in theta1_range])
# Monitor job status
job_monitor(job_exp)
# Store all counts
counts_exp = [job_exp.result().get_counts(i) for i in range(len(job_exp.result().results))]
# Plot to visualize the result
plt.figure(figsize=(12,6))
plt.rcParams.update({'font.size': 16})
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts: (counts.get('0',0)-counts.get('1',1))/8192,counts)),'r',label='Simulation')
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts_exp: (counts_exp.get('0',0)-counts_exp.get('1',1))/8192,counts_exp)),
'b',label='Experiment')
plt.legend(loc='best')
plt.show()
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager, Layout
display(plot_error_map(provider.get_backend('ibmqx2')))
display(plot_error_map(provider.get_backend('ibmq_burlington')))
# Create a dummy circuit for default transpiler demonstration
qc = QuantumCircuit(4)
qc.h(0)
qc.swap(0,1)
qc.cx(1,0)
qc.s(3)
qc.x(3)
qc.h(3)
qc.h(0)
qc.cx(0,2)
qc.ccx(0,1,2)
qc.h(0)
print('Original circuit')
display(qc.draw(output='mpl'))
# Transpile the circuit to run on ibmqx2
qt_qx2 = transpile(qc,provider.get_backend('ibmqx2'))
print('Transpiled circuit for ibmqx2')
display(qt_qx2.draw(output='mpl'))
# Transpile the circuit to run on ibmq_burlington
qt_bu = transpile(qc,provider.get_backend('ibmq_burlington'))
print('Transpiled circuit for ibmqx_Burlington')
display(qt_bu.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations for ibmqx2 = %s" % qt_qx2.size())
print("Number of operations for ibmq_burlington = %s \n" % qt_bu.size())
# Circuit depth
print("Circuit depth for ibmqx2 = %s" % qt_qx2.depth())
print("Circuit depth for ibmq_burlington = %s \n" % qt_bu.depth())
# Number of qubits
print("Number of qubits for ibmqx2 = %s" % qt_qx2.width())
print("Number of qubits for ibmq_burlington = %s \n" % qt_bu.width())
# Breakdown of operations by type
print("Operations for ibmqx2: %s" % qt_qx2.count_ops())
print("Operations for ibmq_burlington: %s \n" % qt_bu.count_ops())
# Number of unentangled subcircuits in this circuit.
# In principle, each subcircuit can be executed on a different quantum device.
print("Number of unentangled subcircuits for ibmqx2 = %s" % qt_qx2.num_tensor_factors())
print("Number of unentangled subcircuits for ibmq_burlington = %s" % qt_bu.num_tensor_factors())
qr = QuantumRegister(4,'q')
cr = ClassicalRegister(4,'c')
qc_test = QuantumCircuit(qr,cr)
qc_test.h(0)
for i in range(3):
qc_test.cx(i,i+1)
qc_test.barrier()
qc_test.measure(qr,cr)
qc_test.draw(output='mpl')
qc_t = transpile(qc_test, backend = provider.get_backend('ibmq_london'))
# Display transpiled circuit
display(qc_t.draw(output='mpl'))
# Display the qubit layout
display(plot_error_map(provider.get_backend('ibmq_london')))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_t.size())
# Circuit depth
print("Circuit depth = %s" % qc_t.depth())
# Execute the circuit on the qasm simulator.
job_test = execute(qc_test, provider.get_backend('ibmq_london'), shots=8192)
job_monitor(job_test)
# Customize the layout
layout = Layout({qr[0]: 4, qr[1]: 3, qr[2]: 1, qr[3]:0})
# Map it onto 5 qubit backend ibmqx2
qc_test_new = transpile(qc_test, backend = provider.get_backend('ibmq_london'), initial_layout=layout, basis_gates=['u1','u2','u3','cx'])
display(qc_test_new.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_test_new.size())
# Circuit depth
print("Circuit depth = %s" % qc_test_new.depth())
# Execute the circuit on the qasm simulator.
job_test_new = execute(qc_test_new, provider.get_backend('ibmq_london'), shots=8192)
job_monitor(job_test_new)
# Now, compare the two
result_test = job_test.result()
result_test_new = job_test_new.result()
# Plot both experimental and ideal results
plot_histogram([result_test.get_counts(qc_test),result_test_new.get_counts(qc_test_new)],
color=['green','blue'],legend=['default','custom'],figsize = [20,8])
# Apply 4-qubit controlled x gate
qr = QuantumRegister(5,'q')
qc = QuantumCircuit(qr)
qc.h(0)
qc.h(1)
qc.h(3)
qc.ccx(0,1,2)
qc.ccx(2,3,4)
qc.ccx(0,1,2)
display(qc.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s \n" % qc.size())
# Count different types of operations
print("Operation counts = %s \n" % qc.count_ops())
# Circuit depth
print("Circuit depth = %s" % qc.depth())
qc_t = transpile(qc, provider.get_backend('ibmq_valencia'))
display(qc_t.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_t.size())
# Circuit depth
print("Circuit depth = %s" % qc_t.depth())
# Transpile many times (20 times in this example) and pick the best one
trial = 20
# Use ibmq_valencia for example
backend_exp = provider.get_backend('ibmq_valencia')
tcircs0 = transpile([qc]*trial, backend_exp, optimization_level=0)
tcircs1 = transpile([qc]*trial, backend_exp, optimization_level=1)
tcircs2 = transpile([qc]*trial, backend_exp, optimization_level=2)
tcircs3 = transpile([qc]*trial, backend_exp, optimization_level=3)
import matplotlib.pyplot as plt
num_cx0 = [c.count_ops()['cx'] for c in tcircs0]
num_cx1 = [c.count_ops()['cx'] for c in tcircs1]
num_cx2 = [c.count_ops()['cx'] for c in tcircs2]
num_cx3 = [c.count_ops()['cx'] for c in tcircs3]
num_tot0 = [c.size() for c in tcircs0]
num_tot1 = [c.size() for c in tcircs1]
num_tot2 = [c.size() for c in tcircs2]
num_tot3 = [c.size() for c in tcircs3]
num_depth0 = [c.depth() for c in tcircs0]
num_depth1 = [c.depth() for c in tcircs1]
num_depth2 = [c.depth() for c in tcircs2]
num_depth3 = [c.depth() for c in tcircs3]
plt.rcParams.update({'font.size': 16})
# Plot the number of CNOT gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_cx0)),num_cx0,'r',label='level 0')
plt.plot(range(len(num_cx1)),num_cx1,'b',label='level 1')
plt.plot(range(len(num_cx2)),num_cx2,'g',label='level 2')
plt.plot(range(len(num_cx3)),num_cx3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('# of cx gates')
plt.show()
# Plot total number of gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_tot0)),num_tot0,'r',label='level 0')
plt.plot(range(len(num_tot1)),num_tot1,'b',label='level 1')
plt.plot(range(len(num_tot2)),num_tot2,'g',label='level 2')
plt.plot(range(len(num_tot3)),num_tot3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('# of total gates')
plt.show()
# Plot the number of CNOT gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_depth0)),num_depth0,'r',label='level 0')
plt.plot(range(len(num_depth1)),num_depth1,'b',label='level 1')
plt.plot(range(len(num_depth2)),num_depth2,'g',label='level 2')
plt.plot(range(len(num_depth3)),num_depth3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('Circuit depth')
plt.show()
print('Opt0: Minimum # of cx gates = %s' % min(num_cx0))
print('Opt0: The best circuit is the circut %s \n' % num_cx0.index(min(num_cx0)))
print('Opt1: Minimum # of cx gates = %s' % min(num_cx1))
print('Opt1: The best circuit is the circut %s \n' % num_cx1.index(min(num_cx1)))
print('Opt2: Minimum # of cx gates = %s' % min(num_cx2))
print('Opt2: The best circuit is the circut %s \n' % num_cx2.index(min(num_cx2)))
print('Opt3: Minimum # of cx gates = %s' % min(num_cx3))
print('Opt3: The best circuit is the circut %s' % num_cx3.index(min(num_cx3)))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import json
import time
import warnings
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import Statevector
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.circuit.library import RawFeatureVector
from qiskit_machine_learning.neural_networks import SamplerQNN
algorithm_globals.random_seed = 42
def ansatz(num_qubits):
return RealAmplitudes(num_qubits, reps=5)
num_qubits = 5
circ = ansatz(num_qubits)
circ.decompose().draw("mpl")
def auto_encoder_circuit(num_latent, num_trash):
qr = QuantumRegister(num_latent + 2 * num_trash + 1, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.compose(ansatz(num_latent + num_trash), range(0, num_latent + num_trash), inplace=True)
circuit.barrier()
auxiliary_qubit = num_latent + 2 * num_trash
# swap test
circuit.h(auxiliary_qubit)
for i in range(num_trash):
circuit.cswap(auxiliary_qubit, num_latent + i, num_latent + num_trash + i)
circuit.h(auxiliary_qubit)
circuit.measure(auxiliary_qubit, cr[0])
return circuit
num_latent = 3
num_trash = 2
circuit = auto_encoder_circuit(num_latent, num_trash)
circuit.draw("mpl")
def domain_wall(circuit, a, b):
# Here we place the Domain Wall to qubits a - b in our circuit
for i in np.arange(int(b / 2), int(b)):
circuit.x(i)
return circuit
domain_wall_circuit = domain_wall(QuantumCircuit(5), 0, 5)
domain_wall_circuit.draw("mpl")
ae = auto_encoder_circuit(num_latent, num_trash)
qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1)
qc = qc.compose(domain_wall_circuit, range(num_latent + num_trash))
qc = qc.compose(ae)
qc.draw("mpl")
# Here we define our interpret for our SamplerQNN
def identity_interpret(x):
return x
qnn = SamplerQNN(
circuit=qc,
input_params=[],
weight_params=ae.parameters,
interpret=identity_interpret,
output_shape=2,
)
def cost_func_domain(params_values):
probabilities = qnn.forward([], params_values)
# we pick a probability of getting 1 as the output of the network
cost = np.sum(probabilities[:, 1])
# plotting part
clear_output(wait=True)
objective_func_vals.append(cost)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
return cost
opt = COBYLA(maxiter=150)
initial_point = algorithm_globals.random.random(ae.num_parameters)
objective_func_vals = []
# make the plot nicer
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
opt_result = opt.minimize(cost_func_domain, initial_point)
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} seconds")
test_qc = QuantumCircuit(num_latent + num_trash)
test_qc = test_qc.compose(domain_wall_circuit)
ansatz_qc = ansatz(num_latent + num_trash)
test_qc = test_qc.compose(ansatz_qc)
test_qc.barrier()
test_qc.reset(4)
test_qc.reset(3)
test_qc.barrier()
test_qc = test_qc.compose(ansatz_qc.inverse())
test_qc.draw("mpl")
test_qc = test_qc.assign_parameters(opt_result.x)
domain_wall_state = Statevector(domain_wall_circuit).data
output_state = Statevector(test_qc).data
fidelity = np.sqrt(np.dot(domain_wall_state.conj(), output_state) ** 2)
print("Fidelity of our Output State with our Input State: ", fidelity.real)
def zero_idx(j, i):
# Index for zero pixels
return [
[i, j],
[i - 1, j - 1],
[i - 1, j + 1],
[i - 2, j - 1],
[i - 2, j + 1],
[i - 3, j - 1],
[i - 3, j + 1],
[i - 4, j - 1],
[i - 4, j + 1],
[i - 5, j],
]
def one_idx(i, j):
# Index for one pixels
return [[i, j - 1], [i, j - 2], [i, j - 3], [i, j - 4], [i, j - 5], [i - 1, j - 4], [i, j]]
def get_dataset_digits(num, draw=True):
# Create Dataset containing zero and one
train_images = []
train_labels = []
for i in range(int(num / 2)):
# First we introduce background noise
empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape(
8, 4
)
# Now we insert the pixels for the one
for i, j in one_idx(2, 6):
empty[j][i] = algorithm_globals.random.uniform(0.9, 1)
train_images.append(empty)
train_labels.append(1)
if draw:
plt.title("This is a One")
plt.imshow(train_images[-1])
plt.show()
for i in range(int(num / 2)):
empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape(
8, 4
)
# Now we insert the pixels for the zero
for k, j in zero_idx(2, 6):
empty[k][j] = algorithm_globals.random.uniform(0.9, 1)
train_images.append(empty)
train_labels.append(0)
if draw:
plt.imshow(train_images[-1])
plt.title("This is a Zero")
plt.show()
train_images = np.array(train_images)
train_images = train_images.reshape(len(train_images), 32)
for i in range(len(train_images)):
sum_sq = np.sum(train_images[i] ** 2)
train_images[i] = train_images[i] / np.sqrt(sum_sq)
return train_images, train_labels
train_images, __ = get_dataset_digits(2)
num_latent = 3
num_trash = 2
fm = RawFeatureVector(2 ** (num_latent + num_trash))
ae = auto_encoder_circuit(num_latent, num_trash)
qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1)
qc = qc.compose(fm, range(num_latent + num_trash))
qc = qc.compose(ae)
qc.draw("mpl")
def identity_interpret(x):
return x
qnn = SamplerQNN(
circuit=qc,
input_params=fm.parameters,
weight_params=ae.parameters,
interpret=identity_interpret,
output_shape=2,
)
def cost_func_digits(params_values):
probabilities = qnn.forward(train_images, params_values)
cost = np.sum(probabilities[:, 1]) / train_images.shape[0]
# plotting part
clear_output(wait=True)
objective_func_vals.append(cost)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
return cost
with open("12_qae_initial_point.json", "r") as f:
initial_point = json.load(f)
opt = COBYLA(maxiter=150)
objective_func_vals = []
# make the plot nicer
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
opt_result = opt.minimize(fun=cost_func_digits, x0=initial_point)
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} seconds")
# Test
test_qc = QuantumCircuit(num_latent + num_trash)
test_qc = test_qc.compose(fm)
ansatz_qc = ansatz(num_latent + num_trash)
test_qc = test_qc.compose(ansatz_qc)
test_qc.barrier()
test_qc.reset(4)
test_qc.reset(3)
test_qc.barrier()
test_qc = test_qc.compose(ansatz_qc.inverse())
# sample new images
test_images, test_labels = get_dataset_digits(2, draw=False)
for image, label in zip(test_images, test_labels):
original_qc = fm.assign_parameters(image)
original_sv = Statevector(original_qc).data
original_sv = np.reshape(np.abs(original_sv) ** 2, (8, 4))
param_values = np.concatenate((image, opt_result.x))
output_qc = test_qc.assign_parameters(param_values)
output_sv = Statevector(output_qc).data
output_sv = np.reshape(np.abs(output_sv) ** 2, (8, 4))
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(original_sv)
ax1.set_title("Input Data")
ax2.imshow(output_sv)
ax2.set_title("Output Data")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/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.
""" Test blackbox state preparation """
from unittest import TestCase
import numpy as np
from qiskit import QuantumCircuit
from qclib.state_preparation.blackbox import BlackBoxInitialize
from qclib.util import get_state
class TestBlackbox(TestCase):
""" Test blackbox state preparation """
def test_blackbox(self):
""" Run blackbox state preparation """
initialize = BlackBoxInitialize.initialize
state = np.random.rand(16) - 0.5 + (np.random.rand(16) - 0.5) * 1j
state = state / np.linalg.norm(state)
q_circuit = QuantumCircuit(5)
initialize(q_circuit, state.tolist())
out = get_state(q_circuit)
out = out.reshape((len(out)//2, 2))
out = out[:, 0]
self.assertTrue(np.allclose(state, out, atol=0.02))
|
https://github.com/BoschSamuel/QizGloria
|
BoschSamuel
|
# -- coding: utf-8 --
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import torch
from torch.autograd import Function
import torch.optim as optim
from qiskit import QuantumRegister,QuantumCircuit,ClassicalRegister,execute
from qiskit.circuit import Parameter
from qiskit import Aer
import numpy as np
from tqdm import tqdm
from matplotlib import pyplot as plt
%matplotlib inline
np.random.seed = 42
def to_numbers(tensor_list):
num_list = []
for tensor in tensor_list:
num_list += [tensor.item()]
return num_list
class QiskitCircuit():
def __init__(self,shots):
self.theta = Parameter('Theta')
self.phi = Parameter('Phi')
self.lam = Parameter('Lambda')
self.shots = shots
def create_circuit():
qr = QuantumRegister(1,'q')
cr = ClassicalRegister(1,'c')
ckt = QuantumCircuit(qr,cr)
ckt.h(qr[0])
ckt.barrier()
ckt.u3(self.theta,self.phi,self.lam,qr[0])
ckt.barrier()
ckt.measure(qr,cr)
return ckt
self.circuit = create_circuit()
def N_qubit_expectation_Z(self,counts, shots, nr_qubits):
expects = np.zeros(nr_qubits)
for key in counts.keys():
perc = counts[key]/shots
check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)])
expects += check
return expects
def bind(self, parameters):
[self.theta,self.phi,self.lam] = to_numbers(parameters)
self.circuit.data[2][0]._params = to_numbers(parameters)
def run(self, i):
self.bind(i)
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(self.circuit,backend,shots=self.shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(self.circuit)
return self.N_qubit_expectation_Z(counts,self.shots,1)
class TorchCircuit(Function):
@staticmethod
def forward(ctx, i):
if not hasattr(ctx, 'QiskitCirc'):
ctx.QiskitCirc = QiskitCircuit(shots=10000)
exp_value = ctx.QiskitCirc.run(i[0])
result = torch.tensor([exp_value])
ctx.save_for_backward(result, i)
return result
@staticmethod
def backward(ctx, grad_output):
eps = 0.01
forward_tensor, i = ctx.saved_tensors
input_numbers = to_numbers(i[0])
gradient = [0,0,0]
for k in range(len(input_numbers)):
input_eps = input_numbers
input_eps[k] = input_numbers[k] + eps
exp_value = ctx.QiskitCirc.run(torch.tensor(input_eps))[0]
result_eps = torch.tensor([exp_value])
gradient_result = (exp_value - forward_tensor[0][0].item())#/eps
gradient[k] = gradient_result
# print(gradient)
result = torch.tensor([gradient])
# print(result)
return result.float() * grad_output.float()
# x = torch.tensor([np.pi/4, np.pi/4, np.pi/4], requires_grad=True)
x = torch.tensor([[0.0, 0.0, 0.0]], requires_grad=True)
qc = TorchCircuit.apply
y1 = qc(x)
y1.backward()
print(x.grad)
qc = TorchCircuit.apply
def cost(x):
target = -1
expval = qc(x)
return torch.abs(qc(x) - target) ** 2, expval
x = torch.tensor([[np.pi/4, np.pi/4, np.pi/4]], requires_grad=True)
opt = torch.optim.Adam([x], lr=0.1)
num_epoch = 100
loss_list = []
expval_list = []
for i in tqdm(range(num_epoch)):
# for i in range(num_epoch):
opt.zero_grad()
loss, expval = cost(x)
loss.backward()
opt.step()
loss_list.append(loss.item())
expval_list.append(expval.item())
# print(loss.item())
plt.plot(loss_list)
# print(circuit(phi, theta))
# print(cost(x))
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import torchvision
from torchvision import datasets, transforms
batch_size_train = 1
batch_size_test = 1
learning_rate = 0.01
momentum = 0.5
log_interval = 10
torch.backends.cudnn.enabled = False
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor()])
mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
labels = mnist_trainset.targets #get labels
labels = labels.numpy()
idx1 = np.where(labels == 0) #search all zeros
idx2 = np.where(labels == 1) # search all ones
idx = np.concatenate((idx1[0][0:20],idx2[0][0:20])) # concatenate their indices
mnist_trainset.targets = labels[idx]
mnist_trainset.data = mnist_trainset.data[idx]
print(mnist_trainset)
train_loader = torch.utils.data.DataLoader(mnist_trainset, batch_size=batch_size_train, shuffle=True)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 3)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
# return F.softmax(x)
x = np.pi*F.tanh(x)
x = qc(x) # This is the q node
x = (x+1)/2 # Translate expectation values [-1,1] to labels [0,1]
x = torch.cat((x, 1-x), -1)
return x
network = Net()
optimizer = optim.SGD(network.parameters(), lr=learning_rate,
momentum=momentum)
# optimizer = optim.Adam(network.parameters(), lr=learning_rate)
epochs = 10
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
# print(batch_idx)
optimizer.zero_grad()
output = network(data)
loss = F.nll_loss(output, target)
# loss = F.cross_entropy(output, target)
# print(output)
# print(output[0][1].item(), target.item())
loss.backward()
optimizer.step()
total_loss.append(loss.item())
print(loss.item())
accuracy = 0
number = 0
for batch_idx, (data, target) in enumerate(train_loader):
number +=1
output = network(data)
output = (output>0.5).float()
accuracy += (output[0][1].item() == target[0].item())*1
print("Accuracy is: {}".format(accuracy/number))
|
https://github.com/fvarchon/qiskit-intros
|
fvarchon
|
# Your first Qiskit application
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(2) # qubits indexed as qr[0], qr[1] and qr[2]
cr = ClassicalRegister(2) # classical bits indexed as cr[0], cr[1] and cr[2]
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.measure(qr, cr)
circuit.draw()
circuit.draw(output='latex_source')
print(circuit.qasm())
from qiskit import Aer, execute
# pick a backend, in this case a simulator
backend = Aer.get_backend('qasm_simulator')
# start a simulation job on the backend
job = execute(circuit, backend, shots=1000)
# collect the job results and display them
result = job.result()
counts = result.get_counts(circuit)
print(counts)
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
from qiskit import IBMQ
IBMQ.load_accounts()
IBMQ.backends()
# OPTION 1: pick a specific backend
backend = IBMQ.get_backend('ibmq_16_melbourne')
# OPTION 2: pick the least busy backend
from qiskit.providers.ibmq import least_busy
backend = least_busy(IBMQ.backends(simulator=False))
# start a simulation job on the backend
job = execute(circuit, backend, shots=1000)
# collect the job results and display them
result = job.result()
counts = result.get_counts(circuit)
print(counts)
# OPTION 1: pick a specific backend
backend = IBMQ.get_backend('ibmq_16_melbourne')
# OPTION 2: pick the least busy backend
from qiskit.providers.ibmq import least_busy
backend = least_busy(IBMQ.backends(simulator=False))
# start a simulation job on the backend
job = execute(circuit, backend, shots=1000)
# monitor the job
from qiskit.tools.monitor import job_monitor
job_monitor(job)
# collect the job results and display them
result = job.result()
counts = result.get_counts(circuit)
print(counts)
plot_histogram(counts)
%qiskit_backend_monitor backend
qr = QuantumRegister(7, 'q')
qr = QuantumRegister(7, 'q')
tpl_circuit = QuantumCircuit(qr)
tpl_circuit.h(qr[3])
tpl_circuit.cx(qr[0], qr[6])
tpl_circuit.cx(qr[6], qr[0])
tpl_circuit.cx(qr[0], qr[1])
tpl_circuit.cx(qr[3], qr[1])
tpl_circuit.cx(qr[3], qr[0])
tpl_circuit.draw()
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import BasicSwap
from qiskit.transpiler import transpile
from qiskit.mapper import CouplingMap
help(BasicSwap)
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
simulator = Aer.get_backend('qasm_simulator')
coupling_map = CouplingMap(couplinglist=coupling)
pass_manager = PassManager()
pass_manager.append([BasicSwap(coupling_map=coupling_map)])
basic_circ = transpile(tpl_circuit, simulator, pass_manager=pass_manager)
basic_circ.draw()
IBMQ.backends()
realdevice = IBMQ.get_backend('ibmq_16_melbourne')
tpl_realdevice = transpile(tpl_circuit, backend = realdevice)
tpl_realdevice.draw(line_length = 250)
|
https://github.com/daimurat/qiskit-implementation
|
daimurat
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(1)
init_state = [0, 1]
qc.initialize(init_state, 0)
qc.draw()
from qiskit import assemble, Aer
backend = Aer.get_backend('statevector_simulator')
## optional ##
# assemble a list of circuits and create Qobj
qobj = assemble(qc) # A backwards compat (上位互換) alias for QasmQobj
result = backend.run(qobj).result()
result.get_statevector()
from qiskit import execute
result = execute(qc, backend).result()
result.get_statevector()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from __future__ import annotations
import numpy as np
import networkx as nx
num_nodes = 4
w = np.array([[0., 1., 1., 0.],
[1., 0., 1., 1.],
[1., 1., 0., 1.],
[0., 1., 1., 0.]])
G = nx.from_numpy_array(w)
layout = nx.random_layout(G, seed=10)
colors = ['r', 'g', 'b', 'y']
nx.draw(G, layout, node_color=colors)
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels);
def objective_value(x: np.ndarray, w: np.ndarray) -> float:
"""Compute the value of a cut.
Args:
x: Binary string as numpy array.
w: Adjacency matrix.
Returns:
Value of the cut.
"""
X = np.outer(x, (1 - x))
w_01 = np.where(w != 0, 1, 0)
return np.sum(w_01 * X)
def bitfield(n: int, L: int) -> list[int]:
result = np.binary_repr(n, L)
return [int(digit) for digit in result] # [2:] to chop off the "0b" part
# use the brute-force way to generate the oracle
L = num_nodes
max = 2**L
sol = np.inf
for i in range(max):
cur = bitfield(i, L)
how_many_nonzero = np.count_nonzero(cur)
if how_many_nonzero * 2 != L: # not balanced
continue
cur_v = objective_value(np.array(cur), w)
if cur_v < sol:
sol = cur_v
print(f'Objective value computed by the brute-force method is {sol}')
from qiskit.quantum_info import Pauli, SparsePauliOp
def get_operator(weight_matrix: np.ndarray) -> tuple[SparsePauliOp, float]:
r"""Generate Hamiltonian for the graph partitioning
Notes:
Goals:
1 Separate the vertices into two set of the same size.
2 Make sure the number of edges between the two set is minimized.
Hamiltonian:
H = H_A + H_B
H_A = sum\_{(i,j)\in E}{(1-ZiZj)/2}
H_B = (sum_{i}{Zi})^2 = sum_{i}{Zi^2}+sum_{i!=j}{ZiZj}
H_A is for achieving goal 2 and H_B is for achieving goal 1.
Args:
weight_matrix: Adjacency matrix.
Returns:
Operator for the Hamiltonian
A constant shift for the obj function.
"""
num_nodes = len(weight_matrix)
pauli_list = []
coeffs = []
shift = 0
for i in range(num_nodes):
for j in range(i):
if weight_matrix[i, j] != 0:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append(Pauli((z_p, x_p)))
coeffs.append(-0.5)
shift += 0.5
for i in range(num_nodes):
for j in range(num_nodes):
if i != j:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append(Pauli((z_p, x_p)))
coeffs.append(1.0)
else:
shift += 1
return SparsePauliOp(pauli_list, coeffs=coeffs), shift
qubit_op, offset = get_operator(w)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.primitives import Sampler
from qiskit.quantum_info import Pauli, Statevector
from qiskit.result import QuasiDistribution
from qiskit.utils import algorithm_globals
sampler = Sampler()
def sample_most_likely(state_vector: QuasiDistribution | Statevector) -> np.ndarray:
"""Compute the most likely binary string from state vector.
Args:
state_vector: State vector or quasi-distribution.
Returns:
Binary string as an array of ints.
"""
if isinstance(state_vector, QuasiDistribution):
values = list(state_vector.values())
else:
values = state_vector
n = int(np.log2(len(values)))
k = np.argmax(np.abs(values))
x = bitfield(k, n)
x.reverse()
return np.asarray(x)
algorithm_globals.random_seed = 10598
optimizer = COBYLA()
qaoa = QAOA(sampler, optimizer, reps=2)
result = qaoa.compute_minimum_eigenvalue(qubit_op)
x = sample_most_likely(result.eigenstate)
print(x)
print(f'Objective value computed by QAOA is {objective_value(x, w)}')
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.quantum_info import Operator
npme = NumPyMinimumEigensolver()
result = npme.compute_minimum_eigenvalue(Operator(qubit_op))
x = sample_most_likely(result.eigenstate)
print(x)
print(f'Objective value computed by the NumPyMinimumEigensolver is {objective_value(x, w)}')
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
from qiskit.circuit.library import TwoLocal
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 10598
optimizer = COBYLA()
ansatz = TwoLocal(qubit_op.num_qubits, "ry", "cz", reps=2, entanglement="linear")
sampling_vqe = SamplingVQE(sampler, ansatz, optimizer)
result = sampling_vqe.compute_minimum_eigenvalue(qubit_op)
x = sample_most_likely(result.eigenstate)
print(x)
print(f"Objective value computed by VQE is {objective_value(x, w)}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/tanjinadnanabir/qbosons-qiskit-hackathon
|
tanjinadnanabir
|
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
import seaborn as sns
from google.colab import drive
drive.mount('/content/drive')
import warnings
warnings.filterwarnings('ignore')
df = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/iris/Iris.csv')
df.head()
# delete a column
df = df.drop(columns = ['Id'])
df.head()
# to display stats about data
df.describe()
# to basic info about datatype
df.info()
# to display no. of samples on each class
df['Species'].value_counts()
# check for null values
df.isnull().sum()
# histograms
df['SepalLengthCm'].hist()
df['SepalWidthCm'].hist()
df['PetalLengthCm'].hist()
df['PetalWidthCm'].hist()
# scatterplot
colors = ['red', 'orange', 'blue']
species = ['Iris-virginica','Iris-versicolor','Iris-setosa']
for i in range(3):
x = df[df['Species'] == species[i]]
plt.scatter(x['SepalLengthCm'], x['SepalWidthCm'], c = colors[i], label=species[i])
plt.xlabel("Sepal Length")
plt.ylabel("Sepal Width")
plt.legend()
for i in range(3):
x = df[df['Species'] == species[i]]
plt.scatter(x['PetalLengthCm'], x['PetalWidthCm'], c = colors[i], label=species[i])
plt.xlabel("Petal Length")
plt.ylabel("Petal Width")
plt.legend()
for i in range(3):
x = df[df['Species'] == species[i]]
plt.scatter(x['SepalLengthCm'], x['PetalLengthCm'], c = colors[i], label=species[i])
plt.xlabel("Sepal Length")
plt.ylabel("Petal Length")
plt.legend()
for i in range(3):
x = df[df['Species'] == species[i]]
plt.scatter(x['SepalWidthCm'], x['PetalWidthCm'], c = colors[i], label=species[i])
plt.xlabel("Sepal Width")
plt.ylabel("Petal Width")
plt.legend()
df.corr()
corr = df.corr()
fig, ax = plt.subplots(figsize=(5,4))
sns.heatmap(corr, annot=True, ax=ax, cmap = 'coolwarm')
# Feature correlation
def featureCorrelation(s):
import seaborn as sn
import matplotlib.pyplot as plt
sn.set(font_scale=1.3)
sn.set_style("darkgrid")
fig_dims = (10, 4)
fig, ax = plt.subplots(figsize=fig_dims)
sn.heatmap(s.corr(), annot=True, ax=ax)
plt.show()
featureCorrelation(df)
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
df['Species'] = le.fit_transform(df['Species'])
df.head()
featureCorrelation(df)
# Splitting the dataset
from sklearn.model_selection import train_test_split
X = df.drop(columns=['Species'])
Y = df['Species']
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.30)
# logistic regression
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
# model training
model.fit(x_train, y_train)
# print metric to get performance
print("Accuracy: ",model.score(x_test, y_test) * 100)
# knn - k-nearest neighbours
from sklearn.neighbors import KNeighborsClassifier
model = KNeighborsClassifier()
model.fit(x_train, y_train)
# print metric to get performance
print("Accuracy: ",model.score(x_test, y_test) * 100)
# decision tree
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier()
model.fit(x_train, y_train)
# print metric to get performance
print("Accuracy: ",model.score(x_test, y_test) * 100)
from sklearn.svm import SVC
model = SVC()
model.fit(x_train, y_train)
# print metric to get performance
print("Accuracy: ",model.score(x_test, y_test) * 100)
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier()
model.fit(x_train, y_train)
# print metric to get performance
print("Accuracy: ",model.score(x_test, y_test) * 100)
|
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)
filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
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)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, assemble, Aer
from qiskit.tools.visualization import plot_histogram
from math import pi
import matplotlib.pyplot as plt
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
qc = QuantumCircuit(q, c)
qc.h(0)
qc.measure(0,0)
qc.x(0).c_if(c, 0)
qc.draw(output='mpl')
q = QuantumRegister(3,'q')
c = ClassicalRegister(3,'c')
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.barrier()
qc.measure(q,c)
qc.draw('mpl')
print(bin(3))
print(bin(7))
q = QuantumRegister(3,'q')
c = ClassicalRegister(3,'c')
qc = QuantumCircuit(q, c)
qc.h(0)
qc.h(1)
qc.h(2)
qc.barrier()
qc.measure(q,c)
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')
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')
sim = Aer.get_backend('qasm_simulator')
count0 = execute(qc_S, sim).result().get_counts()
key_new = [str(int(key,2)/2**m) for key in list(count0.keys())]
count1 = dict(zip(key_new, count0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(count0, ax=ax[0])
plot_histogram(count1, 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/4,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')
count0 = execute(qc, sim).result().get_counts()
key_new = [str(int(key,2)/2**m) for key in list(count0.keys())]
count1 = dict(zip(key_new, count0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(count0, ax=ax[0])
plot_histogram(count1, ax=ax[1])
fig.tight_layout()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.