repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
gadial/qiskit-terra | qiskit/transpiler/passes/utils/remove_final_measurements.py | <filename>qiskit/transpiler/passes/utils/remove_final_measurements.py
# 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.
"""Remove final measurements and barriers at the end of a circuit."""
from qiskit.transpiler.basepasses import TransformationPass
class RemoveFinalMeasurements(TransformationPass):
"""Remove final measurements and barriers at the end of a circuit.
This pass removes final barriers and final measurements, as well as the
ClassicalRegisters they are connected to if the ClassicalRegister
is unused. Measurements and barriers are considered final if they are
followed by no other operations (aside from other measurements or barriers.)
"""
def run(self, dag):
"""Run the RemoveFinalMeasurements pass on `dag`.
Args:
dag (DAGCircuit): the DAG to be optimized.
Returns:
DAGCircuit: the optimized DAG.
"""
final_op_types = ['measure', 'barrier']
final_ops = []
cregs_to_remove = dict()
clbits_with_final_measures = set()
clbit_registers = {clbit: creg
for creg in dag.cregs.values()
for clbit in creg}
for candidate_node in dag.named_nodes(*final_op_types):
is_final_op = True
for _, child_successors in dag.bfs_successors(candidate_node):
if any(suc.type == 'op' and suc.name not in final_op_types
for suc in child_successors):
is_final_op = False
break
if is_final_op:
final_ops.append(candidate_node)
if not final_ops:
return dag
for node in final_ops:
for carg in node.cargs:
# Add the clbit that was attached to the measure we are removing
clbits_with_final_measures.add(carg)
dag.remove_op_node(node)
# If the clbit is idle, add its register to list of registers we may remove
for clbit in clbits_with_final_measures:
if clbit in dag.idle_wires():
creg = clbit_registers[clbit]
if creg in cregs_to_remove:
cregs_to_remove[creg] += 1
else:
cregs_to_remove[creg] = 1
# Remove creg if all of its clbits were added above
for key, val in zip(list(dag.cregs.keys()), list(dag.cregs.values())):
if val in cregs_to_remove and cregs_to_remove[val] == val.size:
del dag.cregs[key]
new_dag = dag._copy_circuit_metadata()
for node in dag.topological_op_nodes():
# copy the condition over too
new_dag.apply_operation_back(node.op, qargs=node.qargs, cargs=node.cargs)
return new_dag
|
gadial/qiskit-terra | qiskit/pulse/transforms/dag.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A collection of functions to convert ScheduleBlock to DAG representation."""
import retworkx as rx
from qiskit.pulse.schedule import ScheduleBlock
def block_to_dag(block: ScheduleBlock) -> rx.PyDAG:
"""Convert schedule block instruction into DAG.
``ScheduleBlock`` can be represented as a DAG as needed.
For example, equality of two programs are efficiently checked on DAG representation.
.. code-block:: python
with pulse.build() as sched1:
with pulse.align_left():
pulse.play(my_gaussian0, pulse.DriveChannel(0))
pulse.shift_phase(1.57, pulse.DriveChannel(2))
pulse.play(my_gaussian1, pulse.DriveChannel(1))
with pulse.build() as sched2:
with pulse.align_left():
pulse.shift_phase(1.57, pulse.DriveChannel(2))
pulse.play(my_gaussian1, pulse.DriveChannel(1))
pulse.play(my_gaussian0, pulse.DriveChannel(0))
Here the ``sched1 `` and ``sched2`` are different implementations of the same program,
but it is difficult to confirm on the list representation.
Another example is instruction optimization.
.. code-block:: python
with pulse.build() as sched:
with pulse.align_left():
pulse.shift_phase(1.57, pulse.DriveChannel(1))
pulse.play(my_gaussian0, pulse.DriveChannel(0))
pulse.shift_phase(-1.57, pulse.DriveChannel(1))
In above program two ``shift_phase`` instructions can be cancelled out because
they are consecutive on the same drive channel.
This can be easily found on the DAG representation.
Args:
block: A schedule block to be converted.
Returns:
Instructions in DAG representation.
"""
if block.alignment_context.is_sequential:
return _sequential_allocation(block)
else:
return _parallel_allocation(block)
def _sequential_allocation(block: ScheduleBlock) -> rx.PyDAG:
"""A helper function to create a DAG of a sequential alignment context."""
dag_instructions = rx.PyDAG()
prev_node = None
edges = []
for inst in block.instructions:
current_node = dag_instructions.add_node(inst)
if prev_node is not None:
edges.append((prev_node, current_node))
prev_node = current_node
dag_instructions.add_edges_from_no_data(edges)
return dag_instructions
def _parallel_allocation(block: ScheduleBlock) -> rx.PyDAG:
"""A helper function to create a DAG of a parallel alignment context."""
dag_instructions = rx.PyDAG()
slots = dict()
edges = []
for inst in block.instructions:
current_node = dag_instructions.add_node(inst)
for chan in inst.channels:
prev_node = slots.pop(chan, None)
if prev_node is not None:
edges.append((prev_node, current_node))
slots[chan] = current_node
dag_instructions.add_edges_from_no_data(edges)
return dag_instructions
|
gadial/qiskit-terra | qiskit/tools/jupyter/version_table.py | <filename>qiskit/tools/jupyter/version_table.py
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=unused-argument
"""A module for monitoring backends."""
import sys
import time
from IPython.display import HTML, display
from IPython.core.magic import (line_magic,
Magics, magics_class)
import qiskit
from qiskit.util import local_hardware_info
@magics_class
class VersionTable(Magics):
"""A class of status magic functions.
"""
@line_magic
def qiskit_version_table(self, line='', cell=None):
"""
Print an HTML-formatted table with version numbers for Qiskit and its
dependencies. This should make it possible to reproduce the environment
and the calculation later on.
"""
html = "<h3>Version Information</h3>"
html += "<table>"
html += "<tr><th>Qiskit Software</th><th>Version</th></tr>"
packages = []
qver = qiskit.__qiskit_version__
packages.append(('Qiskit', qver['qiskit']))
packages.append(('Terra', qver['qiskit-terra']))
packages.append(('Aer', qver['qiskit-aer']))
packages.append(('Ignis', qver['qiskit-ignis']))
packages.append(('Aqua', qver['qiskit-aqua']))
packages.append(('IBM Q Provider', qver['qiskit-ibmq-provider']))
for name, version in packages:
html += "<tr><td>%s</td><td>%s</td></tr>" % (name, version)
html += "<tr><th>System information</th></tr>"
local_hw_info = local_hardware_info()
sys_info = [("Python", sys.version),
("OS", "%s" % local_hw_info['os']),
("CPUs", "%s" % local_hw_info['cpus']),
("Memory (Gb)", "%s" % local_hw_info['memory'])
]
for name, version in sys_info:
html += "<tr><td>%s</td><td>%s</td></tr>" % (name, version)
html += "<tr><td colspan='2'>%s</td></tr>" % time.strftime(
'%a %b %d %H:%M:%S %Y %Z')
html += "</table>"
return display(HTML(html))
|
gadial/qiskit-terra | qiskit/quantum_info/operators/mixins/linear.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Mixin for linear operator interface.
"""
from abc import ABC, abstractmethod
from .multiply import MultiplyMixin
class LinearMixin(MultiplyMixin, ABC):
"""Abstract Mixin for linear operator.
This class defines the following operator overloads:
- ``+`` / ``__add__``
- ``-`` / ``__sub__``
- ``*`` / ``__rmul__`
- ``/`` / ``__truediv__``
- ``__neg__``
The following abstract methods must be implemented by subclasses
using this mixin
- ``_add(self, other, qargs=None)``
- ``_multiply(self, other)``
"""
def __add__(self, other):
qargs = getattr(other, 'qargs', None)
return self._add(other, qargs=qargs)
def __sub__(self, other):
qargs = getattr(other, 'qargs', None)
return self._add(-other, qargs=qargs)
@abstractmethod
def _add(self, other, qargs=None):
"""Return the CLASS self + other.
If ``qargs`` are specified the other operator will be added
assuming it is identity on all other subsystems.
Args:
other (CLASS): an operator object.
qargs (None or list): optional subsystems to add on
(Default: None)
Returns:
CLASS: the CLASS self + other.
"""
|
gadial/qiskit-terra | qiskit/quantum_info/synthesis/clifford_decompose.py | <reponame>gadial/qiskit-terra
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Circuit synthesis for the Clifford class.
"""
# pylint: disable=invalid-name
from itertools import product
import numpy as np
from qiskit.exceptions import QiskitError
from qiskit.circuit import QuantumCircuit
from qiskit.quantum_info.operators.symplectic.clifford_circuits import (
_append_z, _append_x, _append_h, _append_s, _append_v, _append_w,
_append_cx, _append_swap)
def decompose_clifford(clifford, method=None):
"""Decompose a Clifford operator into a QuantumCircuit.
For N <= 3 qubits this is based on optimal CX cost decomposition
from reference [1]. For N > 3 qubits this is done using the general
non-optimal greedy compilation routine from reference [3],
which typically yields better CX cost compared to the AG method in [2].
Args:
clifford (Clifford): a clifford operator.
method (str): Optional, a synthesis method ('AG' or 'greedy').
If set this overrides optimal decomposition for N <=3 qubits.
Return:
QuantumCircuit: a circuit implementation of the Clifford.
References:
1. <NAME>, <NAME>, *Hadamard-free circuits expose the
structure of the Clifford group*,
`arXiv:2003.09412 [quant-ph] <https://arxiv.org/abs/2003.09412>`_
2. <NAME>, <NAME>, *Improved Simulation of Stabilizer Circuits*,
Phys. Rev. A 70, 052328 (2004).
`arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_
3. <NAME>, <NAME>, <NAME>, <NAME>,
*Clifford Circuit Optimization with Templates and Symbolic Pauli Gates*
"""
num_qubits = clifford.num_qubits
if method == 'AG':
return decompose_clifford_ag(clifford)
if method == 'greedy':
return decompose_clifford_greedy(clifford)
if num_qubits <= 3:
return decompose_clifford_bm(clifford)
return decompose_clifford_greedy(clifford)
# ---------------------------------------------------------------------
# Synthesis based on Bravyi & Maslov decomposition
# ---------------------------------------------------------------------
def decompose_clifford_bm(clifford):
"""Decompose a clifford"""
num_qubits = clifford.num_qubits
if num_qubits == 1:
return _decompose_clifford_1q(
clifford.table.array, clifford.table.phase)
# Inverse of final decomposed circuit
inv_circuit = QuantumCircuit(num_qubits, name='inv_circ')
# CNOT cost of clifford
cost = _cx_cost(clifford)
# Find composition of circuits with CX and (H.S)^a gates to reduce CNOT count
while cost > 0:
clifford, inv_circuit, cost = _reduce_cost(clifford, inv_circuit, cost)
# Decompose the remaining product of 1-qubit cliffords
ret_circ = QuantumCircuit(num_qubits, name=str(clifford))
for qubit in range(num_qubits):
pos = [qubit, qubit + num_qubits]
table = clifford.table.array[pos][:, pos]
phase = clifford.table.phase[pos]
circ = _decompose_clifford_1q(table, phase)
if len(circ) > 0:
ret_circ.append(circ, [qubit])
# Add the inverse of the 2-qubit reductions circuit
if len(inv_circuit) > 0:
ret_circ.append(inv_circuit.inverse(), range(num_qubits))
return ret_circ.decompose()
# ---------------------------------------------------------------------
# Synthesis based on Aaronson & Gottesman decomposition
# ---------------------------------------------------------------------
def decompose_clifford_ag(clifford):
"""Decompose a Clifford operator into a QuantumCircuit.
Args:
clifford (Clifford): a clifford operator.
Return:
QuantumCircuit: a circuit implementation of the Clifford.
"""
# Use 1-qubit decomposition method
if clifford.num_qubits == 1:
return _decompose_clifford_1q(
clifford.table.array, clifford.table.phase)
# Compose a circuit which we will convert to an instruction
circuit = QuantumCircuit(clifford.num_qubits,
name=str(clifford))
# Make a copy of Clifford as we are going to do row reduction to
# reduce it to an identity
clifford_cpy = clifford.copy()
for i in range(clifford.num_qubits):
# put a 1 one into position by permuting and using Hadamards(i,i)
_set_qubit_x_true(clifford_cpy, circuit, i)
# make all entries in row i except ith equal to 0
# by using phase gate and CNOTS
_set_row_x_zero(clifford_cpy, circuit, i)
# treat Zs
_set_row_z_zero(clifford_cpy, circuit, i)
for i in range(clifford.num_qubits):
if clifford_cpy.destabilizer.phase[i]:
_append_z(clifford_cpy, i)
circuit.z(i)
if clifford_cpy.stabilizer.phase[i]:
_append_x(clifford_cpy, i)
circuit.x(i)
# Next we invert the circuit to undo the row reduction and return the
# result as a gate instruction
return circuit.inverse()
# ---------------------------------------------------------------------
# 1-qubit Clifford decomposition
# ---------------------------------------------------------------------
def _decompose_clifford_1q(pauli, phase):
"""Decompose a single-qubit clifford"""
circuit = QuantumCircuit(1, name='temp')
# Add phase correction
destab_phase, stab_phase = phase
if destab_phase and not stab_phase:
circuit.z(0)
elif not destab_phase and stab_phase:
circuit.x(0)
elif destab_phase and stab_phase:
circuit.y(0)
destab_phase_label = '-' if destab_phase else '+'
stab_phase_label = '-' if stab_phase else '+'
destab_x, destab_z = pauli[0]
stab_x, stab_z = pauli[1]
# Z-stabilizer
if stab_z and not stab_x:
stab_label = 'Z'
if destab_z:
destab_label = 'Y'
circuit.s(0)
else:
destab_label = 'X'
# X-stabilizer
elif not stab_z and stab_x:
stab_label = 'X'
if destab_x:
destab_label = 'Y'
circuit.sdg(0)
else:
destab_label = 'Z'
circuit.h(0)
# Y-stabilizer
else:
stab_label = 'Y'
if destab_z:
destab_label = 'Z'
else:
destab_label = 'X'
circuit.s(0)
circuit.h(0)
circuit.s(0)
# Add circuit name
name_destab = "Destabilizer = ['{}{}']".format(destab_phase_label, destab_label)
name_stab = "Stabilizer = ['{}{}']".format(stab_phase_label, stab_label)
circuit.name = "Clifford: {}, {}".format(name_stab, name_destab)
return circuit
# ---------------------------------------------------------------------
# Helper functions for Bravyi & Maslov decomposition
# ---------------------------------------------------------------------
def _reduce_cost(clifford, inv_circuit, cost):
"""Two-qubit cost reduction step"""
num_qubits = clifford.num_qubits
for qubit0 in range(num_qubits):
for qubit1 in range(qubit0 + 1, num_qubits):
for n0, n1 in product(range(3), repeat=2):
# Apply a 2-qubit block
reduced = clifford.copy()
for qubit, n in [(qubit0, n0), (qubit1, n1)]:
if n == 1:
_append_v(reduced, qubit)
elif n == 2:
_append_w(reduced, qubit)
_append_cx(reduced, qubit0, qubit1)
# Compute new cost
new_cost = _cx_cost(reduced)
if new_cost == cost - 1:
# Add decomposition to inverse circuit
for qubit, n in [(qubit0, n0), (qubit1, n1)]:
if n == 1:
inv_circuit.sdg(qubit)
inv_circuit.h(qubit)
elif n == 2:
inv_circuit.h(qubit)
inv_circuit.s(qubit)
inv_circuit.cx(qubit0, qubit1)
return reduced, inv_circuit, new_cost
# If we didn't reduce cost
raise QiskitError("Failed to reduce Clifford CX cost.")
def _cx_cost(clifford):
"""Return the number of CX gates required for Clifford decomposition."""
if clifford.num_qubits == 2:
return _cx_cost2(clifford)
if clifford.num_qubits == 3:
return _cx_cost3(clifford)
raise Exception("No Clifford CX cost function for num_qubits > 3.")
def _rank2(a, b, c, d):
"""Return rank of 2x2 boolean matrix."""
if (a & d) ^ (b & c):
return 2
if a or b or c or d:
return 1
return 0
def _cx_cost2(clifford):
"""Return CX cost of a 2-qubit clifford."""
U = clifford.table.array
r00 = _rank2(U[0, 0], U[0, 2], U[2, 0], U[2, 2])
r01 = _rank2(U[0, 1], U[0, 3], U[2, 1], U[2, 3])
if r00 == 2:
return r01
return r01 + 1 - r00
def _cx_cost3(clifford):
"""Return CX cost of a 3-qubit clifford."""
# pylint: disable=too-many-return-statements,too-many-boolean-expressions
U = clifford.table.array
n = 3
# create information transfer matrices R1, R2
R1 = np.zeros((n, n), dtype=int)
R2 = np.zeros((n, n), dtype=int)
for q1 in range(n):
for q2 in range(n):
R2[q1, q2] = _rank2(U[q1, q2], U[q1, q2 + n], U[q1 + n, q2], U[q1 + n, q2 + n])
mask = np.zeros(2 * n, dtype=int)
mask[[q2, q2 + n]] = 1
isLocX = np.array_equal(U[q1, :] & mask, U[q1, :])
isLocZ = np.array_equal(U[q1 + n, :] & mask, U[q1 + n, :])
isLocY = np.array_equal((U[q1, :] ^ U[q1 + n, :]) & mask,
(U[q1, :] ^ U[q1 + n, :]))
R1[q1, q2] = 1 * (isLocX or isLocZ or isLocY) + 1 * (isLocX and isLocZ and isLocY)
diag1 = np.sort(np.diag(R1)).tolist()
diag2 = np.sort(np.diag(R2)).tolist()
nz1 = np.count_nonzero(R1)
nz2 = np.count_nonzero(R2)
if diag1 == [2, 2, 2]:
return 0
if diag1 == [1, 1, 2]:
return 1
if (diag1 == [0, 1, 1]
or (diag1 == [1, 1, 1] and nz2 < 9)
or (diag1 == [0, 0, 2] and diag2 == [1, 1, 2])):
return 2
if ((diag1 == [1, 1, 1] and nz2 == 9)
or (diag1 == [0, 0, 1] and (
nz1 == 1 or diag2 == [2, 2, 2] or (diag2 == [1, 1, 2] and nz2 < 9)))
or (diag1 == [0, 0, 2] and diag2 == [0, 0, 2])
or (diag2 == [1, 2, 2] and nz1 == 0)):
return 3
if (diag2 == [0, 0, 1] or (diag1 == [0, 0, 0] and (
(diag2 == [1, 1, 1] and nz2 == 9 and nz1 == 3)
or (diag2 == [0, 1, 1] and nz2 == 8 and nz1 == 2)))):
return 5
if nz1 == 3 and nz2 == 3:
return 6
return 4
# ---------------------------------------------------------------------
# Helper functions for Aaronson & Gottesman decomposition
# ---------------------------------------------------------------------
def _set_qubit_x_true(clifford, circuit, qubit):
"""Set destabilizer.X[qubit, qubit] to be True.
This is done by permuting columns l > qubit or if necessary applying
a Hadamard
"""
x = clifford.destabilizer.X[qubit]
z = clifford.destabilizer.Z[qubit]
if x[qubit]:
return
# Try to find non-zero element
for i in range(qubit + 1, clifford.num_qubits):
if x[i]:
_append_swap(clifford, i, qubit)
circuit.swap(i, qubit)
return
# no non-zero element found: need to apply Hadamard somewhere
for i in range(qubit, clifford.num_qubits):
if z[i]:
_append_h(clifford, i)
circuit.h(i)
if i != qubit:
_append_swap(clifford, i, qubit)
circuit.swap(i, qubit)
return
def _set_row_x_zero(clifford, circuit, qubit):
"""Set destabilizer.X[qubit, i] to False for all i > qubit.
This is done by applying CNOTS assumes k<=N and A[k][k]=1
"""
x = clifford.destabilizer.X[qubit]
z = clifford.destabilizer.Z[qubit]
# Check X first
for i in range(qubit + 1, clifford.num_qubits):
if x[i]:
_append_cx(clifford, qubit, i)
circuit.cx(qubit, i)
# Check whether Zs need to be set to zero:
if np.any(z[qubit:]):
if not z[qubit]:
# to treat Zs: make sure row.Z[k] to True
_append_s(clifford, qubit)
circuit.s(qubit)
# reverse CNOTS
for i in range(qubit + 1, clifford.num_qubits):
if z[i]:
_append_cx(clifford, i, qubit)
circuit.cx(i, qubit)
# set row.Z[qubit] to False
_append_s(clifford, qubit)
circuit.s(qubit)
def _set_row_z_zero(clifford, circuit, qubit):
"""Set stabilizer.Z[qubit, i] to False for all i > qubit.
Implemented by applying (reverse) CNOTS assumes qubit < num_qubits
and _set_row_x_zero has been called first
"""
x = clifford.stabilizer.X[qubit]
z = clifford.stabilizer.Z[qubit]
# check whether Zs need to be set to zero:
if np.any(z[qubit + 1:]):
for i in range(qubit + 1, clifford.num_qubits):
if z[i]:
_append_cx(clifford, i, qubit)
circuit.cx(i, qubit)
# check whether Xs need to be set to zero:
if np.any(x[qubit:]):
_append_h(clifford, qubit)
circuit.h(qubit)
for i in range(qubit + 1, clifford.num_qubits):
if x[i]:
_append_cx(clifford, qubit, i)
circuit.cx(qubit, i)
if z[qubit]:
_append_s(clifford, qubit)
circuit.s(qubit)
_append_h(clifford, qubit)
circuit.h(qubit)
# ---------------------------------------------------------------------
# Synthesis based on Bravyi et. al. greedy clifford compiler
# ---------------------------------------------------------------------
def decompose_clifford_greedy(clifford):
"""Decompose a Clifford operator into a QuantumCircuit.
Args:
clifford (Clifford): a clifford operator.
Return:
QuantumCircuit: a circuit implementation of the Clifford.
Raises:
QiskitError: if symplectic Gaussian elimination fails.
"""
num_qubits = clifford.num_qubits
circ = QuantumCircuit(num_qubits, name=str(clifford))
qubit_list = list(range(num_qubits))
clifford_cpy = clifford.copy()
# Reducing the original Clifford to identity
# via symplectic Gaussian elimination
while len(qubit_list) > 0:
clifford_cpy_inv = clifford_cpy.adjoint()
list_greedy_cost = []
for qubit in qubit_list:
cliff_ox = clifford_cpy.copy()
_append_x(cliff_ox, qubit)
cliff_ox = cliff_ox.compose(clifford_cpy_inv)
cliff_oz = clifford_cpy.copy()
_append_z(cliff_oz, qubit)
cliff_oz = cliff_oz.compose(clifford_cpy_inv)
list_pairs = []
pauli_count = 0
# Compute the CNOT cost in order to find the qubit with the minimal cost
for i in qubit_list:
typeq = _from_pair_cliffs_to_type(cliff_ox, cliff_oz, i)
list_pairs.append(typeq)
pauli_count += 1
cost = _compute_greedy_cost(list_pairs)
list_greedy_cost.append([cost, qubit])
_, min_qubit = (sorted(list_greedy_cost))[0]
# Gaussian elimination step for the qubit with minimal CNOT cost
cliff_ox = clifford_cpy.copy()
_append_x(cliff_ox, min_qubit)
cliff_ox = cliff_ox.compose(clifford_cpy_inv)
cliff_oz = clifford_cpy.copy()
_append_z(cliff_oz, min_qubit)
cliff_oz = cliff_oz.compose(clifford_cpy_inv)
# Compute the decoupling operator of cliff_ox and cliff_oz
decouple_circ, decouple_cliff = _calc_decoupling(cliff_ox, cliff_oz, qubit_list,
min_qubit, num_qubits)
circ = circ.compose(decouple_circ)
# Now the clifford acts trivially on min_qubit
clifford_cpy = decouple_cliff.adjoint().compose(clifford_cpy)
qubit_list.remove(min_qubit)
# Add the phases (Pauli gates) to the Clifford circuit
for qubit in range(num_qubits):
stab = clifford_cpy.stabilizer.phase[qubit]
destab = clifford_cpy.destabilizer.phase[qubit]
if destab and stab:
circ.y(qubit)
elif not destab and stab:
circ.x(qubit)
elif destab and not stab:
circ.z(qubit)
return circ
# ---------------------------------------------------------------------
# Helper functions for Bravyi et. al. greedy clifford compiler
# ---------------------------------------------------------------------
# Global arrays of the 16 pairs of Pauli operators
# divided into 5 equivalence classes under the action of single-qubit Cliffords
# Class A - canonical representative is 'XZ'
A_class = [[[False, True], [True, True]], # 'XY'
[[False, True], [True, False]], # 'XZ'
[[True, True], [False, True]], # 'YX'
[[True, True], [True, False]], # 'YZ'
[[True, False], [False, True]], # 'ZX'
[[True, False], [True, True]]] # 'ZY'
# Class B - canonical representative is 'XX'
B_class = [[[True, False], [True, False]], # 'ZZ'
[[False, True], [False, True]], # 'XX'
[[True, True], [True, True]]] # 'YY'
# Class C - canonical representative is 'XI'
C_class = [[[True, False], [False, False]], # 'ZI'
[[False, True], [False, False]], # 'XI'
[[True, True], [False, False]]] # 'YI'
# Class D - canonical representative is 'IZ'
D_class = [[[False, False], [False, True]], # 'IX'
[[False, False], [True, False]], # 'IZ'
[[False, False], [True, True]]] # 'IY'
# Class E - only 'II'
E_class = [[[False, False], [False, False]]] # 'II'
def _from_pair_cliffs_to_type(cliff_ox, cliff_oz, qubit):
"""Converts a pair of Paulis Ox and Oz into a type"""
type_ox = [cliff_ox.destabilizer.phase[qubit], cliff_ox.stabilizer.phase[qubit]]
type_oz = [cliff_oz.destabilizer.phase[qubit], cliff_oz.stabilizer.phase[qubit]]
return [type_ox, type_oz]
def _compute_greedy_cost(list_pairs):
"""Compute the CNOT cost of one step of the algorithm"""
A_num = 0
B_num = 0
C_num = 0
D_num = 0
for pair in list_pairs:
if pair in A_class:
A_num += 1
elif pair in B_class:
B_num += 1
elif pair in C_class:
C_num += 1
elif pair in D_class:
D_num += 1
if (A_num % 2) == 0:
raise QiskitError("Symplectic Gaussian elimination fails.")
# Calculate the CNOT cost
cost = 3 * (A_num - 1) / 2 + (B_num + 1) * (B_num > 0) + C_num + D_num
if list_pairs[0] not in A_class: # additional SWAP
cost += 3
return cost
def _calc_decoupling(cliff_ox, cliff_oz, qubit_list, min_qubit, num_qubits):
"""Calculate a decoupling operator D:
D^{-1} * Ox * D = x1
D^{-1} * Oz * D = z1
and reduce the clifford such that it will act trivially on min_qubit
"""
circ = QuantumCircuit(num_qubits)
# decouple_cliff is initialized to an identity clifford
decouple_cliff = cliff_ox.copy()
num_qubits = decouple_cliff.num_qubits
decouple_cliff.table.phase = np.zeros(2 * num_qubits)
if (decouple_cliff.table.array != np.eye(2 * num_qubits)).any():
raise QiskitError("Symplectic Gaussian elimination fails.")
qubit0 = min_qubit # The qubit for the symplectic Gaussian elimination
# Reduce the pair of Paulis to a representative in the equivalence class
# ['XZ', 'XX', 'XI', 'IZ', 'II'] by adding single-qubit gates
for qubit in qubit_list:
typeq = _from_pair_cliffs_to_type(cliff_ox, cliff_oz, qubit)
if typeq in [[[True, True], [False, False]], # 'YI'
[[True, True], [True, True]], # 'YY'
[[True, True], [True, False]]]: # 'YZ':
circ.s(qubit)
_append_s(decouple_cliff, qubit)
elif typeq in [[[True, False], [False, False]], # 'ZI'
[[True, False], [True, False]], # 'ZZ'
[[True, False], [False, True]], # 'ZX'
[[False, False], [False, True]]]: # 'IX'
circ.h(qubit)
_append_h(decouple_cliff, qubit)
elif typeq in [[[False, False], [True, True]], # 'IY'
[[True, False], [True, True]]]: # 'ZY'
circ.s(qubit)
circ.h(qubit)
_append_s(decouple_cliff, qubit)
_append_h(decouple_cliff, qubit)
elif typeq == [[True, True], [False, True]]: # 'YX'
circ.h(qubit)
circ.s(qubit)
_append_h(decouple_cliff, qubit)
_append_s(decouple_cliff, qubit)
elif typeq == [[False, True], [True, True]]: # 'XY'
circ.s(qubit)
circ.h(qubit)
circ.s(qubit)
_append_s(decouple_cliff, qubit)
_append_h(decouple_cliff, qubit)
_append_s(decouple_cliff, qubit)
# Reducing each pair of Paulis (except of qubit0) to 'II'
# by adding two-qubit gates and single-qubit gates
A_qubits = []
B_qubits = []
C_qubits = []
D_qubits = []
for qubit in qubit_list:
typeq = _from_pair_cliffs_to_type(cliff_ox, cliff_oz, qubit)
if typeq in A_class:
A_qubits.append(qubit)
elif typeq in B_class:
B_qubits.append(qubit)
elif typeq in C_class:
C_qubits.append(qubit)
elif typeq in D_class:
D_qubits.append(qubit)
if len(A_qubits) % 2 != 1:
raise QiskitError("Symplectic Gaussian elimination fails.")
if qubit0 not in A_qubits: # SWAP qubit0 and qubitA
qubitA = A_qubits[0]
circ.swap(qubit0, qubitA)
_append_swap(decouple_cliff, qubit0, qubitA)
if qubit0 in B_qubits:
B_qubits.remove(qubit0)
B_qubits.append(qubitA)
A_qubits.remove(qubitA)
A_qubits.append(qubit0)
elif qubit0 in C_qubits:
C_qubits.remove(qubit0)
C_qubits.append(qubitA)
A_qubits.remove(qubitA)
A_qubits.append(qubit0)
elif qubit0 in D_qubits:
D_qubits.remove(qubit0)
D_qubits.append(qubitA)
A_qubits.remove(qubitA)
A_qubits.append(qubit0)
else:
A_qubits.remove(qubitA)
A_qubits.append(qubit0)
# Reduce pairs in Class C to 'II'
for qubit in C_qubits:
circ.cx(qubit0, qubit)
_append_cx(decouple_cliff, qubit0, qubit)
# Reduce pairs in Class D to 'II'
for qubit in D_qubits:
circ.cx(qubit, qubit0)
_append_cx(decouple_cliff, qubit, qubit0)
# Reduce pairs in Class B to 'II'
if len(B_qubits) > 1:
for qubit in B_qubits[1:]:
qubitB = B_qubits[0]
circ.cx(qubitB, qubit)
_append_cx(decouple_cliff, qubitB, qubit)
if len(B_qubits) > 0:
qubitB = B_qubits[0]
circ.cx(qubit0, qubitB)
circ.h(qubitB)
circ.cx(qubitB, qubit0)
_append_cx(decouple_cliff, qubit0, qubitB)
_append_h(decouple_cliff, qubitB)
_append_cx(decouple_cliff, qubitB, qubit0)
# Reduce pairs in Class A (except of qubit0) to 'II'
Alen = int((len(A_qubits) - 1) / 2)
if Alen > 0:
A_qubits.remove(qubit0)
for qubit in range(Alen):
circ.cx(A_qubits[2 * qubit + 1], A_qubits[2 * qubit])
circ.cx(A_qubits[2 * qubit], qubit0)
circ.cx(qubit0, A_qubits[2 * qubit + 1])
_append_cx(decouple_cliff, A_qubits[2 * qubit + 1], A_qubits[2 * qubit])
_append_cx(decouple_cliff, A_qubits[2 * qubit], qubit0)
_append_cx(decouple_cliff, qubit0, A_qubits[2 * qubit + 1])
return circ, decouple_cliff
|
gadial/qiskit-terra | qiskit/circuit/library/templates/rzx/rzx_xz.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
RZX based template for CX - RXGate - CX
.. parsed-literal::
┌───┐ ┌───┐┌─────────┐┌─────────┐┌─────────┐┌──────────┐»
q_0: ┤ X ├─────────┤ X ├┤ RZ(π/2) ├┤ RX(π/2) ├┤ RZ(π/2) ├┤0 ├»
└─┬─┘┌───────┐└─┬─┘└─────────┘└─────────┘└─────────┘│ RZX(-ϴ) │»
q_1: ──■──┤ RX(ϴ) ├──■───────────────────────────────────┤1 ├»
└───────┘ └──────────┘»
« ┌─────────┐┌─────────┐┌─────────┐
«q_0: ┤ RZ(π/2) ├┤ RX(π/2) ├┤ RZ(π/2) ├
« └─────────┘└─────────┘└─────────┘
«q_1: ─────────────────────────────────
«
"""
import numpy as np
from qiskit.circuit import Parameter, QuantumCircuit
def rzx_xz(theta: float = None):
"""Template for CX - RXGate - CX."""
if theta is None:
theta = Parameter('ϴ')
qc = QuantumCircuit(2)
qc.cx(1, 0)
qc.rx(theta, 1)
qc.cx(1, 0)
qc.rz(np.pi / 2, 0)
qc.rx(np.pi / 2, 0)
qc.rz(np.pi / 2, 0)
qc.rzx(-1*theta, 0, 1)
qc.rz(np.pi / 2, 0)
qc.rx(np.pi / 2, 0)
qc.rz(np.pi / 2, 0)
return qc
|
gadial/qiskit-terra | test/python/compiler/test_sequencer.py | # 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=missing-function-docstring
"""Tests basic functionality of the sequence function"""
import unittest
from qiskit import QuantumCircuit, pulse
from qiskit.compiler import sequence, transpile, schedule
from qiskit.pulse.transforms import pad
from qiskit.test.mock import FakeParis
from qiskit.test import QiskitTestCase
class TestSequence(QiskitTestCase):
"""Test sequence function."""
def setUp(self):
super().setUp()
self.backend = FakeParis()
def test_sequence_empty(self):
self.assertEqual(sequence([], self.backend), [])
def test_transpile_and_sequence_agree_with_schedule(self):
qc = QuantumCircuit(2, name="bell")
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
sc = transpile(qc, self.backend, scheduling_method='alap')
actual = sequence(sc, self.backend)
expected = schedule(transpile(qc, self.backend), self.backend)
self.assertEqual(actual, pad(expected))
def test_transpile_and_sequence_agree_with_schedule_for_circuit_with_delay(self):
qc = QuantumCircuit(1, 1, name="t2")
qc.h(0)
qc.delay(500, 0, unit='ns')
qc.h(0)
qc.measure(0, 0)
sc = transpile(qc, self.backend, scheduling_method='alap')
actual = sequence(sc, self.backend)
expected = schedule(transpile(qc, self.backend), self.backend)
self.assertEqual(actual.exclude(instruction_types=[pulse.Delay]),
expected.exclude(instruction_types=[pulse.Delay]))
@unittest.skip("not yet determined if delays on ancilla should be removed or not")
def test_transpile_and_sequence_agree_with_schedule_for_circuits_without_measures(self):
qc = QuantumCircuit(2, name="bell_without_measurement")
qc.h(0)
qc.cx(0, 1)
sc = transpile(qc, self.backend, scheduling_method='alap')
actual = sequence(sc, self.backend)
expected = schedule(transpile(qc, self.backend), self.backend)
self.assertEqual(actual, pad(expected))
|
gadial/qiskit-terra | test/python/compiler/test_disassembler.py | <filename>test/python/compiler/test_disassembler.py
# 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.
"""Assembler Test."""
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import pulse
from qiskit.assembler.disassemble import disassemble
from qiskit.assembler.run_config import RunConfig
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Instruction
from qiskit.compiler.assembler import assemble
from qiskit.test import QiskitTestCase
from qiskit.test.mock import FakeOpenPulse2Q
import qiskit.quantum_info as qi
class TestQuantumCircuitDisassembler(QiskitTestCase):
"""Tests for disassembling circuits to qobj."""
def test_disassemble_single_circuit(self):
"""Test disassembling a single circuit.
"""
qr = QuantumRegister(2, name='q')
cr = ClassicalRegister(2, name='c')
circ = QuantumCircuit(qr, cr, name='circ')
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.measure(qr, cr)
qobj = assemble(circ, shots=2000, memory=True)
circuits, run_config_out, headers = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(run_config_out.shots, 2000)
self.assertEqual(run_config_out.memory, True)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, headers)
def test_disassemble_multiple_circuits(self):
"""Test disassembling multiple circuits, all should have the same config.
"""
qr0 = QuantumRegister(2, name='q0')
qc0 = ClassicalRegister(2, name='c0')
circ0 = QuantumCircuit(qr0, qc0, name='circ0')
circ0.h(qr0[0])
circ0.cx(qr0[0], qr0[1])
circ0.measure(qr0, qc0)
qr1 = QuantumRegister(3, name='q1')
qc1 = ClassicalRegister(3, name='c1')
circ1 = QuantumCircuit(qr1, qc1, name='circ0')
circ1.h(qr1[0])
circ1.cx(qr1[0], qr1[1])
circ1.cx(qr1[0], qr1[2])
circ1.measure(qr1, qc1)
qobj = assemble([circ0, circ1], shots=100, memory=False, seed=6)
circuits, run_config_out, headers = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 3)
self.assertEqual(run_config_out.memory_slots, 3)
self.assertEqual(run_config_out.shots, 100)
self.assertEqual(run_config_out.memory, False)
self.assertEqual(run_config_out.seed, 6)
self.assertEqual(len(circuits), 2)
for circuit in circuits:
self.assertIn(circuit, [circ0, circ1])
self.assertEqual({}, headers)
def test_disassemble_no_run_config(self):
"""Test disassembling with no run_config, relying on default.
"""
qr = QuantumRegister(2, name='q')
qc = ClassicalRegister(2, name='c')
circ = QuantumCircuit(qr, qc, name='circ')
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.measure(qr, qc)
qobj = assemble(circ)
circuits, run_config_out, headers = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, headers)
def test_disassemble_initialize(self):
"""Test disassembling a circuit with an initialize.
"""
q = QuantumRegister(2, name='q')
circ = QuantumCircuit(q, name='circ')
circ.initialize([1/np.sqrt(2), 0, 0, 1/np.sqrt(2)], q[:])
qobj = assemble(circ)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 0)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, header)
def test_disassemble_isometry(self):
"""Test disassembling a circuit with an isometry.
"""
q = QuantumRegister(2, name='q')
circ = QuantumCircuit(q, name='circ')
circ.iso(qi.random_unitary(4).data, circ.qubits, [])
qobj = assemble(circ)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 0)
self.assertEqual(len(circuits), 1)
# params array
assert_allclose(circuits[0]._data[0][0].params[0], circ._data[0][0].params[0])
# all other data
self.assertEqual(circuits[0]._data[0][0].params[1:], circ._data[0][0].params[1:])
self.assertEqual(circuits[0]._data[0][1:], circ._data[0][1:])
self.assertEqual(circuits[0]._data[1:], circ._data[1:])
self.assertEqual({}, header)
def test_opaque_instruction(self):
"""Test the disassembler handles opaque instructions correctly."""
opaque_inst = Instruction(name='my_inst', num_qubits=4,
num_clbits=2, params=[0.5, 0.4])
q = QuantumRegister(6, name='q')
c = ClassicalRegister(4, name='c')
circ = QuantumCircuit(q, c, name='circ')
circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]])
qobj = assemble(circ)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 6)
self.assertEqual(run_config_out.memory_slots, 4)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, header)
def test_circuit_with_conditionals(self):
"""Verify disassemble sets conditionals correctly."""
qr = QuantumRegister(2)
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr1, cr2)
qc.measure(qr[0], cr1) # Measure not required for a later conditional
qc.measure(qr[1], cr2[1]) # Measure required for a later conditional
qc.h(qr[1]).c_if(cr2, 3)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 3)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_simple_conditional(self):
"""Verify disassemble handles a simple conditional on the only bits."""
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr, 1)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 1)
self.assertEqual(run_config_out.memory_slots, 1)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_multiple_conditionals_multiple_registers(self):
"""Verify disassemble handles multiple conditionals and registers."""
qr = QuantumRegister(3)
cr1 = ClassicalRegister(3)
cr2 = ClassicalRegister(5)
cr3 = ClassicalRegister(6)
cr4 = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr1, cr2, cr3, cr4)
qc.x(qr[1])
qc.h(qr)
qc.cx(qr[1], qr[0]).c_if(cr3, 14)
qc.ccx(qr[0], qr[2], qr[1]).c_if(cr4, 1)
qc.h(qr).c_if(cr1, 3)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 3)
self.assertEqual(run_config_out.memory_slots, 15)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
class TestPulseScheduleDisassembler(QiskitTestCase):
"""Tests for disassembling pulse schedules to qobj."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.backend_config = self.backend.configuration()
self.backend_config.parametric_pulses = [
'constant', 'gaussian', 'gaussian_square', 'drag'
]
def test_disassemble_single_schedule(self):
"""Test disassembling a single schedule.
"""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build(self.backend) as sched:
with pulse.align_right():
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.set_phase(1.0, d0)
pulse.shift_phase(3.11, d0)
pulse.set_frequency(1e9, d0)
pulse.shift_frequency(1e7, d0)
pulse.delay(20, d0)
pulse.delay(10, d1)
pulse.play(pulse.library.Constant(8, 0.1), d1)
pulse.measure_all()
qobj = assemble(sched, backend=self.backend, shots=2000)
scheds, run_config_out, _ = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(run_config_out.shots, 2000)
self.assertEqual(run_config_out.memory, False)
self.assertEqual(run_config_out.meas_level, 2)
self.assertEqual(run_config_out.meas_lo_freq, self.backend.defaults().meas_freq_est)
self.assertEqual(run_config_out.qubit_lo_freq, self.backend.defaults().qubit_freq_est)
self.assertEqual(run_config_out.rep_time, 99)
self.assertEqual(len(scheds), 1)
self.assertEqual(scheds[0], sched)
def test_disassemble_multiple_schedules(self):
"""Test disassembling multiple schedules, all should have the same config.
"""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build(self.backend) as sched0:
with pulse.align_right():
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.set_phase(1.0, d0)
pulse.shift_phase(3.11, d0)
pulse.set_frequency(1e9, d0)
pulse.shift_frequency(1e7, d0)
pulse.delay(20, d0)
pulse.delay(10, d1)
pulse.play(pulse.library.Constant(8, 0.1), d1)
pulse.measure_all()
with pulse.build(self.backend) as sched1:
with pulse.align_right():
pulse.play(pulse.library.Constant(8, 0.1), d0)
pulse.play(pulse.library.Waveform([0., 1.]), d1)
pulse.set_phase(1.1, d0)
pulse.shift_phase(3.5, d0)
pulse.set_frequency(2e9, d0)
pulse.shift_frequency(3e7, d1)
pulse.delay(20, d1)
pulse.delay(10, d0)
pulse.play(pulse.library.Constant(8, 0.4), d1)
pulse.measure_all()
qobj = assemble([sched0, sched1], backend=self.backend, shots=2000)
scheds, run_config_out, _ = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(run_config_out.shots, 2000)
self.assertEqual(run_config_out.memory, False)
self.assertEqual(len(scheds), 2)
self.assertEqual(scheds[0], sched0)
self.assertEqual(scheds[1], sched1)
def test_disassemble_parametric_pulses(self):
"""Test disassembling multiple schedules all should have the same config.
"""
d0 = pulse.DriveChannel(0)
with pulse.build(self.backend) as sched:
with pulse.align_right():
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.play(pulse.library.Gaussian(10, 1.0, 2.0), d0)
pulse.play(pulse.library.GaussianSquare(10, 1.0, 2.0, 3), d0)
pulse.play(pulse.library.Drag(10, 1.0, 2.0, 0.1), d0)
qobj = assemble(sched, backend=self.backend, shots=2000)
scheds, _, _ = disassemble(qobj)
self.assertEqual(scheds[0], sched)
def test_disassemble_schedule_los(self):
"""Test disassembling schedule los."""
d0 = pulse.DriveChannel(0)
m0 = pulse.MeasureChannel(0)
d1 = pulse.DriveChannel(1)
m1 = pulse.MeasureChannel(1)
sched0 = pulse.Schedule()
sched1 = pulse.Schedule()
schedule_los = [
{d0: 4.5e9, d1: 5e9, m0: 6e9, m1: 7e9},
{d0: 5e9, d1: 4.5e9, m0: 7e9, m1: 6e9}
]
qobj = assemble([sched0, sched1], backend=self.backend, schedule_los=schedule_los)
_, run_config_out, _ = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.schedule_los, schedule_los)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
gadial/qiskit-terra | qiskit/opflow/expectations/aer_pauli_expectation.py | <reponame>gadial/qiskit-terra
# 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.
""" AerPauliExpectation Class """
import logging
from typing import Union
from qiskit.exceptions import MissingOptionalLibraryError
from qiskit.opflow.expectations.expectation_base import ExpectationBase
from qiskit.opflow.list_ops.composed_op import ComposedOp
from qiskit.opflow.list_ops.list_op import ListOp
from qiskit.opflow.list_ops.summed_op import SummedOp
from qiskit.opflow.operator_base import OperatorBase
from qiskit.opflow.primitive_ops.pauli_op import PauliOp
from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp
from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn
from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn
logger = logging.getLogger(__name__)
class AerPauliExpectation(ExpectationBase):
r""" An Expectation converter for using Aer's operator snapshot to
take expectations of quantum state circuits over Pauli observables.
"""
def convert(self, operator: OperatorBase) -> OperatorBase:
""" Accept an Operator and return a new Operator with the Pauli measurements replaced by
AerSnapshot-based expectation circuits.
Args:
operator: The operator to convert.
Returns:
The converted operator.
"""
if isinstance(operator, OperatorStateFn) and operator.is_measurement:
return self._replace_pauli_sums(operator.primitive) * operator.coeff
elif isinstance(operator, ListOp):
return operator.traverse(self.convert)
else:
return operator
# pylint: disable=inconsistent-return-statements
@classmethod
def _replace_pauli_sums(cls, operator):
try:
from qiskit.providers.aer.extensions import SnapshotExpectationValue
except ImportError as ex:
raise MissingOptionalLibraryError(
libname='qiskit-aer',
name='AerPauliExpectation',
pip_install='pip install qiskit-aer') from ex
# The 'expval_measurement' label on the snapshot instruction is special - the
# CircuitSampler will look for it to know that the circuit is a Expectation
# measurement, and not simply a
# circuit to replace with a DictStateFn
if isinstance(operator, PauliSumOp):
paulis = [(meas[1], meas[0]) for meas in operator.primitive.to_list()]
snapshot_instruction = SnapshotExpectationValue('expval_measurement', paulis)
return CircuitStateFn(snapshot_instruction, coeff=operator.coeff, is_measurement=True)
# Change to Pauli representation if necessary
if not {'Pauli'} == operator.primitive_strings():
logger.warning('Measured Observable is not composed of only Paulis, converting to '
'Pauli representation, which can be expensive.')
# Setting massive=False because this conversion is implicit. User can perform this
# action on the Observable with massive=True explicitly if they so choose.
operator = operator.to_pauli_op(massive=False)
if isinstance(operator, SummedOp):
paulis = [[meas.coeff, meas.primitive] for meas in operator.oplist]
snapshot_instruction = SnapshotExpectationValue('expval_measurement', paulis)
snapshot_op = CircuitStateFn(snapshot_instruction, is_measurement=True)
return snapshot_op
if isinstance(operator, PauliOp):
paulis = [[operator.coeff, operator.primitive]]
snapshot_instruction = SnapshotExpectationValue('expval_measurement', paulis)
snapshot_op = CircuitStateFn(snapshot_instruction, is_measurement=True)
return snapshot_op
if isinstance(operator, ListOp):
return operator.traverse(cls._replace_pauli_sums)
def compute_variance(self, exp_op: OperatorBase) -> Union[list, float]:
r"""
Compute the variance of the expectation estimator. Because Aer takes this expectation
with matrix multiplication, the estimation is exact and the variance is always 0,
but we need to return those values in a way which matches the Operator's structure.
Args:
exp_op: The full expectation value Operator after sampling.
Returns:
The variances or lists thereof (if exp_op contains ListOps) of the expectation value
estimation, equal to 0.
"""
# Need to do this to mimic Op structure
def sum_variance(operator):
if isinstance(operator, ComposedOp):
return 0.0
elif isinstance(operator, ListOp):
return operator._combo_fn([sum_variance(op) for op in operator.oplist])
return sum_variance(exp_op)
|
gadial/qiskit-terra | test/python/transpiler/test_pass_call.py | <filename>test/python/transpiler/test_pass_call.py
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test calling passes (passmanager-less)"""
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.transpiler import PropertySet
from ._dummy_passes import PassD_TP_NR_NP, PassE_AP_NR_NP, PassN_AP_NR_NP
class TestPassCall(QiskitTestCase):
"""Test calling passes (passmanager-less)."""
def assertMessageLog(self, context, messages):
"""Checks the log messages"""
self.assertEqual([record.message for record in context.records], messages)
def test_transformation_pass(self):
"""Call a transformation pass without a scheduler"""
qr = QuantumRegister(1, 'qr')
circuit = QuantumCircuit(qr, name='MyCircuit')
pass_d = PassD_TP_NR_NP(argument1=[1, 2])
with self.assertLogs('LocalLogger', level='INFO') as cm:
result = pass_d(circuit)
self.assertMessageLog(cm, ['run transformation pass PassD_TP_NR_NP', 'argument [1, 2]'])
self.assertEqual(circuit, result)
def test_analysis_pass_dict(self):
"""Call an analysis pass without a scheduler (property_set dict)"""
qr = QuantumRegister(1, 'qr')
circuit = QuantumCircuit(qr, name='MyCircuit')
property_set = {'another_property': 'another_value'}
pass_e = PassE_AP_NR_NP('value')
with self.assertLogs('LocalLogger', level='INFO') as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(cm, ['run analysis pass PassE_AP_NR_NP', 'set property as value'])
self.assertEqual(property_set, {'another_property': 'another_value', 'property': 'value'})
self.assertIsInstance(property_set, dict)
self.assertEqual(circuit, result)
def test_analysis_pass_property_set(self):
"""Call an analysis pass without a scheduler (PropertySet dict)"""
qr = QuantumRegister(1, 'qr')
circuit = QuantumCircuit(qr, name='MyCircuit')
property_set = PropertySet({'another_property': 'another_value'})
pass_e = PassE_AP_NR_NP('value')
with self.assertLogs('LocalLogger', level='INFO') as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(cm, ['run analysis pass PassE_AP_NR_NP', 'set property as value'])
self.assertEqual(property_set,
PropertySet({'another_property': 'another_value', 'property': 'value'}))
self.assertIsInstance(property_set, PropertySet)
self.assertEqual(circuit, result)
def test_analysis_pass_remove_property(self):
"""Call an analysis pass that removes a property without a scheduler"""
qr = QuantumRegister(1, 'qr')
circuit = QuantumCircuit(qr, name='MyCircuit')
property_set = {'to remove': 'value to remove', 'to none': 'value to none'}
pass_e = PassN_AP_NR_NP('to remove', 'to none')
with self.assertLogs('LocalLogger', level='INFO') as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(cm, ['run analysis pass PassN_AP_NR_NP',
'property to remove deleted',
'property to none noned'])
self.assertEqual(property_set, PropertySet({'to none': None}))
self.assertIsInstance(property_set, dict)
self.assertEqual(circuit, result)
|
gadial/qiskit-terra | qiskit/algorithms/linear_solvers/observables/linear_system_observable.py | <filename>qiskit/algorithms/linear_solvers/observables/linear_system_observable.py<gh_stars>1-10
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""An abstract class for linear systems solvers in Qiskit's aqua module."""
from abc import ABC, abstractmethod
from typing import Union, List
import numpy as np
from qiskit import QuantumCircuit
from qiskit.opflow import TensoredOp
class LinearSystemObservable(ABC):
"""An abstract class for linear system observables in Qiskit."""
@abstractmethod
def observable(self, num_qubits: int) -> Union[TensoredOp, List[TensoredOp]]:
"""The observable operator.
Args:
num_qubits: The number of qubits on which the observable will be applied.
Returns:
The observable as a sum of Pauli strings.
"""
raise NotImplementedError
@abstractmethod
def observable_circuit(self, num_qubits: int) -> Union[QuantumCircuit, List[QuantumCircuit]]:
"""The circuit implementing the observable.
Args:
num_qubits: The number of qubits on which the observable will be applied.
Returns:
The observable as a QuantumCircuit.
"""
raise NotImplementedError
@abstractmethod
def post_processing(self, solution: Union[float, List[float]],
num_qubits: int,
scaling: float = 1) -> float:
"""Evaluates the given observable on the solution to the linear system.
Args:
solution: The probability calculated from the circuit and the observable.
num_qubits: The number of qubits where the observable was applied.
scaling: Scaling of the solution.
Returns:
The value of the observable.
"""
raise NotImplementedError
@abstractmethod
def evaluate_classically(self, solution: Union[np.array, QuantumCircuit]) -> float:
"""Calculates the analytical value of the given observable from the solution vector to the
linear system.
Args:
solution: The solution to the system as a numpy array or the circuit that prepares it.
Returns:
The value of the observable.
"""
raise NotImplementedError
|
gadial/qiskit-terra | qiskit/quantum_info/operators/symplectic/pauli_utils.py | <gh_stars>1-10
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
PauliTable utility functions.
"""
import numpy as np
from .pauli_table import PauliTable
def pauli_basis(num_qubits, weight=False):
"""Return the ordered PauliTable for the n-qubit Pauli basis.
Args:
num_qubits (int): number of qubits
weight (bool): if True optionally return the basis sorted by Pauli weight
rather than lexicographic order (Default: False)
Returns:
PauliTable: the PauliTable for the basis
"""
pauli_1q = PauliTable(np.array([[False, False],
[True, False],
[True, True],
[False, True]],
dtype=bool))
if num_qubits == 1:
return pauli_1q
pauli = pauli_1q
for _ in range(num_qubits - 1):
pauli = pauli_1q.tensor(pauli)
if weight:
return pauli.sort(weight=True)
return pauli
|
gadial/qiskit-terra | test/python/classical_function_compiler/test_boolean_expression.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test boolean expression."""
import unittest
from os import path
from ddt import ddt, unpack, data
from qiskit.test.base import QiskitTestCase
from qiskit import execute, BasicAer
from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression
@ddt
class TestBooleanExpression(QiskitTestCase):
"""Test boolean expression."""
@data(('x | x', '1', True),
('x & x', '0', False),
('(x0 & x1 | ~x2) ^ x4', '0110', False),
('xx & xxx | ( ~z ^ zz)', '0111', True))
@unpack
def test_evaluate(self, expression, input_bitstring, expected):
""" Test simulate"""
expression = BooleanExpression(expression)
result = expression.simulate(input_bitstring)
self.assertEqual(result, expected)
@data(('x', False),
('not x', True),
('(x0 & x1 | ~x2) ^ x4', True),
('xx & xxx | ( ~z ^ zz)', True))
@unpack
def test_synth(self, expression, expected):
""" Test synth"""
expression = BooleanExpression(expression)
expr_circ = expression.synth()
new_creg = expr_circ._create_creg(1, 'c')
expr_circ.add_register(new_creg)
expr_circ.measure(expression.num_qubits - 1, new_creg)
[result] = execute(expr_circ, backend=BasicAer.get_backend('qasm_simulator'),
shots=1, seed_simulator=14).result().get_counts().keys()
self.assertEqual(bool(int(result)), expected)
class TestBooleanExpressionDIMACS(QiskitTestCase):
""" Loading from a cnf file """
def normalize_filenames(self, filename):
"""Given a filename, returns the directory in terms of __file__."""
dirname = path.dirname(__file__)
return path.join(dirname, filename)
def test_simple(self):
"""Loads simple_v3_c2.cnf and simulate """
filename = self.normalize_filenames('dimacs/simple_v3_c2.cnf')
simple = BooleanExpression.from_dimacs_file(filename)
self.assertEqual(simple.name, 'simple_v3_c2.cnf')
self.assertEqual(simple.num_qubits, 4)
self.assertTrue(simple.simulate('101'))
def test_quinn(self):
"""Loads quinn.cnf and simulate """
filename = self.normalize_filenames('dimacs/quinn.cnf')
simple = BooleanExpression.from_dimacs_file(filename)
self.assertEqual(simple.name, 'quinn.cnf')
self.assertEqual(simple.num_qubits, 16)
self.assertFalse(simple.simulate('1010101010101010'))
if __name__ == '__main__':
unittest.main()
|
gadial/qiskit-terra | qiskit/opflow/gradients/__init__.py | <gh_stars>1-10
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
r"""
Gradients (:mod:`qiskit.opflow.gradients`)
==================================================
Given an operator that represents either a quantum state resp. an expectation value, the gradient
framework enables the evaluation of gradients, natural gradients, Hessians, as well as the Quantum
Fisher Information.
Suppose a parameterized quantum state `|ψ(θ)〉 = V(θ)|ψ〉` with input state `|ψ〉` and parameterized
Ansatz `V(θ)`, and an Operator `O(ω)`.
**Gradients**
We want to compute one of:
* :math:`d⟨ψ(θ)|O(ω)|ψ(θ)〉/ dω`
* :math:`d⟨ψ(θ)|O(ω)|ψ(θ)〉/ dθ`
* :math:`d⟨ψ(θ)|i〉⟨i|ψ(θ)〉/ dθ`
The last case corresponds to the gradient w.r.t. the sampling probabilities of `|ψ(θ)`.
These gradients can be computed with different methods, i.e. a parameter shift, a linear combination
of unitaries and a finite difference method.
**Examples**
.. code-block::
x = Parameter('x')
ham = x * X
a = Parameter('a')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.p(params[0], q[0])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.)
value_dict = {x: 0.1, a: np.pi / 4}
ham_grad = Gradient(grad_method='param_shift').convert(operator=op, params=[x])
ham_grad.assign_parameters(value_dict).eval()
state_grad = Gradient(grad_method='lin_comb').convert(operator=op, params=[a])
state_grad.assign_parameters(value_dict).eval()
prob_grad = Gradient(grad_method='fin_diff').convert(
operator=CircuitStateFn(primitive=qc, coeff=1.), params=[a]
)
prob_grad.assign_parameters(value_dict).eval()
**Hessians**
We want to compute one of:
* :math:`d^2⟨ψ(θ)|O(ω)|ψ(θ)〉/ dω^2`
* :math:`d^2⟨ψ(θ)|O(ω)|ψ(θ)〉/ dθ^2`
* :math:`d^2⟨ψ(θ)|O(ω)|ψ(θ)〉/ dθ dω`
* :math:`d^2⟨ψ(θ)|i〉⟨i|ψ(θ)〉/ dθ^2`
The last case corresponds to the Hessian w.r.t. the sampling probabilities of `|ψ(θ)〉`.
Just as the first order gradients, the Hessians can be evaluated with different methods, i.e. a
parameter shift, a linear combination of unitaries and a finite difference method.
Given a tuple of parameters ``Hessian().convert(op, param_tuple)`` returns the value for the second
order derivative.
If a list of parameters is given ``Hessian().convert(op, param_list)`` returns the full Hessian for
all the given parameters according to the given parameter order.
**QFI**
The Quantum Fisher Information `QFI` is a metric tensor which is representative for the
representation capacity of a parameterized quantum state `|ψ(θ)〉 = V(θ)|ψ〉` generated by an
input state `|ψ〉` and a parameterized Ansatz `V(θ)`.
The entries of the `QFI` for a pure state read
:math:`\mathrm{QFI}_{kl} = 4 \mathrm{Re}[〈∂kψ|∂lψ〉−〈∂kψ|ψ〉〈ψ|∂lψ〉]`.
Just as for the previous derivative types, the QFI can be computed using different methods: a full
representation based on a linear combination of unitaries implementation, a block-diagonal and a
diagonal representation based on an overlap method.
**Examples**
.. code-block::
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.p(params[0], q[0])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.)
value_dict = {x: 0.1, a: np.pi / 4}
qfi = QFI('lin_comb_full').convert(
operator=CircuitStateFn(primitive=qc, coeff=1.), params=[a]
)
qfi.assign_parameters(value_dict).eval()
**NaturalGradients**
The natural gradient is a special gradient method which re-scales a gradient w.r.t. a state
parameter with the inverse of the corresponding Quantum Fisher Information (QFI)
:math:`\mathrm{QFI}^{-1} d⟨ψ(θ)|O(ω)|ψ(θ)〉/ dθ`.
Hereby, we can choose a gradient as well as a QFI method and a regularization method which is used
together with a least square solver instead of exact inversion of the QFI:
**Examples**
.. code-block::
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.)
nat_grad = NaturalGradient(grad_method='lin_comb,
qfi_method='lin_comb_full',
regularization='ridge').convert(operator=op, params=params)
The derivative classes come with a `gradient_wrapper()` function which returns the corresponding
callable and are thus compatible with the optimizers.
.. currentmodule:: qiskit.opflow.gradients
Base Classes
============
.. autosummary::
:toctree: ../stubs/
:nosignatures:
DerivativeBase
GradientBase
HessianBase
QFIBase
Converters
==========
.. autosummary::
:toctree: ../stubs/
:nosignatures:
CircuitGradient
CircuitQFI
Derivatives
===========
.. autosummary::
:toctree: ../stubs/
:nosignatures:
Gradient
Hessian
NaturalGradient
QFI
"""
from .circuit_gradients.circuit_gradient import CircuitGradient
from .circuit_qfis.circuit_qfi import CircuitQFI
from .derivative_base import DerivativeBase
from .gradient_base import GradientBase
from .gradient import Gradient
from .natural_gradient import NaturalGradient
from .hessian_base import HessianBase
from .hessian import Hessian
from .qfi_base import QFIBase
from .qfi import QFI
__all__ = ['DerivativeBase',
'CircuitGradient',
'GradientBase',
'Gradient',
'NaturalGradient',
'HessianBase',
'Hessian',
'QFIBase',
'QFI',
'CircuitQFI']
|
gadial/qiskit-terra | test/python/providers/test_faulty_backend.py | # 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.
"""Testing a Faulty Ourense Backend."""
from qiskit.test import QiskitTestCase
from .faulty_backends import FakeOurenseFaultyCX01, FakeOurenseFaultyQ1, FakeOurenseFaultyCX13
class FaultyQubitBackendTestCase(QiskitTestCase):
"""Test operational-related methods of backend.properties() with FakeOurenseFaultyQ1,
which is like FakeOurense but with a faulty 1Q"""
backend = FakeOurenseFaultyQ1()
def test_operational_false(self):
"""Test operation status of the qubit. Q1 is non-operational """
self.assertFalse(self.backend.properties().is_qubit_operational(1))
def test_faulty_qubits(self):
"""Test faulty_qubits method. """
self.assertEqual(self.backend.properties().faulty_qubits(), [1])
class FaultyGate13BackendTestCase(QiskitTestCase):
"""Test operational-related methods of backend.properties() with FakeOurenseFaultyCX13,
which is like FakeOurense but with a faulty CX(Q1, Q3) and symmetric."""
backend = FakeOurenseFaultyCX13()
def test_operational_gate(self):
"""Test is_gate_operational method. """
self.assertFalse(self.backend.properties().is_gate_operational('cx', [1, 3]))
self.assertFalse(self.backend.properties().is_gate_operational('cx', [3, 1]))
def test_faulty_gates(self):
"""Test faulty_gates method. """
gates = self.backend.properties().faulty_gates()
self.assertEqual(len(gates), 2)
self.assertEqual([gate.gate for gate in gates], ['cx', 'cx'])
self.assertEqual(sorted([gate.qubits for gate in gates]), [[1, 3], [3, 1]])
class FaultyGate01BackendTestCase(QiskitTestCase):
"""Test operational-related methods of backend.properties() with FakeOurenseFaultyCX13,
which is like FakeOurense but with a faulty CX(Q1, Q3) and symmetric."""
backend = FakeOurenseFaultyCX01()
def test_operational_gate(self):
"""Test is_gate_operational method. """
self.assertFalse(self.backend.properties().is_gate_operational('cx', [0, 1]))
self.assertFalse(self.backend.properties().is_gate_operational('cx', [1, 0]))
def test_faulty_gates(self):
"""Test faulty_gates method. """
gates = self.backend.properties().faulty_gates()
self.assertEqual(len(gates), 2)
self.assertEqual([gate.gate for gate in gates], ['cx', 'cx'])
self.assertEqual(sorted([gate.qubits for gate in gates]), [[0, 1], [1, 0]])
|
gadial/qiskit-terra | qiskit/tools/jupyter/copyright.py | # 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.
# pylint: disable=unused-argument
"""A module for monitoring backends."""
import datetime
from IPython.display import HTML, display
from IPython.core.magic import (line_magic,
Magics, magics_class)
@magics_class
class Copyright(Magics):
"""A class of status magic functions.
"""
@line_magic
def qiskit_copyright(self, line='', cell=None):
"""A Jupyter magic function return qiskit copyright
"""
now = datetime.datetime.now()
html = "<div style='width: 100%; background-color:#d5d9e0;"
html += "padding-left: 10px; padding-bottom: 10px; padding-right: 10px; padding-top: 5px'>"
html += "<h3>This code is a part of Qiskit</h3>"
html += "<p>© Copyright IBM 2017, %s.</p>" % now.year
html += "<p>This code is licensed under the Apache License, Version 2.0. You may<br>"
html += "obtain a copy of this license in the LICENSE.txt file in the root directory<br> "
html += "of this source tree or at http://www.apache.org/licenses/LICENSE-2.0."
html += "<p>Any modifications or derivative works of this code must retain this<br>"
html += "copyright notice, and modified files need to carry a notice indicating<br>"
html += "that they have been altered from the originals.</p>"
html += "</div>"
return display(HTML(html))
|
gadial/qiskit-terra | qiskit/pulse/instructions/snapshot.py | # 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.
"""A simulator instruction to capture output within a simulation. The types of snapshot
instructions available are determined by the simulator being used.
"""
from typing import Optional, Tuple
from qiskit.pulse.channels import SnapshotChannel
from qiskit.pulse.exceptions import PulseError
from qiskit.pulse.instructions.instruction import Instruction
class Snapshot(Instruction):
"""An instruction targeted for simulators, to capture a moment in the simulation."""
def __init__(self, label: str, snapshot_type: str = 'statevector', name: Optional[str] = None):
"""Create new snapshot.
Args:
label: Snapshot label which is used to identify the snapshot in the output.
snapshot_type: Type of snapshot, e.g., “state” (take a snapshot of the quantum state).
The types of snapshots offered are defined by the simulator used.
name: Snapshot name which defaults to ``label``. This parameter is only for display
purposes and is not taken into account during comparison.
Raises:
PulseError: If snapshot label is invalid.
"""
if not isinstance(label, str):
raise PulseError('Snapshot label must be a string.')
self._channel = SnapshotChannel()
if name is None:
name = label
super().__init__(operands=(label, snapshot_type), name=name)
@property
def label(self) -> str:
"""Label of snapshot."""
return self.operands[0]
@property
def type(self) -> str:
"""Type of snapshot."""
return self.operands[1]
@property
def channel(self) -> SnapshotChannel:
"""Return the :py:class:`~qiskit.pulse.channels.Channel` that this instruction is
scheduled on; trivially, a ``SnapshotChannel``.
"""
return self._channel
@property
def channels(self) -> Tuple[SnapshotChannel]:
"""Returns the channels that this schedule uses."""
return (self.channel, )
@property
def duration(self) -> int:
"""Duration of this instruction."""
return 0
def is_parameterized(self) -> bool:
"""Return True iff the instruction is parameterized."""
return False
|
gadial/qiskit-terra | test/python/transpiler/test_enlarge_with_ancilla_pass.py | <filename>test/python/transpiler/test_enlarge_with_ancilla_pass.py<gh_stars>1-10
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the EnlargeWithAncilla pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import Layout
from qiskit.transpiler.passes import EnlargeWithAncilla
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestEnlargeWithAncilla(QiskitTestCase):
"""Tests the EnlargeWithAncilla pass."""
def setUp(self):
super().setUp()
self.qr3 = QuantumRegister(3, 'qr')
circuit = QuantumCircuit(self.qr3)
circuit.h(self.qr3)
self.dag = circuit_to_dag(circuit)
def test_no_extension(self):
"""There are no virtual qubits to extend."""
layout = Layout({self.qr3[0]: 0, self.qr3[1]: 1, self.qr3[2]: 2})
pass_ = EnlargeWithAncilla()
pass_.property_set['layout'] = layout
after = pass_.run(self.dag)
qregs = list(after.qregs.values())
self.assertEqual(1, len(qregs))
self.assertEqual(self.qr3, qregs[0])
def test_with_extension(self):
"""There are 2 virtual qubit to extend."""
ancilla = QuantumRegister(2, 'ancilla')
layout = Layout({0: self.qr3[0], 1: ancilla[0],
2: self.qr3[1], 3: ancilla[1],
4: self.qr3[2]})
layout.add_register(ancilla)
pass_ = EnlargeWithAncilla()
pass_.property_set['layout'] = layout
after = pass_.run(self.dag)
qregs = list(after.qregs.values())
self.assertEqual(2, len(qregs))
self.assertEqual(self.qr3, qregs[0])
self.assertEqual(ancilla, qregs[1])
if __name__ == '__main__':
unittest.main()
|
gadial/qiskit-terra | qiskit/test/mock/fake_provider.py | <reponame>gadial/qiskit-terra<filename>qiskit/test/mock/fake_provider.py
# 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=wildcard-import,unused-argument
"""
Fake provider class that provides access to fake backends.
"""
from qiskit.providers.baseprovider import BaseProvider
from qiskit.providers.exceptions import QiskitBackendNotFoundError
from .backends import *
from .fake_qasm_simulator import FakeQasmSimulator
from .fake_openpulse_2q import FakeOpenPulse2Q
from .fake_openpulse_3q import FakeOpenPulse3Q
class FakeProvider(BaseProvider):
"""Dummy provider just for testing purposes.
Only filtering backends by name is implemented.
"""
def get_backend(self, name=None, **kwargs):
backend = self._backends[0]
if name:
filtered_backends = [backend for backend in self._backends
if backend.name() == name]
if not filtered_backends:
raise QiskitBackendNotFoundError()
backend = filtered_backends[0]
return backend
def backends(self, name=None, **kwargs):
return self._backends
def __init__(self):
self._backends = [FakeQasmSimulator(),
FakeOpenPulse2Q(),
FakeOpenPulse3Q(),
FakeArmonk(),
FakeYorktown(),
FakeTenerife(),
FakeOurense(),
FakeVigo(),
FakeValencia(),
FakeEssex(),
FakeLondon(),
FakeBurlington(),
FakeMelbourne(),
FakeRueschlikon(),
FakeTokyo(),
FakePoughkeepsie(),
FakeAlmaden(),
FakeSingapore(),
FakeJohannesburg(),
FakeBoeblingen(),
FakeCambridge(),
FakeCambridgeAlternativeBasis(),
FakeParis(),
FakeRochester(),
FakeRome(),
FakeAthens(),
FakeBogota(),
FakeMontreal(),
FakeToronto(),
FakeManhattan(),
FakeSantiago(),
FakeCasablanca(),
FakeSydney(),
FakeMumbai(),
FakeLima(),
FakeBelem(),
FakeQuito()]
super().__init__()
class FakeProviderFactory:
"""Fake provider factory class."""
def __init__(self):
self.fake_provider = FakeProvider()
def load_account(self):
"""Fake load_account method to mirror the IBMQ provider."""
pass
def enable_account(self, *args, **kwargs):
"""Fake enable_account method to mirror the IBMQ provider factory."""
pass
def disable_account(self):
"""Fake disable_account method to mirror the IBMQ provider factory."""
pass
def save_account(self, *args, **kwargs):
"""Fake save_account method to mirror the IBMQ provider factory."""
pass
@staticmethod
def delete_account():
"""Fake delete_account method to mirror the IBMQ provider factory."""
pass
def update_account(self, force=False):
"""Fake update_account method to mirror the IBMQ provider factory."""
pass
def providers(self):
"""Fake providers method to mirror the IBMQ provider."""
return [self.fake_provider]
def get_provider(self, hub=None, group=None, project=None):
"""Fake get_provider method to mirror the IBMQ provider."""
return self.fake_provider
|
gadial/qiskit-terra | qiskit/circuit/library/arithmetic/integer_comparator.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Integer Comparator."""
from typing import List, Optional
import warnings
import numpy as np
from qiskit.circuit import QuantumRegister, AncillaRegister
from qiskit.circuit.exceptions import CircuitError
from ..boolean_logic import OR
from ..blueprintcircuit import BlueprintCircuit
class IntegerComparator(BlueprintCircuit):
r"""Integer Comparator.
Operator compares basis states :math:`|i\rangle_n` against a classically given integer
:math:`L` of fixed value and flips a target qubit if :math:`i \geq L`
(or :math:`<` depending on the parameter ``geq``):
.. math::
|i\rangle_n |0\rangle \mapsto |i\rangle_n |i \geq L\rangle
This operation is based on two's complement implementation of binary subtraction but only
uses carry bits and no actual result bits. If the most significant carry bit
(the results bit) is 1, the :math:`\geq` condition is ``True`` otherwise it is ``False``.
"""
def __init__(self, num_state_qubits: Optional[int] = None,
value: Optional[int] = None,
geq: bool = True,
name: str = 'cmp') -> None:
"""Create a new fixed value comparator circuit.
Args:
num_state_qubits: Number of state qubits. If this is set it will determine the number
of qubits required for the circuit.
value: The fixed value to compare with.
geq: If True, evaluate a ``>=`` condition, else ``<``.
name: Name of the circuit.
"""
super().__init__(name=name)
self._data = None
self._value = None
self._geq = None
self._num_state_qubits = None
self.value = value
self.geq = geq
self.num_state_qubits = num_state_qubits
@property
def value(self) -> int:
"""The value to compare the qubit register to.
Returns:
The value against which the value of the qubit register is compared.
"""
return self._value
@value.setter
def value(self, value: int) -> None:
if value != self._value:
self._invalidate()
self._value = value
@property
def geq(self) -> bool:
"""Return whether the comparator compares greater or less equal.
Returns:
True, if the comparator compares ``>=``, False if ``<``.
"""
return self._geq
@geq.setter
def geq(self, geq: bool) -> None:
"""Set whether the comparator compares greater or less equal.
Args:
geq: If True, the comparator compares ``>=``, if False ``<``.
"""
if geq != self._geq:
self._invalidate()
self._geq = geq
@property
def num_ancilla_qubits(self):
"""Deprecated. Use num_ancillas instead."""
warnings.warn('The IntegerComparator.num_ancilla_qubits property is deprecated '
'as of 0.16.0. It will be removed no earlier than 3 months after the release '
'date. You should use the num_ancillas property instead.')
return self.num_ancillas
@property
def num_state_qubits(self) -> int:
"""The number of qubits encoding the state for the comparison.
Returns:
The number of state qubits.
"""
return self._num_state_qubits
@num_state_qubits.setter
def num_state_qubits(self, num_state_qubits: Optional[int]) -> None:
"""Set the number of state qubits.
Note that this will change the quantum registers.
Args:
num_state_qubits: The new number of state qubits.
"""
if self._num_state_qubits is None or num_state_qubits != self._num_state_qubits:
self._invalidate() # reset data
self._num_state_qubits = num_state_qubits
if num_state_qubits is not None:
# set the new qubit registers
qr_state = QuantumRegister(num_state_qubits, name='state')
q_compare = QuantumRegister(1, name='compare')
self.qregs = [qr_state, q_compare]
# add ancillas is required
num_ancillas = num_state_qubits - 1
if num_ancillas > 0:
qr_ancilla = AncillaRegister(num_ancillas)
self.add_register(qr_ancilla)
def _get_twos_complement(self) -> List[int]:
"""Returns the 2's complement of ``self.value`` as array.
Returns:
The 2's complement of ``self.value``.
"""
twos_complement = pow(2, self.num_state_qubits) - int(np.ceil(self.value))
twos_complement = '{:b}'.format(twos_complement).rjust(self.num_state_qubits, '0')
twos_complement = \
[1 if twos_complement[i] == '1' else 0 for i in reversed(range(len(twos_complement)))]
return twos_complement
def _check_configuration(self, raise_on_failure: bool = True) -> bool:
"""Check if the current configuration is valid."""
valid = True
if self._num_state_qubits is None:
valid = False
if raise_on_failure:
raise AttributeError('Number of state qubits is not set.')
if self._value is None:
valid = False
if raise_on_failure:
raise AttributeError('No comparison value set.')
required_num_qubits = 2 * self.num_state_qubits
if self.num_qubits != required_num_qubits:
valid = False
if raise_on_failure:
raise CircuitError('Number of qubits does not match required number of qubits.')
return valid
def _build(self) -> None:
"""Build the comparator circuit."""
super()._build()
qr_state = self.qubits[:self.num_state_qubits]
q_compare = self.qubits[self.num_state_qubits]
qr_ancilla = self.qubits[self.num_state_qubits + 1:]
if self.value <= 0: # condition always satisfied for non-positive values
if self._geq: # otherwise the condition is never satisfied
self.x(q_compare)
# condition never satisfied for values larger than or equal to 2^n
elif self.value < pow(2, self.num_state_qubits):
if self.num_state_qubits > 1:
twos = self._get_twos_complement()
for i in range(self.num_state_qubits):
if i == 0:
if twos[i] == 1:
self.cx(qr_state[i], qr_ancilla[i])
elif i < self.num_state_qubits - 1:
if twos[i] == 1:
self.compose(OR(2), [qr_state[i], qr_ancilla[i - 1], qr_ancilla[i]],
inplace=True)
else:
self.ccx(qr_state[i], qr_ancilla[i - 1], qr_ancilla[i])
else:
if twos[i] == 1:
# OR needs the result argument as qubit not register, thus
# access the index [0]
self.compose(OR(2), [qr_state[i], qr_ancilla[i - 1], q_compare],
inplace=True)
else:
self.ccx(qr_state[i], qr_ancilla[i - 1], q_compare)
# flip result bit if geq flag is false
if not self._geq:
self.x(q_compare)
# uncompute ancillas state
for i in reversed(range(self.num_state_qubits-1)):
if i == 0:
if twos[i] == 1:
self.cx(qr_state[i], qr_ancilla[i])
else:
if twos[i] == 1:
self.compose(OR(2), [qr_state[i], qr_ancilla[i - 1], qr_ancilla[i]],
inplace=True)
else:
self.ccx(qr_state[i], qr_ancilla[i - 1], qr_ancilla[i])
else:
# num_state_qubits == 1 and value == 1:
self.cx(qr_state[0], q_compare)
# flip result bit if geq flag is false
if not self._geq:
self.x(q_compare)
else:
if not self._geq: # otherwise the condition is never satisfied
self.x(q_compare)
|
gadial/qiskit-terra | test/python/opflow/test_two_qubit_reduction.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" Test TwoQubitReduction """
from test.python.opflow import QiskitOpflowTestCase
from qiskit.opflow import PauliSumOp, TwoQubitReduction, TaperedPauliSumOp, Z2Symmetries
from qiskit.quantum_info import Pauli, SparsePauliOp
class TestTwoQubitReduction(QiskitOpflowTestCase):
"""TwoQubitReduction tests."""
def test_convert(self):
""" convert test """
qubit_op = PauliSumOp.from_list([
("IIII", -0.8105479805373266),
("IIIZ", 0.17218393261915552),
("IIZZ", -0.22575349222402472),
("IZZI", 0.1721839326191556),
("ZZII", -0.22575349222402466),
("IIZI", 0.1209126326177663),
("IZZZ", 0.16892753870087912),
("IXZX", -0.045232799946057854),
("ZXIX", 0.045232799946057854),
("IXIX", 0.045232799946057854),
("ZXZX", -0.045232799946057854),
("ZZIZ", 0.16614543256382414),
("IZIZ", 0.16614543256382414),
("ZZZZ", 0.17464343068300453),
("ZIZI", 0.1209126326177663),
])
tapered_qubit_op = TwoQubitReduction(num_particles=2).convert(qubit_op)
self.assertIsInstance(tapered_qubit_op, TaperedPauliSumOp)
primitive = SparsePauliOp.from_list([
("II", -1.052373245772859),
("ZI", -0.39793742484318007),
("IZ", 0.39793742484318007),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423142),
])
symmetries = [Pauli("IIZI"), Pauli("ZIII")]
sq_paulis = [Pauli("IIXI"), Pauli("XIII")]
sq_list = [1, 3]
tapering_values = [-1, 1]
z2_symmetries = Z2Symmetries(symmetries, sq_paulis, sq_list, tapering_values)
expected_op = TaperedPauliSumOp(primitive, z2_symmetries)
self.assertEqual(tapered_qubit_op, expected_op)
|
gadial/qiskit-terra | test/python/opflow/test_pauli_expectation.py | <gh_stars>1-10
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" Test PauliExpectation """
import unittest
from test.python.opflow import QiskitOpflowTestCase
import itertools
import numpy as np
from qiskit.utils import QuantumInstance
from qiskit.utils import algorithm_globals
from qiskit.opflow import (X, Y, Z, I, CX, H, S,
ListOp, Zero, One, Plus, Minus, StateFn,
PauliExpectation, CircuitSampler)
from qiskit import BasicAer
# pylint: disable=invalid-name
class TestPauliExpectation(QiskitOpflowTestCase):
"""Pauli Change of Basis Expectation tests."""
def setUp(self) -> None:
super().setUp()
self.seed = 97
backend = BasicAer.get_backend('qasm_simulator')
q_instance = QuantumInstance(backend, seed_simulator=self.seed, seed_transpiler=self.seed)
self.sampler = CircuitSampler(q_instance, attach_results=True)
self.expect = PauliExpectation()
def test_pauli_expect_pair(self):
""" pauli expect pair test """
op = (Z ^ Z)
# wf = (Pl^Pl) + (Ze^Ze)
wf = CX @ (H ^ I) @ Zero
converted_meas = self.expect.convert(~StateFn(op) @ wf)
self.assertAlmostEqual(converted_meas.eval(), 0, delta=.1)
sampled = self.sampler.convert(converted_meas)
self.assertAlmostEqual(sampled.eval(), 0, delta=.1)
def test_pauli_expect_single(self):
""" pauli expect single test """
paulis = [Z, X, Y, I]
states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus]
for pauli, state in itertools.product(paulis, states):
converted_meas = self.expect.convert(~StateFn(pauli) @ state)
matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix()
self.assertAlmostEqual(converted_meas.eval(), matmulmean, delta=.1)
sampled = self.sampler.convert(converted_meas)
self.assertAlmostEqual(sampled.eval(), matmulmean, delta=.1)
def test_pauli_expect_op_vector(self):
""" pauli expect op vector test """
paulis_op = ListOp([X, Y, Z, I])
converted_meas = self.expect.convert(~StateFn(paulis_op))
plus_mean = (converted_meas @ Plus)
np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1)
sampled_plus = self.sampler.convert(plus_mean)
np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1)
minus_mean = (converted_meas @ Minus)
np.testing.assert_array_almost_equal(minus_mean.eval(), [-1, 0, 0, 1], decimal=1)
sampled_minus = self.sampler.convert(minus_mean)
np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1)
zero_mean = (converted_meas @ Zero)
np.testing.assert_array_almost_equal(zero_mean.eval(), [0, 0, 1, 1], decimal=1)
sampled_zero = self.sampler.convert(zero_mean)
np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1)
sum_zero = (Plus + Minus) * (.5 ** .5)
sum_zero_mean = (converted_meas @ sum_zero)
np.testing.assert_array_almost_equal(sum_zero_mean.eval(), [0, 0, 1, 1], decimal=1)
sampled_zero_mean = self.sampler.convert(sum_zero_mean)
# !!NOTE!!: Depolarizing channel (Sampling) means interference
# does not happen between circuits in sum, so expectation does
# not equal expectation for Zero!!
np.testing.assert_array_almost_equal(sampled_zero_mean.eval(), [0, 0, 0, 1], decimal=1)
for i, op in enumerate(paulis_op.oplist):
mat_op = op.to_matrix()
np.testing.assert_array_almost_equal(zero_mean.eval()[i],
Zero.adjoint().to_matrix() @
mat_op @ Zero.to_matrix(),
decimal=1)
np.testing.assert_array_almost_equal(plus_mean.eval()[i],
Plus.adjoint().to_matrix() @
mat_op @ Plus.to_matrix(),
decimal=1)
np.testing.assert_array_almost_equal(minus_mean.eval()[i],
Minus.adjoint().to_matrix() @
mat_op @ Minus.to_matrix(),
decimal=1)
def test_pauli_expect_state_vector(self):
""" pauli expect state vector test """
states_op = ListOp([One, Zero, Plus, Minus])
paulis_op = X
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1)
sampled = self.sampler.convert(converted_meas)
np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1)
# Small test to see if execution results are accessible
for composed_op in sampled:
self.assertIn('counts', composed_op[1].execution_results)
def test_pauli_expect_op_vector_state_vector(self):
""" pauli expect op vector state vector test """
paulis_op = ListOp([X, Y, Z, I])
states_op = ListOp([One, Zero, Plus, Minus])
valids = [[+0, 0, 1, -1],
[+0, 0, 0, 0],
[-1, 1, 0, -0],
[+1, 1, 1, 1]]
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
np.testing.assert_array_almost_equal(converted_meas.eval(), valids, decimal=1)
sampled = self.sampler.convert(converted_meas)
np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1)
def test_to_matrix_called(self):
""" test to matrix called in different situations """
qs = 45
states_op = ListOp([Zero ^ qs,
One ^ qs,
(Zero ^ qs) + (One ^ qs)])
paulis_op = ListOp([Z ^ qs,
(I ^ Z ^ I) ^ int(qs / 3)])
# 45 qubit calculation - throws exception if to_matrix is called
# massive is False
with self.assertRaises(ValueError):
states_op.to_matrix()
paulis_op.to_matrix()
# now set global variable or argument
try:
algorithm_globals.massive = True
with self.assertRaises(MemoryError):
states_op.to_matrix()
paulis_op.to_matrix()
algorithm_globals.massive = False
with self.assertRaises(MemoryError):
states_op.to_matrix(massive=True)
paulis_op.to_matrix(massive=True)
finally:
algorithm_globals.massive = False
def test_not_to_matrix_called(self):
""" 45 qubit calculation - literally will not work if to_matrix is
somehow called (in addition to massive=False throwing an error)"""
qs = 45
states_op = ListOp([Zero ^ qs,
One ^ qs,
(Zero ^ qs) + (One ^ qs)])
paulis_op = ListOp([Z ^ qs,
(I ^ Z ^ I) ^ int(qs / 3)])
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
np.testing.assert_array_almost_equal(converted_meas.eval(), [[1, -1, 0], [1, -1, 0]])
def test_grouped_pauli_expectation(self):
""" grouped pauli expectation test """
two_qubit_H2 = (-1.052373245772859 * I ^ I) + \
(0.39793742484318045 * I ^ Z) + \
(-0.39793742484318045 * Z ^ I) + \
(-0.01128010425623538 * Z ^ Z) + \
(0.18093119978423156 * X ^ X)
wf = CX @ (H ^ I) @ Zero
expect_op = PauliExpectation(group_paulis=False).convert(~StateFn(two_qubit_H2) @ wf)
self.sampler._extract_circuitstatefns(expect_op)
num_circuits_ungrouped = len(self.sampler._circuit_ops_cache)
self.assertEqual(num_circuits_ungrouped, 5)
expect_op_grouped = PauliExpectation(group_paulis=True).convert(~StateFn(two_qubit_H2) @ wf)
q_instance = QuantumInstance(BasicAer.get_backend('statevector_simulator'),
seed_simulator=self.seed, seed_transpiler=self.seed)
sampler = CircuitSampler(q_instance)
sampler._extract_circuitstatefns(expect_op_grouped)
num_circuits_grouped = len(sampler._circuit_ops_cache)
self.assertEqual(num_circuits_grouped, 2)
@unittest.skip(reason="IBMQ testing not available in general.")
def test_ibmq_grouped_pauli_expectation(self):
""" pauli expect op vector state vector test """
from qiskit import IBMQ
p = IBMQ.load_account()
backend = p.get_backend('ibmq_qasm_simulator')
q_instance = QuantumInstance(backend, seed_simulator=self.seed, seed_transpiler=self.seed)
paulis_op = ListOp([X, Y, Z, I])
states_op = ListOp([One, Zero, Plus, Minus])
valids = [[+0, 0, 1, -1],
[+0, 0, 0, 0],
[-1, 1, 0, -0],
[+1, 1, 1, 1]]
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
sampled = CircuitSampler(q_instance).convert(converted_meas)
np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1)
def test_multi_representation_ops(self):
""" Test observables with mixed representations """
mixed_ops = ListOp([X.to_matrix_op(),
H,
H + I,
X])
converted_meas = self.expect.convert(~StateFn(mixed_ops))
plus_mean = (converted_meas @ Plus)
sampled_plus = self.sampler.convert(plus_mean)
np.testing.assert_array_almost_equal(sampled_plus.eval(),
[1, .5**.5, (1 + .5**.5), 1],
decimal=1)
if __name__ == '__main__':
unittest.main()
|
gadial/qiskit-terra | qiskit/opflow/state_fns/cvar_measurement.py | <gh_stars>1-10
# 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.
"""CVaRMeasurement class."""
from typing import Callable, Optional, Tuple, Union, cast
import numpy as np
from qiskit.circuit import ParameterExpression
from qiskit.opflow.exceptions import OpflowError
from qiskit.opflow.list_ops import ListOp, SummedOp, TensoredOp
from qiskit.opflow.operator_base import OperatorBase
from qiskit.opflow.primitive_ops import PauliOp
from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn
from qiskit.opflow.state_fns.dict_state_fn import DictStateFn
from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn
from qiskit.opflow.state_fns.state_fn import StateFn
from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn
from qiskit.quantum_info import Statevector
class CVaRMeasurement(OperatorStateFn):
r"""A specialized measurement class to compute CVaR expectation values.
See https://arxiv.org/pdf/1907.04769.pdf for further details.
Used in :class:`~qiskit.opflow.CVaRExpectation`, see there for more details.
"""
primitive: OperatorBase
# TODO allow normalization somehow?
def __init__(self,
primitive: Union[OperatorBase] = None,
alpha: float = 1.0,
coeff: Union[complex, ParameterExpression] = 1.0) -> None:
"""
Args:
primitive: The ``OperatorBase`` which defines the diagonal operator
measurement.
coeff: A coefficient by which to multiply the state function
alpha: A real-valued parameter between 0 and 1 which specifies the
fraction of observed samples to include when computing the
objective value. alpha = 1 corresponds to a standard observable
expectation value. alpha = 0 corresponds to only using the single
sample with the lowest energy. alpha = 0.5 corresponds to ranking each
observation by lowest energy and using the best
Raises:
ValueError: TODO remove that this raises an error
ValueError: If alpha is not in [0, 1].
OpflowError: If the primitive is not diagonal.
"""
if primitive is None:
raise ValueError
if not 0 <= alpha <= 1:
raise ValueError('The parameter alpha must be in [0, 1].')
self._alpha = alpha
if not _check_is_diagonal(primitive):
raise OpflowError('Input operator to CVaRMeasurement must be diagonal, but is not:',
str(primitive))
super().__init__(primitive, coeff=coeff, is_measurement=True)
@property
def alpha(self) -> float:
"""A real-valued parameter between 0 and 1 which specifies the
fraction of observed samples to include when computing the
objective value. alpha = 1 corresponds to a standard observable
expectation value. alpha = 0 corresponds to only using the single
sample with the lowest energy. alpha = 0.5 corresponds to ranking each
observation by lowest energy and using the best half.
Returns:
The parameter alpha which was given at initialization
"""
return self._alpha
def add(self, other: OperatorBase) -> SummedOp:
return SummedOp([self, other])
def adjoint(self):
"""The adjoint of a CVaRMeasurement is not defined.
Returns:
Does not return anything, raises an error.
Raises:
OpflowError: The adjoint of a CVaRMeasurement is not defined.
"""
raise OpflowError('Adjoint of a CVaR measurement not defined')
def mul(self, scalar: Union[complex, ParameterExpression]) -> "CVaRMeasurement":
if not isinstance(scalar, (int, float, complex, ParameterExpression)):
raise ValueError('Operators can only be scalar multiplied by float or complex, not '
'{} of type {}.'.format(scalar, type(scalar)))
return self.__class__(self.primitive,
coeff=self.coeff * scalar,
alpha=self._alpha)
def tensor(self, other: OperatorBase) -> Union["OperatorStateFn", TensoredOp]:
if isinstance(other, OperatorStateFn):
return OperatorStateFn(self.primitive.tensor(other.primitive),
coeff=self.coeff * other.coeff)
return TensoredOp([self, other])
def to_density_matrix(self, massive: bool = False):
"""Not defined."""
raise NotImplementedError
def to_matrix_op(self, massive: bool = False):
"""Not defined."""
raise NotImplementedError
def to_matrix(self, massive: bool = False):
"""Not defined."""
raise NotImplementedError
def to_circuit_op(self):
"""Not defined."""
raise NotImplementedError
def __str__(self) -> str:
return 'CVaRMeasurement({}) * {}'.format(str(self.primitive), self.coeff)
def eval(self,
front: Union[str, dict, np.ndarray, OperatorBase, Statevector] = None) -> complex:
r"""
Given the energies of each sampled measurement outcome (H_i) as well as the
sampling probability of each measurement outcome (p_i, we can compute the
CVaR as H_j + 1/α*(sum_i<j p_i*(H_i - H_j)). Note that index j corresponds
to the measurement outcome such that only some of the samples with
measurement outcome j will be used in computing CVaR. Note also that the
sampling probabilities serve as an alternative to knowing the counts of each
observation.
This computation is broken up into two subroutines. One which evaluates each
measurement outcome and determines the sampling probabilities of each. And one
which carries out the above calculation. The computation is split up this way
to enable a straightforward calculation of the variance of this estimator.
Args:
front: A StateFn or primitive which specifies the results of evaluating
a quantum state.
Returns:
The CVaR of the diagonal observable specified by self.primitive and
the sampled quantum state described by the inputs
(energies, probabilities). For index j (described above), the CVaR
is computed as H_j + 1/α*(sum_i<j p_i*(H_i - H_j))
"""
energies, probabilities = self.get_outcome_energies_probabilities(front)
return self.compute_cvar(energies, probabilities)
def eval_variance(
self, front: Optional[Union[str, dict, np.ndarray, OperatorBase]] = None
) -> complex:
r"""
Given the energies of each sampled measurement outcome (H_i) as well as the
sampling probability of each measurement outcome (p_i, we can compute the
variance of the CVaR estimator as
H_j^2 + 1/α * (sum_i<j p_i*(H_i^2 - H_j^2)).
This follows from the definition that Var[X] = E[X^2] - E[X]^2.
In this case, X = E[<bi|H|bi>], where H is the diagonal observable and bi
corresponds to measurement outcome i. Given this, E[X^2] = E[<bi|H|bi>^2]
Args:
front: A StateFn or primitive which specifies the results of evaluating
a quantum state.
Returns:
The Var[CVaR] of the diagonal observable specified by self.primitive
and the sampled quantum state described by the inputs
(energies, probabilities). For index j (described above), the CVaR
is computed as H_j^2 + 1/α*(sum_i<j p_i*(H_i^2 - H_j^2))
"""
energies, probabilities = self.get_outcome_energies_probabilities(front)
sq_energies = [energy**2 for energy in energies]
return self.compute_cvar(sq_energies, probabilities) - self.eval(front)**2
def get_outcome_energies_probabilities(
self, front: Optional[Union[str, dict, np.ndarray, OperatorBase, Statevector]] = None
) -> Tuple[list, list]:
r"""
In order to compute the CVaR of an observable expectation, we require
the energies of each sampled measurement outcome as well as the sampling
probability of each measurement outcome. Note that the counts for each
measurement outcome will also suffice (and this is often how the CVaR
is presented).
Args:
front: A StateFn or a primitive which defines a StateFn.
This input holds the results of a sampled/simulated circuit.
Returns:
Two lists of equal length. `energies` contains the energy of each
unique measurement outcome computed against the diagonal observable
stored in self.primitive. `probabilities` contains the corresponding
sampling probability for each measurement outcome in `energies`.
Raises:
ValueError: front isn't a DictStateFn or VectorStateFn
"""
if isinstance(front, CircuitStateFn):
front = cast(StateFn, front.eval())
# Standardize the inputs to a dict
if isinstance(front, DictStateFn):
data = front.primitive
elif isinstance(front, VectorStateFn):
vec = front.primitive.data
# Determine how many bits are needed
key_len = int(np.ceil(np.log2(len(vec))))
# Convert the vector primitive into a dict. The formatting here ensures
# that the proper number of leading `0` characters are added.
data = {format(index, '0'+str(key_len)+'b'): val for index, val in enumerate(vec)}
else:
raise ValueError('Unsupported input to CVaRMeasurement.eval:', type(front))
obs = self.primitive
outcomes = list(data.items())
# add energy evaluation
for i, outcome in enumerate(outcomes):
key = outcome[0]
outcomes[i] += (obs.eval(key).adjoint().eval(key),) # type: ignore
# Sort each observation based on it's energy
outcomes = sorted(outcomes, key=lambda x: x[2]) # type: ignore
# Here probabilities are the (root) probabilities of
# observing each state. energies are the expectation
# values of each state with the provided Hamiltonian.
_, root_probabilities, energies = zip(*outcomes)
# Square the dict values
# (since CircuitSampler takes the root...)
probabilities = [p_i * np.conj(p_i) for p_i in root_probabilities]
return list(energies), probabilities
def compute_cvar(self, energies: list, probabilities: list) -> complex:
r"""
Given the energies of each sampled measurement outcome (H_i) as well as the
sampling probability of each measurement outcome (p_i, we can compute the
CVaR. Note that the sampling probabilities serve as an alternative to knowing
the counts of each observation and that the input energies are assumed to be
sorted in increasing order.
Consider the outcome with index j, such that only some of the samples with
measurement outcome j will be used in computing CVaR. The CVaR calculation
can then be separated into two parts. First we sum each of the energies for
outcomes i < j, weighted by the probability of observing that outcome (i.e
the normalized counts). Second, we add the energy for outcome j, weighted by
the difference (α - \sum_i<j p_i)
Args:
energies: A list containing the energies (H_i) of each sample measurement
outcome, sorted in increasing order.
probabilities: The sampling probabilities (p_i) for each corresponding
measurement outcome.
Returns:
The CVaR of the diagonal observable specified by self.primitive and
the sampled quantum state described by the inputs
(energies, probabilities). For index j (described above), the CVaR
is computed as H_j + 1/α * (sum_i<j p_i*(H_i - H_j))
Raises:
ValueError: front isn't a DictStateFn or VectorStateFn
"""
alpha = self._alpha
# Determine j, the index of the measurement outcome such
# that only some samples with this outcome will be used to
# compute the CVaR.
j = 0
running_total = 0
for i, p_i in enumerate(probabilities):
running_total += p_i
j = i
if running_total > alpha:
break
h_j = energies[j]
cvar = alpha * h_j
if alpha == 0 or j == 0:
return self.coeff * h_j
energies = energies[:j]
probabilities = probabilities[:j]
# Let H_i be the energy associated with outcome i
# and let the outcomes be sorted by ascending energy.
# Let p_i be the probability of observing outcome i.
# CVaR = H_j + 1/α*(sum_i<j p_i*(H_i - H_j))
for h_i, p_i in zip(energies, probabilities):
cvar += p_i * (h_i - h_j)
return self.coeff * cvar/alpha
def traverse(self,
convert_fn: Callable,
coeff: Optional[Union[complex, ParameterExpression]] = None
) -> OperatorBase:
r"""
Apply the convert_fn to the internal primitive if the primitive is an Operator (as in
the case of ``OperatorStateFn``). Otherwise do nothing. Used by converters.
Args:
convert_fn: The function to apply to the internal OperatorBase.
coeff: A coefficient to multiply by after applying convert_fn.
If it is None, self.coeff is used instead.
Returns:
The converted StateFn.
"""
if coeff is None:
coeff = self.coeff
if isinstance(self.primitive, OperatorBase):
return self.__class__(convert_fn(self.primitive), coeff=coeff, alpha=self._alpha)
return self
def sample(self,
shots: int = 1024,
massive: bool = False,
reverse_endianness: bool = False):
raise NotImplementedError
def _check_is_diagonal(operator: OperatorBase) -> bool:
"""Check whether ``operator`` is diagonal.
Args:
operator: The operator to check for diagonality.
Returns:
True, if the operator is diagonal, False otherwise.
Raises:
OpflowError: If the operator is not diagonal.
"""
if isinstance(operator, PauliOp):
# every X component must be False
if not np.any(operator.primitive.x):
return True
return False
if isinstance(operator, SummedOp):
# cover the case of sums of diagonal paulis, but don't raise since there might be summands
# canceling the non-diagonal parts
# ignoring mypy since we know that all operators are PauliOps
if all(isinstance(op, PauliOp) and not np.any(op.primitive.x) for op in operator.oplist):
return True
if isinstance(operator, ListOp):
return all(operator.traverse(_check_is_diagonal))
# cannot efficiently check if a operator is diagonal, converting to matrix
matrix = operator.to_matrix()
if np.all(matrix == np.diag(np.diagonal(matrix))):
return True
return False
|
gadial/qiskit-terra | qiskit/visualization/qcstyle.py | <filename>qiskit/visualization/qcstyle.py<gh_stars>1-10
# 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.
"""mpl circuit visualization style."""
from warnings import warn
class DefaultStyle:
"""Creates a Default Style dictionary
**Style Dict Details**
The style dict contains numerous options that define the style of the
output circuit visualization. The style dict is only used by the `mpl`
output. The options available in the style dict are defined below:
name (str): the name of the style. The name can be set to ``iqx``,
``bw``, ``default``, or the name of a user-created json file. This
overrides the setting in the user config file (usually
``~/.qiskit/settings.conf``).
textcolor (str): the color code to use for all text not inside a gate.
Defaults to ``#000000``
subtextcolor (str): the color code to use for subtext. Defaults to
``#000000``
linecolor (str): the color code to use for lines. Defaults to
``#000000``
creglinecolor (str): the color code to use for classical register
lines. Defaults to ``#778899``
gatetextcolor (str): the color code to use for gate text. Defaults to
``#000000``
gatefacecolor (str): the color code to use for a gate if no color
specified in the 'displaycolor' dict. Defaults to ``#BB8BFF``
barrierfacecolor (str): the color code to use for barriers. Defaults to
``#BDBDBD``
backgroundcolor (str): the color code to use for the background.
Defaults to ``#FFFFFF``
edgecolor (str): the color code to use for gate edges when using the
`bw` style. Defaults to ``#000000``.
fontsize (int): the font size to use for text. Defaults to 13.
subfontsize (int): the font size to use for subtext. Defaults to 8.
showindex (bool): if set to True, show the index numbers at the top.
Defaults to False.
figwidth (int): the maximum width (in inches) for the output figure.
If set to -1, the maximum displayable width will be used.
Defaults to -1.
dpi (int): the DPI to use for the output image. Defaults to 150.
margin (list): a list of margin values to adjust spacing around output
image. Takes a list of 4 ints: [x left, x right, y bottom, y top].
Defaults to [2.0, 0.1, 0.1, 0.3].
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``.
displaytext (dict): a dictionary of the text to use for certain element
types in the output visualization. These items allow the use of
LaTeX formatting for gate names. The 'displaytext' dict can contain
any number of elements from one to the entire dict above.The default
values are (`default.json`)::
{
'u1': '$\\mathrm{U}_1$',
'u2': '$\\mathrm{U}_2$',
'u3': '$\\mathrm{U}_3$',
'u': 'U',
'p': 'P',
'id': 'I',
'x': 'X',
'y': 'Y',
'z': 'Z',
'h': 'H',
's': 'S',
'sdg': '$\\mathrm{S}^\\dagger$',
'sx': '$\\sqrt{\\mathrm{X}}$',
'sxdg': '$\\sqrt{\\mathrm{X}}^\\dagger$',
't': 'T',
'tdg': '$\\mathrm{T}^\\dagger$',
'dcx': 'Dcx',
'iswap': 'Iswap',
'ms': 'MS',
'r': 'R',
'rx': '$\\mathrm{R}_\\mathrm{X}$',
'ry': '$\\mathrm{R}_\\mathrm{Y}$',
'rz': '$\\mathrm{R}_\\mathrm{Z}$',
'rxx': '$\\mathrm{R}_{\\mathrm{XX}}$',
'ryy': '$\\mathrm{R}_{\\mathrm{YY}}$',
'rzx': '$\\mathrm{R}_{\\mathrm{ZX}}$',
'rzz': '$\\mathrm{R}_{\\mathrm{ZZ}}$',
'reset': '$\\left|0\\right\\rangle$',
'initialize': '$|\\psi\\rangle$'
}
displaycolor (dict): the color codes to use for each circuit element in
the form (gate_color, text_color). Colors can also be entered without
the text color, such as 'u1': '#FA74A6', in which case the text color
will always be `gatetextcolor`. The `displaycolor` dict can contain
any number of elements from one to the entire dict above. The default
values are (`default.json`)::
{
'u1': ('#FA74A6', '#000000'),
'u2': ('#FA74A6', '#000000'),
'u3': ('#FA74A6', '#000000'),
'id': ('#05BAB6', '#000000'),
'u': ('#BB8BFF', '#000000'),
'p': ('#BB8BFF', '#000000'),
'x': ('#05BAB6', '#000000'),
'y': ('#05BAB6', '#000000'),
'z': ('#05BAB6', '#000000'),
'h': ('#6FA4FF', '#000000'),
'cx': ('#6FA4FF', '#000000'),
'ccx': ('#BB8BFF', '#000000'),
'mcx': ('#BB8BFF', '#000000'),
'mcx_gray': ('#BB8BFF', '#000000'),
'cy': ('#6FA4FF', '#000000'),
'cz': ('#6FA4FF', '#000000'),
'swap': ('#6FA4FF', '#000000'),
'cswap': ('#BB8BFF', '#000000'),
'ccswap': ('#BB8BFF', '#000000'),
'dcx': ('#6FA4FF', '#000000'),
'cdcx': ('#BB8BFF', '#000000'),
'ccdcx': ('#BB8BFF', '#000000'),
'iswap': ('#6FA4FF', '#000000'),
's': ('#6FA4FF', '#000000'),
'sdg': ('#6FA4FF', '#000000'),
't': ('#BB8BFF', '#000000'),
'tdg': ('#BB8BFF', '#000000'),
'sx': ('#BB8BFF', '#000000'),
'sxdg': ('#BB8BFF', '#000000')
'r': ('#BB8BFF', '#000000'),
'rx': ('#BB8BFF', '#000000'),
'ry': ('#BB8BFF', '#000000'),
'rz': ('#BB8BFF', '#000000'),
'rxx': ('#BB8BFF', '#000000'),
'ryy': ('#BB8BFF', '#000000'),
'rzx': ('#BB8BFF', '#000000'),
'reset': ('#000000', '#FFFFFF'),
'target': ('#FFFFFF', '#FFFFFF'),
'measure': ('#000000', '#FFFFFF'),
}
"""
def __init__(self):
colors = {
'### Default Colors': 'Default Colors',
'basis': '#FA74A6', # Red
'clifford': '#6FA4FF', # Light Blue
'pauli': '#05BAB6', # Green
'def_other': '#BB8BFF', # Purple
'### IQX Colors': 'IQX Colors',
'classical': '#002D9C', # Dark Blue
'phase': '#33B1FF', # Cyan
'hadamard': '#FA4D56', # Light Red
'non_unitary': '#A8A8A8', # Medium Gray
'iqx_other': '#9F1853', # Dark Red
'### B/W': 'B/W',
'black': '#000000',
'white': '#FFFFFF',
'dark_gray': '#778899',
'light_gray': '#BDBDBD'
}
self.style = {
'name': 'default',
'tc': colors['black'], # Non-gate Text Color
'gt': colors['black'], # Gate Text Color
'sc': colors['black'], # Gate Subtext Color
'lc': colors['black'], # Line Color
'cc': colors['dark_gray'], # creg Line Color
'gc': colors['def_other'], # Default Gate Color
'bc': colors['light_gray'], # Barrier Color
'bg': colors['white'], # Background Color
'ec': None, # Edge Color (B/W only)
'fs': 13, # Gate Font Size
'sfs': 8, # Subtext Font Size
'index': False,
'figwidth': -1,
'dpi': 150,
'margin': [2.0, 0.1, 0.1, 0.3],
'cline': 'doublet',
'disptex': {
'u1': '$\\mathrm{U}_1$',
'u2': '$\\mathrm{U}_2$',
'u3': '$\\mathrm{U}_3$',
'u': 'U',
'p': 'P',
'id': 'I',
'x': 'X',
'y': 'Y',
'z': 'Z',
'h': 'H',
's': 'S',
'sdg': '$\\mathrm{S}^\\dagger$',
'sx': '$\\sqrt{\\mathrm{X}}$',
'sxdg': '$\\sqrt{\\mathrm{X}}^\\dagger$',
't': 'T',
'tdg': '$\\mathrm{T}^\\dagger$',
'dcx': 'Dcx',
'iswap': 'Iswap',
'ms': 'MS',
'r': 'R',
'rx': '$\\mathrm{R}_\\mathrm{X}$',
'ry': '$\\mathrm{R}_\\mathrm{Y}$',
'rz': '$\\mathrm{R}_\\mathrm{Z}$',
'rxx': '$\\mathrm{R}_{\\mathrm{XX}}$',
'ryy': '$\\mathrm{R}_{\\mathrm{YY}}$',
'rzx': '$\\mathrm{R}_{\\mathrm{ZX}}$',
'rzz': '$\\mathrm{ZZ}$',
'reset': '$\\left|0\\right\\rangle$',
'initialize': '$|\\psi\\rangle$'
},
'dispcol': {
'u1': (colors['basis'], colors['black']),
'u2': (colors['basis'], colors['black']),
'u3': (colors['basis'], colors['black']),
'u': (colors['def_other'], colors['black']),
'p': (colors['def_other'], colors['black']),
'id': (colors['pauli'], colors['black']),
'x': (colors['pauli'], colors['black']),
'y': (colors['pauli'], colors['black']),
'z': (colors['pauli'], colors['black']),
'h': (colors['clifford'], colors['black']),
'cx': (colors['clifford'], colors['black']),
'ccx': (colors['def_other'], colors['black']),
'mcx': (colors['def_other'], colors['black']),
'mcx_gray': (colors['def_other'], colors['black']),
'cy': (colors['clifford'], colors['black']),
'cz': (colors['clifford'], colors['black']),
'swap': (colors['clifford'], colors['black']),
'cswap': (colors['def_other'], colors['black']),
'ccswap': (colors['def_other'], colors['black']),
'dcx': (colors['clifford'], colors['black']),
'cdcx': (colors['def_other'], colors['black']),
'ccdcx': (colors['def_other'], colors['black']),
'iswap': (colors['clifford'], colors['black']),
's': (colors['clifford'], colors['black']),
'sdg': (colors['clifford'], colors['black']),
't': (colors['def_other'], colors['black']),
'tdg': (colors['def_other'], colors['black']),
'sx': (colors['def_other'], colors['black']),
'sxdg': (colors['def_other'], colors['black']),
'r': (colors['def_other'], colors['black']),
'rx': (colors['def_other'], colors['black']),
'ry': (colors['def_other'], colors['black']),
'rz': (colors['def_other'], colors['black']),
'rxx': (colors['def_other'], colors['black']),
'ryy': (colors['def_other'], colors['black']),
'rzx': (colors['def_other'], colors['black']),
'reset': (colors['black'], colors['white']),
'target': (colors['white'], colors['white']),
'measure': (colors['black'], colors['white'])
}
}
def set_style(current_style, new_style):
"""Utility function to take elements in new_style and
write them into current_style.
"""
valid_fieds = {'name', 'textcolor', 'gatetextcolor', 'subtextcolor', 'linecolor',
'creglinecolor', 'gatefacecolor', 'barrierfacecolor', 'backgroundcolor',
'edgecolor', 'fontsize', 'subfontsize', 'showindex', 'figwidth', 'dpi',
'margin', 'creglinestyle', 'displaytext', 'displaycolor'}
current_style.update(new_style)
current_style['tc'] = current_style.get('textcolor', current_style['tc'])
current_style['gt'] = current_style.get('gatetextcolor', current_style['gt'])
current_style['sc'] = current_style.get('subtextcolor', current_style['sc'])
current_style['lc'] = current_style.get('linecolor', current_style['lc'])
current_style['cc'] = current_style.get('creglinecolor', current_style['cc'])
current_style['gc'] = current_style.get('gatefacecolor', current_style['gc'])
current_style['bc'] = current_style.get('barrierfacecolor', current_style['bc'])
current_style['bg'] = current_style.get('backgroundcolor', current_style['bg'])
current_style['ec'] = current_style.get('edgecolor', current_style['ec'])
current_style['fs'] = current_style.get('fontsize', current_style['fs'])
current_style['sfs'] = current_style.get('subfontsize', current_style['sfs'])
current_style['index'] = current_style.get('showindex', current_style['index'])
current_style['cline'] = current_style.get('creglinestyle', current_style['cline'])
current_style['disptex'] = {**current_style['disptex'], **new_style.get('displaytext', {})}
current_style['dispcol'] = {**current_style['dispcol'], **new_style.get('displaycolor', {})}
unsupported_keys = set(new_style) - valid_fieds
if unsupported_keys:
warn('style option/s ({}) is/are not supported'.format(', '.join(unsupported_keys)),
UserWarning, 2)
|
gadial/qiskit-terra | qiskit/qasm/node/external.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Node for an OPENQASM external function."""
import warnings
import numpy as np
from .node import Node
from .nodeexception import NodeException
class External(Node):
"""Node for an OPENQASM external function.
children[0] is an id node with the name of the function.
children[1] is an expression node.
"""
def __init__(self, children):
"""Create the external node."""
super().__init__('external', children, None)
def qasm(self, prec=None):
"""Return the corresponding OPENQASM string."""
if prec is not None:
warnings.warn('Parameter \'External.qasm(..., prec)\' is no longer used and is being '
'deprecated.', DeprecationWarning, 2)
return self.children[0].qasm() + "(" + self.children[1].qasm() + ")"
def latex(self, prec=None, nested_scope=None):
"""Return the corresponding math mode latex string."""
if prec is not None:
warnings.warn('Parameter \'External.latex(..., prec)\' is no longer used and is being '
'deprecated.', DeprecationWarning, 2)
if nested_scope is not None:
warnings.warn('Parameter \'External.latex(..., nested_scope)\' is no longer used and '
'is being deprecated.', DeprecationWarning, 2)
try:
from pylatexenc.latexencode import utf8tolatex
except ImportError as ex:
raise ImportError("To export latex from qasm "
"pylatexenc needs to be installed. Run "
"'pip install pylatexenc' before using this "
"method.") from ex
return utf8tolatex(self.sym())
def real(self, nested_scope=None):
"""Return the correspond floating point number."""
op = self.children[0].name
expr = self.children[1]
dispatch = {
'sin': np.sin,
'cos': np.cos,
'tan': np.tan,
'asin': np.arcsin,
'acos': np.arccos,
'atan': np.arctan,
'exp': np.exp,
'ln': np.log,
'sqrt': np.sqrt
}
if op in dispatch:
arg = expr.real(nested_scope)
return dispatch[op](arg)
else:
raise NodeException("internal error: undefined external")
def sym(self, nested_scope=None):
"""Return the corresponding symbolic expression."""
op = self.children[0].name
expr = self.children[1]
dispatch = {
'sin': np.sin,
'cos': np.cos,
'tan': np.tan,
'asin': np.arcsin,
'acos': np.arccos,
'atan': np.arctan,
'exp': np.exp,
'ln': np.log,
'sqrt': np.sqrt
}
if op in dispatch:
arg = expr.sym(nested_scope)
return dispatch[op](arg)
else:
raise NodeException("internal error: undefined external")
|
gadial/qiskit-terra | qiskit/opflow/evolutions/trotterizations/suzuki.py | <gh_stars>1-10
# 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.
""" Suzuki Class """
from typing import List, Union, cast
from numpy import isreal
from qiskit.circuit import ParameterExpression
from qiskit.opflow.evolutions.trotterizations.trotterization_base import TrotterizationBase
from qiskit.opflow.list_ops.composed_op import ComposedOp
from qiskit.opflow.list_ops.summed_op import SummedOp
from qiskit.opflow.operator_base import OperatorBase
from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp
from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp
class Suzuki(TrotterizationBase):
r"""
Suzuki Trotter expansion, composing the evolution circuits of each Operator in the sum
together by a recursive "bookends" strategy, repeating the whole composed circuit
``reps`` times.
Detailed in https://arxiv.org/pdf/quant-ph/0508139.pdf.
"""
def __init__(self,
reps: int = 1,
order: int = 2) -> None:
"""
Args:
reps: The number of times to repeat the expansion circuit.
order: The order of the expansion to perform.
"""
super().__init__(reps=reps)
self._order = order
@property
def order(self) -> int:
""" returns order """
return self._order
@order.setter
def order(self, order: int) -> None:
""" sets order """
self._order = order
def convert(self, operator: OperatorBase) -> OperatorBase:
if not isinstance(operator, (SummedOp, PauliSumOp)):
raise TypeError('Trotterization converters can only convert SummedOp or PauliSumOp.')
if isinstance(operator.coeff, (float, ParameterExpression)):
coeff = operator.coeff
else:
if isreal(operator.coeff):
coeff = operator.coeff.real
else:
raise TypeError(
"Coefficient of the operator must be float or ParameterExpression, "
f"but {operator.coeff}:{type(operator.coeff)} is given."
)
if isinstance(operator, PauliSumOp):
comp_list = self._recursive_expansion(operator, coeff, self.order, self.reps)
if isinstance(operator, SummedOp):
comp_list = Suzuki._recursive_expansion(
operator.oplist, coeff, self.order, self.reps
)
single_rep = ComposedOp(cast(List[OperatorBase], comp_list))
full_evo = single_rep.power(self.reps)
return full_evo.reduce()
@staticmethod
def _recursive_expansion(op_list: Union[List[OperatorBase], PauliSumOp],
evo_time: Union[float, ParameterExpression],
expansion_order: int,
reps: int) -> List[PrimitiveOp]:
"""
Compute the list of pauli terms for a single slice of the Suzuki expansion
following the paper https://arxiv.org/pdf/quant-ph/0508139.pdf.
Args:
op_list: The slice's weighted Pauli list for the Suzuki expansion
evo_time: The parameter lambda as defined in said paper,
adjusted for the evolution time and the number of time slices
expansion_order: The order for the Suzuki expansion.
reps: The number of times to repeat the expansion circuit.
Returns:
The evolution list after expansion.
"""
if expansion_order == 1:
# Base first-order Trotter case
return [(op * (evo_time / reps)).exp_i() for op in op_list] # type: ignore
if expansion_order == 2:
half = Suzuki._recursive_expansion(op_list, evo_time / 2,
expansion_order - 1, reps)
return list(reversed(half)) + half
else:
p_k = (4 - 4 ** (1 / (2 * expansion_order - 1))) ** -1
side = 2 * Suzuki._recursive_expansion(op_list, evo_time
* p_k, expansion_order - 2, reps)
middle = Suzuki._recursive_expansion(op_list, evo_time * (1 - 4 * p_k),
expansion_order - 2, reps)
return side + middle + side
|
gadial/qiskit-terra | qiskit/quantum_info/analysis/distance.py | # 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.
"""A collection of discrete probability metrics."""
import numpy as np
def hellinger_distance(dist_p, dist_q):
"""Computes the Hellinger distance between
two counts distributions.
Parameters:
dist_p (dict): First dict of counts.
dist_q (dict): Second dict of counts.
Returns:
float: Distance
References:
`Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_
"""
p_sum = sum(dist_p.values())
q_sum = sum(dist_q.values())
p_normed = {}
for key, val in dist_p.items():
p_normed[key] = val/p_sum
q_normed = {}
for key, val in dist_q.items():
q_normed[key] = val/q_sum
total = 0
for key, val in p_normed.items():
if key in q_normed.keys():
total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2
del q_normed[key]
else:
total += val
total += sum(q_normed.values())
dist = np.sqrt(total)/np.sqrt(2)
return dist
def hellinger_fidelity(dist_p, dist_q):
"""Computes the Hellinger fidelity between
two counts distributions.
The fidelity is defined as :math:`\\left(1-H^{2}\\right)^{2}` where H is the
Hellinger distance. This value is bounded in the range [0, 1].
This is equivalent to the standard classical fidelity
:math:`F(Q,P)=\\left(\\sum_{i}\\sqrt{p_{i}q_{i}}\\right)^{2}` that in turn
is equal to the quantum state fidelity for diagonal density matrices.
Parameters:
dist_p (dict): First dict of counts.
dist_q (dict): Second dict of counts.
Returns:
float: Fidelity
Example:
.. jupyter-execute::
from qiskit import QuantumCircuit, execute, BasicAer
from qiskit.quantum_info.analysis import hellinger_fidelity
qc = QuantumCircuit(5, 5)
qc.h(2)
qc.cx(2, 1)
qc.cx(2, 3)
qc.cx(3, 4)
qc.cx(1, 0)
qc.measure(range(5), range(5))
sim = BasicAer.get_backend('qasm_simulator')
res1 = execute(qc, sim).result()
res2 = execute(qc, sim).result()
hellinger_fidelity(res1.get_counts(), res2.get_counts())
References:
`Quantum Fidelity @ wikipedia <https://en.wikipedia.org/wiki/Fidelity_of_quantum_states>`_
`Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_
"""
dist = hellinger_distance(dist_p, dist_q)
return (1-dist**2)**2
|
gadial/qiskit-terra | qiskit/opflow/evolutions/matrix_evolution.py | # 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.
""" MatrixEvolution Class """
import logging
from qiskit.opflow.evolutions.evolution_base import EvolutionBase
from qiskit.opflow.evolutions.evolved_op import EvolvedOp
from qiskit.opflow.list_ops.list_op import ListOp
from qiskit.opflow.operator_base import OperatorBase
from qiskit.opflow.primitive_ops.matrix_op import MatrixOp
from qiskit.opflow.primitive_ops.pauli_op import PauliOp
logger = logging.getLogger(__name__)
class MatrixEvolution(EvolutionBase):
r"""
Performs Evolution by classical matrix exponentiation, constructing a circuit with
``UnitaryGates`` or ``HamiltonianGates`` containing the exponentiation of the Operator.
"""
def convert(self, operator: OperatorBase) -> OperatorBase:
r"""
Traverse the operator, replacing ``EvolvedOps`` with ``CircuitOps`` containing
``UnitaryGates`` or ``HamiltonianGates`` (if self.coeff is a ``ParameterExpression``)
equalling the exponentiation of -i * operator. This is done by converting the
``EvolvedOp.primitive`` to a ``MatrixOp`` and simply calling ``.exp_i()`` on that.
Args:
operator: The Operator to convert.
Returns:
The converted operator.
"""
if isinstance(operator, EvolvedOp):
if not {'Matrix'} == operator.primitive_strings():
logger.warning('Evolved Hamiltonian is not composed of only MatrixOps, converting '
'to Matrix representation, which can be expensive.')
# Setting massive=False because this conversion is implicit. User can perform this
# action on the Hamiltonian with massive=True explicitly if they so choose.
# TODO explore performance to see whether we should avoid doing this repeatedly
matrix_ham = operator.primitive.to_matrix_op(massive=False)
operator = EvolvedOp(matrix_ham, coeff=operator.coeff)
if isinstance(operator.primitive, ListOp):
return operator.primitive.exp_i() * operator.coeff
elif isinstance(operator.primitive, (MatrixOp, PauliOp)):
return operator.primitive.exp_i()
elif isinstance(operator, ListOp):
return operator.traverse(self.convert).reduce()
return operator
|
gadial/qiskit-terra | qiskit/quantum_info/operators/channel/choi.py | # 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.
"""
Choi-matrix representation of a Quantum Channel.
"""
import copy
import numpy as np
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.circuit.instruction import Instruction
from qiskit.exceptions import QiskitError
from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel
from qiskit.quantum_info.operators.op_shape import OpShape
from qiskit.quantum_info.operators.channel.superop import SuperOp
from qiskit.quantum_info.operators.channel.transformations import _to_choi
from qiskit.quantum_info.operators.channel.transformations import _bipartite_tensor
from qiskit.quantum_info.operators.mixins import generate_apidocs
class Choi(QuantumChannel):
r"""Choi-matrix representation of a Quantum Channel.
The Choi-matrix representation of a quantum channel :math:`\mathcal{E}`
is a matrix
.. math::
\Lambda = \sum_{i,j} |i\rangle\!\langle j|\otimes
\mathcal{E}\left(|i\rangle\!\langle j|\right)
Evolution of a :class:`~qiskit.quantum_info.DensityMatrix`
:math:`\rho` with respect to the Choi-matrix is given by
.. math::
\mathcal{E}(\rho) = \mbox{Tr}_{1}\left[\Lambda
(\rho^T \otimes \mathbb{I})\right]
where :math:`\mbox{Tr}_1` is the :func:`partial_trace` over subsystem 1.
See reference [1] for further details.
References:
1. <NAME>, <NAME>, <NAME>, *Tensor networks and graphical calculus
for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015).
`arXiv:1111.6950 [quant-ph] <https://arxiv.org/abs/1111.6950>`_
"""
def __init__(self, data, input_dims=None, output_dims=None):
"""Initialize a quantum channel Choi matrix operator.
Args:
data (QuantumCircuit or
Instruction or
BaseOperator or
matrix): data to initialize superoperator.
input_dims (tuple): the input subsystem dimensions.
[Default: None]
output_dims (tuple): the output subsystem dimensions.
[Default: None]
Raises:
QiskitError: if input data cannot be initialized as a
Choi matrix.
Additional Information:
If the input or output dimensions are None, they will be
automatically determined from the input data. If the input data is
a Numpy array of shape (4**N, 4**N) qubit systems will be used. If
the input operator is not an N-qubit operator, it will assign a
single subsystem with dimension specified by the shape of the input.
"""
# If the input is a raw list or matrix we assume that it is
# already a Choi matrix.
if isinstance(data, (list, np.ndarray)):
# Initialize from raw numpy or list matrix.
choi_mat = np.asarray(data, dtype=complex)
# Determine input and output dimensions
dim_l, dim_r = choi_mat.shape
if dim_l != dim_r:
raise QiskitError('Invalid Choi-matrix input.')
if input_dims:
input_dim = np.product(input_dims)
if output_dims:
output_dim = np.product(output_dims)
if output_dims is None and input_dims is None:
output_dim = int(np.sqrt(dim_l))
input_dim = dim_l // output_dim
elif input_dims is None:
input_dim = dim_l // output_dim
elif output_dims is None:
output_dim = dim_l // input_dim
# Check dimensions
if input_dim * output_dim != dim_l:
raise QiskitError("Invalid shape for input Choi-matrix.")
op_shape = OpShape.auto(dims_l=output_dims, dims_r=input_dims,
shape=(output_dim, input_dim))
else:
# Otherwise we initialize by conversion from another Qiskit
# object into the QuantumChannel.
if isinstance(data, (QuantumCircuit, Instruction)):
# If the input is a Terra QuantumCircuit or Instruction we
# convert it to a SuperOp
data = SuperOp._init_instruction(data)
else:
# We use the QuantumChannel init transform to initialize
# other objects into a QuantumChannel or Operator object.
data = self._init_transformer(data)
op_shape = data._op_shape
output_dim, input_dim = op_shape.shape
# Now that the input is an operator we convert it to a Choi object
rep = getattr(data, '_channel_rep', 'Operator')
choi_mat = _to_choi(rep, data._data, input_dim, output_dim)
super().__init__(choi_mat, op_shape=op_shape)
def __array__(self, dtype=None):
if dtype:
return np.asarray(self.data, dtype=dtype)
return self.data
@property
def _bipartite_shape(self):
"""Return the shape for bipartite matrix"""
return (self._input_dim, self._output_dim, self._input_dim,
self._output_dim)
def _evolve(self, state, qargs=None):
return SuperOp(self)._evolve(state, qargs)
# ---------------------------------------------------------------------
# BaseOperator methods
# ---------------------------------------------------------------------
def conjugate(self):
ret = copy.copy(self)
ret._data = np.conj(self._data)
return ret
def transpose(self):
ret = copy.copy(self)
ret._op_shape = self._op_shape.transpose()
# Make bipartite matrix
d_in, d_out = self.dim
data = np.reshape(self._data, (d_in, d_out, d_in, d_out))
# Swap input and output indices on bipartite matrix
data = np.transpose(data, (1, 0, 3, 2))
ret._data = np.reshape(data, (d_in * d_out, d_in * d_out))
return ret
def compose(self, other, qargs=None, front=False):
if qargs is None:
qargs = getattr(other, 'qargs', None)
if qargs is not None:
return Choi(
SuperOp(self).compose(other, qargs=qargs, front=front))
if not isinstance(other, Choi):
other = Choi(other)
new_shape = self._op_shape.compose(other._op_shape, qargs, front)
output_dim, input_dim = new_shape.shape
if front:
first = np.reshape(other._data, other._bipartite_shape)
second = np.reshape(self._data, self._bipartite_shape)
else:
first = np.reshape(self._data, self._bipartite_shape)
second = np.reshape(other._data, other._bipartite_shape)
# Contract Choi matrices for composition
data = np.reshape(np.einsum('iAjB,AkBl->ikjl', first, second),
(input_dim * output_dim, input_dim * output_dim))
ret = Choi(data)
ret._op_shape = new_shape
return ret
def tensor(self, other):
if not isinstance(other, Choi):
other = Choi(other)
return self._tensor(self, other)
def expand(self, other):
if not isinstance(other, Choi):
other = Choi(other)
return self._tensor(other, self)
@classmethod
def _tensor(cls, a, b):
ret = copy.copy(a)
ret._op_shape = a._op_shape.tensor(b._op_shape)
ret._data = _bipartite_tensor(a._data, b.data,
shape1=a._bipartite_shape,
shape2=b._bipartite_shape)
return ret
# Update docstrings for API docs
generate_apidocs(Choi)
|
gadial/qiskit-terra | test/python/circuit/test_register.py | # 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=missing-function-docstring
"""Test library of quantum circuits."""
from ddt import data, ddt
from qiskit.test import QiskitTestCase
from qiskit.circuit import bit
from qiskit.circuit import QuantumRegister
from qiskit.circuit import AncillaRegister
from qiskit.circuit import ClassicalRegister
from qiskit.circuit.exceptions import CircuitError
@ddt
class TestRegisterClass(QiskitTestCase):
"""Tests for Register class."""
@data(QuantumRegister, ClassicalRegister, AncillaRegister)
def test_raise_on_init_with_invalid_size(self, reg_type):
with self.assertRaisesRegex(CircuitError, "must be an integer"):
_ = reg_type(1j, 'foo')
@data(QuantumRegister, ClassicalRegister, AncillaRegister)
def test_raise_if_init_passed_both_size_and_bits(self, reg_type):
bits = [reg_type.bit_type()]
with self.assertRaisesRegex(CircuitError, "Exactly one of the size or bits"):
_ = reg_type(1, 'foo', bits)
@data(QuantumRegister, ClassicalRegister, AncillaRegister)
def test_init_raise_if_bits_of_incorrect_type(self, reg_type):
bits = [bit.Bit()]
with self.assertRaisesRegex(CircuitError, "did not all match register type"):
_ = reg_type(bits=bits)
@data(QuantumRegister, ClassicalRegister, AncillaRegister)
def test_init_raise_if_passed_invalid_name(self, reg_type):
with self.assertRaisesRegex(CircuitError, "invalid OPENQASM register name"):
_ = reg_type(size=1, name='_q')
@data(QuantumRegister, ClassicalRegister, AncillaRegister)
def test_implicit_bit_construction_from_size(self, reg_type):
reg = reg_type(2)
self.assertEqual(len(reg), 2)
self.assertEqual(reg.size, 2)
self.assertTrue(all(isinstance(bit, reg.bit_type)
for bit in reg))
@data(QuantumRegister, ClassicalRegister, AncillaRegister)
def test_implicit_size_calculation_from_bits(self, reg_type):
bits = [reg_type.bit_type() for _ in range(3)]
reg = reg_type(bits=bits)
self.assertEqual(reg.size, 3)
@data(QuantumRegister, ClassicalRegister, AncillaRegister)
def test_oldstyle_register_eq(self, reg_type):
test_reg = reg_type(3, 'foo')
self.assertEqual(test_reg, test_reg)
reg_copy = reg_type(3, 'foo')
self.assertEqual(reg_copy, test_reg)
reg_larger = reg_type(4, 'foo')
self.assertNotEqual(reg_larger, test_reg)
reg_renamed = reg_type(3, 'bar')
self.assertNotEqual(reg_renamed, test_reg)
difftype = ({QuantumRegister, ClassicalRegister, AncillaRegister} - {reg_type}).pop()
reg_difftype = difftype(3, 'foo')
self.assertNotEqual(reg_difftype, test_reg)
@data(QuantumRegister, ClassicalRegister, AncillaRegister)
def test_newstyle_register_eq(self, reg_type):
test_bits = [reg_type.bit_type() for _ in range(3)]
test_reg = reg_type(name='foo', bits=test_bits)
self.assertEqual(test_reg, test_reg)
reg_samebits = reg_type(name='foo', bits=test_bits)
self.assertEqual(reg_samebits, test_reg)
test_diffbits = [reg_type.bit_type() for _ in range(3)]
reg_diffbits = reg_type(name='foo', bits=test_diffbits)
self.assertNotEqual(reg_diffbits, test_reg)
reg_oldstyle = reg_type(3, 'foo')
self.assertNotEqual(reg_oldstyle, test_reg)
test_largerbits = [reg_type.bit_type() for _ in range(4)]
reg_larger = reg_type(name='foo', bits=test_largerbits)
self.assertNotEqual(reg_larger, test_reg)
reg_renamed = reg_type(name='bar', bits=test_bits)
self.assertNotEqual(reg_renamed, test_reg)
difftype = ({QuantumRegister, ClassicalRegister, AncillaRegister} - {reg_type}).pop()
bits_difftype = [difftype.bit_type() for _ in range(3)]
reg_difftype = difftype(name='foo', bits=bits_difftype)
self.assertNotEqual(reg_difftype, test_reg)
|
gadial/qiskit-terra | test/python/visualization/timeline/test_core.py | <reponame>gadial/qiskit-terra
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for core modules of timeline drawer."""
from qiskit import QuantumCircuit, transpile
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import core, stylesheet, generators, layouts
class TestCanvas(QiskitTestCase):
"""Test for canvas."""
def setUp(self):
super().setUp()
self.style = stylesheet.QiskitTimelineStyle()
circ = QuantumCircuit(4)
circ.h(0)
circ.barrier()
circ.cx(0, 2)
circ.cx(1, 3)
self.circ = transpile(circ,
scheduling_method='alap',
basis_gates=['h', 'cx'],
instruction_durations=[('h', 0, 200),
('cx', [0, 2], 1000),
('cx', [1, 3], 1000)],
optimization_level=0)
def test_time_range(self):
"""Test calculating time range."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter = {
'margin.left_percent': 0.1,
'margin.right_percent': 0.1
}
canvas.time_range = (0, 100)
ref_range = [-10., 110.]
self.assertListEqual(list(canvas.time_range), ref_range)
def test_load_program(self):
"""Test loading program."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
'gates': [generators.gen_sched_gate],
'bits': [],
'barriers': [],
'gate_links': []
}
canvas.layout = {
'bit_arrange': layouts.qreg_creg_ascending,
'time_axis_map': layouts.time_map_in_dt
}
canvas.load_program(self.circ)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 8)
ref_coord = {
self.circ.qregs[0][0]: -1.,
self.circ.qregs[0][1]: -2.,
self.circ.qregs[0][2]: -3.,
self.circ.qregs[0][3]: -4.
}
self.assertDictEqual(canvas.assigned_coordinates, ref_coord)
def test_gate_link_overlap(self):
"""Test shifting gate link overlap."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({
'margin.link_interval_percent': 0.01,
'margin.left_percent': 0,
'margin.right_percent': 0
})
canvas.generator = {
'gates': [],
'bits': [],
'barriers': [],
'gate_links': [generators.gen_gate_link]
}
canvas.layout = {
'bit_arrange': layouts.qreg_creg_ascending,
'time_axis_map': layouts.time_map_in_dt
}
canvas.load_program(self.circ)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 2)
self.assertListEqual(drawings_tested[0][1].xvals, [706.])
self.assertListEqual(drawings_tested[1][1].xvals, [694.])
ref_keys = list(canvas._collections.keys())
self.assertEqual(drawings_tested[0][0], ref_keys[0])
self.assertEqual(drawings_tested[1][0], ref_keys[1])
def test_object_outside_xlimit(self):
"""Test eliminating drawings outside the horizontal limit."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
'gates': [generators.gen_sched_gate],
'bits': [generators.gen_bit_name, generators.gen_timeslot],
'barriers': [],
'gate_links': []
}
canvas.layout = {
'bit_arrange': layouts.qreg_creg_ascending,
'time_axis_map': layouts.time_map_in_dt
}
canvas.load_program(self.circ)
canvas.set_time_range(t_start=400, t_end=600)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 12)
def test_non_transpiled_delay_circuit(self):
"""Test non-transpiled circuit containing instruction which is trivial on duration."""
circ = QuantumCircuit(1)
circ.delay(10, 0)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
'gates': [generators.gen_sched_gate],
'bits': [],
'barriers': [],
'gate_links': []
}
canvas.load_program(circ)
self.assertEqual(len(canvas._collections), 1)
def test_multi_measurement_with_clbit_not_shown(self):
"""Test generating bit link drawings of measurements when clbits is disabled."""
circ = QuantumCircuit(2, 2)
circ.measure(0, 0)
circ.measure(1, 1)
circ = transpile(circ,
scheduling_method='alap',
basis_gates=[],
instruction_durations=[('measure', 0, 2000), ('measure', 1, 2000)],
optimization_level=0)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({
'control.show_clbits': False
})
canvas.layout = {
'bit_arrange': layouts.qreg_creg_ascending,
'time_axis_map': layouts.time_map_in_dt
}
canvas.generator = {
'gates': [],
'bits': [],
'barriers': [],
'gate_links': [generators.gen_gate_link]
}
canvas.load_program(circ)
canvas.update()
self.assertEqual(len(canvas._output_dataset), 0)
def test_multi_measurement_with_clbit_shown(self):
"""Test generating bit link drawings of measurements when clbits is enabled."""
circ = QuantumCircuit(2, 2)
circ.measure(0, 0)
circ.measure(1, 1)
circ = transpile(circ,
scheduling_method='alap',
basis_gates=[],
instruction_durations=[('measure', 0, 2000), ('measure', 1, 2000)],
optimization_level=0)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({
'control.show_clbits': True
})
canvas.layout = {
'bit_arrange': layouts.qreg_creg_ascending,
'time_axis_map': layouts.time_map_in_dt
}
canvas.generator = {
'gates': [],
'bits': [],
'barriers': [],
'gate_links': [generators.gen_gate_link]
}
canvas.load_program(circ)
canvas.update()
self.assertEqual(len(canvas._output_dataset), 2)
|
gadial/qiskit-terra | qiskit/algorithms/algorithm_result.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
This module implements the abstract base class for algorithm results.
"""
from abc import ABC
import inspect
import pprint
class AlgorithmResult(ABC):
""" Abstract Base Class for algorithm results."""
def __str__(self) -> str:
result = {}
for name, value in inspect.getmembers(self):
if not name.startswith('_') and \
not inspect.ismethod(value) and not inspect.isfunction(value) and \
hasattr(self, name):
result[name] = value
return pprint.pformat(result, indent=4)
def combine(self, result: 'AlgorithmResult') -> None:
"""
Any property from the argument that exists in the receiver is
updated.
Args:
result: Argument result with properties to be set.
Raises:
TypeError: Argument is None
"""
if result is None:
raise TypeError('Argument result expected.')
if result == self:
return
# find any result public property that exists in the receiver
for name, value in inspect.getmembers(result):
if not name.startswith('_') and \
not inspect.ismethod(value) and not inspect.isfunction(value) and \
hasattr(self, name):
try:
setattr(self, name, value)
except AttributeError:
# some attributes may be read only
pass
|
gadial/qiskit-terra | qiskit/pulse/instructions/frequency.py | # 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.
"""Frequency instructions module. These instructions allow the user to manipulate
the frequency of a channel.
"""
from typing import Optional, Union, Tuple
from qiskit.circuit.parameterexpression import ParameterExpression
from qiskit.pulse.channels import PulseChannel
from qiskit.pulse.instructions.instruction import Instruction
class SetFrequency(Instruction):
r"""Set the channel frequency. This instruction operates on ``PulseChannel`` s.
A ``PulseChannel`` creates pulses of the form
.. math::
Re[\exp(i 2\pi f jdt + \phi) d_j].
Here, :math:`f` is the frequency of the channel. The instruction ``SetFrequency`` allows
the user to set the value of :math:`f`. All pulses that are played on a channel
after SetFrequency has been called will have the corresponding frequency.
The duration of SetFrequency is 0.
"""
def __init__(self, frequency: Union[float, ParameterExpression],
channel: PulseChannel,
name: Optional[str] = None):
"""Creates a new set channel frequency instruction.
Args:
frequency: New frequency of the channel in Hz.
channel: The channel this instruction operates on.
name: Name of this set channel frequency instruction.
"""
if not isinstance(frequency, ParameterExpression):
frequency = float(frequency)
super().__init__(operands=(frequency, channel), name=name)
@property
def frequency(self) -> Union[float, ParameterExpression]:
"""New frequency."""
return self.operands[0]
@property
def channel(self) -> PulseChannel:
"""Return the :py:class:`~qiskit.pulse.channels.Channel` that this instruction is
scheduled on.
"""
return self.operands[1]
@property
def channels(self) -> Tuple[PulseChannel]:
"""Returns the channels that this schedule uses."""
return (self.channel, )
@property
def duration(self) -> int:
"""Duration of this instruction."""
return 0
def is_parameterized(self) -> bool:
"""Return True iff the instruction is parameterized."""
return isinstance(self.frequency, ParameterExpression) or super().is_parameterized()
class ShiftFrequency(Instruction):
"""Shift the channel frequency away from the current frequency."""
def __init__(self,
frequency: Union[float, ParameterExpression],
channel: PulseChannel,
name: Optional[str] = None):
"""Creates a new shift frequency instruction.
Args:
frequency: Frequency shift of the channel in Hz.
channel: The channel this instruction operates on.
name: Name of this set channel frequency instruction.
"""
if not isinstance(frequency, ParameterExpression):
frequency = float(frequency)
super().__init__(operands=(frequency, channel), name=name)
@property
def frequency(self) -> Union[float, ParameterExpression]:
"""Frequency shift from the set frequency."""
return self.operands[0]
@property
def channel(self) -> PulseChannel:
"""Return the :py:class:`~qiskit.pulse.channels.Channel` that this instruction is
scheduled on.
"""
return self.operands[1]
@property
def channels(self) -> Tuple[PulseChannel]:
"""Returns the channels that this schedule uses."""
return (self.channel, )
@property
def duration(self) -> int:
"""Duration of this instruction."""
return 0
def is_parameterized(self) -> bool:
"""Return True iff the instruction is parameterized."""
return isinstance(self.frequency, ParameterExpression) or super().is_parameterized()
|
gadial/qiskit-terra | qiskit/test/utils.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Utils for using with Qiskit unit tests."""
import logging
import os
from enum import Enum
from itertools import product
from qiskit import __path__ as qiskit_path
class Path(Enum):
"""Helper with paths commonly used during the tests."""
# Main SDK path: qiskit/
SDK = qiskit_path[0]
# test.python path: qiskit/test/python/
TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python'))
# Examples path: examples/
EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples'))
# Schemas path: qiskit/schemas
SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas'))
# Sample QASMs path: qiskit/test/python/qasm
QASMS = os.path.normpath(os.path.join(TEST, 'qasm'))
def setup_test_logging(logger, log_level, filename):
"""Set logging to file and stdout for a logger.
Args:
logger (Logger): logger object to be updated.
log_level (str): logging level.
filename (str): name of the output file.
"""
# Set up formatter.
log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
' %(message)s'.format(logger.name))
formatter = logging.Formatter(log_fmt)
# Set up the file handler.
file_handler = logging.FileHandler(filename)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
if os.getenv('STREAM_LOG'):
# Set up the stream handler.
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
# Set the logging level from the environment variable, defaulting
# to INFO if it is not a valid level.
level = logging._nameToLevel.get(log_level, logging.INFO)
logger.setLevel(level)
class Case(dict):
"""<no description>"""
pass
def generate_cases(docstring, dsc=None, name=None, **kwargs):
"""Combines kwargs in Cartesian product and creates Case with them"""
ret = []
keys = kwargs.keys()
vals = kwargs.values()
for values in product(*vals):
case = Case(zip(keys, values))
if docstring is not None:
setattr(case, "__doc__", docstring.format(**case))
if dsc is not None:
setattr(case, "__doc__", dsc.format(**case))
if name is not None:
setattr(case, "__name__", name.format(**case))
ret.append(case)
return ret
|
gadial/qiskit-terra | qiskit/circuit/__init__.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
========================================
Quantum Circuits (:mod:`qiskit.circuit`)
========================================
.. currentmodule:: qiskit.circuit
Overview
========
The fundamental element of quantum computing is the **quantum circuit**.
A quantum circuit is a computational routine consisting of coherent quantum
operations on quantum data, such as qubits. It is an ordered sequence of quantum
gates, measurements and resets, which may be conditioned on real-time classical
computation. A set of quantum gates is said to be universal if any unitary
transformation of the quantum data can be efficiently approximated arbitrarily well
as as sequence of gates in the set. Any quantum program can be represented by a
sequence of quantum circuits and classical near-time computation.
In Qiskit, this core element is represented by the :class:`QuantumCircuit` class.
Below is an example of a quantum circuit that makes a three-qubit GHZ state
defined as:
.. math::
|\\psi\\rangle = \\left(|000\\rangle+|111\\rangle\\right)/\\sqrt{2}
.. jupyter-execute::
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()
Supplementary Information
=========================
.. dropdown:: Quantum Circuit Properties
:animate: fade-in-slide-down
When constructing quantum circuits, there are several properties that help quantify
the "size" of the circuits, and their ability to be run on a noisy quantum device.
Some of these, like number of qubits, are straightforward to understand, while others
like depth and number of tensor components require a bit more explanation. Here we will
explain all of these properties, and, in preparation for understanding how circuits change
when run on actual devices, highlight the conditions under which they change.
Consider the following circuit:
.. jupyter-execute::
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
for idx in range(5):
qc.h(idx)
qc.cx(idx, idx+5)
qc.cx(1, 7)
qc.x(8)
qc.cx(1, 9)
qc.x(7)
qc.cx(1, 11)
qc.swap(6, 11)
qc.swap(6, 9)
qc.swap(6, 10)
qc.x(6)
qc.draw()
From the plot, it is easy to see that this circuit has 12 qubits, and a collection of
Hadamard, CNOT, X, and SWAP gates. But how to quantify this programmatically? Because we
can do single-qubit gates on all the qubits simultaneously, the number of qubits in this
circuit is equal to the **width** of the circuit:
.. jupyter-execute::
qc.width()
We can also just get the number of qubits directly:
.. jupyter-execute::
qc.num_qubits
.. important::
For a quantum circuit composed from just qubits, the circuit width is equal
to the number of qubits. This is the definition used in quantum computing. However,
for more complicated circuits with classical registers, and classically controlled gates,
this equivalence breaks down. As such, from now on we will not refer to the number of
qubits in a quantum circuit as the width.
It is also straightforward to get the number and type of the gates in a circuit using
:meth:`QuantumCircuit.count_ops`:
.. jupyter-execute::
qc.count_ops()
We can also get just the raw count of operations by computing the circuits
:meth:`QuantumCircuit.size`:
.. jupyter-execute::
qc.size()
A particularly important circuit property is known as the circuit **depth**. The depth
of a quantum circuit is a measure of how many "layers" of quantum gates, executed in
parallel, it takes to complete the computation defined by the circuit. Because quantum
gates take time to implement, the depth of a circuit roughly corresponds to the amount of
time it takes the quantum computer to execute the circuit. Thus, the depth of a circuit
is one important quantity used to measure if a quantum circuit can be run on a device.
The depth of a quantum circuit has a mathematical definition as the longest path in a
directed acyclic graph (DAG). However, such a definition is a bit hard to grasp, even for
experts. Fortunately, the depth of a circuit can be easily understood by anyone familiar
with playing `Tetris <https://en.wikipedia.org/wiki/Tetris>`_. Lets see how to compute this
graphically:
.. image:: /source_images/depth.gif
.. raw:: html
<br><br>
We can verify our graphical result using :meth:`QuantumCircuit.depth`:
.. jupyter-execute::
qc.depth()
.. raw:: html
<br>
Quantum Circuit API
===================
Quantum Circuit Construction
----------------------------
.. autosummary::
:toctree: ../stubs/
QuantumCircuit
QuantumRegister
Qubit
ClassicalRegister
Clbit
AncillaRegister
AncillaQubit
Gates and Instructions
----------------------
.. autosummary::
:toctree: ../stubs/
Gate
ControlledGate
Delay
Measure
Reset
Instruction
InstructionSet
EquivalenceLibrary
Parametric Quantum Circuits
---------------------------
.. autosummary::
:toctree: ../stubs/
Parameter
ParameterVector
ParameterExpression
Random Circuits
---------------
.. autosummary::
:toctree: ../stubs/
random.random_circuit
"""
from .quantumcircuit import QuantumCircuit
from .classicalregister import ClassicalRegister, Clbit
from .quantumregister import QuantumRegister, Qubit, AncillaRegister, AncillaQubit
from .gate import Gate
# pylint: disable=cyclic-import
from .controlledgate import ControlledGate
from .instruction import Instruction
from .instructionset import InstructionSet
from .barrier import Barrier
from .delay import Delay
from .measure import Measure
from .reset import Reset
from .parameter import Parameter
from .parametervector import ParameterVector
from .parameterexpression import ParameterExpression
from .equivalence import EquivalenceLibrary
from .classicalfunction.types import Int1, Int2
from .classicalfunction import classical_function, BooleanExpression
|
gadial/qiskit-terra | qiskit/algorithms/linear_solvers/matrices/linear_system_matrix.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""An abstract class for matrices input to the linear systems solvers in Qiskit."""
from abc import ABC, abstractmethod
from typing import Tuple
from qiskit import QuantumCircuit
from qiskit.circuit.library import BlueprintCircuit
class LinearSystemMatrix(BlueprintCircuit, ABC):
"""Base class for linear system matrices."""
def __init__(self, num_state_qubits: int, tolerance: float, evolution_time: float,
name: str = 'ls_matrix') -> None:
"""
Args:
num_state_qubits: the number of qubits where the unitary acts.
tolerance: the accuracy desired for the approximation
evolution_time: the time of the Hamiltonian simulation
name: The name of the object.
"""
super().__init__(name=name)
# define internal parameters
self._num_state_qubits = None
self._tolerance = None
self._evolution_time = None # makes sure the eigenvalues are contained in [0,1)
# store parameters
self.num_state_qubits = num_state_qubits
self.tolerance = tolerance
self.evolution_time = evolution_time
@property
def num_state_qubits(self) -> int:
r"""The number of state qubits representing the state :math:`|x\rangle`.
Returns:
The number of state qubits.
"""
return self._num_state_qubits
@num_state_qubits.setter
def num_state_qubits(self, num_state_qubits: int) -> None:
"""Set the number of state qubits.
Note that this may change the underlying quantum register, if the number of state qubits
changes.
Args:
num_state_qubits: The new number of qubits.
"""
if num_state_qubits != self._num_state_qubits:
self._invalidate()
self._num_state_qubits = num_state_qubits
self._reset_registers(num_state_qubits)
@property
def tolerance(self) -> float:
"""Return the error tolerance"""
return self._tolerance
@tolerance.setter
def tolerance(self, tolerance: float) -> None:
"""Set the error tolerance
Args:
tolerance: The new error tolerance.
"""
self._tolerance = tolerance
@property
def evolution_time(self) -> float:
"""Return the time of the evolution."""
return self._evolution_time
@evolution_time.setter
def evolution_time(self, evolution_time: float) -> None:
"""Set the time of the evolution.
Args:
evolution_time: The new time of the evolution.
"""
self._evolution_time = evolution_time
@abstractmethod
def eigs_bounds(self) -> Tuple[float, float]:
"""Return lower and upper bounds on the eigenvalues of the matrix."""
raise NotImplementedError
@abstractmethod
def condition_bounds(self) -> Tuple[float, float]:
"""Return lower and upper bounds on the condition number of the matrix."""
raise NotImplementedError
@abstractmethod
def _reset_registers(self, num_state_qubits: int) -> None:
"""Reset the registers according to the new number of state qubits.
Args:
num_state_qubits: The new number of qubits.
"""
raise NotImplementedError
@abstractmethod
def power(self, power: int, matrix_power: bool = False) -> QuantumCircuit:
"""Build powers of the circuit.
Args:
power: The power to raise this circuit to.
matrix_power: If True, the circuit is converted to a matrix and then the
matrix power is computed. If False, and ``power`` is a positive integer,
the implementation defaults to ``repeat``.
Returns:
The quantum circuit implementing powers of the unitary.
"""
raise NotImplementedError
|
gadial/qiskit-terra | qiskit/circuit/parametervector.py | <filename>qiskit/circuit/parametervector.py
# 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.
"""Parameter Vector Class to simplify management of parameter lists."""
from uuid import uuid4
from .parameter import Parameter
class ParameterVectorElement(Parameter):
"""An element of a ParameterVector."""
def __new__(cls, vector, index, uuid=None): # pylint:disable=unused-argument
obj = object.__new__(cls)
if uuid is None:
obj._uuid = uuid4()
else:
obj._uuid = uuid
obj._hash = hash(obj._uuid)
return obj
def __getnewargs__(self):
return (self.vector, self.index, self._uuid)
def __init__(self, vector, index):
name = f'{vector.name}[{index}]'
super().__init__(name)
self._vector = vector
self._index = index
@property
def index(self):
"""Get the index of this element in the parent vector."""
return self._index
@property
def vector(self):
"""Get the parent vector instance."""
return self._vector
class ParameterVector:
"""ParameterVector class to quickly generate lists of parameters."""
def __init__(self, name, length=0):
self._name = name
self._params = []
self._size = length
for i in range(length):
self._params += [ParameterVectorElement(self, i)]
@property
def name(self):
"""Returns the name of the ParameterVector."""
return self._name
@property
def params(self):
"""Returns the list of parameters in the ParameterVector."""
return self._params
def index(self, value):
"""Returns first index of value."""
return self._params.index(value)
def __getitem__(self, key):
if isinstance(key, slice):
start, stop, step = key.indices(self._size)
return self.params[start:stop:step]
if key > self._size:
raise IndexError('Index out of range: {} > {}'.format(key, self._size))
return self.params[key]
def __iter__(self):
return iter(self.params[:self._size])
def __len__(self):
return self._size
def __str__(self):
return '{}, {}'.format(self.name, [str(item) for item in self.params[:self._size]])
def __repr__(self):
return '{}(name={}, length={})'.format(self.__class__.__name__, self.name, len(self))
def resize(self, length):
"""Resize the parameter vector.
If necessary, new elements are generated. If length is smaller than before, the
previous elements are cached and not re-generated if the vector is enlarged again.
This is to ensure that the parameter instances do not change.
"""
if length > len(self._params):
for i in range(len(self._params), length):
self._params += [ParameterVectorElement(self, i)]
self._size = length
|
gadial/qiskit-terra | test/python/opflow/test_aer_pauli_expectation.py | <reponame>gadial/qiskit-terra
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" Test AerPauliExpectation """
import itertools
import unittest
from test.python.opflow import QiskitOpflowTestCase
import numpy as np
from qiskit.utils import QuantumInstance
from qiskit.opflow import (X, Y, Z, I, CX, H, S,
ListOp, Zero, One, Plus, Minus, StateFn,
AerPauliExpectation, CircuitSampler, CircuitStateFn,
PauliExpectation)
from qiskit.circuit.library import RealAmplitudes
class TestAerPauliExpectation(QiskitOpflowTestCase):
"""Pauli Change of Basis Expectation tests."""
def setUp(self) -> None:
super().setUp()
try:
from qiskit import Aer
self.seed = 97
self.backend = Aer.get_backend('qasm_simulator')
q_instance = QuantumInstance(self.backend, seed_simulator=self.seed,
seed_transpiler=self.seed)
self.sampler = CircuitSampler(q_instance, attach_results=True)
self.expect = AerPauliExpectation()
except Exception as ex: # pylint: disable=broad-except
self.skipTest("Aer doesn't appear to be installed. Error: '{}'".format(str(ex)))
return
def test_pauli_expect_pair(self):
""" pauli expect pair test """
op = (Z ^ Z)
# wvf = (Pl^Pl) + (Ze^Ze)
wvf = CX @ (H ^ I) @ Zero
converted_meas = self.expect.convert(~StateFn(op) @ wvf)
sampled = self.sampler.convert(converted_meas)
self.assertAlmostEqual(sampled.eval(), 0, delta=.1)
def test_pauli_expect_single(self):
""" pauli expect single test """
# TODO bug in Aer with Y measurements
# paulis = [Z, X, Y, I]
paulis = [Z, X, I]
states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus]
for pauli, state in itertools.product(paulis, states):
converted_meas = self.expect.convert(~StateFn(pauli) @ state)
matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix()
sampled = self.sampler.convert(converted_meas)
self.assertAlmostEqual(sampled.eval(), matmulmean, delta=.1)
def test_pauli_expect_op_vector(self):
""" pauli expect op vector test """
paulis_op = ListOp([X, Y, Z, I])
converted_meas = self.expect.convert(~StateFn(paulis_op))
plus_mean = (converted_meas @ Plus)
sampled_plus = self.sampler.convert(plus_mean)
np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1)
minus_mean = (converted_meas @ Minus)
sampled_minus = self.sampler.convert(minus_mean)
np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1)
zero_mean = (converted_meas @ Zero)
sampled_zero = self.sampler.convert(zero_mean)
np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1)
sum_zero = (Plus + Minus) * (.5 ** .5)
sum_zero_mean = (converted_meas @ sum_zero)
sampled_zero_mean = self.sampler.convert(sum_zero_mean)
# !!NOTE!!: Depolarizing channel (Sampling) means interference
# does not happen between circuits in sum, so expectation does
# not equal expectation for Zero!!
np.testing.assert_array_almost_equal(sampled_zero_mean.eval(), [0, 0, 0, 2], decimal=1)
def test_pauli_expect_state_vector(self):
""" pauli expect state vector test """
states_op = ListOp([One, Zero, Plus, Minus])
paulis_op = X
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
sampled = self.sampler.convert(converted_meas)
# Small test to see if execution results are accessible
for composed_op in sampled:
self.assertIn('counts', composed_op[0].execution_results)
np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1)
def test_pauli_expect_op_vector_state_vector(self):
""" pauli expect op vector state vector test """
# TODO Bug in Aer with Y Measurements!!
# paulis_op = ListOp([X, Y, Z, I])
paulis_op = ListOp([X, Z, I])
states_op = ListOp([One, Zero, Plus, Minus])
valids = [[+0, 0, 1, -1],
# [+0, 0, 0, 0],
[-1, 1, 0, -0],
[+1, 1, 1, 1]]
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
sampled = self.sampler.convert(converted_meas)
np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1)
def test_multi_representation_ops(self):
""" Test observables with mixed representations """
mixed_ops = ListOp([X.to_matrix_op(),
H,
H + I,
X])
converted_meas = self.expect.convert(~StateFn(mixed_ops))
plus_mean = (converted_meas @ Plus)
sampled_plus = self.sampler.convert(plus_mean)
np.testing.assert_array_almost_equal(sampled_plus.eval(),
[1, .5 ** .5, (1 + .5 ** .5), 1],
decimal=1)
def test_parameterized_qobj(self):
""" grouped pauli expectation test """
two_qubit_h2 = (-1.052373245772859 * I ^ I) + \
(0.39793742484318045 * I ^ Z) + \
(-0.39793742484318045 * Z ^ I) + \
(-0.01128010425623538 * Z ^ Z) + \
(0.18093119978423156 * X ^ X)
aer_sampler = CircuitSampler(self.sampler.quantum_instance,
param_qobj=True,
attach_results=True)
ansatz = RealAmplitudes()
ansatz.num_qubits = 2
observable_meas = self.expect.convert(StateFn(two_qubit_h2, is_measurement=True))
ansatz_circuit_op = CircuitStateFn(ansatz)
expect_op = observable_meas.compose(ansatz_circuit_op).reduce()
def generate_parameters(num):
param_bindings = {}
for param in ansatz.parameters:
values = []
for _ in range(num):
values.append(np.random.rand())
param_bindings[param] = values
return param_bindings
def validate_sampler(ideal, sut, param_bindings):
expect_sampled = ideal.convert(expect_op, params=param_bindings).eval()
actual_sampled = sut.convert(expect_op, params=param_bindings).eval()
self.assertAlmostEqual(actual_sampled, expect_sampled, delta=.1)
def get_circuit_templates(sampler):
return sampler._transpiled_circ_templates
def validate_aer_binding_used(templates):
self.assertIsNotNone(templates)
def validate_aer_templates_reused(prev_templates, cur_templates):
self.assertIs(prev_templates, cur_templates)
validate_sampler(self.sampler, aer_sampler, generate_parameters(1))
cur_templates = get_circuit_templates(aer_sampler)
validate_aer_binding_used(cur_templates)
prev_templates = cur_templates
validate_sampler(self.sampler, aer_sampler, generate_parameters(2))
cur_templates = get_circuit_templates(aer_sampler)
validate_aer_templates_reused(prev_templates, cur_templates)
prev_templates = cur_templates
validate_sampler(self.sampler, aer_sampler, generate_parameters(2)) # same num of params
cur_templates = get_circuit_templates(aer_sampler)
validate_aer_templates_reused(prev_templates, cur_templates)
def test_pauli_expectation_param_qobj(self):
""" Test PauliExpectation with param_qobj """
q_instance = QuantumInstance(self.backend, seed_simulator=self.seed,
seed_transpiler=self.seed, shots=10000)
qubit_op = (0.1 * I ^ I) + (0.2 * I ^ Z) + (0.3 * Z ^ I) + (0.4 * Z ^ Z) + (0.5 * X ^ X)
ansatz = RealAmplitudes(qubit_op.num_qubits)
ansatz_circuit_op = CircuitStateFn(ansatz)
observable = PauliExpectation().convert(~StateFn(qubit_op))
expect_op = observable.compose(ansatz_circuit_op).reduce()
params1 = {}
params2 = {}
for param in ansatz.parameters:
params1[param] = [0]
params2[param] = [0, 0]
sampler1 = CircuitSampler(backend=q_instance, param_qobj=False)
samples1 = sampler1.convert(expect_op, params=params1)
val1 = np.real(samples1.eval())[0]
samples2 = sampler1.convert(expect_op, params=params2)
val2 = np.real(samples2.eval())
sampler2 = CircuitSampler(backend=q_instance, param_qobj=True)
samples3 = sampler2.convert(expect_op, params=params1)
val3 = np.real(samples3.eval())
samples4 = sampler2.convert(expect_op, params=params2)
val4 = np.real(samples4.eval())
np.testing.assert_array_almost_equal([val1] * 2, val2, decimal=2)
np.testing.assert_array_almost_equal(val1, val3, decimal=2)
np.testing.assert_array_almost_equal([val1] * 2, val4, decimal=2)
if __name__ == '__main__':
unittest.main()
|
gadial/qiskit-terra | qiskit/opflow/evolutions/evolution_base.py | <filename>qiskit/opflow/evolutions/evolution_base.py
# 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.
""" EvolutionBase Class """
from abc import ABC, abstractmethod
from qiskit.opflow.operator_base import OperatorBase
from qiskit.opflow.converters.converter_base import ConverterBase
class EvolutionBase(ConverterBase, ABC):
r"""
A base for Evolution converters.
Evolutions are converters which traverse an Operator tree, replacing any ``EvolvedOp`` `e`
with a Schrodinger equation-style evolution ``CircuitOp`` equalling or approximating the
matrix exponential of -i * the Operator contained inside (`e.primitive`). The Evolutions are
essentially implementations of Hamiltonian Simulation algorithms, including various methods
for Trotterization.
"""
@abstractmethod
def convert(self, operator: OperatorBase) -> OperatorBase:
""" Traverse the operator, replacing any ``EvolutionOps`` with their equivalent evolution
``CircuitOps``.
Args:
operator: The Operator to convert.
Returns:
The converted Operator, with ``EvolutionOps`` replaced by ``CircuitOps``.
"""
raise NotImplementedError
# TODO @abstractmethod
# def error_bounds(self):
# """ error bounds """
# raise NotImplementedError
|
gadial/qiskit-terra | qiskit/visualization/dag_visualization.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""
Visualization function for DAG circuit representation.
"""
import os
import sys
import tempfile
from .exceptions import VisualizationError
try:
from PIL import Image
HAS_PIL = True
except ImportError:
HAS_PIL = False
def dag_drawer(dag, scale=0.7, filename=None, style='color'):
"""Plot the directed acyclic graph (dag) to represent operation dependencies
in a quantum circuit.
Note this function leverages
`pydot <https://github.com/erocarrera/pydot>`_ to generate the graph, which
means that having `Graphviz <https://www.graphviz.org/>`_ installed on your
system is required for this to work.
The current release of Graphviz can be downloaded here: <https://graphviz.gitlab.io/download/>.
Download the version of the software that matches your environment and follow the instructions
to install Graph Visualization Software (Graphviz) on your operating system.
Args:
dag (DAGCircuit): The dag to draw.
scale (float): scaling factor
filename (str): file path to save image to (format inferred from name)
style (str): 'plain': B&W graph
'color' (default): color input/output/op nodes
Returns:
PIL.Image: if in Jupyter notebook and not saving to file,
otherwise None.
Raises:
VisualizationError: when style is not recognized.
ImportError: when pydot or pillow are not installed.
Example:
.. jupyter-execute::
%matplotlib inline
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.visualization import dag_drawer
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
dag_drawer(dag)
"""
try:
import pydot
except ImportError as ex:
raise ImportError("dag_drawer requires pydot. "
"Run 'pip install pydot'.") from ex
# NOTE: use type str checking to avoid potential cyclical import
# the two tradeoffs ere that it will not handle subclasses and it is
# slower (which doesn't matter for a visualization function)
type_str = str(type(dag))
if 'DAGDependency' in type_str:
graph_attrs = {'dpi': str(100 * scale)}
def node_attr_func(node):
if style == 'plain':
return {}
if style == 'color':
n = {}
n['label'] = str(node.node_id) + ': ' + str(node.name)
if node.name == 'measure':
n['color'] = 'blue'
n['style'] = 'filled'
n['fillcolor'] = 'lightblue'
if node.name == 'barrier':
n['color'] = 'black'
n['style'] = 'filled'
n['fillcolor'] = 'green'
if node.op._directive:
n['color'] = 'black'
n['style'] = 'filled'
n['fillcolor'] = 'red'
if node.op.condition:
n['label'] = str(node.node_id) + ': ' + str(node.name) + ' (conditional)'
n['color'] = 'black'
n['style'] = 'filled'
n['fillcolor'] = 'lightgreen'
return n
else:
raise VisualizationError("Unrecognized style %s for the dag_drawer." % style)
edge_attr_func = None
else:
bit_labels = {bit: "%s[%s]" % (reg.name, idx)
for reg in list(dag.qregs.values()) + list(dag.cregs.values())
for (idx, bit) in enumerate(reg)}
graph_attrs = {'dpi': str(100 * scale)}
def node_attr_func(node):
if style == 'plain':
return {}
if style == 'color':
n = {}
if node.type == 'op':
n['label'] = node.name
n['color'] = 'blue'
n['style'] = 'filled'
n['fillcolor'] = 'lightblue'
if node.type == 'in':
n['label'] = bit_labels[node.wire]
n['color'] = 'black'
n['style'] = 'filled'
n['fillcolor'] = 'green'
if node.type == 'out':
n['label'] = bit_labels[node.wire]
n['color'] = 'black'
n['style'] = 'filled'
n['fillcolor'] = 'red'
return n
else:
raise VisualizationError('Invalid style %s' % style)
def edge_attr_func(edge):
e = {}
e['label'] = bit_labels[edge]
return e
dot_str = dag._multi_graph.to_dot(node_attr_func, edge_attr_func,
graph_attrs)
dot = pydot.graph_from_dot_data(dot_str)[0]
if filename:
extension = filename.split('.')[-1]
dot.write(filename, format=extension)
return None
elif ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
if not HAS_PIL:
raise ImportError(
"dag_drawer requires pillow for drawing in jupyter directly. "
"Run 'pip install pillow'.")
with tempfile.TemporaryDirectory() as tmpdirname:
tmp_path = os.path.join(tmpdirname, 'dag.png')
dot.write_png(tmp_path)
image = Image.open(tmp_path)
os.remove(tmp_path)
return image
else:
if not HAS_PIL:
raise ImportError(
"dag_drawer requires pillow for drawing to a window directly. "
"Run 'pip install pillow'.")
with tempfile.TemporaryDirectory() as tmpdirname:
tmp_path = os.path.join(tmpdirname, 'dag.png')
dot.write_png(tmp_path)
image = Image.open(tmp_path)
image.show()
os.remove(tmp_path)
return None
|
gadial/qiskit-terra | test/python/compiler/test_assembler.py | <reponame>gadial/qiskit-terra
# 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.
"""Assembler Test."""
import unittest
import io
from logging import StreamHandler, getLogger
import sys
import numpy as np
import qiskit.pulse as pulse
from qiskit.circuit import Instruction, Gate, Parameter, ParameterVector
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler.assembler import assemble
from qiskit.exceptions import QiskitError
from qiskit.pulse import Schedule, Acquire, Play
from qiskit.pulse.channels import MemorySlot, AcquireChannel, DriveChannel, MeasureChannel
from qiskit.pulse.configuration import Kernel, Discriminator
from qiskit.pulse.library import gaussian
from qiskit.qobj import QasmQobj, validate_qobj_against_schema
from qiskit.qobj.utils import MeasLevel, MeasReturnType
from qiskit.pulse.macros import measure
from qiskit.test import QiskitTestCase
from qiskit.test.mock import FakeOpenPulse2Q, FakeOpenPulse3Q, FakeYorktown, FakeAlmaden
from qiskit.validation.jsonschema import SchemaValidationError
class RxGate(Gate):
"""Used to test custom gate assembly.
Useful for testing pulse gates with parameters, as well.
Note: Parallel maps (e.g., in assemble_circuits) pickle their input,
so circuit features have to be defined top level.
"""
def __init__(self, theta):
super().__init__('rxtheta', 1, [theta])
class TestCircuitAssembler(QiskitTestCase):
"""Tests for assembling circuits to qobj."""
def setUp(self):
super().setUp()
qr = QuantumRegister(2, name='q')
cr = ClassicalRegister(2, name='c')
self.circ = QuantumCircuit(qr, cr, name='circ')
self.circ.h(qr[0])
self.circ.cx(qr[0], qr[1])
self.circ.measure(qr, cr)
def test_assemble_single_circuit(self):
"""Test assembling a single circuit.
"""
qobj = assemble(self.circ, shots=2000, memory=True)
validate_qobj_against_schema(qobj)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 2000)
self.assertEqual(qobj.config.memory, True)
self.assertEqual(len(qobj.experiments), 1)
self.assertEqual(qobj.experiments[0].instructions[1].name, 'cx')
def test_assemble_multiple_circuits(self):
"""Test assembling multiple circuits, all should have the same config.
"""
qr0 = QuantumRegister(2, name='q0')
qc0 = ClassicalRegister(2, name='c0')
circ0 = QuantumCircuit(qr0, qc0, name='circ0')
circ0.h(qr0[0])
circ0.cx(qr0[0], qr0[1])
circ0.measure(qr0, qc0)
qr1 = QuantumRegister(3, name='q1')
qc1 = ClassicalRegister(3, name='c1')
circ1 = QuantumCircuit(qr1, qc1, name='circ0')
circ1.h(qr1[0])
circ1.cx(qr1[0], qr1[1])
circ1.cx(qr1[0], qr1[2])
circ1.measure(qr1, qc1)
qobj = assemble([circ0, circ1], shots=100, memory=False, seed_simulator=6)
validate_qobj_against_schema(qobj)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.seed_simulator, 6)
self.assertEqual(len(qobj.experiments), 2)
self.assertEqual(qobj.experiments[1].config.n_qubits, 3)
self.assertEqual(len(qobj.experiments), 2)
self.assertEqual(len(qobj.experiments[1].instructions), 6)
def test_assemble_no_run_config(self):
"""Test assembling with no run_config, relying on default.
"""
qobj = assemble(self.circ)
validate_qobj_against_schema(qobj)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 1024)
def test_shots_greater_than_max_shots(self):
"""Test assembling with shots greater than max shots"""
backend = FakeYorktown()
self.assertRaises(QiskitError, assemble, backend, shots=1024000)
def test_shots_not_of_type_int(self):
"""Test assembling with shots having type other than int"""
backend = FakeYorktown()
self.assertRaises(QiskitError, assemble, backend, shots="1024")
def test_default_shots_greater_than_max_shots(self):
"""Test assembling with default shots greater than max shots"""
backend = FakeYorktown()
backend._configuration.max_shots = 5
qobj = assemble(self.circ, backend)
validate_qobj_against_schema(qobj)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 5)
def test_assemble_initialize(self):
"""Test assembling a circuit with an initialize.
"""
q = QuantumRegister(2, name='q')
circ = QuantumCircuit(q, name='circ')
circ.initialize([1/np.sqrt(2), 0, 0, 1/np.sqrt(2)], q[:])
qobj = assemble(circ)
validate_qobj_against_schema(qobj)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.experiments[0].instructions[0].name, 'initialize')
np.testing.assert_almost_equal(qobj.experiments[0].instructions[0].params,
[0.7071067811865, 0, 0, 0.707106781186])
def test_assemble_meas_level_meas_return(self):
"""Test assembling a circuit schedule with `meas_level`."""
qobj = assemble(self.circ,
meas_level=1,
meas_return='single')
validate_qobj_against_schema(qobj)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.meas_level, 1)
self.assertEqual(qobj.config.meas_return, 'single')
# no meas_level set
qobj = assemble(self.circ)
validate_qobj_against_schema(qobj)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.meas_level, 2)
self.assertEqual(hasattr(qobj.config, 'meas_return'), False)
def test_assemble_backend_rep_delays(self):
"""Check that rep_delay is properly set from backend values."""
backend = FakeYorktown()
backend_config = backend.configuration()
rep_delay_range = [2.5e-3, 4.5e-3] # sec
default_rep_delay = 3.0e-3
setattr(backend_config, 'rep_delay_range', rep_delay_range)
setattr(backend_config, 'default_rep_delay', default_rep_delay)
# dynamic rep rates off
setattr(backend_config, 'dynamic_reprate_enabled', False)
qobj = assemble(self.circ, backend)
self.assertEqual(hasattr(qobj.config, 'rep_delay'), False)
# dynamic rep rates on
setattr(backend_config, 'dynamic_reprate_enabled', True)
qobj = assemble(self.circ, backend)
self.assertEqual(qobj.config.rep_delay, default_rep_delay*1e6)
def test_assemble_user_rep_time_delay(self):
"""Check that user runtime config rep_delay works."""
backend = FakeYorktown()
backend_config = backend.configuration()
# set custom rep_delay in runtime config
rep_delay = 2.2e-6
rep_delay_range = [0, 3e-6] # sec
setattr(backend_config, 'rep_delay_range', rep_delay_range)
# dynamic rep rates off (no default so shouldn't be in qobj config)
setattr(backend_config, 'dynamic_reprate_enabled', False)
qobj = assemble(self.circ, backend, rep_delay=rep_delay)
self.assertEqual(hasattr(qobj.config, 'rep_delay'), False)
# turn on dynamic rep rates, rep_delay should be set
setattr(backend_config, 'dynamic_reprate_enabled', True)
qobj = assemble(self.circ, backend, rep_delay=rep_delay)
self.assertEqual(qobj.config.rep_delay, 2.2)
# test ``rep_delay=0``
qobj = assemble(self.circ, backend, rep_delay=0)
self.assertEqual(qobj.config.rep_delay, 0)
# use ``rep_delay`` outside of ``rep_delay_range```
rep_delay_large = 5.0e-6
with self.assertRaises(SchemaValidationError):
assemble(self.circ, backend, rep_delay=rep_delay_large)
def test_assemble_opaque_inst(self):
"""Test opaque instruction is assembled as-is"""
opaque_inst = Instruction(name='my_inst', num_qubits=4,
num_clbits=2, params=[0.5, 0.4])
q = QuantumRegister(6, name='q')
c = ClassicalRegister(4, name='c')
circ = QuantumCircuit(q, c, name='circ')
circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]])
qobj = assemble(circ)
validate_qobj_against_schema(qobj)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(len(qobj.experiments[0].instructions), 1)
self.assertEqual(qobj.experiments[0].instructions[0].name, 'my_inst')
self.assertEqual(qobj.experiments[0].instructions[0].qubits, [0, 2, 5, 3])
self.assertEqual(qobj.experiments[0].instructions[0].memory, [3, 0])
self.assertEqual(qobj.experiments[0].instructions[0].params, [0.5, 0.4])
def test_assemble_unroll_parametervector(self):
"""Verfiy that assemble unrolls parametervectors ref #5467"""
pv1 = ParameterVector('pv1', 3)
pv2 = ParameterVector('pv2', 3)
qc = QuantumCircuit(2, 2)
for i in range(3):
qc.rx(pv1[i], 0)
qc.ry(pv2[i], 1)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.bind_parameters({pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]})
qobj = assemble(qc, parameter_binds=[{pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]}])
validate_qobj_against_schema(qobj)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.experiments[0].instructions[0].params[0], 0.100000000000000)
self.assertEqual(qobj.experiments[0].instructions[1].params[0], 0.400000000000000)
self.assertEqual(qobj.experiments[0].instructions[2].params[0], 0.200000000000000)
self.assertEqual(qobj.experiments[0].instructions[3].params[0], 0.500000000000000)
self.assertEqual(qobj.experiments[0].instructions[4].params[0], 0.300000000000000)
self.assertEqual(qobj.experiments[0].instructions[5].params[0], 0.600000000000000)
def test_measure_to_registers_when_conditionals(self):
"""Verify assemble_circuits maps all measure ops on to a register slot
for a circuit containing conditionals."""
qr = QuantumRegister(2)
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr1, cr2)
qc.measure(qr[0], cr1) # Measure not required for a later conditional
qc.measure(qr[1], cr2[1]) # Measure required for a later conditional
qc.h(qr[1]).c_if(cr2, 3)
qobj = assemble(qc)
validate_qobj_against_schema(qobj)
first_measure, second_measure = [op for op in qobj.experiments[0].instructions
if op.name == 'measure']
self.assertTrue(hasattr(first_measure, 'register'))
self.assertEqual(first_measure.register, first_measure.memory)
self.assertTrue(hasattr(second_measure, 'register'))
self.assertEqual(second_measure.register, second_measure.memory)
def test_convert_to_bfunc_plus_conditional(self):
"""Verify assemble_circuits converts conditionals from QASM to Qobj."""
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr, 1)
qobj = assemble(qc)
validate_qobj_against_schema(qobj)
bfunc_op, h_op = qobj.experiments[0].instructions
self.assertEqual(bfunc_op.name, 'bfunc')
self.assertEqual(bfunc_op.mask, '0x1')
self.assertEqual(bfunc_op.val, '0x1')
self.assertEqual(bfunc_op.relation, '==')
self.assertTrue(hasattr(h_op, 'conditional'))
self.assertEqual(bfunc_op.register, h_op.conditional)
def test_resize_value_to_register(self):
"""Verify assemble_circuits converts the value provided on the classical
creg to its mapped location on the device register."""
qr = QuantumRegister(1)
cr1 = ClassicalRegister(2)
cr2 = ClassicalRegister(2)
cr3 = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr1, cr2, cr3)
qc.h(qr[0]).c_if(cr2, 2)
qobj = assemble(qc)
validate_qobj_against_schema(qobj)
bfunc_op, h_op = qobj.experiments[0].instructions
self.assertEqual(bfunc_op.name, 'bfunc')
self.assertEqual(bfunc_op.mask, '0xC')
self.assertEqual(bfunc_op.val, '0x8')
self.assertEqual(bfunc_op.relation, '==')
self.assertTrue(hasattr(h_op, 'conditional'))
self.assertEqual(bfunc_op.register, h_op.conditional)
def test_assemble_circuits_raises_for_bind_circuit_mismatch(self):
"""Verify assemble_circuits raises error for parameterized circuits without matching
binds."""
qr = QuantumRegister(2)
x = Parameter('x')
y = Parameter('y')
full_bound_circ = QuantumCircuit(qr)
full_param_circ = QuantumCircuit(qr)
partial_param_circ = QuantumCircuit(qr)
partial_param_circ.p(x, qr[0])
full_param_circ.p(x, qr[0])
full_param_circ.p(y, qr[1])
partial_bind_args = {'parameter_binds': [{x: 1}, {x: 0}]}
full_bind_args = {'parameter_binds': [{x: 1, y: 1}, {x: 0, y: 0}]}
inconsistent_bind_args = {'parameter_binds': [{x: 1}, {x: 0, y: 0}]}
# Raise when parameters passed for non-parametric circuit
self.assertRaises(QiskitError, assemble,
full_bound_circ, **partial_bind_args)
# Raise when no parameters passed for parametric circuit
self.assertRaises(QiskitError, assemble, partial_param_circ)
self.assertRaises(QiskitError, assemble, full_param_circ)
# Raise when circuit has more parameters than run_config
self.assertRaises(QiskitError, assemble,
full_param_circ, **partial_bind_args)
# Raise when not all circuits have all parameters
self.assertRaises(QiskitError, assemble,
[full_param_circ, partial_param_circ], **full_bind_args)
# Raise when not all binds have all circuit params
self.assertRaises(QiskitError, assemble,
full_param_circ, **inconsistent_bind_args)
def test_assemble_circuits_rases_for_bind_mismatch_over_expressions(self):
"""Verify assemble_circuits raises for invalid binds for circuit including
ParameterExpressions.
"""
qr = QuantumRegister(1)
x = Parameter('x')
y = Parameter('y')
expr_circ = QuantumCircuit(qr)
expr_circ.p(x+y, qr[0])
partial_bind_args = {'parameter_binds': [{x: 1}, {x: 0}]}
# Raise when no parameters passed for parametric circuit
self.assertRaises(QiskitError, assemble, expr_circ)
# Raise when circuit has more parameters than run_config
self.assertRaises(QiskitError, assemble,
expr_circ, **partial_bind_args)
def test_assemble_circuits_binds_parameters(self):
"""Verify assemble_circuits applies parameter bindings and output circuits are bound."""
qr = QuantumRegister(1)
qc1 = QuantumCircuit(qr)
qc2 = QuantumCircuit(qr)
qc3 = QuantumCircuit(qr)
x = Parameter('x')
y = Parameter('y')
sum_ = x + y
product_ = x * y
qc1.u(x, y, 0, qr[0])
qc2.rz(x, qr[0])
qc2.rz(y, qr[0])
qc3.u(sum_, product_, 0, qr[0])
bind_args = {'parameter_binds': [{x: 0, y: 0},
{x: 1, y: 0},
{x: 1, y: 1}]}
qobj = assemble([qc1, qc2, qc3], **bind_args)
validate_qobj_against_schema(qobj)
self.assertEqual(len(qobj.experiments), 9)
self.assertEqual([len(expt.instructions) for expt in qobj.experiments],
[1, 1, 1, 2, 2, 2, 1, 1, 1])
def _qobj_inst_params(expt_no, inst_no):
expt = qobj.experiments[expt_no]
inst = expt.instructions[inst_no]
return [float(p) for p in inst.params]
self.assertEqual(_qobj_inst_params(0, 0), [0, 0, 0])
self.assertEqual(_qobj_inst_params(1, 0), [1, 0, 0])
self.assertEqual(_qobj_inst_params(2, 0), [1, 1, 0])
self.assertEqual(_qobj_inst_params(3, 0), [0])
self.assertEqual(_qobj_inst_params(3, 1), [0])
self.assertEqual(_qobj_inst_params(4, 0), [1])
self.assertEqual(_qobj_inst_params(4, 1), [0])
self.assertEqual(_qobj_inst_params(5, 0), [1])
self.assertEqual(_qobj_inst_params(5, 1), [1])
self.assertEqual(_qobj_inst_params(6, 0), [0, 0, 0])
self.assertEqual(_qobj_inst_params(7, 0), [1, 0, 0])
self.assertEqual(_qobj_inst_params(8, 0), [2, 1, 0])
def test_init_qubits_default(self):
"""Check that the init_qubits=None assemble option is passed on to the qobj."""
qobj = assemble(self.circ)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_true(self):
"""Check that the init_qubits=True assemble option is passed on to the qobj."""
qobj = assemble(self.circ, init_qubits=True)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_false(self):
"""Check that the init_qubits=False assemble option is passed on to the qobj."""
qobj = assemble(self.circ, init_qubits=False)
self.assertEqual(qobj.config.init_qubits, False)
def test_circuit_with_global_phase(self):
"""Test that global phase for a circuit is handled correctly."""
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.measure_all()
circ.global_phase = .3 * np.pi
qobj = assemble([circ, self.circ])
self.assertEqual(getattr(qobj.experiments[1].header, 'global_phase'),
0)
self.assertEqual(getattr(qobj.experiments[0].header, 'global_phase'),
.3 * np.pi)
def test_circuit_global_phase_gate_definitions(self):
"""Test circuit with global phase on gate definitions."""
class TestGate(Gate):
"""dummy gate"""
def __init__(self):
super().__init__('test_gate', 1, [])
def _define(self):
circ_def = QuantumCircuit(1)
circ_def.x(0)
circ_def.global_phase = np.pi
self._definition = circ_def
gate = TestGate()
circ = QuantumCircuit(1)
circ.append(gate, [0])
qobj = assemble([circ])
self.assertEqual(getattr(qobj.experiments[0].header, 'global_phase'), 0)
circ.global_phase = np.pi / 2
qobj = assemble([circ])
self.assertEqual(getattr(qobj.experiments[0].header, 'global_phase'), np.pi/2)
def test_pulse_gates_single_circ(self):
"""Test that we can add calibrations to circuits."""
theta = Parameter('theta')
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [0])
circ.append(RxGate(theta), [1])
circ = circ.assign_parameters({theta: 3.14})
with pulse.build() as custom_h_schedule:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
with pulse.build() as x180:
pulse.play(pulse.library.Gaussian(50, 0.2, 5), pulse.DriveChannel(1))
circ.add_calibration('h', [0], custom_h_schedule)
circ.add_calibration(RxGate(3.14), [0], x180)
circ.add_calibration(RxGate(3.14), [1], x180)
qobj = assemble(circ, FakeOpenPulse2Q())
# Only one circuit, so everything is stored at the job level
cals = qobj.config.calibrations
lib = qobj.config.pulse_library
self.assertFalse(hasattr(qobj.experiments[0].config, 'calibrations'))
self.assertEqual([gate.name == 'rxtheta' for gate in cals.gates].count(True), 2)
self.assertEqual([gate.name == 'h' for gate in cals.gates].count(True), 1)
self.assertEqual(len(lib), 2)
self.assertTrue(all(len(item.samples) == 50 for item in lib))
def test_pulse_gates_with_parameteric_pulses(self):
"""Test that pulse gates are assembled efficiently for backends that enable
parametric pulses.
"""
with pulse.build() as custom_h_schedule:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.add_calibration('h', [0], custom_h_schedule)
backend = FakeOpenPulse2Q()
backend.configuration().parametric_pulses = ['drag']
qobj = assemble(circ, backend)
self.assertFalse(hasattr(qobj.config, 'pulse_library'))
self.assertTrue(hasattr(qobj.config, 'calibrations'))
def test_pulse_gates_multiple_circuits(self):
"""Test one circuit with cals and another without."""
with pulse.build() as dummy_sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [1])
circ.add_calibration('h', [0], dummy_sched)
circ.add_calibration(RxGate(3.14), [1], dummy_sched)
circ2 = QuantumCircuit(2)
circ2.h(0)
qobj = assemble([circ, circ2], FakeOpenPulse2Q())
self.assertEqual(len(qobj.config.pulse_library), 1)
self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 2)
self.assertFalse(hasattr(qobj.config, 'calibrations'))
self.assertFalse(hasattr(qobj.experiments[1].config, 'calibrations'))
def test_pulse_gates_common_cals(self):
"""Test that common calibrations are added at the top level."""
with pulse.build() as dummy_sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [1])
circ.add_calibration('h', [0], dummy_sched)
circ.add_calibration(RxGate(3.14), [1], dummy_sched)
circ2 = QuantumCircuit(2)
circ2.h(0)
circ2.add_calibration(RxGate(3.14), [1], dummy_sched)
qobj = assemble([circ, circ2], FakeOpenPulse2Q())
# Identical pulses are only added once
self.assertEqual(len(qobj.config.pulse_library), 1)
# Identical calibrations are only added once
self.assertEqual(qobj.config.calibrations.gates[0].name, 'rxtheta')
self.assertEqual(qobj.config.calibrations.gates[0].params, [3.14])
self.assertEqual(qobj.config.calibrations.gates[0].qubits, [1])
self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 1)
self.assertFalse(hasattr(qobj.experiments[1].config, 'calibrations'))
def test_assemble_adds_circuit_metadata_to_experiment_header(self):
"""Verify that any circuit metadata is added to the exeriment header."""
circ = QuantumCircuit(2, metadata=dict(experiment_type="gst", execution_number='1234'))
qobj = assemble(circ, shots=100, memory=False, seed_simulator=6)
self.assertEqual(qobj.experiments[0].header.metadata,
{'experiment_type': 'gst',
'execution_number': '1234'})
def test_pulse_gates_delay_only(self):
"""Test that a single delay gate is translated to an instruction."""
circ = QuantumCircuit(2)
circ.append(Gate('test', 1, []), [0])
test_sched = pulse.Delay(64, DriveChannel(0)) + pulse.Delay(160, DriveChannel(0))
circ.add_calibration('test', [0], test_sched)
qobj = assemble(circ, FakeOpenPulse2Q())
self.assertEqual(len(qobj.config.calibrations.gates[0].instructions), 2)
self.assertEqual(qobj.config.calibrations.gates[0].instructions[1].to_dict(),
{"name": "delay", "t0": 64, "ch": "d0", "duration": 160})
class TestPulseAssembler(QiskitTestCase):
"""Tests for assembling schedules to qobj."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.backend_config = self.backend.configuration()
test_pulse = pulse.Waveform(
samples=np.array([0.02739068, 0.05, 0.05, 0.05, 0.02739068], dtype=np.complex128),
name='pulse0'
)
self.schedule = pulse.Schedule(name='fake_experiment')
self.schedule = self.schedule.insert(0, Play(test_pulse, self.backend_config.drive(0)))
for i in range(self.backend_config.n_qubits):
self.schedule = self.schedule.insert(5, Acquire(5,
self.backend_config.acquire(i),
MemorySlot(i)))
self.user_lo_config_dict = {self.backend_config.drive(0): 4.91e9}
self.user_lo_config = pulse.LoConfig(self.user_lo_config_dict)
self.default_qubit_lo_freq = [4.9e9, 5.0e9]
self.default_meas_lo_freq = [6.5e9, 6.6e9]
self.config = {
'meas_level': 1,
'memory_slot_size': 100,
'meas_return': 'avg'
}
self.header = {
'backend_name': 'FakeOpenPulse2Q',
'backend_version': '0.0.0'
}
def test_assemble_adds_schedule_metadata_to_experiment_header(self):
"""Verify that any circuit metadata is added to the exeriment header."""
self.schedule.metadata = {'experiment_type': 'gst', 'execution_number': '1234'}
qobj = assemble(self.schedule, shots=100, qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[])
self.assertEqual(qobj.experiments[0].header.metadata,
{'experiment_type': 'gst',
'execution_number': '1234'})
def test_assemble_sample_pulse(self):
"""Test that the pulse lib and qobj instruction can be paired up."""
schedule = pulse.Schedule()
schedule += pulse.Play(pulse.Waveform([0.1]*16, name='test0'),
pulse.DriveChannel(0),
name='test1')
schedule += pulse.Play(pulse.Waveform([0.1]*16, name='test1'),
pulse.DriveChannel(0),
name='test2')
schedule += pulse.Play(pulse.Waveform([0.5]*16, name='test0'),
pulse.DriveChannel(0),
name='test1')
qobj = assemble(schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config)
validate_qobj_against_schema(qobj)
test_dict = qobj.to_dict()
experiment = test_dict['experiments'][0]
inst0_name = experiment['instructions'][0]['name']
inst1_name = experiment['instructions'][1]['name']
inst2_name = experiment['instructions'][2]['name']
pulses = {}
for item in test_dict['config']['pulse_library']:
pulses[item['name']] = item['samples']
self.assertTrue(all(name in pulses for name in [inst0_name, inst1_name, inst2_name]))
# Their pulses are the same
self.assertEqual(inst0_name, inst1_name)
self.assertTrue(np.allclose(pulses[inst0_name], [0.1]*16))
self.assertTrue(np.allclose(pulses[inst2_name], [0.5]*16))
def test_assemble_single_schedule_without_lo_config(self):
"""Test assembling a single schedule, no lo config."""
qobj = assemble(self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config)
validate_qobj_against_schema(qobj)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict['config']['qubit_lo_freq'], [4.9, 5.0])
self.assertEqual(len(test_dict['experiments']), 1)
self.assertEqual(len(test_dict['experiments'][0]['instructions']), 2)
def test_assemble_multi_schedules_without_lo_config(self):
"""Test assembling schedules, no lo config."""
qobj = assemble([self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
**self.config)
validate_qobj_against_schema(qobj)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict['config']['qubit_lo_freq'], [4.9, 5.0])
self.assertEqual(len(test_dict['experiments']), 2)
self.assertEqual(len(test_dict['experiments'][0]['instructions']), 2)
def test_assemble_single_schedule_with_lo_config(self):
"""Test assembling a single schedule, with a single lo config."""
qobj = assemble(self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config,
**self.config)
validate_qobj_against_schema(qobj)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict['config']['qubit_lo_freq'], [4.91, 5.0])
self.assertEqual(len(test_dict['experiments']), 1)
self.assertEqual(len(test_dict['experiments'][0]['instructions']), 2)
def test_assemble_single_schedule_with_lo_config_dict(self):
"""Test assembling a single schedule, with a single lo config supplied as dictionary."""
qobj = assemble(self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config_dict,
**self.config)
validate_qobj_against_schema(qobj)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict['config']['qubit_lo_freq'], [4.91, 5.0])
self.assertEqual(len(test_dict['experiments']), 1)
self.assertEqual(len(test_dict['experiments'][0]['instructions']), 2)
def test_assemble_single_schedule_with_multi_lo_configs(self):
"""Test assembling a single schedule, with lo configs (frequency sweep)."""
qobj = assemble(self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict['config']['qubit_lo_freq'], [4.9, 5.0])
self.assertEqual(len(test_dict['experiments']), 2)
self.assertEqual(len(test_dict['experiments'][0]['instructions']), 2)
self.assertDictEqual(test_dict['experiments'][0]['config'],
{'qubit_lo_freq': [4.91, 5.0]})
def test_assemble_multi_schedules_with_multi_lo_configs(self):
"""Test assembling schedules, with the same number of lo configs (n:n setup)."""
qobj = assemble([self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config)
validate_qobj_against_schema(qobj)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict['config']['qubit_lo_freq'], [4.9, 5.0])
self.assertEqual(len(test_dict['experiments']), 2)
self.assertEqual(len(test_dict['experiments'][0]['instructions']), 2)
self.assertDictEqual(test_dict['experiments'][0]['config'],
{'qubit_lo_freq': [4.91, 5.0]})
def test_assemble_multi_schedules_with_wrong_number_of_multi_lo_configs(self):
"""Test assembling schedules, with a different number of lo configs (n:m setup)."""
with self.assertRaises(QiskitError):
assemble([self.schedule, self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config)
def test_assemble_meas_map(self):
"""Test assembling a single schedule, no lo config."""
schedule = Schedule(name='fake_experiment')
schedule = schedule.insert(5, Acquire(5, AcquireChannel(0), MemorySlot(0)))
schedule = schedule.insert(5, Acquire(5, AcquireChannel(1), MemorySlot(1)))
qobj = assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]])
validate_qobj_against_schema(qobj)
assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]])
validate_qobj_against_schema(qobj)
def test_assemble_memory_slots(self):
"""Test assembling a schedule and inferring number of memoryslots."""
n_memoryslots = 10
# single acquisition
schedule = Acquire(5,
self.backend_config.acquire(0),
mem_slot=pulse.MemorySlot(n_memoryslots-1))
qobj = assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]])
validate_qobj_against_schema(qobj)
self.assertEqual(qobj.config.memory_slots, n_memoryslots)
# this should be in experimental header as well
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots)
# multiple acquisition
schedule = Acquire(5, self.backend_config.acquire(0),
mem_slot=pulse.MemorySlot(n_memoryslots-1))
schedule = schedule.insert(10, Acquire(5, self.backend_config.acquire(0),
mem_slot=pulse.MemorySlot(n_memoryslots-1)))
qobj = assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]])
validate_qobj_against_schema(qobj)
self.assertEqual(qobj.config.memory_slots, n_memoryslots)
# this should be in experimental header as well
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots)
def test_assemble_memory_slots_for_schedules(self):
"""Test assembling schedules with different memory slots."""
n_memoryslots = [10, 5, 7]
schedules = []
for n_memoryslot in n_memoryslots:
schedule = Acquire(5, self.backend_config.acquire(0),
mem_slot=pulse.MemorySlot(n_memoryslot-1))
schedules.append(schedule)
qobj = assemble(schedules,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]])
validate_qobj_against_schema(qobj)
self.assertEqual(qobj.config.memory_slots, max(n_memoryslots))
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots[0])
self.assertEqual(qobj.experiments[1].header.memory_slots, n_memoryslots[1])
self.assertEqual(qobj.experiments[2].header.memory_slots, n_memoryslots[2])
def test_pulse_name_conflicts(self):
"""Test that pulse name conflicts can be resolved."""
name_conflict_pulse = pulse.Waveform(
samples=np.array([0.02, 0.05, 0.05, 0.05, 0.02], dtype=np.complex128),
name='pulse0'
)
self.schedule = self.schedule.insert(1, Play(name_conflict_pulse,
self.backend_config.drive(1)))
qobj = assemble(self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config)
validate_qobj_against_schema(qobj)
self.assertNotEqual(qobj.config.pulse_library[0].name,
qobj.config.pulse_library[1].name)
def test_pulse_name_conflicts_in_other_schedule(self):
"""Test two pulses with the same name in different schedule can be resolved."""
backend = FakeAlmaden()
schedules = []
ch_d0 = pulse.DriveChannel(0)
for amp in (0.1, 0.2):
sched = Schedule()
sched += Play(gaussian(duration=100, amp=amp, sigma=30, name='my_pulse'), ch_d0)
sched += measure(qubits=[0], backend=backend) << 100
schedules.append(sched)
qobj = assemble(schedules, backend)
# two user pulses and one measurement pulse should be contained
self.assertEqual(len(qobj.config.pulse_library), 3)
def test_assemble_with_delay(self):
"""Test that delay instruction is not ignored in assembly."""
delay_schedule = pulse.Delay(10, self.backend_config.drive(0))
delay_schedule += self.schedule
delay_qobj = assemble(delay_schedule, self.backend)
validate_qobj_against_schema(delay_qobj)
self.assertEqual(delay_qobj.experiments[0].instructions[0].name, "delay")
self.assertEqual(delay_qobj.experiments[0].instructions[0].duration, 10)
self.assertEqual(delay_qobj.experiments[0].instructions[0].t0, 0)
def test_delay_removed_on_acq_ch(self):
"""Test that delay instructions on acquire channels are skipped on assembly with times
shifted properly.
"""
delay0 = pulse.Delay(5, self.backend_config.acquire(0))
delay1 = pulse.Delay(7, self.backend_config.acquire(1))
sched0 = delay0
sched0 += self.schedule # includes ``Acquire`` instr
sched0 += delay1
sched1 = self.schedule # includes ``Acquire`` instr
sched1 += delay0
sched1 += delay1
sched2 = delay0
sched2 += delay1
sched2 += self.schedule # includes ``Acquire`` instr
delay_qobj = assemble([sched0, sched1, sched2], self.backend)
validate_qobj_against_schema(delay_qobj)
# check that no delay instrs occur on acquire channels
is_acq_delay = False
for exp in delay_qobj.experiments:
for instr in exp.instructions:
if instr.name == "delay" and "a" in instr.ch:
is_acq_delay = True
self.assertFalse(is_acq_delay)
# check that acquire instr are shifted from ``t0=5`` as needed
self.assertEqual(delay_qobj.experiments[0].instructions[1].t0, 10)
self.assertEqual(delay_qobj.experiments[0].instructions[1].name, "acquire")
self.assertEqual(delay_qobj.experiments[1].instructions[1].t0, 5)
self.assertEqual(delay_qobj.experiments[1].instructions[1].name, "acquire")
self.assertEqual(delay_qobj.experiments[2].instructions[1].t0, 12)
self.assertEqual(delay_qobj.experiments[2].instructions[1].name, "acquire")
def test_assemble_schedule_enum(self):
"""Test assembling a schedule with enum input values to assemble."""
qobj = assemble(self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
meas_level=MeasLevel.CLASSIFIED,
meas_return=MeasReturnType.AVERAGE)
validate_qobj_against_schema(qobj)
test_dict = qobj.to_dict()
self.assertEqual(test_dict['config']['meas_return'], 'avg')
self.assertEqual(test_dict['config']['meas_level'], 2)
def test_assemble_parametric(self):
"""Test that parametric pulses can be assembled properly into a PulseQobj."""
sched = pulse.Schedule(name='test_parametric')
sched += Play(pulse.Gaussian(duration=25, sigma=4, amp=0.5j), DriveChannel(0))
sched += Play(pulse.Drag(duration=25, amp=0.2+0.3j, sigma=7.8, beta=4), DriveChannel(1))
sched += Play(pulse.Constant(duration=25, amp=1), DriveChannel(2))
sched += Play(pulse.GaussianSquare(duration=150, amp=0.2,
sigma=8, width=140), MeasureChannel(0)) << sched.duration
backend = FakeOpenPulse3Q()
backend.configuration().parametric_pulses = ['gaussian', 'drag',
'gaussian_square', 'constant']
qobj = assemble(sched, backend)
self.assertEqual(qobj.config.pulse_library, [])
qobj_insts = qobj.experiments[0].instructions
self.assertTrue(all(inst.name == 'parametric_pulse'
for inst in qobj_insts))
self.assertEqual(qobj_insts[0].pulse_shape, 'gaussian')
self.assertEqual(qobj_insts[1].pulse_shape, 'drag')
self.assertEqual(qobj_insts[2].pulse_shape, 'constant')
self.assertEqual(qobj_insts[3].pulse_shape, 'gaussian_square')
self.assertDictEqual(qobj_insts[0].parameters, {'duration': 25, 'sigma': 4, 'amp': 0.5j})
self.assertDictEqual(qobj_insts[1].parameters,
{'duration': 25, 'sigma': 7.8, 'amp': 0.2+0.3j, 'beta': 4})
self.assertDictEqual(qobj_insts[2].parameters, {'duration': 25, 'amp': 1})
self.assertDictEqual(qobj_insts[3].parameters,
{'duration': 150, 'sigma': 8, 'amp': 0.2, 'width': 140})
self.assertEqual(
qobj.to_dict()['experiments'][0]['instructions'][0]['parameters']['amp'],
0.5j)
def test_assemble_parametric_unsupported(self):
"""Test that parametric pulses are translated to Waveform if they're not supported
by the backend during assemble time.
"""
sched = pulse.Schedule(name='test_parametric_to_sample_pulse')
sched += Play(pulse.Drag(duration=25, amp=0.2+0.3j, sigma=7.8, beta=4), DriveChannel(1))
sched += Play(pulse.Constant(duration=25, amp=1), DriveChannel(2))
backend = FakeOpenPulse3Q()
backend.configuration().parametric_pulses = ['something_extra']
qobj = assemble(sched, backend)
self.assertNotEqual(qobj.config.pulse_library, [])
qobj_insts = qobj.experiments[0].instructions
self.assertFalse(hasattr(qobj_insts[0], 'pulse_shape'))
def test_init_qubits_default(self):
"""Check that the init_qubits=None assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_true(self):
"""Check that the init_qubits=True assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend, init_qubits=True)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_false(self):
"""Check that the init_qubits=False assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend, init_qubits=False)
self.assertEqual(qobj.config.init_qubits, False)
def test_assemble_backend_rep_times_delays(self):
"""Check that rep_time and rep_delay are properly set from backend values."""
# use first entry from allowed backend values
rep_times = [2.0, 3.0, 4.0] # sec
rep_delay_range = [2.5e-3, 4.5e-3]
default_rep_delay = 3.0e-3
self.backend_config.rep_times = rep_times
setattr(self.backend_config, 'rep_delay_range', rep_delay_range)
setattr(self.backend_config, 'default_rep_delay', default_rep_delay)
# dynamic rep rates off
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.rep_time, int(rep_times[0]*1e6))
self.assertEqual(hasattr(qobj.config, 'rep_delay'), False)
# dynamic rep rates on
setattr(self.backend_config, 'dynamic_reprate_enabled', True)
# RuntimeWarning bc ``rep_time`` is specified`` when dynamic rep rates not enabled
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.rep_time, int(rep_times[0]*1e6))
self.assertEqual(qobj.config.rep_delay, default_rep_delay*1e6)
def test_assemble_user_rep_time_delay(self):
"""Check that user runtime config rep_time and rep_delay work."""
# set custom rep_time and rep_delay in runtime config
rep_time = 200.0e-6
rep_delay = 2.5e-6
self.config['rep_time'] = rep_time
self.config['rep_delay'] = rep_delay
# dynamic rep rates off
# RuntimeWarning bc using ``rep_delay`` when dynamic rep rates off
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_time*1e6))
self.assertEqual(hasattr(qobj.config, 'rep_delay'), False)
# now remove rep_delay and enable dynamic rep rates
# RuntimeWarning bc using ``rep_time`` when dynamic rep rates are enabled
del self.config['rep_delay']
setattr(self.backend_config, 'dynamic_reprate_enabled', True)
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_time*1e6))
self.assertEqual(hasattr(qobj.config, 'rep_delay'), False)
# use ``default_rep_delay``
# ``rep_time`` comes from allowed backend rep_times
rep_times = [0.5, 1.0, 1.5] # sec
self.backend_config.rep_times = rep_times
setattr(self.backend_config, 'rep_delay_range', [0, 3.0e-6])
setattr(self.backend_config, 'default_rep_delay', 2.2e-6)
del self.config['rep_time']
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_times[0]*1e6))
self.assertEqual(qobj.config.rep_delay, 2.2)
# use qobj ``default_rep_delay``
self.config['rep_delay'] = 1.5e-6
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_times[0]*1e6))
self.assertEqual(qobj.config.rep_delay, 1.5)
# use ``rep_delay`` outside of ``rep_delay_range
self.config['rep_delay'] = 5.0e-6
with self.assertRaises(SchemaValidationError):
assemble(self.schedule, self.backend, **self.config)
def test_assemble_with_individual_discriminators(self):
"""Test that assembly works with individual discriminators."""
disc_one = Discriminator('disc_one', test_params=True)
disc_two = Discriminator('disc_two', test_params=False)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two),
)
qobj = assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]])
validate_qobj_against_schema(qobj)
qobj_discriminators = qobj.experiments[0].instructions[0].discriminators
self.assertEqual(len(qobj_discriminators), 2)
self.assertEqual(qobj_discriminators[0].name, 'disc_one')
self.assertEqual(qobj_discriminators[0].params['test_params'], True)
self.assertEqual(qobj_discriminators[1].name, 'disc_two')
self.assertEqual(qobj_discriminators[1].params['test_params'], False)
def test_assemble_with_single_discriminators(self):
"""Test that assembly works with both a single discriminator."""
disc_one = Discriminator('disc_one', test_params=True)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
qobj = assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]])
validate_qobj_against_schema(qobj)
qobj_discriminators = qobj.experiments[0].instructions[0].discriminators
self.assertEqual(len(qobj_discriminators), 1)
self.assertEqual(qobj_discriminators[0].name, 'disc_one')
self.assertEqual(qobj_discriminators[0].params['test_params'], True)
def test_assemble_with_unequal_discriminators(self):
"""Test that assembly works with incorrect number of discriminators for
number of qubits."""
disc_one = Discriminator('disc_one', test_params=True)
disc_two = Discriminator('disc_two', test_params=False)
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one)
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two)
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2))
with self.assertRaises(QiskitError):
assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]])
def test_assemble_with_individual_kernels(self):
"""Test that assembly works with individual kernels."""
disc_one = Kernel('disc_one', test_params=True)
disc_two = Kernel('disc_two', test_params=False)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two),
)
qobj = assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]])
validate_qobj_against_schema(qobj)
qobj_kernels = qobj.experiments[0].instructions[0].kernels
self.assertEqual(len(qobj_kernels), 2)
self.assertEqual(qobj_kernels[0].name, 'disc_one')
self.assertEqual(qobj_kernels[0].params['test_params'], True)
self.assertEqual(qobj_kernels[1].name, 'disc_two')
self.assertEqual(qobj_kernels[1].params['test_params'], False)
def test_assemble_with_single_kernels(self):
"""Test that assembly works with both a single kernel."""
disc_one = Kernel('disc_one', test_params=True)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
qobj = assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]])
validate_qobj_against_schema(qobj)
qobj_kernels = qobj.experiments[0].instructions[0].kernels
self.assertEqual(len(qobj_kernels), 1)
self.assertEqual(qobj_kernels[0].name, 'disc_one')
self.assertEqual(qobj_kernels[0].params['test_params'], True)
def test_assemble_with_unequal_kernels(self):
"""Test that assembly works with incorrect number of discriminators for
number of qubits."""
disc_one = Kernel('disc_one', test_params=True)
disc_two = Kernel('disc_two', test_params=False)
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one)
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two)
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2))
with self.assertRaises(QiskitError):
assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]])
def test_assemble_single_instruction(self):
"""Test assembling schedules, no lo config."""
inst = pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0))
qobj = assemble(inst, self.backend)
validate_qobj_against_schema(qobj)
def test_assemble_overlapping_time(self):
"""Test that assembly errors when qubits are measured in overlapping time."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1,
)
with self.assertRaises(QiskitError):
assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]])
def test_assemble_meas_map_vs_insts(self):
"""Test that assembly errors when the qubits are measured in overlapping time
and qubits are not in the first meas_map list."""
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0))
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1))
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2)) << 2
schedule += Acquire(5, AcquireChannel(3), MemorySlot(3)) << 2
with self.assertRaises(QiskitError):
assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1, 2], [3]])
def test_assemble_non_overlapping_time_single_meas_map(self):
"""Test that assembly works when qubits are measured in non-overlapping
time within the same measurement map list."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 5,
)
qobj = assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]])
validate_qobj_against_schema(qobj)
def test_assemble_disjoint_time(self):
"""Test that assembly works when qubits are in disjoint meas map sets."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1,
)
qobj = assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 2], [1, 3]])
validate_qobj_against_schema(qobj)
def test_assemble_valid_qubits(self):
"""Test that assembly works when qubits that are in the measurement map
is measured."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(2), MemorySlot(2)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(3), MemorySlot(3)),
)
qobj = assemble(schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2], [3]])
validate_qobj_against_schema(qobj)
class TestPulseAssemblerMissingKwargs(QiskitTestCase):
"""Verify that errors are raised in case backend is not provided and kwargs are missing."""
def setUp(self):
super().setUp()
self.schedule = pulse.Schedule(name='fake_experiment')
self.backend = FakeOpenPulse2Q()
self.config = self.backend.configuration()
self.defaults = self.backend.defaults()
self.qubit_lo_freq = list(self.defaults.qubit_freq_est)
self.meas_lo_freq = list(self.defaults.meas_freq_est)
self.qubit_lo_range = self.config.qubit_lo_range
self.meas_lo_range = self.config.meas_lo_range
self.schedule_los = {pulse.DriveChannel(0): self.qubit_lo_freq[0],
pulse.DriveChannel(1): self.qubit_lo_freq[1],
pulse.MeasureChannel(0): self.meas_lo_freq[0],
pulse.MeasureChannel(1): self.meas_lo_freq[1]}
self.meas_map = self.config.meas_map
self.memory_slots = self.config.n_qubits
# default rep_time and rep_delay
self.rep_time = self.config.rep_times[0]
self.rep_delay = None
def test_defaults(self):
"""Test defaults work."""
qobj = assemble(self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay)
validate_qobj_against_schema(qobj)
def test_missing_qubit_lo_freq(self):
"""Test error raised if qubit_lo_freq missing."""
with self.assertRaises(QiskitError):
assemble(self.schedule,
qubit_lo_freq=None,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay)
def test_missing_meas_lo_freq(self):
"""Test error raised if meas_lo_freq missing."""
with self.assertRaises(QiskitError):
assemble(self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=None,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay)
def test_missing_memory_slots(self):
"""Test error is not raised if memory_slots are missing."""
qobj = assemble(self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=None,
rep_time=self.rep_time,
rep_delay=self.rep_delay)
validate_qobj_against_schema(qobj)
def test_missing_rep_time_and_delay(self):
"""Test qobj is valid if rep_time and rep_delay are missing."""
qobj = assemble(self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=None,
rep_time=None,
rep_delay=None)
validate_qobj_against_schema(qobj)
self.assertEqual(hasattr(qobj, 'rep_time'), False)
self.assertEqual(hasattr(qobj, 'rep_delay'), False)
def test_missing_meas_map(self):
"""Test that assembly still works if meas_map is missing."""
qobj = assemble(self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=None,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay)
validate_qobj_against_schema(qobj)
def test_missing_lo_ranges(self):
"""Test that assembly still works if lo_ranges are missing."""
qobj = assemble(self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=None,
meas_lo_range=None,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay)
validate_qobj_against_schema(qobj)
def test_unsupported_meas_level(self):
"""Test that assembly raises an error if meas_level is not supported"""
backend = FakeOpenPulse2Q()
backend.configuration().meas_levels = [1, 2]
with self.assertRaises(SchemaValidationError):
assemble(self.schedule,
backend,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_level=0,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay)
def test_single_and_deprecated_acquire_styles(self):
"""Test that acquires are identically combined with Acquires that take a single channel."""
backend = FakeOpenPulse2Q()
new_style_schedule = Schedule()
acq_dur = 1200
for i in range(2):
new_style_schedule += Acquire(acq_dur, AcquireChannel(i), MemorySlot(i))
deprecated_style_schedule = Schedule()
for i in range(2):
deprecated_style_schedule += Acquire(1200, AcquireChannel(i), MemorySlot(i))
# The Qobj IDs will be different
n_qobj = assemble(new_style_schedule, backend)
n_qobj.qobj_id = None
n_qobj.experiments[0].header.name = None
d_qobj = assemble(deprecated_style_schedule, backend)
d_qobj.qobj_id = None
d_qobj.experiments[0].header.name = None
self.assertEqual(n_qobj, d_qobj)
assembled_acquire = n_qobj.experiments[0].instructions[0]
self.assertEqual(assembled_acquire.qubits, [0, 1])
self.assertEqual(assembled_acquire.memory_slot, [0, 1])
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestLogAssembler(QiskitTestCase):
"""Testing the log_assembly option."""
def setUp(self):
super().setUp()
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel('DEBUG')
self.output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.output))
self.circuit = QuantumCircuit(QuantumRegister(1))
def assertAssembleLog(self, log_msg):
""" Runs assemble and checks for logs containing specified message"""
assemble(self.circuit, shots=2000, memory=True)
self.output.seek(0)
# Filter unrelated log lines
output_lines = self.output.readlines()
assembly_log_lines = [x for x in output_lines if log_msg in x]
self.assertTrue(len(assembly_log_lines) == 1)
def test_assembly_log_time(self):
"""Check Total Assembly Time is logged"""
self.assertAssembleLog('Total Assembly Time')
if __name__ == '__main__':
unittest.main(verbosity=2)
|
gadial/qiskit-terra | qiskit/transpiler/passes/optimization/remove_diagonal_gates_before_measure.py | <filename>qiskit/transpiler/passes/optimization/remove_diagonal_gates_before_measure.py
# 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.
"""Remove diagonal gates (including diagonal 2Q gates) before a measurement."""
from qiskit.circuit import Measure
from qiskit.circuit.library.standard_gates import RZGate, ZGate, TGate, SGate, TdgGate, SdgGate, \
U1Gate, CZGate, CRZGate, CU1Gate, RZZGate
from qiskit.transpiler.basepasses import TransformationPass
class RemoveDiagonalGatesBeforeMeasure(TransformationPass):
"""Remove diagonal gates (including diagonal 2Q gates) before a measurement.
Transpiler pass to remove diagonal gates (like RZ, T, Z, etc) before
a measurement. Including diagonal 2Q gates.
"""
def run(self, dag):
"""Run the RemoveDiagonalGatesBeforeMeasure pass on `dag`.
Args:
dag (DAGCircuit): the DAG to be optimized.
Returns:
DAGCircuit: the optimized DAG.
"""
diagonal_1q_gates = (RZGate, ZGate, TGate, SGate, TdgGate, SdgGate, U1Gate)
diagonal_2q_gates = (CZGate, CRZGate, CU1Gate, RZZGate)
nodes_to_remove = set()
for measure in dag.op_nodes(Measure):
predecessor = next(dag.quantum_predecessors(measure))
if predecessor.type == 'op' and isinstance(predecessor.op, diagonal_1q_gates):
nodes_to_remove.add(predecessor)
if predecessor.type == 'op' and isinstance(predecessor.op, diagonal_2q_gates):
successors = dag.quantum_successors(predecessor)
if all(s.type == 'op' and isinstance(s.op, Measure) for s in successors):
nodes_to_remove.add(predecessor)
for node_to_remove in nodes_to_remove:
dag.remove_op_node(node_to_remove)
return dag
|
gadial/qiskit-terra | qiskit/algorithms/linear_solvers/numpy_linear_solver.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""The Numpy LinearSolver algorithm (classical)."""
from typing import List, Union, Optional, Callable
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator, Statevector
from qiskit.quantum_info.operators.base_operator import BaseOperator
from .linear_solver import LinearSolverResult, LinearSolver
from .observables.linear_system_observable import LinearSystemObservable
class NumPyLinearSolver(LinearSolver):
"""The Numpy Linear Solver algorithm (classical).
This linear system solver computes the exact value of the given observable(s) or the full
solution vector if no observable is specified.
Examples:
.. jupyter-execute::
import numpy as np
from qiskit.algorithms import NumPyLinearSolver
from qiskit.algorithms.linear_solvers.matrices import TridiagonalToeplitz
from qiskit.algorithms.linear_solvers.observables import MatrixFunctional
matrix = TridiagonalToeplitz(2, 1, 1 / 3, trotter_steps=2)
right_hand_side = [1.0, -2.1, 3.2, -4.3]
observable = MatrixFunctional(1, 1 / 2)
rhs = right_hand_side / np.linalg.norm(right_hand_side)
np_solver = NumPyLinearSolver()
solution = np_solver.solve(matrix, rhs, observable)
result = solution.observable
"""
def solve(self, matrix: Union[np.ndarray, QuantumCircuit],
vector: Union[np.ndarray, QuantumCircuit],
observable: Optional[Union[LinearSystemObservable, BaseOperator,
List[BaseOperator]]] = None,
observable_circuit: Optional[Union[QuantumCircuit, List[QuantumCircuit]]] = None,
post_processing: Optional[Callable[[Union[float, List[float]]],
Union[float, List[float]]]] = None) \
-> LinearSolverResult:
"""Solve classically the linear system and compute the observable(s)
Args:
matrix: The matrix specifying the system, i.e. A in Ax=b.
vector: The vector specifying the right hand side of the equation in Ax=b.
observable: Optional information to be extracted from the solution.
Default is the probability of success of the algorithm.
observable_circuit: Optional circuit to be applied to the solution to extract
information. Default is ``None``.
post_processing: Optional function to compute the value of the observable.
Default is the raw value of measuring the observable.
Returns:
The result of the linear system.
"""
# Check if either matrix or vector are QuantumCircuits and get the array from them
if isinstance(vector, QuantumCircuit):
vector = Statevector(vector).data
if isinstance(matrix, QuantumCircuit):
if hasattr(matrix, "matrix"):
matrix = matrix.matrix
else:
matrix = Operator(matrix).data
solution_vector = np.linalg.solve(matrix, vector)
solution = LinearSolverResult()
solution.state = solution_vector
if observable is not None:
if isinstance(observable, list):
solution.observable = []
for obs in observable:
solution.observable.append(obs.evaluate_classically(solution_vector))
else:
solution.observable = observable.evaluate_classically(solution_vector)
solution.euclidean_norm = np.linalg.norm(solution_vector)
return solution
|
gadial/qiskit-terra | test/python/algorithms/optimizers/test_optimizer_aqgd.py | <gh_stars>1-10
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, 2021
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" Test of AQGD optimizer """
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from qiskit import Aer
from qiskit.circuit.library import RealAmplitudes
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.opflow import PauliSumOp
from qiskit.algorithms.optimizers import AQGD
from qiskit.algorithms import VQE, AlgorithmError
from qiskit.opflow.gradients import Gradient
from qiskit.test import slow_test
@unittest.skipUnless(Aer, 'Aer is required to run these tests')
class TestOptimizerAQGD(QiskitAlgorithmsTestCase):
""" Test AQGD optimizer using RY for analytic gradient with VQE """
def setUp(self):
super().setUp()
self.seed = 50
algorithm_globals.random_seed = self.seed
self.qubit_op = PauliSumOp.from_list([
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
])
@slow_test
def test_simple(self):
""" test AQGD optimizer with the parameters as single values."""
q_instance = QuantumInstance(Aer.get_backend('statevector_simulator'),
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed)
aqgd = AQGD(momentum=0.0)
vqe = VQE(ansatz=RealAmplitudes(),
optimizer=aqgd,
gradient=Gradient('fin_diff'),
quantum_instance=q_instance)
result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op)
self.assertAlmostEqual(result.eigenvalue.real, -1.857, places=3)
def test_list(self):
""" test AQGD optimizer with the parameters as lists. """
q_instance = QuantumInstance(Aer.get_backend('statevector_simulator'),
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed)
aqgd = AQGD(maxiter=[1000, 1000, 1000], eta=[1.0, 0.5, 0.3], momentum=[0.0, 0.5, 0.75])
vqe = VQE(ansatz=RealAmplitudes(),
optimizer=aqgd,
quantum_instance=q_instance)
result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op)
self.assertAlmostEqual(result.eigenvalue.real, -1.857, places=3)
def test_raises_exception(self):
""" tests that AQGD raises an exception when incorrect values are passed. """
self.assertRaises(AlgorithmError, AQGD, maxiter=[1000], eta=[1.0, 0.5], momentum=[0.0, 0.5])
@slow_test
def test_int_values(self):
""" test AQGD with int values passed as eta and momentum. """
q_instance = QuantumInstance(Aer.get_backend('statevector_simulator'),
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed)
aqgd = AQGD(maxiter=1000, eta=1, momentum=0)
vqe = VQE(ansatz=RealAmplitudes(),
optimizer=aqgd,
gradient=Gradient('lin_comb'),
quantum_instance=q_instance)
result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op)
self.assertAlmostEqual(result.eigenvalue.real, -1.857, places=3)
if __name__ == '__main__':
unittest.main()
|
gadial/qiskit-terra | test/python/tools/monitor/test_job_monitor.py | # 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.
"""Tests for the wrapper functionality."""
import io
import unittest
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import BasicAer
from qiskit import execute
from qiskit.tools.monitor import job_monitor
from qiskit.test import QiskitTestCase
class TestJobMonitor(QiskitTestCase):
"""Tools test case."""
def test_job_monitor(self):
"""Test job_monitor"""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
qc = QuantumCircuit(qreg, creg)
qc.h(qreg[0])
qc.cx(qreg[0], qreg[1])
qc.measure(qreg, creg)
backend = BasicAer.get_backend('qasm_simulator')
job_sim = execute([qc]*10, backend)
output = io.StringIO()
job_monitor(job_sim, output=output)
self.assertEqual(job_sim.status().name, 'DONE')
if __name__ == '__main__':
unittest.main(verbosity=2)
|
gadial/qiskit-terra | test/python/opflow/test_z2_symmetries.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" Test Z2Symmetries """
from test.python.opflow import QiskitOpflowTestCase
from qiskit.opflow import PauliSumOp, TaperedPauliSumOp, Z2Symmetries
from qiskit.quantum_info import Pauli, SparsePauliOp
class TestZ2Symmetries(QiskitOpflowTestCase):
"""Z2Symmetries tests."""
def test_find_Z2_symmetries(self): # pylint: disable=invalid-name
""" test for find_Z2_symmetries """
qubit_op = PauliSumOp.from_list([
("II", -1.0537076071291125),
("IZ", 0.393983679438514),
("ZI", -0.39398367943851387),
("ZZ", -0.01123658523318205),
("XX", 0.1812888082114961),
])
z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op)
self.assertEqual(z2_symmetries.symmetries, [Pauli("ZZ")])
self.assertEqual(z2_symmetries.sq_paulis, [Pauli("IX")])
self.assertEqual(z2_symmetries.sq_list, [0])
self.assertEqual(z2_symmetries.tapering_values, None)
tapered_op = z2_symmetries.taper(qubit_op)[1]
self.assertEqual(tapered_op.z2_symmetries.symmetries, [Pauli("ZZ")])
self.assertEqual(tapered_op.z2_symmetries.sq_paulis, [Pauli("IX")])
self.assertEqual(tapered_op.z2_symmetries.sq_list, [0])
self.assertEqual(tapered_op.z2_symmetries.tapering_values, [-1])
z2_symmetries.tapering_values = [-1]
primitive = SparsePauliOp.from_list([
("I", -1.0424710218959303),
("Z", -0.7879673588770277),
("X", -0.18128880821149604),
])
expected_op = TaperedPauliSumOp(primitive, z2_symmetries)
self.assertEqual(tapered_op, expected_op)
|
gadial/qiskit-terra | test/python/classical_function_compiler/test_synthesis.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests classicalfunction compiler synthesis."""
import unittest
from qiskit.test import QiskitTestCase
from qiskit.circuit.classicalfunction import classical_function as compile_classical_function
from qiskit.circuit.classicalfunction.classicalfunction import HAS_TWEEDLEDUM
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import XGate
from . import examples
class TestSynthesis(QiskitTestCase):
"""Tests ClassicalFunction.synth method."""
@unittest.skipUnless(HAS_TWEEDLEDUM, 'tweedledum not available')
def test_grover_oracle(self):
"""Synthesis of grover_oracle example"""
oracle = compile_classical_function(examples.grover_oracle)
quantum_circuit = oracle.synth()
expected = QuantumCircuit(5)
expected.append(XGate().control(4, ctrl_state='1010'), [0, 1, 2, 3, 4])
self.assertEqual(quantum_circuit.name, 'grover_oracle')
self.assertEqual(quantum_circuit, expected)
@unittest.skipUnless(HAS_TWEEDLEDUM, 'tweedledum not available')
def test_grover_oracle_arg_regs(self):
"""Synthesis of grover_oracle example with arg_regs"""
oracle = compile_classical_function(examples.grover_oracle)
quantum_circuit = oracle.synth(registerless=False)
qr_a = QuantumRegister(1, 'a')
qr_b = QuantumRegister(1, 'b')
qr_c = QuantumRegister(1, 'c')
qr_d = QuantumRegister(1, 'd')
qr_return = QuantumRegister(1, 'return')
expected = QuantumCircuit(qr_d, qr_c, qr_b, qr_a, qr_return)
expected.append(XGate().control(4, ctrl_state='1010'),
[qr_d[0], qr_c[0], qr_b[0], qr_a[0], qr_return[0]])
self.assertEqual(quantum_circuit.name, 'grover_oracle')
self.assertEqual(quantum_circuit, expected)
|
gadial/qiskit-terra | qiskit/opflow/converters/__init__.py | <gh_stars>1-10
# 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.
"""
Converters (:mod:`qiskit.opflow.converters`)
====================================================
.. currentmodule:: qiskit.opflow.converters
Converters are objects which manipulate Operators, usually traversing an Operator to
change certain sub-Operators into a desired representation. Often the converted Operator is
isomorphic or approximate to the original Operator in some way, but not always. For example,
a converter may accept :class:`~qiskit.opflow.primitive_ops.CircuitOp` and return a
:class:`~qiskit.opflow.list_ops.SummedOp` of
:class:`~qiskit.opflow.primitive_ops.PauliOp`'s representing the
circuit unitary. Converters may not have polynomial space or time scaling in their operations.
On the contrary, many converters, such as a
:class:`~qiskit.opflow.expectations.MatrixExpectation` or
:class:`~qiskit.opflow.evolutions.MatrixEvolution`,
which convert :class:`~qiskit.opflow.primitive_ops.PauliOp`'s to
:class:`~qiskit.opflow.primitive_ops.MatrixOp`'s internally, will require time or space
exponential in the number of qubits unless a clever trick is known
(such as the use of sparse matrices).
Note:
Not all converters are in this module, as :mod:`~qiskit.opflow.expectations`
and :mod:`~qiskit.opflow.evolutions` are also converters.
Converter Base Class
====================
The converter base class simply enforces the presence of a :meth:`~ConverterBase.convert` method.
.. autosummary::
:toctree: ../stubs/
:nosignatures:
ConverterBase
Converters
==========
In addition to the base class, directory holds a few miscellaneous converters which are used
frequently around the Operator flow.
.. autosummary::
:toctree: ../stubs/
:nosignatures:
CircuitSampler
AbelianGrouper
DictToCircuitSum
PauliBasisChange
TwoQubitReduction
"""
from .converter_base import ConverterBase
from .circuit_sampler import CircuitSampler
from .pauli_basis_change import PauliBasisChange
from .dict_to_circuit_sum import DictToCircuitSum
from .abelian_grouper import AbelianGrouper
from .two_qubit_reduction import TwoQubitReduction
__all__ = ['ConverterBase',
'CircuitSampler',
'PauliBasisChange',
'DictToCircuitSum',
'AbelianGrouper',
'TwoQubitReduction',
]
|
gadial/qiskit-terra | qiskit/qasm/qasmparser.py | <gh_stars>1-10
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""OpenQASM parser."""
import os
import shutil
import tempfile
import numpy as np
import ply.yacc as yacc
from . import node
from .exceptions import QasmError
from .qasmlexer import QasmLexer
class QasmParser:
"""OPENQASM Parser."""
# pylint: disable=missing-function-docstring,invalid-name
def __init__(self, filename):
"""Create the parser."""
if filename is None:
filename = ""
self.lexer = QasmLexer(filename)
self.tokens = self.lexer.tokens
self.parse_dir = tempfile.mkdtemp(prefix='qiskit')
self.precedence = (
('left', '+', '-'),
('left', '*', '/'),
('left', 'negative', 'positive'),
('right', '^'))
# For yacc, also, write_tables = Bool and optimize = Bool
self.parser = yacc.yacc(module=self, debug=False,
outputdir=self.parse_dir)
self.qasm = None
self.parse_deb = False
self.global_symtab = {} # global symtab
self.current_symtab = self.global_symtab # top of symbol stack
self.symbols = [] # symbol stack
self.external_functions = ['sin', 'cos', 'tan', 'exp', 'ln', 'sqrt',
'acos', 'atan', 'asin']
def __enter__(self):
return self
def __exit__(self, *args):
if os.path.exists(self.parse_dir):
shutil.rmtree(self.parse_dir)
def update_symtab(self, obj):
"""Update a node in the symbol table.
Everything in the symtab must be a node with these attributes:
name - the string name of the object
type - the string type of the object
line - the source line where the type was first found
file - the source file where the type was first found
"""
if obj.name in self.current_symtab:
prev = self.current_symtab[obj.name]
raise QasmError("Duplicate declaration for", obj.type + " '"
+ obj.name + "' at line", str(obj.line)
+ ', file', obj.file
+ '.\nPrevious occurrence at line',
str(prev.line) + ', file', prev.file)
self.current_symtab[obj.name] = obj
def verify_declared_bit(self, obj):
"""Verify a qubit id against the gate prototype."""
# We are verifying gate args against the formal parameters of a
# gate prototype.
if obj.name not in self.current_symtab:
raise QasmError("Cannot find symbol '" + obj.name
+ "' in argument list for gate, line",
str(obj.line), 'file', obj.file)
# This insures the thing is from the bitlist and not from the
# argument list.
sym = self.current_symtab[obj.name]
if not (sym.type == 'id' and sym.is_bit):
raise QasmError("Bit", obj.name,
'is not declared as a bit in the gate.')
def verify_bit_list(self, obj):
"""Verify each qubit in a list of ids."""
# We expect the object to be a bitlist or an idlist, we don't care.
# We will iterate it and ensure everything in it is declared as a bit,
# and throw if not.
for children in obj.children:
self.verify_declared_bit(children)
def verify_exp_list(self, obj):
"""Verify each expression in a list."""
# A tad harder. This is a list of expressions each of which could be
# the head of a tree. We need to recursively walk each of these and
# ensure that any Id elements resolve to the current stack.
#
# I believe we only have to look at the current symtab.
if obj.children is not None:
for children in obj.children:
if isinstance(children, node.Id):
if children.name in self.external_functions:
continue
if children.name not in self.current_symtab:
raise QasmError("Argument '" + children.name
+ "' in expression cannot be "
+ "found, line", str(children.line),
"file", children.file)
else:
if hasattr(children, "children"):
self.verify_exp_list(children)
def verify_as_gate(self, obj, bitlist, arglist=None):
"""Verify a user defined gate call."""
if obj.name not in self.global_symtab:
raise QasmError("Cannot find gate definition for '" + obj.name
+ "', line", str(obj.line), 'file', obj.file)
g_sym = self.global_symtab[obj.name]
if not (g_sym.type == 'gate' or g_sym.type == 'opaque'):
raise QasmError("'" + obj.name + "' is used as a gate "
+ "or opaque call but the symbol is neither;"
+ " it is a '" + g_sym.type + "' line",
str(obj.line), 'file', obj.file)
if g_sym.n_bits() != bitlist.size():
raise QasmError("Gate or opaque call to '" + obj.name
+ "' uses", str(bitlist.size()),
"qubits but is declared for",
str(g_sym.n_bits()), "qubits", "line",
str(obj.line), 'file', obj.file)
if arglist:
if g_sym.n_args() != arglist.size():
raise QasmError("Gate or opaque call to '" + obj.name
+ "' uses", str(arglist.size()),
"qubits but is declared for",
str(g_sym.n_args()), "qubits", "line",
str(obj.line), 'file', obj.file)
else:
if g_sym.n_args() > 0:
raise QasmError("Gate or opaque call to '" + obj.name
+ "' has no arguments but is declared for",
str(g_sym.n_args()), "qubits", "line",
str(obj.line), 'file', obj.file)
def verify_reg(self, obj, object_type):
"""Verify a register."""
# How to verify:
# types must match
# indexes must be checked
if obj.name not in self.global_symtab:
raise QasmError('Cannot find definition for', object_type, "'"
+ obj.name + "'", 'at line', str(obj.line),
'file', obj.file)
g_sym = self.global_symtab[obj.name]
if g_sym.type != object_type:
raise QasmError("Type for '" + g_sym.name + "' should be '"
+ object_type + "' but was found to be '"
+ g_sym.type + "'", "line", str(obj.line),
"file", obj.file)
if obj.type == 'indexed_id':
bound = g_sym.index
ndx = obj.index
if ndx < 0 or ndx >= bound:
raise QasmError("Register index for '" + g_sym.name
+ "' out of bounds. Index is", str(ndx),
"bound is 0 <= index <", str(bound),
"at line", str(obj.line), "file", obj.file)
def verify_reg_list(self, obj, object_type):
"""Verify a list of registers."""
# We expect the object to be a bitlist or an idlist, we don't care.
# We will iterate it and ensure everything in it is declared as a bit,
# and throw if not.
for children in obj.children:
self.verify_reg(children, object_type)
def id_tuple_list(self, id_node):
"""Return a list of (name, index) tuples for this id node."""
if id_node.type != "id":
raise QasmError("internal error, id_tuple_list")
bit_list = []
try:
g_sym = self.current_symtab[id_node.name]
except KeyError:
g_sym = self.global_symtab[id_node.name]
if g_sym.type == "qreg" or g_sym.type == "creg":
# Return list of (name, idx) for reg ids
for idx in range(g_sym.index):
bit_list.append((id_node.name, idx))
else:
# Return (name, -1) for other ids
bit_list.append((id_node.name, -1))
return bit_list
def verify_distinct(self, list_of_nodes):
"""Check that objects in list_of_nodes represent distinct (qu)bits.
list_of_nodes is a list containing nodes of type id, indexed_id,
primary_list, or id_list. We assume these are all the same type
'qreg' or 'creg'.
This method raises an exception if list_of_nodes refers to the
same object more than once.
"""
bit_list = []
line_number = -1
filename = ""
for node_ in list_of_nodes:
# id node: add all bits in register or (name, -1) for id
if node_.type == "id":
bit_list.extend(self.id_tuple_list(node_))
line_number = node_.line
filename = node_.file
# indexed_id: add the bit
elif node_.type == "indexed_id":
bit_list.append((node_.name, node_.index))
line_number = node_.line
filename = node_.file
# primary_list: for each id or indexed_id child, add
elif node_.type == "primary_list":
for child in node_.children:
if child.type == "id":
bit_list.extend(self.id_tuple_list(child))
else:
bit_list.append((child.name, child.index))
line_number = child.line
filename = child.file
# id_list: for each id, add
elif node_.type == "id_list":
for child in node_.children:
bit_list.extend(self.id_tuple_list(child))
line_number = child.line
filename = child.file
else:
raise QasmError("internal error, verify_distinct")
if len(bit_list) != len(set(bit_list)):
raise QasmError("duplicate identifiers at line %d file %s"
% (line_number, filename))
def pop_scope(self):
"""Return to the previous scope."""
self.current_symtab = self.symbols.pop()
def push_scope(self):
"""Enter a new scope."""
self.symbols.append(self.current_symtab)
self.current_symtab = {}
# ---- Begin the PLY parser ----
start = 'main'
def p_main(self, program):
"""
main : program
"""
self.qasm = program[1]
# ----------------------------------------
# program : statement
# | program statement
# ----------------------------------------
def p_program_0(self, program):
"""
program : statement
"""
program[0] = node.Program([program[1]])
def p_program_1(self, program):
"""
program : program statement
"""
program[0] = program[1]
program[0].add_child(program[2])
# ----------------------------------------
# statement : decl
# | quantum_op ';'
# | format ';'
# ----------------------------------------
def p_statement(self, program):
"""
statement : decl
| quantum_op ';'
| format ';'
| ignore
| quantum_op error
| format error
"""
if len(program) > 2:
if program[2] != ';':
raise QasmError("Missing ';' at end of statement; "
+ "received", str(program[2].value))
program[0] = program[1]
def p_format(self, program):
"""
format : FORMAT
"""
program[0] = node.Format(program[1])
def p_format_0(self, _):
"""
format : FORMAT error
"""
version = "2.0;"
raise QasmError("Invalid version string. Expected '" + version
+ "'. Is the semicolon missing?")
# ----------------------------------------
# id : ID
# ----------------------------------------
def p_id(self, program):
"""
id : ID
"""
program[0] = program[1]
def p_id_e(self, program):
"""
id : error
"""
raise QasmError("Expected an ID, received '"
+ str(program[1].value) + "'")
# ----------------------------------------
# indexed_id : ID [ int ]
# ----------------------------------------
def p_indexed_id(self, program):
"""
indexed_id : id '[' NNINTEGER ']'
| id '[' NNINTEGER error
| id '[' error
"""
if len(program) == 4:
raise QasmError("Expecting an integer index; received",
str(program[3].value))
if program[4] != ']':
raise QasmError("Missing ']' in indexed ID; received",
str(program[4].value))
program[0] = node.IndexedId([program[1], node.Int(program[3])])
# ----------------------------------------
# primary : id
# | indexed_id
# ----------------------------------------
def p_primary(self, program):
"""
primary : id
| indexed_id
"""
program[0] = program[1]
# ----------------------------------------
# id_list : id
# | id_list ',' id
# ----------------------------------------
def p_id_list_0(self, program):
"""
id_list : id
"""
program[0] = node.IdList([program[1]])
def p_id_list_1(self, program):
"""
id_list : id_list ',' id
"""
program[0] = program[1]
program[0].add_child(program[3])
# ----------------------------------------
# gate_id_list : id
# | gate_id_list ',' id
# ----------------------------------------
def p_gate_id_list_0(self, program):
"""
gate_id_list : id
"""
program[0] = node.IdList([program[1]])
self.update_symtab(program[1])
def p_gate_id_list_1(self, program):
"""
gate_id_list : gate_id_list ',' id
"""
program[0] = program[1]
program[0].add_child(program[3])
self.update_symtab(program[3])
# ----------------------------------------
# bit_list : bit
# | bit_list ',' bit
# ----------------------------------------
def p_bit_list_0(self, program):
"""
bit_list : id
"""
program[0] = node.IdList([program[1]])
program[1].is_bit = True
self.update_symtab(program[1])
def p_bit_list_1(self, program):
"""
bit_list : bit_list ',' id
"""
program[0] = program[1]
program[0].add_child(program[3])
program[3].is_bit = True
self.update_symtab(program[3])
# ----------------------------------------
# primary_list : primary
# | primary_list ',' primary
# ----------------------------------------
def p_primary_list_0(self, program):
"""
primary_list : primary
"""
program[0] = node.PrimaryList([program[1]])
def p_primary_list_1(self, program):
"""
primary_list : primary_list ',' primary
"""
program[0] = program[1]
program[1].add_child(program[3])
# ----------------------------------------
# decl : qreg_decl
# | creg_decl
# | gate_decl
# ----------------------------------------
def p_decl(self, program):
"""
decl : qreg_decl ';'
| creg_decl ';'
| qreg_decl error
| creg_decl error
| gate_decl
"""
if len(program) > 2:
if program[2] != ';':
raise QasmError("Missing ';' in qreg or creg declaration."
" Instead received '" + program[2].value + "'")
program[0] = program[1]
# ----------------------------------------
# qreg_decl : QREG indexed_id
# ----------------------------------------
def p_qreg_decl(self, program):
"""
qreg_decl : QREG indexed_id
"""
program[0] = node.Qreg([program[2]])
if program[2].name in self.external_functions:
raise QasmError("QREG names cannot be reserved words. "
+ "Received '" + program[2].name + "'")
if program[2].index == 0:
raise QasmError("QREG size must be positive")
self.update_symtab(program[0])
def p_qreg_decl_e(self, program):
"""
qreg_decl : QREG error
"""
raise QasmError("Expecting indexed id (ID[int]) in QREG"
+ " declaration; received", program[2].value)
# ----------------------------------------
# creg_decl : QREG indexed_id
# ----------------------------------------
def p_creg_decl(self, program):
"""
creg_decl : CREG indexed_id
"""
program[0] = node.Creg([program[2]])
if program[2].name in self.external_functions:
raise QasmError("CREG names cannot be reserved words. "
+ "Received '" + program[2].name + "'")
if program[2].index == 0:
raise QasmError("CREG size must be positive")
self.update_symtab(program[0])
def p_creg_decl_e(self, program):
"""
creg_decl : CREG error
"""
raise QasmError("Expecting indexed id (ID[int]) in CREG"
+ " declaration; received", program[2].value)
# Gate_body will throw if there are errors, so we don't need to cover
# that here. Same with the id_lists - if they are not legal, we die
# before we get here
#
# ----------------------------------------
# gate_decl : GATE id gate_scope bit_list gate_body
# | GATE id gate_scope '(' ')' bit_list gate_body
# | GATE id gate_scope '(' gate_id_list ')' bit_list gate_body
#
# ----------------------------------------
def p_gate_decl_0(self, program):
"""
gate_decl : GATE id gate_scope bit_list gate_body
"""
program[0] = node.Gate([program[2], program[4], program[5]])
if program[2].name in self.external_functions:
raise QasmError("GATE names cannot be reserved words. "
+ "Received '" + program[2].name + "'")
self.pop_scope()
self.update_symtab(program[0])
def p_gate_decl_1(self, program):
"""
gate_decl : GATE id gate_scope '(' ')' bit_list gate_body
"""
program[0] = node.Gate([program[2], program[6], program[7]])
if program[2].name in self.external_functions:
raise QasmError("GATE names cannot be reserved words. "
+ "Received '" + program[2].name + "'")
self.pop_scope()
self.update_symtab(program[0])
def p_gate_decl_2(self, program):
"""
gate_decl : GATE id gate_scope '(' gate_id_list ')' bit_list gate_body
"""
program[0] = node.Gate(
[program[2], program[5], program[7], program[8]])
if program[2].name in self.external_functions:
raise QasmError("GATE names cannot be reserved words. "
+ "Received '" + program[2].name + "'")
self.pop_scope()
self.update_symtab(program[0])
def p_gate_scope(self, _):
"""
gate_scope :
"""
self.push_scope()
# ----------------------------------------
# gate_body : '{' gate_op_list '}'
# | '{' '}'
#
# | '{' gate_op_list error
# | '{' error
#
# Error handling: gete_op will throw if there's a problem so we won't
# get here with in the gate_op_list
# ----------------------------------------
def p_gate_body_0(self, program):
"""
gate_body : '{' '}'
"""
if program[2] != '}':
raise QasmError("Missing '}' in gate definition; received'"
+ str(program[2].value) + "'")
program[0] = node.GateBody(None)
def p_gate_body_1(self, program):
"""
gate_body : '{' gate_op_list '}'
"""
program[0] = node.GateBody(program[2])
# ----------------------------------------
# gate_op_list : gate_op
# | gate_op_ist gate_op
#
# Error handling: gete_op will throw if there's a problem so we won't
# get here with errors
# ----------------------------------------
def p_gate_op_list_0(self, program):
"""
gate_op_list : gate_op
"""
program[0] = [program[1]]
def p_gate_op_list_1(self, program):
"""
gate_op_list : gate_op_list gate_op
"""
program[0] = program[1]
program[0].append(program[2])
# ----------------------------------------
# These are for use outside of gate_bodies and allow
# indexed ids everywhere.
#
# unitary_op : U '(' exp_list ')' primary
# | CX primary ',' primary
# | id primary_list
# | id '(' ')' primary_list
# | id '(' exp_list ')' primary_list
#
# Note that it might not be unitary - this is the mechanism that
# is also used to invoke calls to 'opaque'
# ----------------------------------------
def p_unitary_op_0(self, program):
"""
unitary_op : U '(' exp_list ')' primary
"""
program[0] = node.UniversalUnitary([program[3], program[5]])
self.verify_reg(program[5], 'qreg')
self.verify_exp_list(program[3])
def p_unitary_op_1(self, program):
"""
unitary_op : CX primary ',' primary
"""
program[0] = node.Cnot([program[2], program[4]])
self.verify_reg(program[2], 'qreg')
self.verify_reg(program[4], 'qreg')
self.verify_distinct([program[2], program[4]])
# TODO: check that if both primary are id, same size
# TODO: this needs to be checked in other cases too
def p_unitary_op_2(self, program):
"""
unitary_op : id primary_list
"""
program[0] = node.CustomUnitary([program[1], program[2]])
self.verify_as_gate(program[1], program[2])
self.verify_reg_list(program[2], 'qreg')
self.verify_distinct([program[2]])
def p_unitary_op_3(self, program):
"""
unitary_op : id '(' ')' primary_list
"""
program[0] = node.CustomUnitary([program[1], program[4]])
self.verify_as_gate(program[1], program[4])
self.verify_reg_list(program[4], 'qreg')
self.verify_distinct([program[4]])
def p_unitary_op_4(self, program):
"""
unitary_op : id '(' exp_list ')' primary_list
"""
program[0] = node.CustomUnitary([program[1], program[3], program[5]])
self.verify_as_gate(program[1], program[5], arglist=program[3])
self.verify_reg_list(program[5], 'qreg')
self.verify_exp_list(program[3])
self.verify_distinct([program[5]])
# ----------------------------------------
# This is a restricted set of "quantum_op" which also
# prohibits indexed ids, for use in a gate_body
#
# gate_op : U '(' exp_list ')' id ';'
# | CX id ',' id ';'
# | id id_list ';'
# | id '(' ')' id_list ';'
# | id '(' exp_list ')' id_list ';'
# | BARRIER id_list ';'
# ----------------------------------------
def p_gate_op_0(self, program):
"""
gate_op : U '(' exp_list ')' id ';'
"""
program[0] = node.UniversalUnitary([program[3], program[5]])
self.verify_declared_bit(program[5])
self.verify_exp_list(program[3])
def p_gate_op_0e1(self, p):
"""
gate_op : U '(' exp_list ')' error
"""
raise QasmError("Invalid U inside gate definition. "
+ "Missing bit id or ';'")
def p_gate_op_0e2(self, _):
"""
gate_op : U '(' exp_list error
"""
raise QasmError("Missing ')' in U invocation in gate definition.")
def p_gate_op_1(self, program):
"""
gate_op : CX id ',' id ';'
"""
program[0] = node.Cnot([program[2], program[4]])
self.verify_declared_bit(program[2])
self.verify_declared_bit(program[4])
self.verify_distinct([program[2], program[4]])
def p_gate_op_1e1(self, program):
"""
gate_op : CX error
"""
raise QasmError("Invalid CX inside gate definition. "
+ "Expected an ID or ',', received '"
+ str(program[2].value) + "'")
def p_gate_op_1e2(self, program):
"""
gate_op : CX id ',' error
"""
raise QasmError("Invalid CX inside gate definition. "
+ "Expected an ID or ';', received '"
+ str(program[4].value) + "'")
def p_gate_op_2(self, program):
"""
gate_op : id id_list ';'
"""
program[0] = node.CustomUnitary([program[1], program[2]])
# To verify:
# 1. id is declared as a gate in global scope
# 2. everything in the id_list is declared as a bit in local scope
self.verify_as_gate(program[1], program[2])
self.verify_bit_list(program[2])
self.verify_distinct([program[2]])
def p_gate_op_2e(self, _):
"""
gate_op : id id_list error
"""
raise QasmError("Invalid gate invocation inside gate definition.")
def p_gate_op_3(self, program):
"""
gate_op : id '(' ')' id_list ';'
"""
program[0] = node.CustomUnitary([program[1], program[4]])
self.verify_as_gate(program[1], program[4])
self.verify_bit_list(program[4])
self.verify_distinct([program[4]])
def p_gate_op_4(self, program):
"""
gate_op : id '(' exp_list ')' id_list ';'
"""
program[0] = node.CustomUnitary([program[1], program[3], program[5]])
self.verify_as_gate(program[1], program[5], arglist=program[3])
self.verify_bit_list(program[5])
self.verify_exp_list(program[3])
self.verify_distinct([program[5]])
def p_gate_op_4e0(self, _):
"""
gate_op : id '(' ')' error
"""
raise QasmError("Invalid bit list inside gate definition or"
+ " missing ';'")
def p_gate_op_4e1(self, _):
"""
gate_op : id '(' error
"""
raise QasmError("Unmatched () for gate invocation inside gate"
+ " invocation.")
def p_gate_op_5(self, program):
"""
gate_op : BARRIER id_list ';'
"""
program[0] = node.Barrier([program[2]])
self.verify_bit_list(program[2])
self.verify_distinct([program[2]])
def p_gate_op_5e(self, _):
"""
gate_op : BARRIER error
"""
raise QasmError("Invalid barrier inside gate definition.")
# ----------------------------------------
# opaque : OPAQUE id gate_scope bit_list
# | OPAQUE id gate_scope '(' ')' bit_list
# | OPAQUE id gate_scope '(' gate_id_list ')' bit_list
#
# These are like gate declarations only without a body.
# ----------------------------------------
def p_opaque_0(self, program):
"""
opaque : OPAQUE id gate_scope bit_list
"""
# TODO: Review Opaque function
program[0] = node.Opaque([program[2], program[4]])
if program[2].name in self.external_functions:
raise QasmError("OPAQUE names cannot be reserved words. "
+ "Received '" + program[2].name + "'")
self.pop_scope()
self.update_symtab(program[0])
def p_opaque_1(self, program):
"""
opaque : OPAQUE id gate_scope '(' ')' bit_list
"""
program[0] = node.Opaque([program[2], program[6]])
self.pop_scope()
self.update_symtab(program[0])
def p_opaque_2(self, program):
"""
opaque : OPAQUE id gate_scope '(' gate_id_list ')' bit_list
"""
program[0] = node.Opaque([program[2], program[5], program[7]])
if program[2].name in self.external_functions:
raise QasmError("OPAQUE names cannot be reserved words. "
+ "Received '" + program[2].name + "'")
self.pop_scope()
self.update_symtab(program[0])
def p_opaque_1e(self, _):
"""
opaque : OPAQUE id gate_scope '(' error
"""
raise QasmError("Poorly formed OPAQUE statement.")
# ----------------------------------------
# measure : MEASURE primary ASSIGN primary
# ----------------------------------------
def p_measure(self, program):
"""
measure : MEASURE primary ASSIGN primary
"""
program[0] = node.Measure([program[2], program[4]])
self.verify_reg(program[2], 'qreg')
self.verify_reg(program[4], 'creg')
def p_measure_e(self, program):
"""
measure : MEASURE primary error
"""
raise QasmError("Illegal measure statement." +
str(program[3].value))
# ----------------------------------------
# barrier : BARRIER primary_list
#
# Errors are covered by handling errors in primary_list
# ----------------------------------------
def p_barrier(self, program):
"""
barrier : BARRIER primary_list
"""
program[0] = node.Barrier([program[2]])
self.verify_reg_list(program[2], 'qreg')
self.verify_distinct([program[2]])
# ----------------------------------------
# reset : RESET primary
# ----------------------------------------
def p_reset(self, program):
"""
reset : RESET primary
"""
program[0] = node.Reset([program[2]])
self.verify_reg(program[2], 'qreg')
# ----------------------------------------
# IF '(' ID MATCHES NNINTEGER ')' quantum_op
# ----------------------------------------
def p_if(self, program):
"""
if : IF '(' id MATCHES NNINTEGER ')' quantum_op
if : IF '(' id error
if : IF '(' id MATCHES error
if : IF '(' id MATCHES NNINTEGER error
if : IF error
"""
if len(program) == 3:
raise QasmError("Ill-formed IF statement. Perhaps a"
+ " missing '('?")
if len(program) == 5:
raise QasmError("Ill-formed IF statement. Expected '==', "
+ "received '" + str(program[4].value))
if len(program) == 6:
raise QasmError("Ill-formed IF statement. Expected a number, "
+ "received '" + str(program[5].value))
if len(program) == 7:
raise QasmError("Ill-formed IF statement, unmatched '('")
if program[7].type == 'if':
raise QasmError("Nested IF statements not allowed")
if program[7].type == 'barrier':
raise QasmError("barrier not permitted in IF statement")
program[0] = node.If([program[3], node.Int(program[5]), program[7]])
# ----------------------------------------
# These are all the things you can have outside of a gate declaration
# quantum_op : unitary_op
# | opaque
# | measure
# | reset
# | barrier
# | if
#
# ----------------------------------------
def p_quantum_op(self, program):
"""
quantum_op : unitary_op
| opaque
| measure
| barrier
| reset
| if
"""
program[0] = program[1]
# ----------------------------------------
# unary : NNINTEGER
# | REAL
# | PI
# | ID
# | '(' expression ')'
# | id '(' expression ')'
#
# We will trust 'expression' to throw before we have to handle it here
# ----------------------------------------
def p_unary_0(self, program):
"""
unary : NNINTEGER
"""
program[0] = node.Int(program[1])
def p_unary_1(self, program):
"""
unary : REAL
"""
program[0] = node.Real(program[1])
def p_unary_2(self, program):
"""
unary : PI
"""
program[0] = node.Real(np.pi)
def p_unary_3(self, program):
"""
unary : id
"""
program[0] = program[1]
def p_unary_4(self, program):
"""
unary : '(' expression ')'
"""
program[0] = program[2]
def p_unary_6(self, program):
"""
unary : id '(' expression ')'
"""
# note this is a semantic check, not syntactic
if program[1].name not in self.external_functions:
raise QasmError("Illegal external function call: ",
str(program[1].name))
program[0] = node.External([program[1], program[3]])
# ----------------------------------------
# Prefix
# ----------------------------------------
def p_expression_1(self, program):
"""
expression : '-' expression %prec negative
| '+' expression %prec positive
"""
program[0] = node.Prefix([node.UnaryOperator(program[1]), program[2]])
def p_expression_0(self, program):
"""
expression : expression '*' expression
| expression '/' expression
| expression '+' expression
| expression '-' expression
| expression '^' expression
"""
program[0] = node.BinaryOp([node.BinaryOperator(program[2]),
program[1], program[3]])
def p_expression_2(self, program):
"""
expression : unary
"""
program[0] = program[1]
# ----------------------------------------
# exp_list : exp
# | exp_list ',' exp
# ----------------------------------------
def p_exp_list_0(self, program):
"""
exp_list : expression
"""
program[0] = node.ExpressionList([program[1]])
def p_exp_list_1(self, program):
"""
exp_list : exp_list ',' expression
"""
program[0] = program[1]
program[0].add_child(program[3])
def p_ignore(self, _):
"""
ignore : STRING
"""
# this should never hit but it keeps the insuppressible warnings at bay
pass
def p_error(self, program):
# EOF is a special case because the stupid error token isn't placed
# on the stack
if not program:
raise QasmError("Error at end of file. "
+ "Perhaps there is a missing ';'")
col = self.find_column(self.lexer.data, program)
print("Error near line", str(self.lexer.lineno), 'Column', col)
def find_column(self, input_, token):
"""Compute the column.
Input is the input text string.
token is a token instance.
"""
if token is None:
return 0
last_cr = input_.rfind('\n', 0, token.lexpos)
if last_cr < 0:
last_cr = 0
column = (token.lexpos - last_cr) + 1
return column
def read_tokens(self):
"""finds and reads the tokens."""
try:
while True:
token = self.lexer.token()
if not token:
break
yield token
except QasmError as e:
print('Exception tokenizing qasm file:', e.msg)
def parse_debug(self, val):
"""Set the parse_deb field."""
if val is True:
self.parse_deb = True
elif val is False:
self.parse_deb = False
else:
raise QasmError("Illegal debug value '" + str(val)
+ "' must be True or False.")
def parse(self, data):
"""Parse some data."""
self.parser.parse(data, lexer=self.lexer, debug=self.parse_deb)
if self.qasm is None:
raise QasmError("Uncaught exception in parser; "
+ "see previous messages for details.")
return self.qasm
def print_tree(self):
"""Print parsed OPENQASM."""
if self.qasm is not None:
self.qasm.to_string(0)
else:
print("No parsed qasm to print")
def run(self, data):
"""Parser runner.
To use this module stand-alone.
"""
ast = self.parser.parse(data, debug=True)
self.parser.parse(data, debug=True)
ast.to_string(0)
|
gadial/qiskit-terra | qiskit/visualization/array.py | <filename>qiskit/visualization/array.py
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Tools to create LaTeX arrays.
"""
import math
from fractions import Fraction
import numpy as np
def _num_to_latex(num, precision=5):
"""Takes a complex number as input and returns a latex representation
Args:
num (numerical): The number to be converted to latex.
precision (int): If the real or imaginary parts of num are not close
to an integer, the number of decimal places to round to
Returns:
str: Latex representation of num
"""
# Result is combination of maximum 4 strings in the form:
# {common_facstring} ( {realstring} {operation} {imagstring}i )
# common_facstring: A common factor between the real and imaginary part
# realstring: The real part (inc. a negative sign if applicable)
# operation: The operation between the real and imaginary parts ('+' or '-')
# imagstring: Absolute value of the imaginary parts (i.e. not inc. any negative sign).
# This function computes each of these strings and combines appropriately.
r = np.real(num)
i = np.imag(num)
common_factor = None
# try to factor out common terms in imaginary numbers
if np.isclose(abs(r), abs(i)) and not np.isclose(r, 0) and not np.isclose(i, 0):
common_factor = abs(r)
r = r/common_factor
i = i/common_factor
common_terms = {
1/math.sqrt(2): '\\tfrac{1}{\\sqrt{2}}',
1/math.sqrt(3): '\\tfrac{1}{\\sqrt{3}}',
math.sqrt(2/3): '\\sqrt{\\tfrac{2}{3}}',
math.sqrt(3/4): '\\sqrt{\\tfrac{3}{4}}',
1/math.sqrt(8): '\\tfrac{1}{\\sqrt{8}}'
}
def _proc_value(val):
# This function converts a real value to a latex string
# First, see if val is close to an integer:
val_mod = np.mod(val, 1)
if (np.isclose(val_mod, 0) or np.isclose(val_mod, 1)):
# If so, return that integer
return str(int(np.round(val)))
# Otherwise, see if it matches one of the common terms
for term, latex_str in common_terms.items():
if np.isclose(abs(val), term):
if val > 0:
return latex_str
else:
return "-" + latex_str
# try to factorise val nicely
frac = Fraction(val).limit_denominator()
num, denom = frac.numerator, frac.denominator
if num + denom < 20:
# If fraction is 'nice' return
if val > 0:
return f"\\tfrac{{{abs(num)}}}{{{abs(denom)}}}"
else:
return f"-\\tfrac{{{abs(num)}}}{{{abs(denom)}}}"
else:
# Failing everything else, return val as a decimal
return "{:.{}f}".format(val, precision).rstrip("0")
# Get string (or None) for common factor between real and imag
if common_factor is None:
common_facstring = None
else:
common_facstring = _proc_value(common_factor)
# Get string for real part
realstring = _proc_value(r)
# Get string for both imaginary part and operation between real and imaginary parts
if i > 0:
operation = "+"
imagstring = _proc_value(i)
else:
operation = "-"
imagstring = _proc_value(-i)
if imagstring == "1":
imagstring = "" # Don't want to return '1i', just 'i'
# Now combine the strings appropriately:
if imagstring == "0":
return realstring # realstring already contains the negative sign (if needed)
if realstring == "0":
# imagstring needs the negative sign adding
if operation == "-":
return f"-{imagstring}i"
else:
return f"{imagstring}i"
if common_facstring is not None:
return f"{common_facstring}({realstring} {operation} {imagstring}i)"
else:
return f"{realstring} {operation} {imagstring}i"
def _matrix_to_latex(matrix, precision=5, prefix="", max_size=(8, 8)):
"""Latex representation of a complex numpy array (with maximum dimension 2)
Args:
matrix (ndarray): The matrix to be converted to latex, must have dimension 2.
precision (int): For numbers not close to integers, the number of decimal places
to round to.
prefix (str): Latex string to be prepended to the latex, intended for labels.
max_size (list(```int```)): Indexable containing two integers: Maximum width and maximum
height of output Latex matrix (including dots characters). If the
width and/or height of matrix exceeds the maximum, the centre values
will be replaced with dots. Maximum width or height must be greater
than 3.
Returns:
str: Latex representation of the matrix
Raises:
ValueError: If minimum value in max_size < 3
"""
if min(max_size) < 3:
raise ValueError("""Smallest value in max_size must be greater than or equal to 3""")
out_string = f"\n{prefix}\n"
out_string += "\\begin{bmatrix}\n"
def _elements_to_latex(elements):
# Takes a list of elements (a row) and creates a latex
# string from it; Each element separated by `&`
el_string = ""
for el in elements:
num_string = _num_to_latex(el, precision=precision)
el_string += num_string + " & "
el_string = el_string[:-2] # remove trailing ampersands
return el_string
def _rows_to_latex(rows, max_width):
# Takes a list of lists (list of 'rows') and creates a
# latex string from it
row_string = ""
for r in rows:
if len(r) <= max_width:
row_string += _elements_to_latex(r)
else:
row_string += _elements_to_latex(r[:max_width//2])
row_string += "& \\cdots & "
row_string += _elements_to_latex(r[-max_width//2+1:])
row_string += " \\\\\n "
return row_string
max_width, max_height = max_size
if matrix.ndim == 1:
out_string += _rows_to_latex([matrix], max_width)
elif len(matrix) > max_height:
# We need to truncate vertically, so we process the rows at the beginning
# and end, and add a line of vertical elipse (dots) characters between them
out_string += _rows_to_latex(matrix[:max_height//2], max_width)
if max_width >= matrix.shape[1]:
out_string += "\\vdots & "*matrix.shape[1]
else:
# In this case we need to add the diagonal dots in line with the column
# of horizontal dots
pre_vdots = max_width//2
post_vdots = max_width//2 + np.mod(max_width, 2) - 1
out_string += "\\vdots & "*pre_vdots
out_string += "\\ddots & "
out_string += "\\vdots & "*post_vdots
out_string = out_string[:-2] + "\\\\\n "
out_string += _rows_to_latex(matrix[-max_height//2+1:], max_width)
else:
out_string += _rows_to_latex(matrix, max_width)
out_string += "\\end{bmatrix}\n"
return out_string
def array_to_latex(array, precision=5, prefix="", source=False, max_size=8):
"""Latex representation of a complex numpy array (with dimension 1 or 2)
Args:
array (ndarray): The array to be converted to latex, must have dimension 1 or 2 and
contain only numerical data.
precision (int): For numbers not close to integers or common terms, the number of
decimal places to round to.
prefix (str): Latex string to be prepended to the latex, intended for labels.
source (bool): If ``False``, will return IPython.display.Latex object. If display is
``True``, will instead return the LaTeX source string.
max_size (list(int) or int): The maximum size of the output Latex array.
* If list(``int``), then the 0th element of the list specifies the maximum
width (including dots characters) and the 1st specifies the maximum height
(also inc. dots characters).
* If a single ``int`` then this value sets the maximum width _and_ maximum
height.
Returns:
str or IPython.display.Latex: If ``source`` is ``True``, a ``str`` of the LaTeX
representation of the array, else an ``IPython.display.Latex`` representation of
the array.
Raises:
TypeError: If array can not be interpreted as a numerical numpy array.
ValueError: If the dimension of array is not 1 or 2.
ImportError: If ``source`` is ``False`` and ``IPython.display.Latex`` cannot be
imported.
"""
try:
array = np.asarray(array)
_ = array[0]+1 # Test first element contains numerical data
except TypeError as err:
raise TypeError("""array_to_latex can only convert numpy arrays containing numerical data,
or types that can be converted to such arrays""") from err
if array.ndim <= 2:
if isinstance(max_size, int):
max_size = (max_size, max_size)
outstr = _matrix_to_latex(array, precision=precision, prefix=prefix, max_size=max_size)
else:
raise ValueError("array_to_latex can only convert numpy ndarrays of dimension 1 or 2")
if source is False:
try:
from IPython.display import Latex
except ImportError as err:
raise ImportError(str(err) + ". Try `pip install ipython` (If you just want the LaTeX"
" source string, set `source=True`).") from err
return Latex(f"$${outstr}$$")
else:
return outstr
|
gadial/qiskit-terra | qiskit/test/mock/utils/configurable_backend.py | <gh_stars>1-10
# 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.
"""Configurable backend."""
import itertools
from datetime import datetime
from typing import Optional, List, Union
import numpy as np
from qiskit.exceptions import QiskitError
from qiskit.providers.models import (PulseBackendConfiguration,
BackendProperties, PulseDefaults,
Command, UchannelLO)
from qiskit.providers.models.backendproperties import Nduv, Gate
from qiskit.qobj import PulseQobjInstruction
from qiskit.test.mock.fake_backend import FakeBackend
class ConfigurableFakeBackend(FakeBackend):
"""Configurable backend."""
def __init__(self,
name: str,
n_qubits: int,
version: Optional[str] = None,
coupling_map: Optional[List[List[int]]] = None,
basis_gates: Optional[List[str]] = None,
qubit_t1: Optional[Union[float, List[float]]] = None,
qubit_t2: Optional[Union[float, List[float]]] = None,
qubit_frequency: Optional[Union[float, List[float]]] = None,
qubit_readout_error: Optional[Union[float, List[float]]] = None,
single_qubit_gates: Optional[List[str]] = None,
dt: Optional[float] = None,
std: Optional[float] = None,
seed: Optional[int] = None):
"""Creates backend based on provided configuration.
Args:
name: Name of the backend.
n_qubits: Number of qubits in the backend.
version: Version of the fake backend.
coupling_map: Coupling map.
basis_gates: Basis gates of the backend.
qubit_t1: Longitudinal coherence times.
qubit_t2: Transverse coherence times.
qubit_frequency: Frequency of qubits.
qubit_readout_error: Readout error of qubits.
single_qubit_gates: List of single qubit gates for backend properties.
dt: Discretization of the input time sequences.
std: Standard deviation of the generated distributions.
seed: Random seed.
"""
np.random.seed(seed)
if version is None:
version = '0.0.0'
if basis_gates is None:
basis_gates = ['id', 'u1', 'u2', 'u3', 'cx']
if std is None:
std = 0.01
if not isinstance(qubit_t1, list):
qubit_t1 = np.random.normal(loc=qubit_t1 or 113.,
scale=std,
size=n_qubits).tolist()
if not isinstance(qubit_t2, list):
qubit_t2 = np.random.normal(loc=qubit_t1 or 150.2,
scale=std,
size=n_qubits).tolist()
if not isinstance(qubit_frequency, list):
qubit_frequency = np.random.normal(loc=qubit_frequency or 4.8,
scale=std,
size=n_qubits).tolist()
if not isinstance(qubit_readout_error, list):
qubit_readout_error = np.random.normal(loc=qubit_readout_error or 0.04,
scale=std,
size=n_qubits).tolist()
if single_qubit_gates is None:
single_qubit_gates = ['id', 'u1', 'u2', 'u3']
if dt is None:
dt = 1.33
self.name = name
self.version = version
self.basis_gates = basis_gates
self.qubit_t1 = qubit_t1
self.qubit_t2 = qubit_t2
self.qubit_frequency = qubit_frequency
self.qubit_readout_error = qubit_readout_error
self.n_qubits = n_qubits
self.single_qubit_gates = single_qubit_gates
self.now = datetime.now()
self.dt = dt
self.std = std
if coupling_map is None:
coupling_map = self._generate_cmap()
self.coupling_map = coupling_map
configuration = self._build_conf()
self._configuration = configuration
self._defaults = self._build_defaults()
self._properties = self._build_props()
super().__init__(configuration)
def defaults(self):
"""Return backend defaults."""
return self._defaults
def properties(self):
"""Return backend properties"""
return self._properties
def _generate_cmap(self) -> List[List[int]]:
"""Generate default grid-like coupling map."""
cmap = []
grid_size = int(np.ceil(np.sqrt(self.n_qubits)))
for row in range(grid_size):
for column in range(grid_size):
if column + 1 < grid_size and column + row * grid_size + 1 < self.n_qubits:
qubit1 = column + row * grid_size
qubit2 = qubit1 + 1
cmap.append([qubit1, qubit2])
if row + 1 < grid_size and column + (row + 1) * grid_size < self.n_qubits:
qubit1 = column + row * grid_size
qubit2 = qubit1 + grid_size
cmap.append([qubit1, qubit2])
return cmap
def _build_props(self) -> BackendProperties:
"""Build properties for backend."""
qubits = []
gates = []
for (qubit_t1, qubit_t2, freq, read_err) in zip(self.qubit_t1,
self.qubit_t2,
self.qubit_frequency,
self.qubit_readout_error):
qubits.append([
Nduv(date=self.now, name='T1', unit='µs', value=qubit_t1),
Nduv(date=self.now, name='T2', unit='µs', value=qubit_t2),
Nduv(date=self.now, name='frequency', unit='GHz', value=freq),
Nduv(date=self.now, name='readout_error', unit='', value=read_err)
])
for gate in self.basis_gates:
parameters = [Nduv(date=self.now, name='gate_error', unit='', value=0.01),
Nduv(date=self.now, name='gate_length', unit='ns', value=4*self.dt)]
if gate in self.single_qubit_gates:
for i in range(self.n_qubits):
gates.append(Gate(gate=gate, name="{}_{}".format(gate, i),
qubits=[i], parameters=parameters))
elif gate == 'cx':
for (qubit1, qubit2) in list(itertools.combinations(range(self.n_qubits), 2)):
gates.append(Gate(gate=gate,
name="{gate}{q1}_{q2}".format(gate=gate,
q1=qubit1,
q2=qubit2),
qubits=[qubit1, qubit2],
parameters=parameters))
else:
raise QiskitError("{gate} is not supported by fake backend builder."
"".format(gate=gate))
return BackendProperties(backend_name=self.name,
backend_version=self.version,
last_update_date=self.now,
qubits=qubits,
gates=gates,
general=[])
def _build_conf(self) -> PulseBackendConfiguration:
"""Build configuration for backend."""
h_str = [
",".join(["_SUM[i,0,{n_qubits}".format(n_qubits=self.n_qubits),
"wq{i}/2*(I{i}-Z{i})]"]),
",".join(["_SUM[i,0,{n_qubits}".format(n_qubits=self.n_qubits),
"omegad{i}*X{i}||D{i}]"])
]
variables = []
for (qubit1, qubit2) in self.coupling_map:
h_str += [
"jq{q1}q{q2}*Sp{q1}*Sm{q2}".format(q1=qubit1, q2=qubit2),
"jq{q1}q{q2}*Sm{q1}*Sp{q2}".format(q1=qubit1, q2=qubit2)
]
variables.append(("jq{q1}q{q2}".format(q1=qubit1, q2=qubit2), 0))
for i, (qubit1, qubit2) in enumerate(self.coupling_map):
h_str.append("omegad{}*X{}||U{}".format(qubit1, qubit2, i))
for i in range(self.n_qubits):
variables += [
("omegad{}".format(i), 0),
("wq{}".format(i), 0)
]
hamiltonian = {
'h_str': h_str,
'description': 'Hamiltonian description for {} qubits backend.'.format(self.n_qubits),
'qub': {i: 2 for i in range(self.n_qubits)},
'vars': dict(variables)
}
meas_map = [list(range(self.n_qubits))]
qubit_lo_range = [[freq - 0.5, freq + 0.5] for freq in self.qubit_frequency]
meas_lo_range = [[6.5, 7.5] for _ in range(self.n_qubits)]
u_channel_lo = [[UchannelLO(q=i, scale=1.0+0.0j)] for i in range(len(self.coupling_map))]
return PulseBackendConfiguration(
backend_name=self.name,
backend_version=self.version,
n_qubits=self.n_qubits,
meas_levels=[0, 1, 2],
basis_gates=self.basis_gates,
simulator=False,
local=True,
conditional=True,
open_pulse=True,
memory=False,
max_shots=65536,
gates=[],
coupling_map=self.coupling_map,
n_registers=self.n_qubits,
n_uchannels=self.n_qubits,
u_channel_lo=u_channel_lo,
meas_level=[1, 2],
qubit_lo_range=qubit_lo_range,
meas_lo_range=meas_lo_range,
dt=self.dt,
dtm=10.5,
rep_times=[1000],
meas_map=meas_map,
channel_bandwidth=[],
meas_kernels=['kernel1'],
discriminators=['max_1Q_fidelity'],
acquisition_latency=[],
conditional_latency=[],
hamiltonian=hamiltonian
)
def _build_defaults(self) -> PulseDefaults:
"""Build backend defaults."""
qubit_freq_est = self.qubit_frequency
meas_freq_est = np.linspace(6.4, 6.6, self.n_qubits).tolist()
pulse_library = [
{
'name': 'test_pulse_1',
'samples': [[0.0, 0.0], [0.0, 0.1]]
},
{
'name': 'test_pulse_2',
'samples': [[0.0, 0.0], [0.0, 0.1], [0.0, 1.0]]
},
{
'name': 'test_pulse_3',
'samples': [[0.0, 0.0], [0.0, 0.1], [0.0, 1.0], [0.5, 0.0]]
},
{
'name': 'test_pulse_4',
'samples': 7 * [[0.0, 0.0], [0.0, 0.1], [0.0, 1.0], [0.5, 0.0]]
}
]
measure_command_sequence = [PulseQobjInstruction(name='acquire', duration=10, t0=0,
qubits=list(range(self.n_qubits)),
memory_slot=list(range(self.n_qubits))
).to_dict()]
measure_command_sequence += [PulseQobjInstruction(name='test_pulse_1',
ch='m{}'.format(i), t0=0).to_dict()
for i in range(self.n_qubits)]
measure_command = Command.from_dict({
'name': 'measure',
'qubits': list(range(self.n_qubits)),
'sequence': measure_command_sequence
}).to_dict()
cmd_def = [measure_command]
for gate in self.single_qubit_gates:
for i in range(self.n_qubits):
cmd_def.append(Command.from_dict({
'name': gate,
'qubits': [i],
'sequence': [PulseQobjInstruction(name='fc', ch='d{}'.format(i),
t0=0, phase='-P0').to_dict(),
PulseQobjInstruction(name='test_pulse_3',
ch='d{}'.format(i),
t0=0).to_dict()]
}).to_dict())
for qubit1, qubit2 in self.coupling_map:
cmd_def += [
Command.from_dict({
'name': 'cx',
'qubits': [qubit1, qubit2],
'sequence': [PulseQobjInstruction(name='test_pulse_1',
ch='d{}'.format(qubit1),
t0=0).to_dict(),
PulseQobjInstruction(name='test_pulse_2',
ch='u{}'.format(qubit1),
t0=10).to_dict(),
PulseQobjInstruction(name='test_pulse_1',
ch='d{}'.format(qubit2),
t0=20).to_dict(),
PulseQobjInstruction(name='fc', ch='d{}'.format(qubit2),
t0=20, phase=2.1).to_dict()]
}).to_dict()
]
return PulseDefaults.from_dict({
'qubit_freq_est': qubit_freq_est,
'meas_freq_est': meas_freq_est,
'buffer': 0,
'pulse_library': pulse_library,
'cmd_def': cmd_def
})
|
gadial/qiskit-terra | qiskit/opflow/evolutions/trotterizations/trotterization_factory.py | <reponame>gadial/qiskit-terra<gh_stars>1-10
# 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.
"""TrotterizationFactory Class """
from qiskit.opflow.evolutions.trotterizations.qdrift import QDrift
from qiskit.opflow.evolutions.trotterizations.suzuki import Suzuki
from qiskit.opflow.evolutions.trotterizations.trotter import Trotter
from qiskit.opflow.evolutions.trotterizations.trotterization_base import TrotterizationBase
class TrotterizationFactory():
""" A factory for conveniently creating TrotterizationBase instances. """
@staticmethod
def build(mode: str = 'trotter',
reps: int = 1) -> TrotterizationBase:
""" A factory for conveniently creating TrotterizationBase instances.
Args:
mode: One of 'trotter', 'suzuki', 'qdrift'
reps: The number of times to repeat the Trotterization circuit.
Returns:
The desired TrotterizationBase instance.
Raises:
ValueError: A string not in ['trotter', 'suzuki', 'qdrift'] is given for mode.
"""
if mode == 'trotter':
return Trotter(reps=reps)
elif mode == 'suzuki':
return Suzuki(reps=reps)
elif mode == 'qdrift':
return QDrift(reps=reps)
raise ValueError('Trotter mode {} not supported'.format(mode))
|
gadial/qiskit-terra | qiskit/qobj/utils.py | <reponame>gadial/qiskit-terra
# 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.
"""Qobj utilities and enums."""
from enum import Enum, IntEnum
import warnings
from fastjsonschema.exceptions import JsonSchemaException
from qiskit.validation.jsonschema.exceptions import SchemaValidationError
class QobjType(str, Enum):
"""Qobj.type allowed values."""
QASM = 'QASM'
PULSE = 'PULSE'
class MeasReturnType(str, Enum):
"""PulseQobjConfig meas_return allowed values."""
AVERAGE = 'avg'
SINGLE = 'single'
class MeasLevel(IntEnum):
"""MeasLevel allowed values."""
RAW = 0
KERNELED = 1
CLASSIFIED = 2
def validate_qobj_against_schema(qobj):
"""Validates a QObj against the .json schema.
Args:
qobj (Qobj): Qobj to be validated.
Raises:
SchemaValidationError: if the qobj fails schema validation
"""
warnings.warn(
"The jsonschema validation included in qiskit-terra is "
"deprecated and will be removed in a future release. "
"If you're relying on this schema validation you should "
"pull the schemas from the Qiskit/ibmq-schemas and directly "
"validate your payloads with that", DeprecationWarning,
stacklevel=2)
try:
qobj.to_dict(validate=True)
except JsonSchemaException as err:
raise SchemaValidationError(
f"Qobj validation failed. Specifically path: {err.path}" # pylint: disable=no-member
f" failed to fulfil {err.definition}" # pylint: disable=no-member
) from err
|
gadial/qiskit-terra | test/python/algorithms/optimizers/test_optimizers_scikitquant.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" Test of scikit-quant optimizers. """
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from qiskit import BasicAer
from qiskit.circuit.library import RealAmplitudes
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.exceptions import MissingOptionalLibraryError
from qiskit.opflow import PauliSumOp
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import BOBYQA, SNOBFIT, IMFIL
class TestOptimizers(QiskitAlgorithmsTestCase):
""" Test scikit-quant optimizers. """
def setUp(self):
""" Set the problem. """
super().setUp()
algorithm_globals.random_seed = 50
self.qubit_op = PauliSumOp.from_list([
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
])
def _optimize(self, optimizer):
""" launch vqe """
qe = QuantumInstance(BasicAer.get_backend('statevector_simulator'),
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed)
vqe = VQE(ansatz=RealAmplitudes(),
optimizer=optimizer,
quantum_instance=qe)
result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op)
self.assertAlmostEqual(result.eigenvalue.real, -1.857, places=1)
def test_bobyqa(self):
""" BOBYQA optimizer test. """
try:
optimizer = BOBYQA(maxiter=150)
self._optimize(optimizer)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
def test_snobfit(self):
""" SNOBFIT optimizer test. """
try:
optimizer = SNOBFIT(maxiter=100, maxfail=100, maxmp=20)
self._optimize(optimizer)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
def test_imfil(self):
""" IMFIL test. """
try:
optimizer = IMFIL(maxiter=100)
self._optimize(optimizer)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
if __name__ == '__main__':
unittest.main()
|
gadial/qiskit-terra | test/python/dagcircuit/test_compose.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test for the DAGCircuit object"""
import unittest
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.dagcircuit.exceptions import DAGCircuitError
from qiskit.test import QiskitTestCase
from qiskit.pulse import Schedule
from qiskit.circuit.gate import Gate
class TestDagCompose(QiskitTestCase):
"""Test composition of two dags"""
def setUp(self):
super().setUp()
qreg1 = QuantumRegister(3, 'lqr_1')
qreg2 = QuantumRegister(2, 'lqr_2')
creg = ClassicalRegister(2, 'lcr')
self.circuit_left = QuantumCircuit(qreg1, qreg2, creg)
self.circuit_left.h(qreg1[0])
self.circuit_left.x(qreg1[1])
self.circuit_left.p(0.1, qreg1[2])
self.circuit_left.cx(qreg2[0], qreg2[1])
self.left_qubit0 = qreg1[0]
self.left_qubit1 = qreg1[1]
self.left_qubit2 = qreg1[2]
self.left_qubit3 = qreg2[0]
self.left_qubit4 = qreg2[1]
self.left_clbit0 = creg[0]
self.left_clbit1 = creg[1]
self.condition1 = (creg, 1)
self.condition2 = (creg, 2)
def test_compose_inorder(self):
"""Composing two dags of the same width, default order.
┌───┐
lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■───────
├───┤ │ ┌───┐
lqr_1_1: |0>──┤ X ├─── rqr_1: |0>──┼──┤ X ├
┌─┴───┴──┐ │ ├───┤
lqr_1_2: |0>┤ P(0.1) ├ + rqr_2: |0>──┼──┤ Y ├ =
└────────┘ ┌─┴─┐└───┘
lqr_2_0: |0>────■───── rqr_3: |0>┤ X ├─────
┌─┴─┐ └───┘┌───┐
lqr_2_1: |0>──┤ X ├─── rqr_4: |0>─────┤ Z ├
└───┘ └───┘
lcr_0: 0 ═══════════
lcr_1: 0 ═══════════
┌───┐
lqr_1_0: |0>──┤ H ├─────■───────
├───┤ │ ┌───┐
lqr_1_1: |0>──┤ X ├─────┼──┤ X ├
┌─┴───┴──┐ │ ├───┤
lqr_1_2: |0>┤ P(0.1) ├──┼──┤ Y ├
└────────┘┌─┴─┐└───┘
lqr_2_0: |0>────■─────┤ X ├─────
┌─┴─┐ └───┘┌───┐
lqr_2_1: |0>──┤ X ├────────┤ Z ├
└───┘ └───┘
lcr_0: 0 ═══════════════════════
lcr_1: 0 ═══════════════════════
"""
qreg = QuantumRegister(5, 'rqr')
circuit_right = QuantumCircuit(qreg)
circuit_right.cx(qreg[0], qreg[3])
circuit_right.x(qreg[1])
circuit_right.y(qreg[2])
circuit_right.z(qreg[4])
dag_left = circuit_to_dag(self.circuit_left)
dag_right = circuit_to_dag(circuit_right)
# default wiring: i <- i
dag_left.compose(dag_right)
circuit_composed = dag_to_circuit(dag_left)
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit0, self.left_qubit3)
circuit_expected.x(self.left_qubit1)
circuit_expected.y(self.left_qubit2)
circuit_expected.z(self.left_qubit4)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_inorder_smaller(self):
"""Composing with a smaller RHS dag, default order.
┌───┐ ┌─────┐
lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■──┤ Tdg ├
├───┤ ┌─┴─┐└─────┘
lqr_1_1: |0>──┤ X ├─── rqr_1: |0>┤ X ├───────
┌─┴───┴──┐ └───┘
lqr_1_2: |0>┤ P(0.1) ├ + =
└────────┘
lqr_2_0: |0>────■─────
┌─┴─┐
lqr_2_1: |0>──┤ X ├───
└───┘
lcr_0: 0 ══════════════
lcr_1: 0 ══════════════
┌───┐ ┌─────┐
lqr_1_0: |0>──┤ H ├─────■──┤ Tdg ├
├───┤ ┌─┴─┐└─────┘
lqr_1_1: |0>──┤ X ├───┤ X ├───────
┌─┴───┴──┐└───┘
lqr_1_2: |0>┤ P(0.1) ├────────────
└────────┘
lqr_2_0: |0>────■─────────────────
┌─┴─┐
lqr_2_1: |0>──┤ X ├───────────────
└───┘
lcr_0: 0 ═════════════════════════
lcr_1: 0 ═════════════════════════
"""
qreg = QuantumRegister(2, 'rqr')
circuit_right = QuantumCircuit(qreg)
circuit_right.cx(qreg[0], qreg[1])
circuit_right.tdg(qreg[0])
dag_left = circuit_to_dag(self.circuit_left)
dag_right = circuit_to_dag(circuit_right)
# default wiring: i <- i
dag_left.compose(dag_right)
circuit_composed = dag_to_circuit(dag_left)
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit0, self.left_qubit1)
circuit_expected.tdg(self.left_qubit0)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_permuted(self):
"""Composing two dags of the same width, permuted wires.
┌───┐
lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■───────
├───┤ │ ┌───┐
lqr_1_1: |0>──┤ X ├─── rqr_1: |0>──┼──┤ X ├
┌─┴───┴──┐ │ ├───┤
lqr_1_2: |0>┤ P(0.1) ├ rqr_2: |0>──┼──┤ Y ├
└────────┘ ┌─┴─┐└───┘
lqr_2_0: |0>────■───── + rqr_3: |0>┤ X ├───── =
┌─┴─┐ └───┘┌───┐
lqr_2_1: |0>──┤ X ├─── rqr_4: |0>─────┤ Z ├
└───┘ └───┘
lcr_0: 0 ═════════════
lcr_1: 0 ═════════════
┌───┐ ┌───┐
lqr_1_0: |0>──┤ H ├───┤ Z ├
├───┤ ├───┤
lqr_1_1: |0>──┤ X ├───┤ X ├
┌─┴───┴──┐├───┤
lqr_1_2: |0>┤ P(0.1) ├┤ Y ├
└────────┘└───┘
lqr_2_0: |0>────■───────■──
┌─┴─┐ ┌─┴─┐
lqr_2_1: |0>──┤ X ├───┤ X ├
└───┘ └───┘
lcr_0: 0 ══════════════════
lcr_1: 0 ══════════════════
"""
qreg = QuantumRegister(5, 'rqr')
circuit_right = QuantumCircuit(qreg)
circuit_right.cx(qreg[0], qreg[3])
circuit_right.x(qreg[1])
circuit_right.y(qreg[2])
circuit_right.z(qreg[4])
dag_left = circuit_to_dag(self.circuit_left)
dag_right = circuit_to_dag(circuit_right)
# permuted wiring
dag_left.compose(dag_right, qubits=[self.left_qubit3,
self.left_qubit1,
self.left_qubit2,
self.left_qubit4,
self.left_qubit0])
circuit_composed = dag_to_circuit(dag_left)
circuit_expected = self.circuit_left.copy()
circuit_expected.z(self.left_qubit0)
circuit_expected.x(self.left_qubit1)
circuit_expected.y(self.left_qubit2)
circuit_expected.cx(self.left_qubit3, self.left_qubit4)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_permuted_smaller(self):
"""Composing with a smaller RHS dag, and permuted wires.
┌───┐ ┌─────┐
lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■──┤ Tdg ├
├───┤ ┌─┴─┐└─────┘
lqr_1_1: |0>──┤ X ├─── rqr_1: |0>┤ X ├───────
┌─┴───┴──┐ └───┘
lqr_1_2: |0>┤ P(0.1) ├ + =
└────────┘
lqr_2_0: |0>────■─────
┌─┴─┐
lqr_2_1: |0>──┤ X ├───
└───┘
lcr_0: 0 ═════════════
lcr_1: 0 ═════════════
┌───┐
lqr_1_0: |0>──┤ H ├───────────────
├───┤
lqr_1_1: |0>──┤ X ├───────────────
┌─┴───┴──┐┌───┐
lqr_1_2: |0>┤ P(0.1) ├┤ X ├───────
└────────┘└─┬─┘┌─────┐
lqr_2_0: |0>────■───────■──┤ Tdg ├
┌─┴─┐ └─────┘
lqr_2_1: |0>──┤ X ├───────────────
└───┘
lcr_0: 0 ═════════════════════════
lcr_1: 0 ═════════════════════════
"""
qreg = QuantumRegister(2, 'rqr')
circuit_right = QuantumCircuit(qreg)
circuit_right.cx(qreg[0], qreg[1])
circuit_right.tdg(qreg[0])
dag_left = circuit_to_dag(self.circuit_left)
dag_right = circuit_to_dag(circuit_right)
# permuted wiring of subset
dag_left.compose(dag_right, qubits=[self.left_qubit3, self.left_qubit2])
circuit_composed = dag_to_circuit(dag_left)
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit3, self.left_qubit2)
circuit_expected.tdg(self.left_qubit3)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_conditional(self):
"""Composing on classical bits.
┌───┐ ┌───┐ ┌─┐
lqr_1_0: |0>──┤ H ├─── rqr_0: ────────┤ H ├─┤M├───
├───┤ ┌───┐ └─┬─┘ └╥┘┌─┐
lqr_1_1: |0>──┤ X ├─── rqr_1: ─┤ X ├────┼────╫─┤M├
┌─┴───┴──┐ └─┬─┘ │ ║ └╥┘
lqr_1_2: |0>┤ P(0.1) ├ + ┌──┴──┐┌──┴──┐ ║ ║
└────────┘ rcr_0: ╡ ╞╡ ╞═╩══╬═
lqr_2_0: |0>────■───── │ = 2 ││ = 1 │ ║
┌─┴─┐ rcr_1: ╡ ╞╡ ╞════╩═
lqr_2_1: |0>──┤ X ├─── └─────┘└─────┘
└───┘
lcr_0: 0 ═════════════
lcr_1: 0 ═════════════
┌───┐
lqr_1_0: ──┤ H ├───────────────────────
├───┤ ┌───┐ ┌─┐
lqr_1_1: ──┤ X ├───────────┤ H ├────┤M├
┌─┴───┴──┐ └─┬─┘ └╥┘
lqr_1_2: ┤ P(0.1) ├──────────┼───────╫─
└────────┘ │ ║
lqr_2_0: ────■───────────────┼───────╫─
┌─┴─┐ ┌───┐ │ ┌─┐ ║
lqr_2_1: ──┤ X ├────┤ X ├────┼───┤M├─╫─
└───┘ └─┬─┘ │ └╥┘ ║
┌──┴──┐┌──┴──┐ ║ ║
lcr_0: ════════════╡ ╞╡ ╞═╩══╬═
│ = 1 ││ = 2 │ ║
lcr_1: ════════════╡ ╞╡ ╞════╩═
└─────┘└─────┘
"""
qreg = QuantumRegister(2, 'rqr')
creg = ClassicalRegister(2, 'rcr')
circuit_right = QuantumCircuit(qreg, creg)
circuit_right.x(qreg[1]).c_if(creg, 2)
circuit_right.h(qreg[0]).c_if(creg, 1)
circuit_right.measure(qreg, creg)
# permuted subset of qubits and clbits
dag_left = circuit_to_dag(self.circuit_left)
dag_right = circuit_to_dag(circuit_right)
# permuted subset of qubits and clbits
dag_left.compose(dag_right, qubits=[self.left_qubit1, self.left_qubit4],
clbits=[self.left_clbit1, self.left_clbit0])
circuit_composed = dag_to_circuit(dag_left)
circuit_expected = self.circuit_left.copy()
circuit_expected.x(self.left_qubit4).c_if(*self.condition1)
circuit_expected.h(self.left_qubit1).c_if(*self.condition2)
circuit_expected.measure(self.left_qubit4, self.left_clbit0)
circuit_expected.measure(self.left_qubit1, self.left_clbit1)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_classical(self):
"""Composing on classical bits.
┌───┐ ┌─────┐┌─┐
lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■──┤ Tdg ├┤M├
├───┤ ┌─┴─┐└─┬─┬─┘└╥┘
lqr_1_1: |0>──┤ X ├─── rqr_1: |0>┤ X ├──┤M├───╫─
┌─┴───┴──┐ └───┘ └╥┘ ║
lqr_1_2: |0>┤ P(0.1) ├ + rcr_0: 0 ════════╬════╩═ =
└────────┘ ║
lqr_2_0: |0>────■───── rcr_1: 0 ════════╩══════
┌─┴─┐
lqr_2_1: |0>──┤ X ├───
└───┘
lcr_0: 0 ═════════════
lcr_1: 0 ═════════════
┌───┐
lqr_1_0: |0>──┤ H ├──────────────────
├───┤ ┌─────┐┌─┐
lqr_1_1: |0>──┤ X ├─────■──┤ Tdg ├┤M├
┌─┴───┴──┐ │ └─────┘└╥┘
lqr_1_2: |0>┤ P(0.1) ├──┼──────────╫─
└────────┘ │ ║
lqr_2_0: |0>────■───────┼──────────╫─
┌─┴─┐ ┌─┴─┐ ┌─┐ ║
lqr_2_1: |0>──┤ X ├───┤ X ├──┤M├───╫─
└───┘ └───┘ └╥┘ ║
lcr_0: 0 ══════════════════╩════╬═
║
lcr_1: 0 ═══════════════════════╩═
"""
qreg = QuantumRegister(2, 'rqr')
creg = ClassicalRegister(2, 'rcr')
circuit_right = QuantumCircuit(qreg, creg)
circuit_right.cx(qreg[0], qreg[1])
circuit_right.tdg(qreg[0])
circuit_right.measure(qreg, creg)
dag_left = circuit_to_dag(self.circuit_left)
dag_right = circuit_to_dag(circuit_right)
# permuted subset of qubits and clbits
dag_left.compose(dag_right, qubits=[self.left_qubit1, self.left_qubit4],
clbits=[self.left_clbit1, self.left_clbit0])
circuit_composed = dag_to_circuit(dag_left)
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit1, self.left_qubit4)
circuit_expected.tdg(self.left_qubit1)
circuit_expected.measure(self.left_qubit4, self.left_clbit0)
circuit_expected.measure(self.left_qubit1, self.left_clbit1)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_condition_multiple_classical(self):
"""Compose a circuit with more than one creg.
┌───┐ ┌───┐
q5_0: q5_0: ─┤ H ├─ q5_0: ─┤ H ├─
└─┬─┘ └─┬─┘
┌──┴──┐ ┌──┴──┐
c0: + c0: 1/╡ = 1 ╞ = c0: 1/╡ = 1 ╞
└─────┘ └─────┘
c1: c1: 1/═══════ c1: 1/═══════
"""
# ref: https://github.com/Qiskit/qiskit-terra/issues/4964
qreg = QuantumRegister(1)
creg1 = ClassicalRegister(1)
creg2 = ClassicalRegister(1)
circuit_left = QuantumCircuit(qreg, creg1, creg2)
circuit_right = QuantumCircuit(qreg, creg1, creg2)
circuit_right.h(0).c_if(creg1, 1)
dag_left = circuit_to_dag(circuit_left)
dag_right = circuit_to_dag(circuit_right)
dag_composed = dag_left.compose(dag_right,
qubits=[0],
clbits=[0, 1],
inplace=False)
dag_expected = circuit_to_dag(circuit_right.copy())
self.assertEqual(dag_composed, dag_expected)
def test_compose_raises_if_splitting_condition_creg(self):
"""Verify compose raises if a condition is mapped to more than one creg.
┌───┐
q_0: q_0: ─┤ H ├─
└─┬─┘
c0: 1/ + ┌──┴──┐ = DAGCircuitError
c: 2/╡ = 2 ╞
c1: 1/ └─────┘
"""
qreg = QuantumRegister(1)
creg1 = ClassicalRegister(1)
creg2 = ClassicalRegister(1)
circuit_left = QuantumCircuit(qreg, creg1, creg2)
wide_creg = ClassicalRegister(2)
circuit_right = QuantumCircuit(qreg, wide_creg)
circuit_right.h(0).c_if(wide_creg, 2)
with self.assertRaisesRegex(DAGCircuitError, 'more than one creg'):
circuit_left.compose(circuit_right)
def test_compose_calibrations(self):
"""Test that compose carries over the calibrations."""
dag_cal = QuantumCircuit(1)
dag_cal.append(Gate('', 1, []), qargs=[0])
dag_cal.add_calibration(Gate('', 1, []), [0], Schedule())
empty_dag = circuit_to_dag(QuantumCircuit(1))
calibrated_dag = circuit_to_dag(dag_cal)
composed_dag = empty_dag.compose(calibrated_dag, inplace=False)
cal = {'': {((0,), ()): Schedule(name="sched0")}}
self.assertEqual(composed_dag.calibrations, cal)
self.assertEqual(calibrated_dag.calibrations, cal)
if __name__ == '__main__':
unittest.main()
|
gadial/qiskit-terra | qiskit/algorithms/optimizers/slsqp.py | <gh_stars>1-10
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Sequential Least SQuares Programming optimizer"""
from typing import Optional
from scipy.optimize import minimize
from .optimizer import Optimizer, OptimizerSupportLevel
class SLSQP(Optimizer):
"""
Sequential Least SQuares Programming optimizer.
SLSQP minimizes a function of several variables with any combination of bounds, equality
and inequality constraints. The method wraps the SLSQP Optimization subroutine originally
implemented by <NAME>.
SLSQP is ideal for mathematical problems for which the objective function and the constraints
are twice continuously differentiable. Note that the wrapper handles infinite values in bounds
by converting them into large floating values.
Uses scipy.optimize.minimize SLSQP.
For further detail, please refer to
See https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html
"""
_OPTIONS = ['maxiter', 'disp', 'ftol', 'eps']
# pylint: disable=unused-argument
def __init__(self,
maxiter: int = 100,
disp: bool = False,
ftol: float = 1e-06,
tol: Optional[float] = None,
eps: float = 1.4901161193847656e-08) -> None:
"""
Args:
maxiter: Maximum number of iterations.
disp: Set to True to print convergence messages.
ftol: Precision goal for the value of f in the stopping criterion.
tol: Tolerance for termination.
eps: Step size used for numerical approximation of the Jacobian.
"""
super().__init__()
for k, v in list(locals().items()):
if k in self._OPTIONS:
self._options[k] = v
self._tol = tol
def get_support_level(self):
""" Return support level dictionary """
return {
'gradient': OptimizerSupportLevel.supported,
'bounds': OptimizerSupportLevel.supported,
'initial_point': OptimizerSupportLevel.required
}
def optimize(self, num_vars, objective_function, gradient_function=None,
variable_bounds=None, initial_point=None):
super().optimize(num_vars, objective_function,
gradient_function, variable_bounds, initial_point)
if gradient_function is None and self._max_evals_grouped > 1:
epsilon = self._options['eps']
gradient_function = Optimizer.wrap_function(Optimizer.gradient_num_diff,
(objective_function, epsilon,
self._max_evals_grouped))
res = minimize(objective_function, initial_point, jac=gradient_function,
tol=self._tol, bounds=variable_bounds, method="SLSQP",
options=self._options)
return res.x, res.fun, res.nfev
|
gadial/qiskit-terra | qiskit/pulse/instructions/play.py | # 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.
"""An instruction to transmit a given pulse on a ``PulseChannel`` (i.e., those which support
transmitted pulses, such as ``DriveChannel``).
"""
from typing import Dict, Optional, Union, Tuple, Any
from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType
from qiskit.pulse.channels import PulseChannel
from qiskit.pulse.exceptions import PulseError
from qiskit.pulse.library.pulse import Pulse
from qiskit.pulse.instructions.instruction import Instruction
from qiskit.pulse.utils import deprecated_functionality
class Play(Instruction):
"""This instruction is responsible for applying a pulse on a channel.
The pulse specifies the exact time dynamics of the output signal envelope for a limited
time. The output is modulated by a phase and frequency which are controlled by separate
instructions. The pulse duration must be fixed, and is implicitly given in terms of the
cycle time, dt, of the backend.
"""
def __init__(self, pulse: Pulse,
channel: PulseChannel,
name: Optional[str] = None):
"""Create a new pulse instruction.
Args:
pulse: A pulse waveform description, such as
:py:class:`~qiskit.pulse.library.Waveform`.
channel: The channel to which the pulse is applied.
name: Name of the instruction for display purposes. Defaults to ``pulse.name``.
Raises:
PulseError: If pulse is not a Pulse type.
"""
if not isinstance(pulse, Pulse):
raise PulseError("The `pulse` argument to `Play` must be of type `library.Pulse`.")
if not isinstance(channel, PulseChannel):
raise PulseError("The `channel` argument to `Play` must be of type "
"`channels.PulseChannel`.")
if name is None:
name = pulse.name
super().__init__(operands=(pulse, channel), name=name)
@property
def pulse(self) -> Pulse:
"""A description of the samples that will be played."""
return self.operands[0]
@property
def channel(self) -> PulseChannel:
"""Return the :py:class:`~qiskit.pulse.channels.Channel` that this instruction is
scheduled on.
"""
return self.operands[1]
@property
def channels(self) -> Tuple[PulseChannel]:
"""Returns the channels that this schedule uses."""
return (self.channel, )
@property
def duration(self) -> Union[int, ParameterExpression]:
"""Duration of this instruction."""
return self.pulse.duration
def _initialize_parameter_table(self,
operands: Tuple[Any]):
"""A helper method to initialize parameter table.
Args:
operands: List of operands associated with this instruction.
"""
super()._initialize_parameter_table(operands)
if any(isinstance(val, ParameterExpression) for val in self.pulse.parameters.values()):
for value in self.pulse.parameters.values():
if isinstance(value, ParameterExpression):
for param in value.parameters:
# Table maps parameter to operand index, 0 for ``pulse``
self._parameter_table[param].append(0)
@deprecated_functionality
def assign_parameters(self,
value_dict: Dict[ParameterExpression, ParameterValueType]
) -> 'Play':
super().assign_parameters(value_dict)
pulse = self.pulse.assign_parameters(value_dict)
self._operands = (pulse, self.channel)
return self
def is_parameterized(self) -> bool:
"""Return True iff the instruction is parameterized."""
return self.pulse.is_parameterized() or super().is_parameterized()
|
gadial/qiskit-terra | qiskit/visualization/pulse_v2/generators/waveform.py | <reponame>gadial/qiskit-terra<filename>qiskit/visualization/pulse_v2/generators/waveform.py<gh_stars>1-10
# 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=unused-argument
"""Waveform generators.
A collection of functions that generate drawings from formatted input data.
See py:mod:`qiskit.visualization.pulse_v2.types` for more info on the required data.
In this module the input data is `types.PulseInstruction`.
An end-user can write arbitrary functions that generate custom drawings.
Generators in this module are called with the `formatter` and `device` kwargs.
These data provides stylesheet configuration and backend system configuration.
The format of generator is restricted to:
```python
def my_object_generator(data: PulseInstruction,
formatter: Dict[str, Any],
device: DrawerBackendInfo) -> List[ElementaryData]:
pass
```
Arbitrary generator function satisfying the above format can be accepted.
Returned `ElementaryData` can be arbitrary subclasses that are implemented in
the plotter API.
"""
import re
from fractions import Fraction
from typing import Dict, Any, List, Union
import numpy as np
from qiskit import pulse, circuit
from qiskit.pulse import instructions
from qiskit.visualization.exceptions import VisualizationError
from qiskit.visualization.pulse_v2 import drawings, types, device_info
def gen_filled_waveform_stepwise(data: types.PulseInstruction,
formatter: Dict[str, Any],
device: device_info.DrawerBackendInfo
) -> List[Union[drawings.LineData,
drawings.BoxData,
drawings.TextData]]:
"""Generate filled area objects of the real and the imaginary part of waveform envelope.
The curve of envelope is not interpolated nor smoothed and presented
as stepwise function at each data point.
Stylesheets:
- The `fill_waveform` style is applied.
Args:
data: Waveform instruction data to draw.
formatter: Dictionary of stylesheet settings.
device: Backend configuration.
Returns:
List of `LineData`, `BoxData`, or `TextData` drawings.
Raises:
VisualizationError: When the instruction parser returns invalid data format.
"""
# generate waveform data
waveform_data = _parse_waveform(data)
channel = data.inst.channel
# update metadata
meta = waveform_data.meta
qind = device.get_qubit_index(channel)
meta.update({'qubit': qind if qind is not None else 'N/A'})
if isinstance(waveform_data, types.ParsedInstruction):
# Draw waveform with fixed shape
xdata = waveform_data.xvals
ydata = waveform_data.yvals
# phase modulation
if formatter['control.apply_phase_modulation']:
ydata = np.asarray(ydata, dtype=complex) * np.exp(1j * data.frame.phase)
else:
ydata = np.asarray(ydata, dtype=complex)
return _draw_shaped_waveform(xdata=xdata,
ydata=ydata,
meta=meta,
channel=channel,
formatter=formatter)
elif isinstance(waveform_data, types.OpaqueShape):
# Draw parametric pulse with unbound parameters
# parameter name
unbound_params = []
for pname, pval in data.inst.pulse.parameters.items():
if isinstance(pval, circuit.ParameterExpression):
unbound_params.append(pname)
return _draw_opaque_waveform(init_time=data.t0,
duration=waveform_data.duration,
pulse_shape=data.inst.pulse.__class__.__name__,
pnames=unbound_params,
meta=meta,
channel=channel,
formatter=formatter)
else:
raise VisualizationError('Invalid data format is provided.')
def gen_ibmq_latex_waveform_name(data: types.PulseInstruction,
formatter: Dict[str, Any],
device: device_info.DrawerBackendInfo
) -> List[drawings.TextData]:
r"""Generate the formatted instruction name associated with the waveform.
Channel name and ID string are removed and the rotation angle is expressed in units of pi.
The controlled rotation angle associated with the CR pulse name is divided by 2.
Note that in many scientific articles the controlled rotation angle implies
the actual rotation angle, but in IQX backend the rotation angle represents
the difference between rotation angles with different control qubit states.
For example:
- 'X90p_d0_abcdefg' is converted into 'X(\frac{\pi}{2})'
- 'CR90p_u0_abcdefg` is converted into 'CR(\frac{\pi}{4})'
Stylesheets:
- The `annotate` style is applied.
Notes:
This generator can convert pulse names used in the IQX backends.
If pulses are provided by the third party providers or the user defined,
the generator output may be the as-is pulse name.
Args:
data: Waveform instruction data to draw.
formatter: Dictionary of stylesheet settings.
device: Backend configuration.
Returns:
List of `TextData` drawings.
"""
if data.is_opaque:
return []
style = {'zorder': formatter['layer.annotate'],
'color': formatter['color.annotate'],
'size': formatter['text_size.annotate'],
'va': 'center',
'ha': 'center'}
if isinstance(data.inst, pulse.instructions.Acquire):
systematic_name = 'Acquire'
latex_name = None
elif isinstance(data.inst, instructions.Delay):
systematic_name = data.inst.name or 'Delay'
latex_name = None
elif isinstance(data.inst.channel, pulse.channels.MeasureChannel):
systematic_name = 'Measure'
latex_name = None
else:
systematic_name = data.inst.pulse.name or data.inst.pulse.__class__.__name__
template = r'(?P<op>[A-Z]+)(?P<angle>[0-9]+)?(?P<sign>[pm])_(?P<ch>[dum])[0-9]+'
match_result = re.match(template, systematic_name)
if match_result is not None:
match_dict = match_result.groupdict()
sign = '' if match_dict['sign'] == 'p' else '-'
if match_dict['op'] == 'CR':
# cross resonance
if match_dict['ch'] == 'u':
op_name = r'{\rm CR}'
else:
op_name = r'\overline{\rm CR}'
# IQX name def is not standard. Echo CR is annotated with pi/4 rather than pi/2
angle_val = match_dict['angle']
frac = Fraction(int(int(angle_val)/2), 180)
if frac.numerator == 1:
angle = r'\pi/{denom:d}'.format(denom=frac.denominator)
else:
angle = r'{num:d}/{denom:d} \pi'.format(num=frac.numerator,
denom=frac.denominator)
else:
# single qubit pulse
op_name = r'{{\rm {}}}'.format(match_dict['op'])
angle_val = match_dict['angle']
if angle_val is None:
angle = r'\pi'
else:
frac = Fraction(int(angle_val), 180)
if frac.numerator == 1:
angle = r'\pi/{denom:d}'.format(denom=frac.denominator)
else:
angle = r'{num:d}/{denom:d} \pi'.format(num=frac.numerator,
denom=frac.denominator)
latex_name = r'{}({}{})'.format(op_name, sign, angle)
else:
latex_name = None
text = drawings.TextData(data_type=types.LabelType.PULSE_NAME,
channels=data.inst.channel,
xvals=[data.t0 + 0.5 * data.inst.duration],
yvals=[-formatter['label_offset.pulse_name']],
text=systematic_name,
latex=latex_name,
ignore_scaling=True,
styles=style)
return [text]
def gen_waveform_max_value(data: types.PulseInstruction,
formatter: Dict[str, Any],
device: device_info.DrawerBackendInfo
) -> List[drawings.TextData]:
"""Generate the annotation for the maximum waveform height for
the real and the imaginary part of the waveform envelope.
Maximum values smaller than the vertical resolution limit is ignored.
Stylesheets:
- The `annotate` style is applied.
Args:
data: Waveform instruction data to draw.
formatter: Dictionary of stylesheet settings.
device: Backend configuration.
Returns:
List of `TextData` drawings.
"""
if data.is_opaque:
return []
style = {'zorder': formatter['layer.annotate'],
'color': formatter['color.annotate'],
'size': formatter['text_size.annotate'],
'ha': 'center'}
# only pulses.
if isinstance(data.inst, instructions.Play):
# pulse
operand = data.inst.pulse
if isinstance(operand, pulse.ParametricPulse):
pulse_data = operand.get_waveform()
else:
pulse_data = operand
xdata = np.arange(pulse_data.duration) + data.t0
ydata = pulse_data.samples
else:
return []
# phase modulation
if formatter['control.apply_phase_modulation']:
ydata = np.asarray(ydata, dtype=complex) * np.exp(1j * data.frame.phase)
else:
ydata = np.asarray(ydata, dtype=complex)
texts = []
# max of real part
re_maxind = np.argmax(np.abs(ydata.real))
if np.abs(ydata.real[re_maxind]) > 0.01:
# generator shows only 2 digits after the decimal point.
if ydata.real[re_maxind] > 0:
max_val = u'{val:.2f}\n\u25BE'.format(val=ydata.real[re_maxind])
re_style = {'va': 'bottom'}
else:
max_val = u'\u25B4\n{val:.2f}'.format(val=ydata.real[re_maxind])
re_style = {'va': 'top'}
re_style.update(style)
re_text = drawings.TextData(data_type=types.LabelType.PULSE_INFO,
channels=data.inst.channel,
xvals=[xdata[re_maxind]],
yvals=[ydata.real[re_maxind]],
text=max_val,
styles=re_style)
texts.append(re_text)
# max of imag part
im_maxind = np.argmax(np.abs(ydata.imag))
if np.abs(ydata.imag[im_maxind]) > 0.01:
# generator shows only 2 digits after the decimal point.
if ydata.imag[im_maxind] > 0:
max_val = u'{val:.2f}\n\u25BE'.format(val=ydata.imag[im_maxind])
im_style = {'va': 'bottom'}
else:
max_val = u'\u25B4\n{val:.2f}'.format(val=ydata.imag[im_maxind])
im_style = {'va': 'top'}
im_style.update(style)
im_text = drawings.TextData(data_type=types.LabelType.PULSE_INFO,
channels=data.inst.channel,
xvals=[xdata[im_maxind]],
yvals=[ydata.imag[im_maxind]],
text=max_val,
styles=im_style)
texts.append(im_text)
return texts
def _draw_shaped_waveform(xdata: np.ndarray,
ydata: np.ndarray,
meta: Dict[str, Any],
channel: pulse.channels.PulseChannel,
formatter: Dict[str, Any],
) -> List[Union[drawings.LineData, drawings.BoxData, drawings.TextData]]:
"""A private function that generates drawings of stepwise pulse lines.
Args:
xdata: Array of horizontal coordinate of waveform envelope.
ydata: Array of vertical coordinate of waveform envelope.
meta: Metadata dictionary of the waveform.
channel: Channel associated with the waveform to draw.
formatter: Dictionary of stylesheet settings.
Returns:
List of drawings.
Raises:
VisualizationError: When the waveform color for channel is not defined.
"""
fill_objs = []
resolution = formatter['general.vertical_resolution']
# stepwise interpolation
xdata = np.concatenate((xdata, [xdata[-1] + 1]))
ydata = np.repeat(ydata, 2)
re_y = np.real(ydata)
im_y = np.imag(ydata)
time = np.concatenate(([xdata[0]], np.repeat(xdata[1:-1], 2), [xdata[-1]]))
# setup style options
style = {'alpha': formatter['alpha.fill_waveform'],
'zorder': formatter['layer.fill_waveform'],
'linewidth': formatter['line_width.fill_waveform'],
'linestyle': formatter['line_style.fill_waveform']}
try:
color_real, color_imag = formatter['color.waveforms'][channel.prefix.upper()]
except KeyError as ex:
raise VisualizationError(
f"Waveform color for channel type {channel.prefix} is not defined"
) from ex
# create real part
if np.any(re_y):
# data compression
re_valid_inds = _find_consecutive_index(re_y, resolution)
# stylesheet
re_style = {'color': color_real}
re_style.update(style)
# metadata
re_meta = {'data': 'real'}
re_meta.update(meta)
# active xy data
re_xvals = time[re_valid_inds]
re_yvals = re_y[re_valid_inds]
# object
real = drawings.LineData(data_type=types.WaveformType.REAL,
channels=channel,
xvals=re_xvals,
yvals=re_yvals,
fill=True,
meta=re_meta,
styles=re_style)
fill_objs.append(real)
# create imaginary part
if np.any(im_y):
# data compression
im_valid_inds = _find_consecutive_index(im_y, resolution)
# stylesheet
im_style = {'color': color_imag}
im_style.update(style)
# metadata
im_meta = {'data': 'imag'}
im_meta.update(meta)
# active xy data
im_xvals = time[im_valid_inds]
im_yvals = im_y[im_valid_inds]
# object
imag = drawings.LineData(data_type=types.WaveformType.IMAG,
channels=channel,
xvals=im_xvals,
yvals=im_yvals,
fill=True,
meta=im_meta,
styles=im_style)
fill_objs.append(imag)
return fill_objs
def _draw_opaque_waveform(init_time: int,
duration: int,
pulse_shape: str,
pnames: List[str],
meta: Dict[str, Any],
channel: pulse.channels.PulseChannel,
formatter: Dict[str, Any],
) -> List[Union[drawings.LineData, drawings.BoxData, drawings.TextData]]:
"""A private function that generates drawings of stepwise pulse lines.
Args:
init_time: Time when the opaque waveform starts.
duration: Duration of opaque waveform. This can be None or ParameterExpression.
pulse_shape: String that represents pulse shape.
pnames: List of parameter names.
meta: Metadata dictionary of the waveform.
channel: Channel associated with the waveform to draw.
formatter: Dictionary of stylesheet settings.
Returns:
List of drawings.
"""
fill_objs = []
fc, ec = formatter['color.opaque_shape']
# setup style options
box_style = {'zorder': formatter['layer.fill_waveform'],
'alpha': formatter['alpha.opaque_shape'],
'linewidth': formatter['line_width.opaque_shape'],
'linestyle': formatter['line_style.opaque_shape'],
'facecolor': fc,
'edgecolor': ec}
if duration is None or isinstance(duration, circuit.ParameterExpression):
duration = formatter['box_width.opaque_shape']
box_obj = drawings.BoxData(data_type=types.WaveformType.OPAQUE,
channels=channel,
xvals=[init_time, init_time + duration],
yvals=[-0.5 * formatter['box_height.opaque_shape'],
0.5 * formatter['box_height.opaque_shape']],
meta=meta,
ignore_scaling=True,
styles=box_style)
fill_objs.append(box_obj)
# parameter name
func_repr = '{func}({params})'.format(func=pulse_shape, params=', '.join(pnames))
text_style = {'zorder': formatter['layer.annotate'],
'color': formatter['color.annotate'],
'size': formatter['text_size.annotate'],
'va': 'bottom',
'ha': 'center'}
text_obj = drawings.TextData(data_type=types.LabelType.OPAQUE_BOXTEXT,
channels=channel,
xvals=[init_time + 0.5 * duration],
yvals=[0.5 * formatter['box_height.opaque_shape']],
text=func_repr,
ignore_scaling=True,
styles=text_style)
fill_objs.append(text_obj)
return fill_objs
def _find_consecutive_index(data_array: np.ndarray, resolution: float) -> np.ndarray:
"""A helper function to return non-consecutive index from the given list.
This drastically reduces memory footprint to represent a drawing,
especially for samples of very long flat-topped Gaussian pulses.
Tiny value fluctuation smaller than `resolution` threshold is removed.
Args:
data_array: The array of numbers.
resolution: Minimum resolution of sample values.
Returns:
The compressed data array.
"""
try:
vector = np.asarray(data_array, dtype=float)
diff = np.diff(vector)
diff[np.where(np.abs(diff) < resolution)] = 0
# keep left and right edges
consecutive_l = np.insert(diff.astype(bool), 0, True)
consecutive_r = np.append(diff.astype(bool), True)
return consecutive_l | consecutive_r
except ValueError:
return np.ones_like(data_array).astype(bool)
def _parse_waveform(data: types.PulseInstruction
) -> Union[types.ParsedInstruction, types.OpaqueShape]:
"""A helper function that generates an array for the waveform with
instruction metadata.
Args:
data: Instruction data set
Raises:
VisualizationError: When invalid instruction type is loaded.
Returns:
A data source to generate a drawing.
"""
inst = data.inst
meta = dict()
if isinstance(inst, instructions.Play):
# pulse
operand = inst.pulse
if isinstance(operand, pulse.ParametricPulse):
# parametric pulse
params = operand.parameters
duration = params.pop('duration', None)
if isinstance(duration, circuit.Parameter):
duration = None
meta.update({'waveform shape': operand.__class__.__name__})
meta.update({key: val.name if isinstance(val, circuit.Parameter) else val for
key, val in params.items()})
if data.is_opaque:
# parametric pulse with unbound parameter
if duration:
meta.update({'duration (cycle time)': inst.duration,
'duration (sec)': inst.duration * data.dt if data.dt else 'N/A'})
else:
meta.update({'duration (cycle time)': 'N/A',
'duration (sec)': 'N/A'})
meta.update({'t0 (cycle time)': data.t0,
't0 (sec)': data.t0 * data.dt if data.dt else 'N/A',
'phase': data.frame.phase,
'frequency': data.frame.freq,
'name': inst.name})
return types.OpaqueShape(duration=duration, meta=meta)
else:
# fixed shape parametric pulse
pulse_data = operand.get_waveform()
else:
# waveform
pulse_data = operand
xdata = np.arange(pulse_data.duration) + data.t0
ydata = pulse_data.samples
elif isinstance(inst, instructions.Delay):
# delay
xdata = np.arange(inst.duration) + data.t0
ydata = np.zeros(inst.duration)
elif isinstance(inst, instructions.Acquire):
# acquire
xdata = np.arange(inst.duration) + data.t0
ydata = np.ones(inst.duration)
acq_data = {'memory slot': inst.mem_slot.name,
'register slot': inst.reg_slot.name if inst.reg_slot else 'N/A',
'discriminator': inst.discriminator.name if inst.discriminator else 'N/A',
'kernel': inst.kernel.name if inst.kernel else 'N/A'}
meta.update(acq_data)
else:
raise VisualizationError('Unsupported instruction {inst} by '
'filled envelope.'.format(inst=inst.__class__.__name__))
meta.update({'duration (cycle time)': inst.duration,
'duration (sec)': inst.duration * data.dt if data.dt else 'N/A',
't0 (cycle time)': data.t0,
't0 (sec)': data.t0 * data.dt if data.dt else 'N/A',
'phase': data.frame.phase,
'frequency': data.frame.freq,
'name': inst.name})
return types.ParsedInstruction(xvals=xdata, yvals=ydata, meta=meta)
|
gadial/qiskit-terra | qiskit/tools/jupyter/library.py | # 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.
# pylint: disable=invalid-name,no-name-in-module,ungrouped-imports
"""A circuit library widget module"""
import ipywidgets as wid
from IPython.display import display
from qiskit import QuantumCircuit
try:
import pygments
from pygments.formatters import HtmlFormatter
from qiskit.qasm.pygments import QasmHTMLStyle, OpenQASMLexer
HAS_PYGMENTS = True
except Exception: # pylint: disable=broad-except
HAS_PYGMENTS = False
def circuit_data_table(circuit: QuantumCircuit) -> wid.HTML:
"""Create a HTML table widget for a given quantum circuit.
Args:
circuit: Input quantum circuit.
Returns:
Output widget.
"""
ops = circuit.count_ops()
num_nl = circuit.num_nonlocal_gates()
html = "<table>"
html += """<style>
table {
font-family: "IBM Plex Sans", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
border-left: 2px solid #212121;
}
th {
text-align: left;
padding: 5px 5px 5px 5px;
width: 100%;
background-color: #988AFC;
color: #fff;
font-size: 14px;
border-left: 2px solid #988AFC;
}
td {
text-align: left;
padding: 5px 5px 5px 5px;
width: 100%;
font-size: 12px;
font-weight: medium;
}
tr:nth-child(even) {background-color: #f6f6f6;}
</style>"""
html += "<tr><th>{}</th><th></tr>".format(circuit.name)
html += "<tr><td>Width</td><td>{}</td></tr>".format(circuit.width())
html += "<tr><td>Depth</td><td>{}</td></tr>".format(circuit.depth())
html += "<tr><td>Total Gates</td><td>{}</td></tr>".format(sum(ops.values()))
html += "<tr><td>Non-local Gates</td><td>{}</td></tr>".format(num_nl)
html += "</table>"
out_wid = wid.HTML(html)
return out_wid
head_style = 'font-family: IBM Plex Sans, Arial, Helvetica, sans-serif;' \
' font-size: 20px; font-weight: medium;'
property_label = wid.HTML("<p style='{}'>Circuit Properties</p>".format(head_style),
layout=wid.Layout(margin='0px 0px 10px 0px'))
def properties_widget(circuit: QuantumCircuit) -> wid.VBox:
"""Create a HTML table widget with header for a given quantum circuit.
Args:
circuit: Input quantum circuit.
Returns:
Output widget.
"""
properties = wid.VBox(children=[property_label,
circuit_data_table(circuit)],
layout=wid.Layout(width='40%',
height='auto'))
return properties
def qasm_widget(circuit: QuantumCircuit) -> wid.VBox:
"""Generate a QASM widget with header for a quantum circuit.
Args:
circuit: Input quantum circuit.
Returns:
Output widget.
Raises:
ImportError: If pygments is not installed
"""
if not HAS_PYGMENTS:
raise ImportError("pygments>2.4 must be installed for to use the qasm "
'widget. To install run "pip install pygments"')
qasm_code = circuit.qasm()
code = pygments.highlight(qasm_code, OpenQASMLexer(),
HtmlFormatter())
html_style = HtmlFormatter(style=QasmHTMLStyle).get_style_defs('.highlight')
code_style = """
<style>
.highlight
{
font-family: monospace;
font-size: 14px;
line-height: 1.7em;
}
.highlight .err { color: #000000; background-color: #FFFFFF }
%s
</style>
""" % html_style
out = wid.HTML(code_style+code,
layout=wid.Layout(max_height='500px',
height='auto',
overflow='scroll scroll'))
out_label = wid.HTML("<p style='{}'>OpenQASM</p>".format(head_style),
layout=wid.Layout(margin='0px 0px 10px 0px'))
qasm = wid.VBox(children=[out_label, out],
layout=wid.Layout(height='auto', max_height='500px', width='60%',
margin='0px 0px 0px 20px'))
qasm._code_length = len(qasm_code.split('\n'))
return qasm
def circuit_diagram_widget() -> wid.Box:
"""Create a circuit diagram widget.
Returns:
Output widget.
"""
# The max circuit height corresponds to a 20Q circuit with flat
# classical register.
top_out = wid.Output(layout=wid.Layout(width='100%',
height='auto',
max_height='1000px',
overflow='hidden scroll',))
top = wid.Box(children=[top_out], layout=wid.Layout(width='100%', height='auto'))
return top
def circuit_library_widget(circuit: QuantumCircuit) -> None:
"""Create a circuit library widget.
Args:
circuit: Input quantum circuit.
"""
qasm_wid = qasm_widget(circuit)
sep_length = str(min(20*qasm_wid._code_length, 495))
# The separator widget
sep = wid.HTML("<div style='border-left: 3px solid #212121;"
"height: {}px;'></div>".format(sep_length),
layout=wid.Layout(height='auto',
max_height='495px',
margin='40px 0px 0px 20px'))
bottom = wid.HBox(children=[properties_widget(circuit),
sep,
qasm_widget(circuit)],
layout=wid.Layout(max_height='550px',
height='auto'))
top = circuit_diagram_widget()
with top.children[0]:
display(circuit.draw(output='mpl'))
display(wid.VBox(children=[top, bottom],
layout=wid.Layout(width='100%',
height='auto')))
|
gadial/qiskit-terra | qiskit/algorithms/phase_estimators/hamiltonian_phase_estimation.py | <gh_stars>1-10
# 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.
"""Phase estimation for the spectrum of a Hamiltonian"""
from typing import Optional, Union
from qiskit import QuantumCircuit
from qiskit.utils import QuantumInstance
from qiskit.opflow import (EvolutionBase, PauliTrotterEvolution, OperatorBase,
SummedOp, PauliOp, MatrixOp, PauliSumOp, StateFn)
from qiskit.providers import BaseBackend
from .phase_estimation import PhaseEstimation
from .hamiltonian_phase_estimation_result import HamiltonianPhaseEstimationResult
from .phase_estimation_scale import PhaseEstimationScale
class HamiltonianPhaseEstimation:
r"""Run the Quantum Phase Estimation algorithm to find the eigenvalues of a Hermitian operator.
This class is nearly the same as :class:`~qiskit.algorithms.PhaseEstimation`, differing only
in that the input in that class is a unitary operator, whereas here the input is a Hermitian
operator from which a unitary will be obtained by scaling and exponentiating. The scaling is
performed in order to prevent the phases from wrapping around :math:`2\pi`.
The problem of estimating eigenvalues :math:`\lambda_j` of the Hermitian operator
:math:`H` is solved by running a circuit representing
.. math::
\exp(i b H) |\psi\rangle = \sum_j \exp(i b \lambda_j) c_j |\lambda_j\rangle,
where the input state is
.. math::
|\psi\rangle = \sum_j c_j |\lambda_j\rangle,
and :math:`\lambda_j` are the eigenvalues of :math:`H`.
Here, :math:`b` is a scaling factor sufficiently large to map positive :math:`\lambda` to
:math:`[0,\pi)` and negative :math:`\lambda` to :math:`[\pi,2\pi)`. Each time the circuit is
run, one measures a phase corresponding to :math:`lambda_j` with probability :math:`|c_j|^2`.
If :math:`H` is a Pauli sum, the bound :math:`b` is computed from the sum of the absolute
values of the coefficients of the terms. There is no way to reliably recover eigenvalues
from phases very near the endpoints of these intervals. Because of this you should be aware
that for degenerate cases, such as :math:`H=Z`, the eigenvalues :math:`\pm 1` will be
mapped to the same phase, :math:`\pi`, and so cannot be distinguished. In this case, you need
to specify a larger bound as an argument to the method ``estimate``.
This class uses and works together with :class:`~qiskit.algorithms.PhaseEstimationScale` to
manage scaling the Hamiltonian and the phases that are obtained by the QPE algorithm. This
includes setting, or computing, a bound on the eigenvalues of the operator, using this
bound to obtain a scale factor, scaling the operator, and shifting and scaling the measured
phases to recover the eigenvalues.
Note that, although we speak of "evolving" the state according the the Hamiltonian, in the
present algorithm, we are not actually considering time evolution. Rather, the role of time is
played by the scaling factor, which is chosen to best extract the eigenvalues of the
Hamiltonian.
A few of the ideas in the algorithm may be found in Ref. [1].
**Reference:**
[1]: Quantum phase estimation of multiple eigenvalues for small-scale (noisy) experiments
<NAME>, <NAME>, <NAME>
`arXiv:1809.09697 <https://arxiv.org/abs/1809.09697>`_
"""
def __init__(self,
num_evaluation_qubits: int,
quantum_instance: Optional[Union[QuantumInstance, BaseBackend]] = None) -> None:
"""
Args:
num_evaluation_qubits: The number of qubits used in estimating the phase. The phase will
be estimated as a binary string with this many bits.
quantum_instance: The quantum instance on which the circuit will be run.
"""
self._phase_estimation = PhaseEstimation(
num_evaluation_qubits=num_evaluation_qubits,
quantum_instance=quantum_instance)
def _get_scale(self, hamiltonian, bound=None) -> None:
if bound is None:
return PhaseEstimationScale.from_pauli_sum(hamiltonian)
return PhaseEstimationScale(bound)
def _get_unitary(self, hamiltonian, pe_scale, evolution) -> QuantumCircuit:
"""Evolve the Hamiltonian to obtain a unitary.
Apply the scaling to the Hamiltonian that has been computed from an eigenvalue bound
and compute the unitary by applying the evolution object.
"""
# scale so that phase does not wrap.
scaled_hamiltonian = -pe_scale.scale * hamiltonian
unitary = evolution.convert(scaled_hamiltonian.exp_i())
if not isinstance(unitary, QuantumCircuit):
unitary_circuit = unitary.to_circuit()
else:
unitary_circuit = unitary
# Decomposing twice allows some 1Q Hamiltonians to give correct results
# when using MatrixEvolution(), that otherwise would give incorrect results.
# It does not break any others that we tested.
return unitary_circuit.decompose().decompose()
# pylint: disable=arguments-differ
def estimate(self, hamiltonian: OperatorBase,
state_preparation: Optional[StateFn] = None,
evolution: Optional[EvolutionBase] = None,
bound: Optional[float] = None) -> HamiltonianPhaseEstimationResult:
"""Run the Hamiltonian phase estimation algorithm.
Args:
hamiltonian: A Hermitian operator.
state_preparation: The ``StateFn`` to be prepared, 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.
evolution: An evolution converter that generates a unitary from ``hamiltonian``. If
``None``, then the default ``PauliTrotterEvolution`` is used.
bound: An upper bound on the absolute value of the eigenvalues of
``hamiltonian``. If omitted, then ``hamiltonian`` must be a Pauli sum, or a
``PauliOp``, in which case a bound will be computed. If ``hamiltonian``
is a ``MatrixOp``, then ``bound`` may not be ``None``. The tighter the bound,
the higher the resolution of computed phases.
Returns:
HamiltonianPhaseEstimationResult instance containing the result of the estimation
and diagnostic information.
Raises:
ValueError: If ``bound`` is ``None`` and ``hamiltonian`` is not a Pauli sum, i.e. a
``PauliSumOp`` or a ``SummedOp`` whose terms are of type ``PauliOp``.
TypeError: If ``evolution`` is not of type ``EvolutionBase``.
"""
if evolution is None:
evolution = PauliTrotterEvolution()
elif not isinstance(evolution, EvolutionBase):
raise TypeError(f'Expecting type EvolutionBase, got {type(evolution)}')
if isinstance(hamiltonian, PauliSumOp):
hamiltonian = hamiltonian.to_pauli_op()
elif isinstance(hamiltonian, PauliOp):
hamiltonian = SummedOp([hamiltonian])
if isinstance(hamiltonian, SummedOp):
# remove identitiy terms
# The term propto the identity is removed from hamiltonian.
# This is done for three reasons:
# 1. Work around an unknown bug that otherwise causes the energies to be wrong in some
# cases.
# 2. Allow working with a simpler Hamiltonian, one with fewer terms.
# 3. Tighten the bound on the eigenvalues so that the spectrum is better resolved, i.e.
# occupies more of the range of values representable by the qubit register.
# The coefficient of this term will be added to the eigenvalues.
id_coefficient, hamiltonian_no_id = _remove_identity(hamiltonian)
# get the rescaling object
pe_scale = self._get_scale(hamiltonian_no_id, bound)
# get the unitary
unitary = self._get_unitary(hamiltonian_no_id, pe_scale, evolution)
elif isinstance(hamiltonian, MatrixOp):
if bound is None:
raise ValueError('bound must be specified if Hermitian operator is MatrixOp')
# Do not subtract an identity term from the matrix, so do not compensate.
id_coefficient = 0.0
pe_scale = self._get_scale(hamiltonian, bound)
unitary = self._get_unitary(hamiltonian, pe_scale, evolution)
else:
raise TypeError(f'Hermitian operator of type {type(hamiltonian)} not supported.')
if state_preparation is not None:
state_preparation = state_preparation.to_circuit_op().to_circuit()
# run phase estimation
phase_estimation_result = self._phase_estimation.estimate(
unitary=unitary, state_preparation=state_preparation)
return HamiltonianPhaseEstimationResult(
phase_estimation_result=phase_estimation_result,
id_coefficient=id_coefficient,
phase_estimation_scale=pe_scale)
def _remove_identity(pauli_sum):
"""Remove any identity operators from `pauli_sum`. Return
the sum of the coefficients of the identities and the new operator.
"""
idcoeff = 0.0
ops = []
for op in pauli_sum:
p = op.primitive
if p.x.any() or p.z.any():
ops.append(op)
else:
idcoeff += op.coeff
return idcoeff, SummedOp(ops)
|
gadial/qiskit-terra | qiskit/opflow/primitive_ops/primitive_op.py | # 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.
""" PrimitiveOp Class """
from typing import Dict, List, Optional, Set, Union, cast
import numpy as np
import scipy.linalg
from scipy.sparse import spmatrix
from qiskit import QuantumCircuit
from qiskit.circuit import Instruction, ParameterExpression
from qiskit.opflow.operator_base import OperatorBase
from qiskit.quantum_info import Operator, Pauli, SparsePauliOp, Statevector
class PrimitiveOp(OperatorBase):
r"""
A class for representing basic Operators, backed by Operator primitives from
Terra. This class (and inheritors) primarily serves to allow the underlying
primitives to "flow" - i.e. interoperability and adherence to the Operator formalism
- while the core computational logic mostly remains in the underlying primitives.
For example, we would not produce an interface in Terra in which
``QuantumCircuit1 + QuantumCircuit2`` equaled the Operator sum of the circuit
unitaries, rather than simply appending the circuits. However, within the Operator
flow summing the unitaries is the expected behavior.
Note that all mathematical methods are not in-place, meaning that they return a
new object, but the underlying primitives are not copied.
"""
def __init_subclass__(cls):
cls.__new__ = lambda cls, *args, **kwargs: super().__new__(cls)
@staticmethod
# pylint: disable=unused-argument
def __new__(cls,
primitive: Union[Instruction, QuantumCircuit, List,
np.ndarray, spmatrix, Operator, Pauli, SparsePauliOp],
coeff: Union[complex, ParameterExpression] = 1.0) -> 'PrimitiveOp':
""" A factory method to produce the correct type of PrimitiveOp subclass
based on the primitive passed in. Primitive and coeff arguments are passed into
subclass's init() as-is automatically by new().
Args:
primitive: The operator primitive being wrapped.
coeff: A coefficient multiplying the primitive.
Returns:
The appropriate PrimitiveOp subclass for ``primitive``.
Raises:
TypeError: Unsupported primitive type passed.
"""
# pylint: disable=cyclic-import
if isinstance(primitive, (Instruction, QuantumCircuit)):
from .circuit_op import CircuitOp
return super().__new__(CircuitOp)
if isinstance(primitive, (list, np.ndarray, spmatrix, Operator)):
from .matrix_op import MatrixOp
return super().__new__(MatrixOp)
if isinstance(primitive, Pauli):
from .pauli_op import PauliOp
return super().__new__(PauliOp)
if isinstance(primitive, SparsePauliOp):
from .pauli_sum_op import PauliSumOp
return super().__new__(PauliSumOp)
raise TypeError('Unsupported primitive type {} passed into PrimitiveOp '
'factory constructor'.format(type(primitive)))
def __init__(self,
primitive: Union[QuantumCircuit, Operator, Pauli, SparsePauliOp, OperatorBase],
coeff: Union[complex, ParameterExpression] = 1.0) -> None:
"""
Args:
primitive: The operator primitive being wrapped.
coeff: A coefficient multiplying the primitive.
"""
super().__init__()
self._primitive = primitive
self._coeff = coeff
@property
def primitive(self) -> Union[QuantumCircuit, Operator, Pauli, SparsePauliOp, OperatorBase]:
""" The primitive defining the underlying function of the Operator.
Returns:
The primitive object.
"""
return self._primitive
@property
def coeff(self) -> Union[complex, ParameterExpression]:
"""
The scalar coefficient multiplying the Operator.
Returns:
The coefficient.
"""
return self._coeff
@property
def num_qubits(self) -> int:
raise NotImplementedError
def primitive_strings(self) -> Set[str]:
raise NotImplementedError
def add(self, other: OperatorBase) -> OperatorBase:
raise NotImplementedError
def adjoint(self) -> OperatorBase:
raise NotImplementedError
def equals(self, other: OperatorBase) -> bool:
raise NotImplementedError
def mul(self, scalar: Union[complex, ParameterExpression]) -> OperatorBase:
if not isinstance(scalar, (int, float, complex, ParameterExpression)):
raise ValueError('Operators can only be scalar multiplied by float or complex, not '
'{} of type {}.'.format(scalar, type(scalar)))
# Need to return self.__class__ in case the object is one of the inherited OpPrimitives
return self.__class__(self.primitive, coeff=self.coeff * scalar)
def tensor(self, other: OperatorBase) -> OperatorBase:
raise NotImplementedError
def tensorpower(self, other: int) -> Union[OperatorBase, int]:
# Hack to make Z^(I^0) work as intended.
if other == 0:
return 1
if not isinstance(other, int) or other < 0:
raise TypeError('Tensorpower can only take positive int arguments')
temp = PrimitiveOp(self.primitive, coeff=self.coeff) # type: OperatorBase
for _ in range(other - 1):
temp = temp.tensor(self)
return temp
def compose(self, other: OperatorBase,
permutation: Optional[List[int]] = None, front: bool = False) -> \
OperatorBase:
# pylint: disable=cyclic-import
from ..list_ops.composed_op import ComposedOp
new_self, other = self._expand_shorter_operator_and_permute(other, permutation)
if isinstance(other, ComposedOp):
comp_with_first = new_self.compose(other.oplist[0])
if not isinstance(comp_with_first, ComposedOp):
new_oplist = [comp_with_first] + other.oplist[1:]
return ComposedOp(new_oplist, coeff=other.coeff)
return ComposedOp([new_self] + other.oplist, coeff=other.coeff)
return ComposedOp([new_self, other])
def power(self, exponent: int) -> OperatorBase:
if not isinstance(exponent, int) or exponent <= 0:
raise TypeError('power can only take positive int arguments')
temp = PrimitiveOp(self.primitive, coeff=self.coeff) # type: OperatorBase
for _ in range(exponent - 1):
temp = temp.compose(self)
return temp
def _expand_dim(self, num_qubits: int) -> OperatorBase:
raise NotImplementedError
def permute(self, permutation: List[int]) -> OperatorBase:
raise NotImplementedError
def exp_i(self) -> OperatorBase:
""" Return Operator exponentiation, equaling e^(-i * op)"""
# pylint: disable=cyclic-import
from ..evolutions.evolved_op import EvolvedOp
return EvolvedOp(self)
def log_i(self, massive: bool = False) -> OperatorBase:
"""Return a ``MatrixOp`` equivalent to log(H)/-i for this operator H. This
function is the effective inverse of exp_i, equivalent to finding the Hermitian
Operator which produces self when exponentiated."""
# pylint: disable=cyclic-import
from ..operator_globals import EVAL_SIG_DIGITS
from .matrix_op import MatrixOp
return MatrixOp(np.around(scipy.linalg.logm(self.to_matrix(massive=massive)) / -1j,
decimals=EVAL_SIG_DIGITS))
def __str__(self) -> str:
raise NotImplementedError
def __repr__(self) -> str:
return "{}({}, coeff={})".format(type(self).__name__, repr(self.primitive), self.coeff)
def eval(
self,
front: Optional[
Union[str, Dict[str, complex], np.ndarray, OperatorBase, Statevector]
] = None,
) -> Union[OperatorBase, complex]:
raise NotImplementedError
@property
def parameters(self):
params = set()
if isinstance(self.primitive, (OperatorBase, QuantumCircuit)):
params.update(self.primitive.parameters)
if isinstance(self.coeff, ParameterExpression):
params.update(self.coeff.parameters)
return params
def assign_parameters(self, param_dict: dict) -> OperatorBase:
param_value = self.coeff
if isinstance(self.coeff, ParameterExpression):
unrolled_dict = self._unroll_param_dict(param_dict)
if isinstance(unrolled_dict, list):
# pylint: disable=cyclic-import
from ..list_ops.list_op import ListOp
return ListOp([self.assign_parameters(param_dict) for param_dict in unrolled_dict])
if self.coeff.parameters <= set(unrolled_dict.keys()):
binds = {param: unrolled_dict[param] for param in self.coeff.parameters}
param_value = float(self.coeff.bind(binds))
return self.__class__(self.primitive, coeff=param_value)
# Nothing to collapse here.
def reduce(self) -> OperatorBase:
return self
def to_matrix(self, massive: bool = False) -> np.ndarray:
raise NotImplementedError
def to_matrix_op(self, massive: bool = False) -> OperatorBase:
""" Returns a ``MatrixOp`` equivalent to this Operator. """
coeff = self.coeff
op = self.copy()
op._coeff = 1
prim_mat = op.to_matrix(massive=massive)
from .matrix_op import MatrixOp
return MatrixOp(prim_mat, coeff=coeff)
def to_instruction(self) -> Instruction:
""" Returns an ``Instruction`` equivalent to this Operator. """
raise NotImplementedError
def to_circuit(self) -> QuantumCircuit:
""" Returns a ``QuantumCircuit`` equivalent to this Operator. """
qc = QuantumCircuit(self.num_qubits)
qc.append(self.to_instruction(), qargs=range(self.primitive.num_qubits))
return qc.decompose()
def to_circuit_op(self) -> OperatorBase:
""" Returns a ``CircuitOp`` equivalent to this Operator. """
from .circuit_op import CircuitOp
if self.coeff == 0:
return CircuitOp(QuantumCircuit(self.num_qubits), coeff=0)
return CircuitOp(self.to_circuit(), coeff=self.coeff)
def to_pauli_op(self, massive: bool = False) -> OperatorBase:
""" Returns a sum of ``PauliOp`` s equivalent to this Operator. """
# pylint: disable=cyclic-import
from .matrix_op import MatrixOp
mat_op = cast(MatrixOp, self.to_matrix_op(massive=massive))
sparse_pauli = SparsePauliOp.from_operator(mat_op.primitive)
if not sparse_pauli.to_list():
from ..operator_globals import I
return (I ^ self.num_qubits) * 0.0
from .pauli_op import PauliOp
if len(sparse_pauli) == 1:
label, coeff = sparse_pauli.to_list()[0]
coeff = coeff.real if np.isreal(coeff) else coeff
return PauliOp(Pauli(label), coeff * self.coeff)
from ..list_ops.summed_op import SummedOp
return SummedOp(
[
PrimitiveOp(
Pauli(label),
coeff.real if coeff == coeff.real else coeff,
)
for (label, coeff) in sparse_pauli.to_list()
],
self.coeff,
)
|
trigaten/DAIDE | tests/str_parse_str_test.py | <gh_stars>0
from DAIDE import Order, Province, Arrangement, Unit
from DAIDE import YES
from DAIDE import MTO, SUP, CVY, CTO, VIA
from DAIDE import PRP, FCT
from DAIDE import ALY
from DAIDE import XDO
from DAIDE import AND, ORR
from utils import EXAMPLE_ORDER, EXAMPLE_UNIT, EXAMPLE_PROVINCE, str_parse_str_test
"""lvl0"""
object = EXAMPLE_PROVINCE
str_parse_str_test(object)
object = EXAMPLE_UNIT
str_parse_str_test(object)
object = ALY(["FFF", "FFF"], ["FFF", "FFF"])
str_parse_str_test(object)
# orders
object = EXAMPLE_ORDER
str_parse_str_test(object)
object = Order(EXAMPLE_UNIT, MTO(EXAMPLE_PROVINCE))
str_parse_str_test(object)
object = Order(EXAMPLE_UNIT, SUP(EXAMPLE_UNIT))
str_parse_str_test(object)
object = Order(EXAMPLE_UNIT, SUP(EXAMPLE_UNIT, MTO(EXAMPLE_PROVINCE)))
str_parse_str_test(object)
object = Order(EXAMPLE_UNIT, CVY(EXAMPLE_UNIT, CTO(EXAMPLE_PROVINCE)))
str_parse_str_test(object)
object = Order(EXAMPLE_UNIT, CTO(EXAMPLE_PROVINCE, VIA([EXAMPLE_PROVINCE, EXAMPLE_PROVINCE])))
str_parse_str_test(object)
"""lvl10"""
object = PRP(AND([XDO(EXAMPLE_ORDER), XDO(EXAMPLE_ORDER)]))
str_parse_str_test(object)
object = FCT(AND([XDO(EXAMPLE_ORDER), XDO(EXAMPLE_ORDER)]))
str_parse_str_test(object)
"""lvl20"""
object = XDO(EXAMPLE_ORDER)
str_parse_str_test(object)
"""lvl30"""
object = AND([EXAMPLE_ORDER, EXAMPLE_ORDER])
str_parse_str_test(object)
object = ORR([EXAMPLE_ORDER, EXAMPLE_ORDER])
str_parse_str_test(object)
object = AND([XDO(EXAMPLE_ORDER), XDO(EXAMPLE_ORDER)])
str_parse_str_test(object)
object = YES(AND([XDO(EXAMPLE_ORDER), XDO(EXAMPLE_ORDER)]))
str_parse_str_test(object)
|
trigaten/DAIDE | src/DAIDE/syntax/lvl10/statement.py | __author__ = "<NAME>"
__email__ = "<EMAIL>"
from DAIDE.core import SimpleParensObject
class FCT(SimpleParensObject):
"""FCT (arrangement)"""
pass |
trigaten/DAIDE | src/DAIDE/syntax/lvl0/unit.py | __author__ = "<NAME>"
__email__ = "<EMAIL>"
import re
from DAIDE.core import DaideObject
from DAIDE.utils.parsing import consume
from DAIDE.utils.exceptions import ParseError
class Unit(DaideObject):
regex = re.compile("^[A-Za-z]{3}\s[A-Za-z]{3}\s[A-Za-z]{3}")
def __init__(self, string):
self.string = string
def __str__(self):
return f"{self.string}"
@classmethod
def parse(cls, string, parens=False):
"""Parse UNIT or (UNIT)"""
if parens:
string = consume(string, "(")
match = cls.regex.match(string)
if match:
matched_string = match.group()
unit = Unit(matched_string)
rest = string[len(matched_string):]
if parens:
rest = consume(rest, ")")
return unit, rest
else:
raise ParseError(string, "UNIT") |
trigaten/DAIDE | src/DAIDE/syntax/lvl0/__init__.py | <gh_stars>0
from DAIDE.syntax.lvl0.order import *
from DAIDE.syntax.lvl0.unit import *
from DAIDE.syntax.lvl0.province import *
from DAIDE.syntax.lvl0.alliance import *
from DAIDE.syntax.lvl0.response import * |
trigaten/DAIDE | src/DAIDE/syntax/lvl20/xdo.py | <reponame>trigaten/DAIDE
__author__ = "<NAME>"
__email__ = "<EMAIL>"
from DAIDE.core import SimpleParensObject
class XDO(SimpleParensObject):
"""XDO (arrangement)"""
pass |
trigaten/DAIDE | src/DAIDE/syntax/lvl30/binop.py | __author__ = "<NAME>"
__email__ = "<EMAIL>"
from abc import ABC
from DAIDE.core import DaideObject
from DAIDE.core import Arrangement
from DAIDE.utils.parsing import consume, parse_with_parens
class Binop(DaideObject, ABC):
"""Abstract Base Class for BINOP DAIDE words like AND, ORR"""
def __init__(self, arrangements):
self.arrangements = arrangements
def __str__(self):
if len(self.arrangements) == 0:
return ""
elif len(self.arrangements) == 1:
return str(self.arrangements[0])
return self.__class__.__name__ + "".join([f" ({str(a)})" for a in self.arrangements])
@classmethod
def parse(cls, string):
OP = string[:3]
rest = string[3:]
arrangements = []
while rest[:2] == " (":
rest = consume(rest, " ")
arrangement, rest = parse_with_parens(rest, Arrangement)
arrangements.append(arrangement)
for subclass in Binop.__subclasses__():
if subclass.__name__ == OP:
return subclass(arrangements), rest
class AND(Binop):
pass
class ORR(Binop):
pass |
trigaten/DAIDE | tests/utils.py | <gh_stars>0
"""Property base testing"""
from DAIDE import Unit, Order, HLD
from DAIDE import Province
EXAMPLE_UNIT = Unit("FFF FFF FFF")
EXAMPLE_ORDER = Order(EXAMPLE_UNIT, HLD())
EXAMPLE_PROVINCE = Province("ADR")
def str_parse_str_test(arrangement):
"""
A property base test which ensures that
the str of an object is equivalent to
parsing that str then converting it back to str
"""
s = str(arrangement)
o, r = type(arrangement).parse(s)
assert r == "", "not everything parsed: " + r
assert s == str(o), f"{arrangement.__class__.__name__} SPS test failed: \n" + s + "\n" + str(o) |
trigaten/DAIDE | src/DAIDE/core.py | __author__ = "<NAME>"
__email__ = "<EMAIL>"
from abc import ABC, abstractmethod
import DAIDE.utils.parsing as parsing
from DAIDE.utils.parsing import consume, parse_with_parens
class DaideObject(ABC):
"""Abstract Base Class for DAIDE objects"""
@abstractmethod
def __str__(self):
raise NotImplementedError()
@classmethod
@abstractmethod
def parse(cls, str):
return Arrangement.parse(str)
class Arrangement(DaideObject, ABC):
@abstractmethod
def __str__(self):
raise NotImplementedError()
@classmethod
@abstractmethod
def parse(cls, string):
from DAIDE.syntax.lvl0.order import Order
from DAIDE.syntax.lvl0.response import Response
from DAIDE.syntax.lvl10.statement import FCT
from DAIDE.syntax.lvl20.xdo import XDO
from DAIDE.syntax.lvl30.binop import Binop
subclasses = Response.__subclasses__() + Binop.__subclasses__() + [XDO,FCT]
for subclass in subclasses:
if consume(string, subclass.__name__, False) != False:
arrangement, rest = subclass.parse(string)
break
else:
arrangement, rest = Order.parse(string)
return arrangement, rest
class SimpleParensObject(DaideObject):
"""
Parsing class for classes that use simple parentheses + arrangement syntax
e.g. YES (arrangement), PRP (arrangement)
"""
def __init__(self, arrangement):
self.arrangement = arrangement
def __str__(self):
return f"{str(self.__class__.__name__)} ({self.arrangement})"
@classmethod
def parse(cls, string):
rest = consume(string, cls.__name__ + " ")
arrangement, rest = parse_with_parens(rest, Arrangement)
return cls(arrangement), rest
def parse(string):
object, rest = DaideObject.parse(string)
if rest != "":
raise parsing.ParseError("Couldnt completely parse string")
return object
|
trigaten/DAIDE | src/DAIDE/syntax/__init__.py | from DAIDE.syntax.lvl0 import *
from DAIDE.syntax.lvl10 import *
from DAIDE.syntax.lvl20 import *
from DAIDE.syntax.lvl30 import *
|
trigaten/DAIDE | src/DAIDE/__init__.py | from DAIDE.syntax import *
from DAIDE.core import (
DaideObject, Arrangement, parse
)
|
trigaten/DAIDE | src/DAIDE/syntax/lvl20/__init__.py | from DAIDE.syntax.lvl20.xdo import XDO |
trigaten/DAIDE | src/DAIDE/syntax/lvl10/proposal.py | <reponame>trigaten/DAIDE<gh_stars>0
__author__ = "<NAME>"
__email__ = "<EMAIL>"
from DAIDE.core import SimpleParensObject
class PRP(SimpleParensObject):
"""PRP (arrangement)"""
pass
|
trigaten/DAIDE | src/DAIDE/syntax/lvl0/order.py | __author__ = "<NAME>"
__email__ = "<EMAIL>"
from functools import reduce
import re
import DAIDE.config as config
from DAIDE.core import DaideObject
from DAIDE.utils.parsing import consume
from DAIDE.utils.exceptions import ParseError
from DAIDE.syntax.lvl0.unit import Unit
from DAIDE.syntax.lvl0.province import Province
class Order(DaideObject):
"""(unit) order_type"""
def __init__(self, unit, order_type, non_DAIDE_order=None):
self.unit = unit
self.order_type = order_type
self.non_DAIDE_order = non_DAIDE_order
def __str__(self):
if self.non_DAIDE_order:
return str(self.non_DAIDE_order)
return f"({str(self.unit)}) {str(self.order_type)}"
@classmethod
def parse(cls, string):
if not config.ORDERS_DAIDE:
regex = re.compile("^([^\(\)]*)")
match = regex.match(string)
if match:
order = match.group()
rest = string[len(order):]
return Order(None, None, non_DAIDE_order=order), rest
unit, rest = Unit.parse(string, True)
rest = consume(rest, " ")
for subclass in Order.__subclasses__():
# print(subclass.__name__, rest)
# print(consume(rest, subclass.__name__, False))
if consume(rest, subclass.__name__, False) != False:
# print("HERE")
order_type, rest = subclass.parse(rest)
break
else:
raise ParseError(string, "Order")
return Order(unit, order_type), rest
class HLD(Order):
"""
(unit) HLD
e.g. (ENG AMY LVP) HLD
"""
def __init__(self):
pass
def __str__(self):
return "HLD"
@classmethod
def parse(cls, string):
rest = consume(string, "HLD")
return HLD(), rest
class MTO(Order):
regex = re.compile("^(ADR|AEG|ALB|ANK|APU|ARM|BAL|BAR|BEL|BER|BLA|BOH|BRE|BUD|BUL|BUR|CLY|CON|DEN|EAS|ECH|EDI|FIN|GAL|GAS|GOB|GOL|GRE|HEL|HOL|ION|IRI|KIE|LON|LVN|LVP|MAO|MAR|MOS|MUN|NAF|NAO|NAP|NTH|NWG|NWY|PAR|PIC|PIE|POR|PRU|ROM|RUH|RUM|SER|SEV|SIL|SKA|SMY|SPA|STP|SWE|SYR|TRI|TUN|TUS|TYR|TYS|UKR|VEN|VIE|WAL|WAR|WES|YOR)")
def __init__(self, province):
"""MTO province"""
self.province = province
def __str__(self):
return "MTO " + str(self.province)
@classmethod
def parse(cls, string):
rest = consume(string, "MTO ")
match = cls.regex.match(rest)
if match:
province = match.group()
rest = rest[len(province):]
else:
raise ParseError(string, "MTO")
return MTO(province), rest
class SUP(Order):
def __init__(self, unit, mto_order=None):
"""SUP (unit) **OR** SUP (unit) MTO prov_no_coast"""
self.unit = unit
self.mto_order = mto_order
def __str__(self):
return f"SUP ({str(self.unit)})" + (" " + str(self.mto_order) if self.mto_order else "")
@classmethod
def parse(cls, string):
rest = consume(string, "SUP ")
unit, rest = Unit.parse(rest, parens=True)
mto = None
if rest[:4] == " MTO":
rest = consume(rest, " ")
mto, rest = MTO.parse(rest)
return SUP(unit, mto), rest
class CVY(Order):
def __init__(self, unit, cto_order):
"""CVY (unit) CTO province"""
self.unit = unit
self.cto_order = cto_order
def __str__(self):
return f"CVY ({str(self.unit)})" + (" " + str(self.cto_order) if self.cto_order else "")
@classmethod
def parse(cls, string):
rest = consume(string, "CVY ")
unit, rest = Unit.parse(rest, parens=True)
cto = None
if rest[:4] == " CTO":
rest = consume(rest, " ")
cto, rest = CTO.parse(rest)
return CVY(unit, cto), rest
class CTO(Order):
def __init__(self, province, via_order=None):
"""CTO province VIA (sea_province sea_province ...)"""
self.province = province
self.via_order = via_order
def __str__(self):
return f"CTO {str(self.province)}" + (" " + str(self.via_order) if self.via_order else "")
@classmethod
def parse(cls, string):
rest = consume(string, "CTO ")
province, rest = Province.parse(rest)
via = None
if rest[:4] == " VIA":
rest = consume(rest, " ")
via, rest = VIA.parse(rest)
return CTO(province, via), rest
class VIA(Order):
def __init__(self, provinces):
self.provinces = provinces
def __str__(self):
return "VIA (" + reduce(lambda s, a: f"{s} " + str(a), self.provinces) + ")"
@classmethod
def parse(cls, string):
rest = consume(string, "VIA (")
provinces = []
province1, rest = Province.parse(rest)
provinces.append(province1)
while rest[0] == " ":
rest = consume(rest, " ")
province, rest = Province.parse(rest)
provinces.append(province)
rest = consume(rest, ")")
return VIA(provinces), rest |
trigaten/DAIDE | src/DAIDE/syntax/lvl10/__init__.py | from DAIDE.syntax.lvl10.proposal import *
from DAIDE.syntax.lvl10.statement import * |
trigaten/DAIDE | src/DAIDE/syntax/lvl0/province.py | <reponame>trigaten/DAIDE<filename>src/DAIDE/syntax/lvl0/province.py
__author__ = "<NAME>"
__email__ = "<EMAIL>"
import re
from DAIDE.core import DaideObject
from DAIDE.utils.exceptions import ParseError
class Province(DaideObject):
regex = re.compile("^(ADR|AEG|ALB|ANK|APU|ARM|BAL|BAR|BEL|BER|BLA|BOH|BRE|BUD|BUL|BUR|CLY|CON|DEN|EAS|ECH|EDI|FIN|GAL|GAS|GOB|GOL|GRE|HEL|HOL|ION|IRI|KIE|LON|LVN|LVP|MAO|MAR|MOS|MUN|NAF|NAO|NAP|NTH|NWG|NWY|PAR|PIC|PIE|POR|PRU|ROM|RUH|RUM|SER|SEV|SIL|SKA|SMY|SPA|STP|SWE|SYR|TRI|TUN|TUS|TYR|TYS|UKR|VEN|VIE|WAL|WAR|WES|YOR)")
def __init__(self, string):
self.string = string
def __str__(self):
return self.string
@classmethod
def parse(cls, string):
"""Parse PROVINCE"""
match = cls.regex.match(string)
if match:
matched_string = match.group()
province = Province(matched_string)
rest = string[len(matched_string):]
return province, rest
else:
raise ParseError(string, "PROVINCE") |
trigaten/DAIDE | src/DAIDE/utils/__init__.py | <filename>src/DAIDE/utils/__init__.py
from DAIDE.utils.exceptions import ParseError
from DAIDE.utils.exceptions import ConsumeError |
trigaten/DAIDE | src/DAIDE/syntax/lvl0/response.py | <filename>src/DAIDE/syntax/lvl0/response.py
__author__ = "<NAME>"
__email__ = "<EMAIL>"
from DAIDE.core import SimpleParensObject, Arrangement
from DAIDE.utils.parsing import consume, parse_with_parens
class Response(SimpleParensObject):
"""YES, REJ, stuff like that"""
@classmethod
def parse(cls, string):
response = string[:3]
rest = string[3:]
rest = consume(rest, " ")
arrangement, rest = parse_with_parens(rest, Arrangement)
for subclass in Response.__subclasses__():
if subclass.__name__ == response:
return subclass(arrangement), rest
class YES(Response):
pass
class HUH(Response):
pass |
trigaten/DAIDE | src/DAIDE/syntax/lvl30/__init__.py | from DAIDE.syntax.lvl30.binop import * |
trigaten/DAIDE | src/DAIDE/utils/parsing.py | __author__ = "<NAME>"
__email__ = "<EMAIL>"
from DAIDE.utils.exceptions import ConsumeError
def consume(string, sub, error=True):
""""""
len_sub = len(sub)
if string[:len_sub] == sub:
return string[len_sub:]
else:
if error:
raise ConsumeError(string, f"Consume \"{sub}\"")
else:
return False
def parse_with_parens(string, _class):
rest = consume(string, "(")
parsed_class, rest = _class.parse(rest)
rest = consume(rest, ")")
return parsed_class, rest |
trigaten/DAIDE | src/DAIDE/syntax/lvl0/alliance.py | <filename>src/DAIDE/syntax/lvl0/alliance.py
__author__ = "<NAME>"
__email__ = "<EMAIL>"
from functools import reduce
import re
import DAIDE.config as config
from DAIDE.core import DaideObject
from DAIDE.utils.parsing import consume
from DAIDE.utils.exceptions import ParseError
from DAIDE.syntax.lvl0.unit import Unit
from DAIDE.syntax.lvl0.province import Province
class ALY(DaideObject):
def __init__(self, allies, opponenents) -> None:
self.allies = allies
self.opponenents = opponenents
def __str__(self):
allies_str = reduce(lambda s, a: f"{s} " + str(a), self.allies)
opponents_str = reduce(lambda s, a: f"{s} " + str(a), self.opponenents)
return f"ALY ({allies_str}) VSS ({opponents_str})"
@classmethod
def parse(self, string):
groups = re.findall(r'\(([a-zA-Z\s]*)\)', string)
if len(groups) != 2:
more = len(groups) > 2
raise ParseError("Found " + "more" if more else "less" + " 2 groups", "ALY")
rest = consume(string, "ALY (")
allies = groups[0].split(" ")
opponents = groups[1].split(" ")
rest = consume(rest, groups[0])
rest = consume(rest, ") VSS (")
rest = consume(rest, groups[1])
rest = consume(rest, ")")
if allies and opponents:
return ALY(allies, opponents), rest
else:
raise ParseError("A minimum of 2 powers are needed for an alliance")
if __name__ == "__main__":
x = ALY(["FFF", "FFF"], ["FFF", "FFF"])
print(ALY.parse(str(x))) |
trigaten/DAIDE | src/DAIDE/config.py | # orders will not necessarily be DAIDE syntax
# Diplomacy Github project uses shorthand (e.g. STP/SC S A WAR - LVN)
ORDERS_DAIDE = True |
trigaten/DAIDE | src/DAIDE/utils/exceptions.py | __author__ = "<NAME>"
__email__ = "<EMAIL>"
class ParseError(Exception):
def __init__(self, string, p_type):
super().__init__("Can't parse \"" + string + "\" as " + p_type + ".")
class ConsumeError(ParseError):
def __init__(self, string, to_consume):
super().__init__(to_consume, string) |
trigaten/DAIDE | src/DAIDE/utils/descend.py |
# def get_leaf_descendents(class_):
# leaf_descendants = []
# for descendent in class_.__subclasses__():
# leaf_descendants.append(descendent)
# leaf_descendants = leaf_descendants + get_leaf_descendents(descendent)
# return leaf_descendants
# if __name__ == "__main__":
# from DAIDE.syntax.daide_object import DAIDE_OBJECT
# print(get_leaf_descendents(DAIDE_OBJECT)) |
DaleMcGrew/WeVoteServer | import_export_targetsmart/controllers.py | # import_export_targetsmart/controllers.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from .models import TargetSmartApiCounterManager
from config.base import get_environment_variable
from exception.models import handle_exception, handle_record_found_more_than_one_exception
import json
import requests
from voter.models import VoterContactEmail
import wevote_functions.admin
from wevote_functions.functions import positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
TARGETSMART_API_KEY = get_environment_variable("TARGETSMART_API_KEY", no_exception=True)
TARGETSMART_EMAIL_SEARCH_URL = "https://api.targetsmart.com/person/email-search"
TARGETSMART_PHONE_SEARCH_URL = "https://api.targetsmart.com/person/phone-search"
def augment_emails_for_voter_with_targetsmart(voter_we_vote_id=''):
status = ''
success = True
from voter.models import VoterManager
voter_manager = VoterManager()
# Augment all voter contacts with data from SendGrid and TargetSmart
voter_contact_results = voter_manager.retrieve_voter_contact_email_list(
imported_by_voter_we_vote_id=voter_we_vote_id)
if voter_contact_results['voter_contact_email_list_found']:
email_addresses_returned_list = voter_contact_results['email_addresses_returned_list']
# Get list of emails which need to be augmented (updated) with data from TargetSmart
contact_email_augmented_list_as_dict = {}
results = voter_manager.retrieve_contact_email_augmented_list(
email_address_text_list=email_addresses_returned_list,
read_only=False,
)
if results['contact_email_augmented_list_found']:
# We retrieve all existing so we don't need 200 queries within update_or_create_contact_email_augmented
contact_email_augmented_list_as_dict = results['contact_email_augmented_list_as_dict']
# Make sure we have an augmented entry for each email
for email_address_text in email_addresses_returned_list:
voter_manager.update_or_create_contact_email_augmented(
email_address_text=email_address_text,
existing_contact_email_augmented_dict=contact_email_augmented_list_as_dict)
# Get list of emails which need to be augmented (updated) with data from TargetSmart
results = voter_manager.retrieve_contact_email_augmented_list(
checked_against_targetsmart_more_than_x_days_ago=15,
email_address_text_list=email_addresses_returned_list,
read_only=False,
)
if results['contact_email_augmented_list_found']:
contact_email_augmented_list = results['contact_email_augmented_list']
contact_email_augmented_list_as_dict = results['contact_email_augmented_list_as_dict']
email_addresses_returned_list = results['email_addresses_returned_list']
email_addresses_remaining_list = email_addresses_returned_list
# Now reach out to TargetSmart, in blocks of 200
failed_api_count = 0
loop_count = 0
safety_valve_triggered = False
while len(email_addresses_remaining_list) > 0 and not safety_valve_triggered:
loop_count += 1
safety_valve_triggered = loop_count >= 250
email_addresses_for_query = email_addresses_remaining_list[:200]
email_addresses_remaining_list = \
list(set(email_addresses_remaining_list) - set(email_addresses_for_query))
targetsmart_augmented_email_list_dict = {}
targetsmart_results = query_targetsmart_api_to_augment_email_list(email_list=email_addresses_for_query)
if not targetsmart_results['success']:
failed_api_count += 1
if failed_api_count >= 3:
safety_valve_triggered = True
status += "TARGET_SMART_API_FAILED_3_TIMES "
elif targetsmart_results['augmented_email_list_found']:
# A dict of results from TargetSmart, with email_address_text as the key
targetsmart_augmented_email_list_dict = targetsmart_results['augmented_email_list_dict']
# Update our cached augmented data
for contact_email_augmented in contact_email_augmented_list:
if contact_email_augmented.email_address_text in targetsmart_augmented_email_list_dict:
augmented_email = \
targetsmart_augmented_email_list_dict[contact_email_augmented.email_address_text]
targetsmart_id = augmented_email['targetsmart_id'] \
if 'targetsmart_id' in augmented_email else None
targetsmart_source_state = augmented_email['targetsmart_source_state'] \
if 'targetsmart_source_state' in augmented_email else None
results = voter_manager.update_or_create_contact_email_augmented(
checked_against_targetsmart=True,
email_address_text=contact_email_augmented.email_address_text,
existing_contact_email_augmented_dict=contact_email_augmented_list_as_dict,
targetsmart_id=targetsmart_id,
targetsmart_source_state=targetsmart_source_state,
)
if results['success']:
# Now update all of the VoterContactEmail entries, irregardless of whose contact it is
defaults = {
'state_code': targetsmart_source_state,
}
number_updated = VoterContactEmail.objects.filter(
email_address_text__iexact=contact_email_augmented.email_address_text) \
.update(defaults)
status += "NUMBER_OF_VOTER_CONTACT_EMAIL_UPDATED: " + str(number_updated) + " "
results = {
'success': success,
'status': status,
}
return results
def query_targetsmart_api_to_augment_email_list(email_list=[]):
success = True
status = ""
augmented_email_list_dict = {}
augmented_email_list_found = False
json_from_targetsmart = {}
if email_list is None or len(email_list) == 0:
status += "MISSING_EMAIL_LIST "
success = False
results = {
'success': success,
'status': status,
'augmented_email_list_found': augmented_email_list_found,
'augmented_email_list_dict': augmented_email_list_dict,
}
return results
number_of_items_sent_in_query = len(email_list)
try:
api_key = TARGETSMART_API_KEY
emails_param = ",".join(email_list)
# Get the ballot info at this address
response = requests.get(
TARGETSMART_EMAIL_SEARCH_URL,
headers={"x-api-key": api_key},
params={
"emails": emails_param,
})
json_from_targetsmart = json.loads(response.text)
if 'message' in json_from_targetsmart:
status += json_from_targetsmart['message'] + " "
if json_from_targetsmart['message'].strip() in ['Failed', 'Forbidden']:
success = False
# Use TargetSmart API call counter to track the number of queries we are doing each day
api_counter_manager = TargetSmartApiCounterManager()
api_counter_manager.create_counter_entry(
'email-search',
number_of_items_sent_in_query=number_of_items_sent_in_query)
except Exception as e:
success = False
status += 'QUERY_TARGETSMART_EMAIL_SEARCH_API_FAILED: ' + str(e) + ' '
handle_exception(e, logger=logger, exception_message=status)
if 'results' in json_from_targetsmart:
results_list_from_targetsmart = json_from_targetsmart['results']
for augmented_email in results_list_from_targetsmart:
email_address_text = augmented_email['vb.email_address']
if positive_value_exists(email_address_text):
targetsmart_id = augmented_email['vb.voterbase_id']
targetsmart_source_state = augmented_email['vb.vf_source_state']
# Last voted?
# Political party?
# Full address so we can find their ballot?
augmented_email_dict = {
'email_address_text': email_address_text,
'targetsmart_id': targetsmart_id,
'targetsmart_source_state': targetsmart_source_state,
}
augmented_email_list_dict[email_address_text.lower()] = augmented_email_dict
results = {
'success': success,
'status': status,
'augmented_email_list_found': augmented_email_list_found,
'augmented_email_list_dict': augmented_email_list_dict,
}
return results
|
DaleMcGrew/WeVoteServer | import_export_ballotpedia/models.py | <reponame>DaleMcGrew/WeVoteServer
# import_export_ballotpedia/models.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from datetime import date, timedelta
from django.db import models
from wevote_functions.functions import convert_to_int, positive_value_exists
class BallotpediaApiCounter(models.Model):
datetime_of_action = models.DateTimeField(verbose_name='date and time of action', null=False, auto_now=True)
kind_of_action = models.CharField(verbose_name="kind of call to ballotpedia", max_length=50, null=True, blank=True)
google_civic_election_id = models.PositiveIntegerField(verbose_name="google civic election id", null=True)
ballotpedia_election_id = models.PositiveIntegerField(verbose_name="ballotpedia election id", null=True)
class BallotpediaApiCounterDailySummary(models.Model):
date_of_action = models.DateField(verbose_name='date of action', null=False, auto_now=False)
kind_of_action = models.CharField(verbose_name="kind of call to ballotpedia", max_length=50, null=True, blank=True)
google_civic_election_id = models.PositiveIntegerField(verbose_name="google civic election id", null=True)
ballotpedia_election_id = models.PositiveIntegerField(verbose_name="ballotpedia election id", null=True)
class BallotpediaApiCounterWeeklySummary(models.Model):
year_of_action = models.SmallIntegerField(verbose_name='year of action', null=False)
week_of_action = models.SmallIntegerField(verbose_name='number of the week', null=False)
kind_of_action = models.CharField(verbose_name="kind of call to ballotpedia", max_length=50, null=True, blank=True)
google_civic_election_id = models.PositiveIntegerField(verbose_name="google civic election id", null=True)
ballotpedia_election_id = models.PositiveIntegerField(verbose_name="ballotpedia election id", null=True)
class BallotpediaApiCounterMonthlySummary(models.Model):
year_of_action = models.SmallIntegerField(verbose_name='year of action', null=False)
month_of_action = models.SmallIntegerField(verbose_name='number of the month', null=False)
kind_of_action = models.CharField(verbose_name="kind of call to ballotpedia", max_length=50, null=True, blank=True)
google_civic_election_id = models.PositiveIntegerField(verbose_name="google civic election id", null=True)
ballotpedia_election_id = models.PositiveIntegerField(verbose_name="ballotpedia election id", null=True)
# noinspection PyBroadException
class BallotpediaApiCounterManager(models.Manager):
def create_counter_entry(self, kind_of_action, google_civic_election_id=0, ballotpedia_election_id=0):
"""
Create an entry that records that a call to the Ballotpedia Api was made.
"""
try:
google_civic_election_id = convert_to_int(google_civic_election_id)
# TODO: We need to work out the timezone questions
BallotpediaApiCounter.objects.create(
kind_of_action=kind_of_action,
google_civic_election_id=google_civic_election_id,
ballotpedia_election_id=ballotpedia_election_id,
)
success = True
status = 'ENTRY_SAVED'
except Exception:
success = False
status = 'SOME_ERROR'
results = {
'success': success,
'status': status,
}
return results
def retrieve_daily_summaries(self, kind_of_action='', google_civic_election_id=0, ballotpedia_election_id=0):
# Start with today and cycle backwards in time
daily_summaries = []
day_on_stage = date.today() # TODO: We need to work out the timezone questions
number_found = 0
days_to_display = 30
maximum_attempts = 45
attempt_count = 0
try:
# Limit the number of times this runs to EITHER 1) 5 positive numbers
# OR 2) 30 days in the past, whichever comes first
while number_found <= days_to_display and attempt_count <= maximum_attempts:
attempt_count += 1
counter_queryset = BallotpediaApiCounter.objects.all()
if positive_value_exists(kind_of_action):
counter_queryset = counter_queryset.filter(kind_of_action=kind_of_action)
if positive_value_exists(google_civic_election_id):
counter_queryset = counter_queryset.filter(google_civic_election_id=google_civic_election_id)
if positive_value_exists(ballotpedia_election_id):
counter_queryset = counter_queryset.filter(ballotpedia_election_id=ballotpedia_election_id)
# Find the number of these entries on that particular day
# counter_queryset = counter_queryset.filter(datetime_of_action__contains=day_on_stage)
counter_queryset = counter_queryset.filter(
datetime_of_action__year=day_on_stage.year,
datetime_of_action__month=day_on_stage.month,
datetime_of_action__day=day_on_stage.day)
api_call_count = counter_queryset.count()
# If any api calls were found on that date, pass it out for display
if positive_value_exists(api_call_count):
daily_summary = {
'date_string': day_on_stage,
'count': api_call_count,
}
daily_summaries.append(daily_summary)
number_found += 1
day_on_stage -= timedelta(days=1)
except Exception:
pass
return daily_summaries
|
abrolon87/journal-app | journal_entries/apps.py | from django.apps import AppConfig
class JournalEntriesConfig(AppConfig):
name = 'journal_entries'
|
abrolon87/journal-app | ja_env/lib/python3.7/site-packages/pry.py | from __future__ import print_function
import code
import types
import inspect
import sys
import tempfile
import re
import shutil
import struct
import fcntl
VERSION = "0.1.1"
try:
import termios
except ImportError:
termios = None
try:
import pygments
import pygments.lexers
import pygments.formatters
has_pygments = True
except ImportError:
has_pygments = False
pass
BdbQuit_excepthook = None
try:
import bpython
has_bpython = True
except ImportError:
has_bpython = False
try:
import IPython
from IPython.core.debugger import BdbQuit_excepthook
from IPython.core import page
from IPython.terminal.ipapp import load_default_config
from IPython.core.magic import (magics_class, line_magic, Magics)
ipython_config = load_default_config()
ipython_config.TerminalInteractiveShell.confirm_exit = False
old_init = IPython.terminal.embed.InteractiveShellEmbed.__init__
def new_init(self, *k, **kw):
frames = kw.pop("frames", None)
old_init(self, *k, **kw)
from pry import get_context, highlight, terminal_size
@magics_class
class MyMagics(Magics):
def __init__(self, shell, frames):
# You must call the parent constructor
super(MyMagics, self).__init__(shell)
self.frame_offset = 0
self.frames = frames
self.calling_frame = frames[0]
@property
def active_frame(self):
return self.frames[self.frame_offset]
def build_terminal_list(self, list, term_width=80):
line = " "
for name in sorted(list):
if len(line + name) > term_width:
yield line
line = " "
line += " %s" % name
if line != " ":
yield line
@line_magic("ls")
def ls(self, query):
"""
Show local variables/methods/class properties
"""
lines = []
width = terminal_size()[0]
methods = []
properties = []
has_query = True
that = self.shell.user_ns.get(query, None)
if that is None:
that = self.active_frame.locals.get("self", [])
has_query = False
# apparently there is no better way to check if the caller
# is a method
for attr in dir(that):
try:
value = getattr(that, attr)
except Exception:
continue
if isinstance(value, types.MethodType):
methods.append(attr)
else:
properties.append(attr)
if len(methods) > 0:
lines.append("local methods:")
lines.extend(self.build_terminal_list(methods, width))
if len(properties) > 0:
lines.append("properties")
props = self.build_terminal_list(properties, width)
lines.extend(props)
if not has_query:
lines.append("local variables:")
local_vars = self.build_terminal_list(
self.active_frame.locals.keys(), width)
lines.extend(local_vars)
page.page("\n".join(lines))
@line_magic("editfile")
def editfile(self, query):
"""
open current breakpoint in editor.
"""
self.shell.hooks.editor(
self.active_frame.filename,
linenum=self.active_frame.lineno)
@line_magic("where")
def where(self, query):
"""
Show backtrace
"""
context = []
for f in reversed(self.frames[self.frame_offset:]):
context.append(get_context(f))
page.page("".join(context))
@line_magic("showsource")
def showsource(self, query):
"""
Show source of object
"""
obj = self.active_frame.locals.get(
query, self.active_frame.globals.get(query, None))
if obj is None:
return "Not found: %s" % query
try:
s = inspect.getsource(obj)
except TypeError as f:
print("%s" % f, file=sys.stderr)
return
if has_pygments:
s = "\n".join(highlight(s.split("\n")))
page.page(s)
def update_context(self):
print(get_context(self.active_frame), file=sys.stderr)
# hacky
scope = self.active_frame.globals.copy()
scope.update(self.active_frame.locals)
self.shell.user_ns.update(scope)
@line_magic("up")
def up(self, query):
"""
Get from call frame up.
"""
self.frame_offset += 1
self.frame_offset = min(self.frame_offset,
len(self.frames) - 1)
self.update_context()
@line_magic("down")
def down(self, query):
"""
Get from call frame down.
"""
self.frame_offset -= 1
self.frame_offset = max(self.frame_offset, 0)
self.update_context()
@line_magic("removepry")
def removepry(self, query):
"""
Remove pry call at current breakpoint.
"""
f = self.calling_frame
with open(f.filename) as src, \
tempfile.NamedTemporaryFile(mode='w') as dst:
for i, line in enumerate(src):
if (i + 1) == f.lineno:
line = re.sub(r'(import pry;)?\s*pry\(\)', "",
line)
if line.strip() == "":
continue
dst.write(line)
dst.flush()
src.close()
shutil.copyfile(dst.name, f.filename)
self.register_magics(MyMagics(self, frames))
IPython.terminal.embed.InteractiveShellEmbed.__init__ = new_init
has_ipython = True
except ImportError:
has_ipython = False
pass
try:
import readline
has_readline = True
except ImportError:
has_readline = False
pass
else:
import rlcompleter
class Frame():
"""
Abstraction around old python traceback api
"""
def __init__(self, *raw_frame):
self.frame = raw_frame[0]
self.filename = raw_frame[1]
self.lineno = raw_frame[2]
self.function = raw_frame[3]
self.lines = raw_frame[4]
self.index = raw_frame[5]
self.locals = self.frame.f_locals
self.globals = self.frame.f_globals
class Pry():
def __init__(self, module):
self.module = module
self.lexer = None
self.formatter = None
def wrap_raw_frames(self, raw_frames):
frames = []
for raw_frame in raw_frames:
frames.append(Frame(*raw_frame))
return frames
def highlight(self, lines):
if not self.module.has_pygments:
return lines
p = self.module.pygments
if self.lexer is None:
self.lexer = p.lexers.PythonLexer()
if self.formatter is None:
self.formatter = p.formatters.Terminal256Formatter()
tokens = self.lexer.get_tokens("\n".join(lines))
source = p.format(tokens, self.formatter)
return source.split("\n")
def __enter__(self):
pass
def __exit__(self, type, value, tb):
self.wrap_sys_excepthook()
if tb is None:
return
frames = self.wrap_raw_frames(self.module.inspect.getinnerframes(tb))
for frame in frames[:-1]:
print(self.get_context(frame), file=sys.stderr)
print("%s: %s\n" % (type.__name__, str(value)), file=sys.stderr)
self(list(reversed(frames)))
def wrap_sys_excepthook(self):
m = self.module
if not m.has_ipython:
return
# make sure we wrap it only once or we would end up with a cycle
# BdbQuit_excepthook.excepthook_ori == BdbQuit_excepthook
if m.sys.excepthook != m.BdbQuit_excepthook:
m.BdbQuit_excepthook.excepthook_ori = m.sys.excepthook
m.sys.excepthook = m.BdbQuit_excepthook
def get_context(self, frame, unwind=True):
before = max(frame.lineno - 6, 0)
after = frame.lineno + 4
context = []
try:
f = open(frame.filename)
for i, line in enumerate(f):
if i >= before:
context.append(line.rstrip())
if i > after:
break
f.close()
except IOError:
context = frame.lines
banner = "From: {} @ line {} :\n".format(frame.filename, frame.lineno)
i = max(frame.lineno - 5, 0)
if self.module.has_pygments and not self.module.has_bpython:
context = self.highlight(context)
for line in context:
pointer = "-->" if i == frame.lineno else " "
banner += "{} {}: {}\n".format(pointer, i, line)
i += 1
return banner
def fix_tty(self):
m = self.module
if m.termios is None:
return
# Sometimes when you do something funky, you may lose your terminal
# echo. This should restore it when spawning new pdb.
termios_fd = m.sys.stdin.fileno()
termios_echo = m.termios.tcgetattr(termios_fd)
termios_echo[3] = termios_echo[3] | m.termios.ECHO
m.termios.tcsetattr(termios_fd, termios.TCSADRAIN, termios_echo)
def terminal_size(self):
m = self.module
if m.termios is None:
return 80, 24
args = m.struct.pack('HHHH', 0, 0, 0, 0)
res = m.fcntl.ioctl(0, m.termios.TIOCGWINSZ, args)
h, w, hp, wp = m.struct.unpack('HHHH', res)
return w, h
def shell(self, context, frames):
active_frame = frames[0]
m = self.module
if m.has_bpython:
globals().update(active_frame.globals)
m.bpython.embed(active_frame.locals.copy(), banner=context)
if m.has_ipython:
shell = m.IPython.terminal.embed.InteractiveShellEmbed(config=m.ipython_config, frames=frames)
scope = active_frame.globals.copy()
scope.update(active_frame.locals)
print(context.rstrip())
shell.mainloop(local_ns=scope)
else:
if m.has_readline:
m.readline.parse_and_bind("tab: complete")
globals().update(active_frame.globals)
m.code.interact(context, local=active_frame.locals.copy())
def __call__(self, frames=None):
if frames is None:
frames = self.module.inspect.getouterframes(
self.module.inspect.currentframe())
frames = self.wrap_raw_frames(frames)
if len(frames) > 1:
frames = frames[1:]
context = self.get_context(frames[0])
self.fix_tty()
self.shell(context, frames)
# hack for convenient access
sys.modules[__name__] = Pry(sys.modules[__name__])
|
MrSupW/Compute-Your-Code-Rows | main.py | import os
parent_dir_path = './'
total_rows = 0
total_files = 0
def walkInDir(dir_path):
global total_rows, total_files
for f_path, dirs, files in os.walk(dir_path):
for dir in dirs:
walkInDir(os.path.join(dir_path, dir))
for file in files:
if file.split(".")[-1] in ['py','java']:
file_path = os.path.join(dir_path, file)
code_rows = getCodeQuantity(file_path)
if code_rows != 0:
total_files += 1
print('{} has {} rows code!'.format(file_path, code_rows))
total_rows += code_rows
def getCodeQuantity(file_path):
global total_files
try:
with open(file_path, encoding="utf-8") as f:
content = f.readlines()
return len(content)
except Exception as e:
return 0
if __name__ == '__main__':
walkInDir(parent_dir_path)
print("一共有{}个有效文件,共计{}行代码!".format(total_files,total_rows))
|
adambkaplan/jenkins | smoke/features/steps/steps.py | <filename>smoke/features/steps/steps.py
# @mark.steps
# ----------------------------------------------------------------------------
# STEPS:
# ----------------------------------------------------------------------------
import os
import time
import urllib3
from behave import given, when, then
from pyshould import should
from kubernetes import config, client
from smoke.features.steps.openshift import Openshift
from smoke.features.steps.project import Project
from smoke.features.steps.plugins import Plugins
# Test results file path
scripts_dir = os.getenv('OUTPUT_DIR')
# Path to pipeline job to test agent images
maven_template ='./smoke/samples/maven_pipeline.yaml'
nodejs_template = './smoke/samples/nodejs_pipeline.yaml'
# variables needed to get the resource status
deploy_pod = "jenkins-1-deploy"
jenkins_master_pod = ''
current_project = ''
config.load_kube_config()
v1 = client.CoreV1Api()
oc = Openshift()
podStatus = {}
buildconfigs = {'sample-pipeline':'1','openshift-jee-sample':'1'}
builds = {}
# Parse the base plugins from the file and store them in a dictonary with key=plugin-name & value=plugin-version
baseplugins = './2/contrib/openshift/base-plugins.txt'
p = Plugins()
plugins = p.getPlugins(baseplugins)
def triggerbuild(buildconfig,namespace):
print('Triggering build: ',buildconfig)
res = oc.start_build(buildconfig,namespace)
print(res)
# STEP
@given(u'Project "{project_name}" is used')
def given_project_is_used(context, project_name):
project = Project(project_name)
global current_project
current_project = project_name
context.current_project = current_project
context.oc = oc
if not project.is_present():
print("Project is not present, creating project: {}...".format(project_name))
project.create() | should.be_truthy.desc(
"Project {} is created".format(project_name))
print("Project {} is created!!!".format(project_name))
context.project = project
# STEP
@given(u'Project [{project_env}] is used')
def given_namespace_from_env_is_used(context, project_env):
env = os.getenv(project_env)
assert env is not None, f"{project_env} environment variable needs to be set"
print(f"{project_env} = {env}")
given_project_is_used(context, env)
@given(u'we have a openshift cluster')
def loginCluster(context):
print("Using [{}]".format(current_project))
@when(u'User enters oc new-app jenkins-ephemeral command')
def ephemeralTemplate(context):
res = oc.new_app('jenkins-ephemeral', current_project)
if(res == None):
print("Error while installing jenkins using ephemeral template")
raise AssertionError
@then(u'route.route.openshift.io "jenkins" created')
def checkRoute(context):
try:
res = oc.get_route('jenkins', current_project)
if not 'jenkins' in res:
raise AssertionError("Route creation failed")
item = oc.search_resource_in_namespace('route', 'jenkins', current_project)
print(f'route {item} created')
except AssertionError:
print('Problem with route')
'''
Pre 4.6 configmap not available'
'''
@then(u'configmap "jenkins-trusted-ca-bundle" created')
def checkConfigmap(context):
try:
res = oc.get_configmap(current_project)
if not 'jenkins' in res:
raise AssertionError("configmap creation failed")
item = oc.search_resource_in_namespace('cm', 'jenkins-trusted-ca-bundle', current_project)
except AssertionError:
print('Problem with configmap')
@then(u'deploymentconfig.apps.openshift.io "jenkins" created')
def checkDC(context):
try:
res = oc.get_deploymentconfig(current_project)
if not 'jenkins' in res:
raise AssertionError("deploymentconfig creation failed")
item = oc.search_resource_in_namespace('dc', 'jenkins', current_project)
print(f'deploymentconfig {item} created')
except AssertionError:
print('Problem with deploymentconfig')
@then(u'serviceaccount "jenkins" created')
def checkSA(context):
try:
res = oc.get_service_account(current_project)
if not 'jenkins' in res:
raise AssertionError("service acoount creation failed")
item = oc.search_resource_in_namespace('sa', 'jenkins', current_project)
print(f'serviceaccount {item} created')
except AssertionError:
print('Problem with serviceaccount')
@then(u'rolebinding.authorization.openshift.io "jenkins_edit" created')
def checkRolebinding(context):
try:
res = oc.get_role_binding(current_project)
if not 'jenkins' in res:
raise AssertionError("rolebinding failed")
item = oc.search_resource_in_namespace('rolebinding', 'jenkins_edit', current_project)
print(f'rolebinding {item} created')
except AssertionError:
print('Problem with rolebinding')
@then(u'service "jenkins-jnlp" created')
def checkSVCJNLP(context):
try:
res = oc.get_service(current_project)
if not 'jenkins-jnlp' in res:
raise AssertionError("service acoount creation failed")
item = oc.search_resource_in_namespace('svc', 'jenkins-jnlp', current_project)
print(f'service {item} created')
except AssertionError:
print(f'Problem with serviceJNLP')
@then(u'service "jenkins" created')
def checkSVC(context):
try:
res = oc.get_service(current_project)
if not 'jenkins' in res:
raise AssertionError("service acoount creation failed")
item = oc.search_resource_in_namespace('svc', 'jenkins', current_project)
print(f'service {item} created')
except AssertionError:
print(f'Problem with service jenkins')
@then(u'We check for deployment pod status to be "Completed"')
def deploymentPodStatus(context):
time.sleep(120)
print("Getting deployment pod status")
deploy_pod_status = oc.get_resource_info_by_jsonpath('pods',deploy_pod,current_project,json_path='{.status.phase}')
if not 'Succeeded' in deploy_pod_status:
raise AssertionError
@then(u'We check for jenkins master pod status to be "Ready"')
def jenkinsMasterPodStatus(context):
global jenkins_master_pod
jenkins_master_pod = ""
jenkins_master_pod = getmasterpod(current_project)
print('---------Getting default jenkins pod name---------')
print(jenkins_master_pod)
containerState = oc.get_resource_info_by_jsonpath('pods',jenkins_master_pod,current_project,json_path='{.status.containerStatuses[*].ready}')
if 'false' in containerState:
raise AssertionError
else:
print(containerState)
@then(u'persistentvolumeclaim "jenkins" created')
def verify_pvc(context):
if not 'jenkins' in oc.search_resource_in_namespace('pvc','jenkins',current_project):
raise AssertionError
else:
res = oc.search_resource_in_namespace('pvc','jenkins',current_project)
print(res)
@then(u'we check the pvc status is "Bound"')
def pvc_status(context):
print('---------Getting pvc status---------')
pvcState = oc.get_resource_info_by_jsonpath('pvc','jenkins',current_project,json_path='{.status.phase}')
if 'Bound' in pvcState:
print(pvcState)
else:
raise AssertionError
@given(u'The jenkins pod is up and runnning')
def checkJenkins(context):
jenkinsMasterPodStatus(context)
@when(u'User enters oc new-app jenkins-persistent command')
def persistentTemplate(context):
res = oc.new_app('jenkins-persistent', current_project)
if(res == None):
print("Error while installing jenkins using persistent template")
raise AssertionError
@when(u'The user enters new-app command with nodejs_template')
def createPipeline(context):
res = oc.new_app_from_file(nodejs_template,current_project)
time.sleep(30)
if 'sample-pipeline' in oc.search_resource_in_namespace('bc','sample', current_project):
print('Buildconfig sample-pipeline created')
elif 'nodejs-postgresql-example' in oc.search_resource_in_namespace('bc','postgersql',current_project):
print('Buildconfig nodejs-postgersql-example created')
else:
raise AssertionError
print(res)
@then(u'Trigger the build using oc start-build')
def startbuild(context):
triggerbuild('sample-pipeline',current_project)
@then(u'verify the build status of "nodejs-postgresql-example-1" build is Complete')
def verifynodejsBuildStatus(context):
time.sleep(300)
buildState = oc.get_resource_info_by_jsonpath('build','nodejs-postgresql-example-1',current_project,json_path='{.status.phase}')
if not 'Complete' in buildState:
raise AssertionError
else:
print("Build nodejs-postgresql-example-1 status:{buildState}")
@then(u'verify the build status of "nodejs-postgresql-example-2" build is Complete')
def verifynodejsBuildBStatus(context):
buildState = oc.get_resource_info_by_jsonpath('build','nodejs-postgresql-example-2',current_project,json_path='{.status.phase}')
if not 'Complete' in buildState:
raise AssertionError
else:
print("Build nodejs-postgresql-example-2 status:{buildState}")
@then(u'route nodejs-postgresql-example must be created and be accessible')
def connectApp(context):
print('Getting application route/url')
app_name = 'nodejs-postgresql-example'
route = oc.get_route_host(app_name,current_project)
url = 'http://'+str(route)
print('--->App url:')
print(url)
http = urllib3.PoolManager()
res = http.request_encode_url('GET',url)
connection_status = res.status
if connection_status == 200:
print('---> Application is accessible via the route')
print(url)
http.clear()
else:
raise Exception
@when(u'The user create objects from the sample maven template by processing the template and piping the output to oc create')
def createMavenTemplate(context):
res = oc.oc_process_template(maven_template)
print(res)
@when(u'verify imagestream.image.openshift.io/openshift-jee-sample & imagestream.image.openshift.io/wildfly exist')
def verifyImageStream(context):
if not 'openshift-jee-sample' in oc.search_resource_in_namespace('imagestream','openshift-jee-sample', current_project):
raise AssertionError
elif not 'wildfly' in oc.search_resource_in_namespace('imagestream','wildfly', current_project):
raise AssertionError
else:
res = oc.get_resource_lst('imagestream',current_project)
print(res)
@when(u'verify buildconfig.build.openshift.io/openshift-jee-sample & buildconfig.build.openshift.io/openshift-jee-sample-docker exist')
def verifyBuildConfig(context):
if not 'openshift-jee-sample' in oc.search_resource_in_namespace('buildconfig','openshift-jee-sample', current_project):
raise AssertionError
elif not 'openshift-jee-sample-docker' in oc.search_resource_in_namespace('buildconfig','openshift-jee-sample-docker', current_project):
raise AssertionError
else:
res = oc.get_resource_lst('buildconfig',current_project)
print(res)
@when(u'verify deploymentconfig.apps.openshift.io/openshift-jee-sample is created')
def verifyDeploymentConfig(context):
if not 'openshift-jee-sample' in oc.search_resource_in_namespace('deploymentconfig','openshift-jee-sample',current_project):
raise AssertionError
else:
res = oc.search_resource_in_namespace('deploymentconfig','openshift-jee-sample',current_project)
print(res)
@when(u'verify service/openshift-jee-sample is created')
def verifySvc(context):
if not 'openshift-jee-sample' in oc.search_resource_in_namespace('service','openshift-jee-sample',current_project):
raise AssertionError
else:
res = oc.search_resource_in_namespace('service','openshift-jee-sample',current_project)
print(res)
@when(u'verify route.route.openshift.io/openshift-jee-sample is created')
def verifyRoute(context):
if not 'openshift-jee-sample' in oc.search_resource_in_namespace('route','openshift-jee-sample',current_project):
raise AssertionError
else:
res = oc.search_resource_in_namespace('route','openshift-jee-sample',current_project)
print(res)
@then(u'Trigger the build using oc start-build openshift-jee-sample')
def startBuild(context):
triggerbuild('openshift-jee-sample',current_project)
time.sleep(300)
@then(u'verify the build status of openshift-jee-sample-docker build is Complete')
def verifyDockerBuildStatus(context):
buildState = oc.get_resource_info_by_jsonpath('build','openshift-jee-sample-docker-1',current_project,json_path='{.status.phase}')
if not 'Complete' in buildState:
raise AssertionError
else:
print("Build openshift-jee-sample-docker-1 status:{buildState}")
@then(u'verify the build status of openshift-jee-sample-1 is Complete')
def verifyJenkinsBuildStatus(context):
buildState = oc.get_resource_info_by_jsonpath('build','openshift-jee-sample-1',current_project,json_path='{.status.phase}')
if not 'Complete' in buildState:
raise AssertionError
else:
print("Build openshift-jee-sample-1-deploy status:{buildState}")
@then(u'verify the JaveEE application is accessible via route openshift-jee-sample')
def pingApp(context):
print('Getting application route/url')
app_name = 'openshift-jee-sample'
route = oc.get_route_host(app_name,current_project)
url = 'http://'+str(route)
print('--->App url:')
print(url)
http = urllib3.PoolManager()
res = http.request_encode_url('GET',url)
connection_status = res.status
if connection_status == 200:
print('---> Application is accessible via the route')
print(url)
http.clear()
else:
raise Exception
@then(u'we delete deploymentconfig.apps.openshift.io "jenkins"')
def del_dc(context):
global jenkins_master_pod
jenkins_master_pod = ''
res = oc.delete("deploymentconfig","jenkins",current_project)
if res == None:
raise AssertionError
@then(u'we delete route.route.openshift.io "jenkins"')
def del_route(context):
res = oc.delete("route","jenkins",current_project)
if res == None:
raise AssertionError
@then(u'delete configmap "jenkins-trusted-ca-bundle"')
def del_cm(context):
res = oc.delete("configmap","jenkins-trusted-ca-bundle",current_project)
if res == None:
raise AssertionError
@then(u'delete serviceaccount "jenkins"')
def del_sa(context):
res = oc.delete("serviceaccount","jenkins",current_project)
if res == None:
raise AssertionError
@then(u'delete rolebinding.authorization.openshift.io "jenkins_edit"')
def del_rb(context):
res = oc.delete("rolebinding","jenkins_edit",current_project)
if res == None:
raise AssertionError
@then(u'delete service "jenkins"')
def del_svc(context):
res = oc.delete("service","jenkins",current_project)
if res == None:
raise AssertionError
@then(u'delete service "jenkins-jnlp"')
def del_svc_jnlp(context):
res = oc.delete("service","jenkins-jnlp",current_project)
if res == None:
raise AssertionError
@then(u'delete all buildconfigs')
def del_bc(context):
res = oc.delete("bc","--all",current_project)
if res == None:
raise AssertionError
@then(u'delete all builds')
def del_builds(context):
res = oc.delete("builds","--all",current_project)
if res == None:
raise AssertionError
@then(u'delete all deploymentconfig')
def del_alldc(context):
res = oc.delete("deploymentconfig","--all",current_project)
if res == None:
raise AssertionError
@then(u'delete all build pods')
def del_pods(context):
pods = v1.list_namespaced_pod(current_project)
buildpods = []
for i in pods.items:
if 'jenkins-1-deploy' not in i.metadata.name and jenkins_master_pod not in i.metadata.name:
buildpods.append(i.metadata.name)
for pod in buildpods:
res = oc.delete('pod',pod,current_project)
print("Deleting: ",res)
@then(u'We rsh into the master pod and check the jobs count')
def getjobcount(context):
for jobnames,_ in buildconfigs.items():
exec_command = 'cat /var/lib/jenkins/jobs/'+current_project+'/jobs/'+current_project+'-'+jobnames+'/nextBuildNumber'
count = oc.exec_in_pod(jenkins_master_pod,exec_command)
buildconfigs[jobnames] = str(count)
print(buildconfigs)
@when(u'We delete the jenkins master pod')
def deletemaster(context):
master_pod = getmasterpod(current_project)
res = oc.delete("pods",master_pod,current_project)
time.sleep(60)
if res == None:
raise AssertionError
@then(u'We rsh into the master pod & Compare if the data persist or is lost upon pod restart')
def comparejobs(context):
for jobnames,_ in buildconfigs.items():
master_pod = getmasterpod(current_project)
exec_command = 'cat /var/lib/jenkins/jobs/'+current_project+'/jobs/'+current_project+'-'+jobnames+'/nextBuildNumber'
count = oc.exec_in_pod(master_pod,exec_command)
buildconfigs[jobnames] = str(count)
for jobnames, _ in buildconfigs.items():
if(buildconfigs[jobnames] == '1'):
print("Data doesnt persist")
raise AssertionError
print(buildconfigs)
def getmasterpod(namespace: str)-> str:
'''
returns the jenkins master pod name
'''
pods = v1.list_namespaced_pod(current_project)
for i in pods.items:
if 'jenkins-1-deploy' not in i.metadata.name and 'jenkins-1' in i.metadata.name:
master_pod = i.metadata.name
return str(master_pod)
@when(u'We rsh into the master pod')
def step_impl(context):
pass
@then(u'We compare the plugins version inside the master pod with the plugins listed in plugins.txt')
def step_impl(context):
pass
@when(u'We Trigger multiple builds using oc start-build openshift-jee-sample')
def multiplebuilds(context):
global builds
count = 1
## creating a dictionary of builds that keeps a track of {buildname: build_status}
# This will be used to check the build reconcilation
while(count <= 5):
triggerbuild('openshift-jee-sample',current_project)
build_name ='openshift-jee-sample-' + str(count)
builds[build_name] = None
count+=1
@when(u'We scale down the pod count in the replication controller to "0" from "1"')
def podscaling(context):
rc_name = 'jenkins-1'
oc.scaleReplicas(current_project,0,rc_name)
replicas = oc.get_resource_info_by_jsonpath("dc","jenkins",current_project,json_path='{.status.availableReplicas}')
if not '0' in replicas:
raise AssertionError
else:
print('There are ',replicas,' running pods of jenkins')
@then(u'We delete some builds')
def deletebuilds(context):
global builds
rm_build = ['openshift-jee-sample-2','openshift-jee-sample-4']
for build_name in builds.keys():
builds[build_name] = oc.get_resource_info_by_jsonpath("build",build_name,current_project,json_path='{.status.phase}')
print("------------Fetching all builds and build status------------")
print(builds)
print("------------Deleting a few builds------------")
for items in rm_build:
res = oc.delete("build",items,current_project)
print(res)
builds.pop(items)
print("------------Fetching all builds and build status------------")
print(builds)
# This sleep is used to give time for the jenkins master pod to be back
time.sleep(60)
@then(u'verify sync plugin is able to reconcile the build state and delete the job runs associated with the builds we deleted')
def verifybuildSync(context):
time.sleep(360)
for build_name in builds.keys():
builds[build_name] = oc.get_resource_info_by_jsonpath("build",build_name,current_project,json_path='{.status.phase}')
if not "Complete" in builds[build_name]:
print(build_name,':',builds[build_name])
raise AssertionError
else:
print(build_name,':',builds[build_name]) |
feliciatrinh/speech-to-intent-benchmark | benchmark/plot.py | import matplotlib.pyplot as plt
import numpy as np
aws_cafe = np.array([0.70, 0.80, 0.85, 0.86, 0.87, 0.87, 0.87])
aws_kitchen = np.array([0.79, 0.83, 0.85, 0.86, 0.87, 0.87, 0.87])
aws = (aws_cafe + aws_kitchen) / 2.
df_cafe = np.array([0.63, 0.70, 0.75, 0.78, 0.79, 0.80, 0.81])
df_kitchen = np.array([0.69, 0.73, 0.77, 0.80, 0.81, 0.81, 0.83])
df = (df_cafe + df_kitchen) / 2.
ibm_cafe = np.array([0.51, 0.76, 0.85, 0.93, 0.95, 0.96, 0.97])
ibm_kitchen = np.array([0.69, 0.82, 0.91, 0.93, 0.94, 0.96, 0.96])
ibm = (ibm_cafe + ibm_kitchen) / 2.
luis_cafe = np.array([0.84, 0.88, 0.91, 0.91, 0.93, 0.91, 0.93])
luis_kitchen = np.array([0.86, 0.90, 0.92, 0.91, 0.94, 0.93, 0.94])
luis = (luis_cafe + luis_kitchen) / 2.
pv_cafe = np.array([0.90, 0.94, 0.97, 0.97, 0.97, 0.98, 0.98])
pv_kitchen = np.array([0.96, 0.97, 0.98, 0.98, 0.99, 0.99, 0.99])
pv = (pv_cafe + pv_kitchen) / 2.
snr = [6, 9, 12, 15, 18, 21, 24]
plt.plot(snr, aws, color='g', marker='^', label='Amazon Lex')
plt.plot(snr, df, color='r', marker='x', label='Google Dialogflow')
plt.plot(snr, ibm, color='k', marker='s', label='IBM Watson')
plt.plot(snr, luis, color='m', marker='d', label='Microsoft LUIS')
plt.plot(snr, pv, color='b', marker='o', label='Picovoice Rhino')
plt.xlim(6, 24)
plt.xlabel('SNR dB')
plt.ylim(0.6, 1)
plt.ylabel('Accuracy (Command Acceptance Probability)')
plt.xticks([6, 9, 12, 15, 18, 21, 24])
plt.legend()
plt.title("Accuracy of NLU Engines")
plt.grid()
plt.show()
|
feliciatrinh/speech-to-intent-benchmark | benchmark/mixer.py | <filename>benchmark/mixer.py
import os
import shutil
import sys
import numpy as np
import soundfile
def _path(x):
return os.path.join(os.path.dirname(__file__), '../%s' % x)
def _max_frame_energy(pcm, frame_length=2048):
num_frames = pcm.size // frame_length
pcm_frames = pcm[:(num_frames * frame_length)].reshape((num_frames, frame_length))
frames_power = (pcm_frames ** 2).sum(axis=1)
return frames_power.max()
def _noise_scale(speech, noise, snr_db):
assert speech.shape[0] == noise.shape[0]
return np.sqrt(_max_frame_energy(speech) / (_max_frame_energy(noise) * (10 ** (snr_db / 10.))))
def mix(clean_folder, mix_folder, noise_name, snr_db):
noise, sample_rate = soundfile.read(_path('data/noise/%s.wav' % noise_name))
assert sample_rate == 16000
for clean_file in os.listdir(clean_folder):
if clean_file.endswith('.wav'):
clean_pcm, sample_rate = soundfile.read(os.path.join(clean_folder, clean_file))
assert sample_rate == 16000
assert len(clean_pcm) <= len(noise)
noise_start_index = np.random.randint(0, len(noise) - len(clean_pcm))
noise_end_index = noise_start_index + len(clean_pcm)
noise_scale = _noise_scale(clean_pcm, noise[noise_start_index:noise_end_index], snr_db)
noisy_pcm = clean_pcm + noise_scale * noise[noise_start_index:noise_end_index]
noisy_pcm /= 2 * np.max(np.abs(noisy_pcm))
soundfile.write(os.path.join(mix_folder, clean_file), noisy_pcm, sample_rate)
def run(noise):
for snr_db in [24, 21, 18, 15, 12, 9, 6]:
snr_dir = _path('data/speech/%s_%ddb' % (noise, snr_db))
if os.path.isdir(snr_dir):
shutil.rmtree(snr_dir)
os.mkdir(snr_dir)
mix(_path('data/speech/clean'), snr_dir, noise, snr_db)
if __name__ == '__main__':
run(sys.argv[1])
|
chhshen/vowpal_wabbit | python/pyvw.py | <filename>python/pyvw.py
import pylibvw
class vw(pylibvw.vw):
"""The pyvw.vw object is a (trivial) wrapper around the pylibvw.vw
object; you're probably best off using this directly and ignoring
the pylibvw.vw structure entirely."""
def __init__(self, argString=""):
"""Initialize the vw object. The (optional) argString is the
same as the command line arguments you'd use to run vw (eg,"--audit")"""
pylibvw.vw.__init__(self,argString)
self.finished = False
def get_weight(self, index, offset=0):
"""Given an (integer) index (and an optional offset), return
the weight for that position in the (learned) weight vector."""
return pylibvw.vw.get_weight(self, index, offset)
def learn(self, example):
"""Perform an online update; example can either be an example
object or a string (in which case it is parsed and then
learned on)."""
if isinstance(example, str):
self.learn_string(example)
else:
pylibvw.vw.learn(self, example)
def finish(self):
"""stop VW by calling finish (and, eg, write weights to disk)"""
if not self.finished:
pylibvw.vw.finish(self)
self.finished = True
def example(self, string=None):
return example(self, string)
def __del__(self):
self.finish()
class namespace_id():
"""The namespace_id class is simply a wrapper to convert between
hash spaces referred to by character (eg 'x') versus their index
in a particular example. Mostly used internally, you shouldn't
really need to touch this."""
def __init__(self, ex, id):
"""Given an example and an id, construct a namespace_id. The
id can either be an integer (in which case we take it to be an
index into ex.indices[]) or a string (in which case we take
the first character as the namespace id)."""
if isinstance(id, int): # you've specified a namespace by index
if id < 0 or id >= ex.num_namespaces():
raise Exception('namespace ' + str(id) + ' out of bounds')
self.id = id
self.ord_ns = ex.namespace(id)
self.ns = chr(self.ord_ns)
elif isinstance(id, str): # you've specified a namespace by string
if len(id) == 0:
id = ' '
self.id = None # we don't know and we don't want to do the linear search requered to find it
self.ns = id[0]
self.ord_ns = ord(self.ns)
else:
raise Exception("ns_to_characterord failed because id type is unknown: " + str(type(id)))
class example_namespace():
"""The example_namespace class is a helper class that allows you
to extract namespaces from examples and operate at a namespace
level rather than an example level. Mainly this is done to enable
indexing like ex['x'][0] to get the 0th feature in namespace 'x'
in example ex."""
def __init__(self, ex, ns):
"""Construct an example_namespace given an example and a
target namespace (ns should be a namespace_id)"""
if not isinstance(ns, namespace_id):
raise TypeError
self.ex = ex
self.ns = ns
def num_features_in(self):
"""Return the total number of features in this namespace."""
return self.ex.num_features_in(self.ns)
def __getitem__(self, i):
"""Get the feature/value pair for the ith feature in this
namespace."""
f = self.ex.feature(self.ns, i)
v = self.ex.feature_weight(self.ns, i)
return (f, v)
def iter_features(self):
"""iterate over all feature/value pairs in this namespace."""
for i in range(self.num_features_in()):
yield self[i]
# TODO: def push_feature(self, feature,
class abstract_label:
"""An abstract class for a VW label."""
def __init__(self):
pass
def from_example(self, ex):
"""grab a label from a given VW example"""
raise Exception("from_example not yet implemented")
class simple_label(abstract_label):
def __init__(self, label=0., weight=1., initial=0., prediction=0.):
abstract_label.__init__(self)
if isinstance(label, example):
self.from_example(label)
else:
self.label = label
self.weight = weight
self.initial = initial
self.prediction = prediction
def from_example(self, ex):
self.label = ex.get_simplelabel_label()
self.weight = ex.get_simplelabel_weight()
self.initial = ex.get_simplelabel_initial()
self.prediction = ex.get_simplelabel_prediction()
def __str__(self):
s = str(self.label)
if self.weight != 1.:
s += ':' + self.weight
return s
class multiclass_label(abstract_label):
def __init__(self, label=1, weight=1., prediction=1):
abstract_label.__init__(self)
self.label = label
self.weight = weight
self.prediction = prediction
def from_example(self, ex):
self.label = ex.get_multiclass_label()
self.weight = ex.get_multiclass_weight()
self.prediction = ex.get_multiclass_prediction()
def __str__(self):
s = str(self.label)
if self.weight != 1.:
s += ':' + self.weight
return s
class cost_sensitive_label(abstract_label):
class wclass:
def __init__(self, label, cost=0., partial_prediction=0., wap_value=0.):
self.label = label
self.cost = cost
self.partial_prediction = partial_prediction
self.wap_value = wap_value
def __init__(self, costs=[], prediction=0):
abstract_label.__init__(self)
self.costs = costs
self.prediction = prediction
def from_example(self, ex):
self.prediction = ex.get_costsensitive_prediction()
self.costs = []
for i in range(ex.get_costsensitive_num_costs):
wc = wclass(ex.get_costsensitive_class(),
ex.get_costsensitive_cost(),
ex.get_costsensitive_partial_prediction(),
ex.get_costsensitive_wap_value())
self.costs.append(wc)
def __str__(self):
return '[' + ' '.join([str(c.label) + ':' + str(c.cost) for c in self.costs])
class cbandits_label(abstract_label):
class wclass:
def __init__(self, label, cost=0., partial_prediction=0., probability=0.):
self.label = label
self.cost = cost
self.partial_prediction = partial_prediction
self.probability = probability
def __init__(self, costs=[], prediction=0):
abstract_label.__init__(self)
self.costs = costs
self.prediction = prediction
def from_example(self, ex):
self.prediction = ex.get_cbandits_prediction()
self.costs = []
for i in range(ex.get_cbandits_num_costs):
wc = wclass(ex.get_cbandits_class(),
ex.get_cbandits_cost(),
ex.get_cbandits_partial_prediction(),
ex.get_cbandits_probability())
self.costs.append(wc)
def __str__(self):
return '[' + ' '.join([str(c.label) + ':' + str(c.cost) for c in self.costs])
class example(pylibvw.example):
"""The example class is a (non-trivial) wrapper around
pylibvw.example. Most of the wrapping is to make the interface
easier to use (by making the types safer via namespace_id) and
also with added python-specific functionality."""
def __init__(self, vw, initString=None):
"""Construct a new example from vw. If initString is None, you
get an"empty" example which you can construct by hand (see, eg,
example.push_features). If initString is a string, then this
string is parsed as it would be from a VW data file into an
example (and "setup_example" is run)."""
if initString is None:
pylibvw.example.__init__(self, vw)
self.setup_done = False
else:
pylibvw.example.__init__(self, vw, initString)
self.setup_done = True
self.vw = vw
self.stride = vw.get_stride()
self.finished = False
def __del__(self):
self.finish()
def get_ns(self, id):
"""Construct a namespace_id from either an integer or string
(or, if a namespace_id is fed it, just return it directly)."""
if isinstance(id, namespace_id):
return id
else:
return namespace_id(self, id)
def __getitem__(self, id):
"""Get an example_namespace object associated with the given
namespace id."""
return example_namespace(self, self.get_ns(id))
def feature(self, ns, i):
"""Get the i-th hashed feature id in a given namespace (i can
range from 0 to self.num_features_in(ns)-1)"""
ns = self.get_ns(ns) # guaranteed to be a single character
f = pylibvw.example.feature(self, ns.ord_ns, i)
if self.setup_done:
f = (f - self.get_ft_offset()) / self.stride
return f
def feature_weight(self, ns, i):
"""Get the value(weight) associated with a given feature id in
a given namespace (i can range from 0 to
self.num_features_in(ns)-1)"""
return pylibvw.example.feature_weight(self, self.get_ns(ns).ord_ns, i)
def set_label_string(self, string):
"""Give this example a new label, formatted as a string (ala
the VW data file format)."""
pylibvw.example.set_label_string(self, self.vw, string)
def setup_example(self):
"""If this example hasn't already been setup (ie, quadratic
features constructed, etc.), do so."""
if self.setup_done:
raise Exception('trying to setup_example on an example that is already setup')
self.vw.setup_example(self)
self.setup_done = True
def learn(self):
"""Learn on this example (and before learning, automatically
call setup_example if the example hasn't yet been setup)."""
if not self.setup_done:
self.setup_example()
self.vw.learn(self)
def sum_feat_sq(self, ns):
"""Return the total sum feature-value squared for a given
namespace."""
return pylibvw.example.sum_feat_sq(self, self.get_ns(ns).ord_ns)
def num_features_in(self, ns):
"""Return the total number of features in a given namespace."""
return pylibvw.example.num_features_in(self, self.get_ns(ns).ord_ns)
def get_feature_id(self, ns, feature, ns_hash=None):
"""Return the hashed feature id for a given feature in a given
namespace. feature can either be an integer (already a feature
id) or a string, in which case it is hashed. Note that if
--hash all is on, then get_feature_id(ns,"5") !=
get_feature_id(ns, 5). If you've already hashed the namespace,
you can optionally provide that value to avoid re-hashing it."""
if isinstance(feature, int):
return feature
if isinstance(feature, str):
if ns_hash is None:
ns_hash = self.vw.hash_space( self.get_ns(ns).ns )
return self.vw.hash_feature(feature, ns_hash)
raise Exception("cannot extract feature of type: " + str(type(feature)))
def push_hashed_feature(self, ns, f, v=1.):
"""Add a hashed feature to a given namespace (fails if setup
has already run on this example). Fails if setup has run."""
if self.setup_done: raise Exception("error: modification to example after setup")
pylibvw.example.push_hashed_feature(self, self.get_ns(ns).ord_ns, f, v)
def push_feature(self, ns, feature, v=1., ns_hash=None):
"""Add an unhashed feature to a given namespace (fails if
setup has already run on this example). Fails if setup has
run."""
f = self.get_feature_id(ns, feature, ns_hash)
self.push_hashed_feature(ns, f, v)
def pop_feature(self, ns):
"""Remove the top feature from a given namespace; returns True
if a feature was removed, returns False if there were no
features to pop. Fails if setup has run."""
if self.setup_done: raise Exception("error: modification to example after setup")
return pylibvw.example.pop_feature(self, self.get_ns(ns).ord_ns)
def push_namespace(self, ns):
"""Push a new namespace onto this example. You should only do
this if you're sure that this example doesn't already have the
given namespace. Fails if setup has run."""
if self.setup_done: raise Exception("error: modification to example after setup")
pylibvw.example.push_namespace(self, self.get_ns(ns).ord_ns)
def pop_namespace(self):
"""Remove the top namespace from an example; returns True if a
namespace was removed, or False if there were no namespaces
left. Fails if setup has run."""
if self.setup_done: raise Exception("error: modification to example after setup")
return pylibvw.example.pop_namespace(self)
def ensure_namespace_exists(self, ns):
"""Check to see if a namespace already exists. If it does, do
nothing. If it doesn't, add it. Fails if setup has run."""
if self.setup_done: raise Exception("error: modification to example after setup")
return pylibvw.example.ensure_namespace_exists(self, self.get_ns(ns).ord_ns)
def push_features(self, ns, featureList):
"""Push a list of features to a given namespace. Each feature
in the list can either be an integer (already hashed) or a
string (to be hashed) and may be paired with a value or not
(if not, the value is assumed to be 1.0).
Examples:
ex.push_features('x', ['a', 'b'])
ex.push_features('y', [('c', 1.), 'd'])
space_hash = vw.hash_space( 'x' )
feat_hash = vw.hash_feature( 'a', space_hash )
ex.push_features('x', [feat_hash]) # note: 'x' should match the space_hash!
Fails if setup has run."""
ns = self.get_ns(ns)
self.ensure_namespace_exists(ns)
ns_hash = self.vw.hash_space(ns.ns)
for feature in featureList:
if isinstance(feature, int) or isinstance(feature, str):
f = feature
v = 1.
elif isinstance(feature, tuple) and len(feature) == 2:
f = feature[0]
v = feature[1]
else:
raise Exception('malformed feature to push of type: ' + str(type(feature)))
self.push_feature(ns, f, v, ns_hash)
def finish(self):
"""Tell VW that you're done with this example and it can
recycle it for later use."""
if not self.finished:
self.vw.finish_example(self)
self.finished = True
def iter_features(self):
"""Iterate over all feature/value pairs in this example (all
namespace included)."""
for ns_id in range( self.num_namespaces() ): # iterate over every namespace
ns = self.get_ns(ns_id)
for i in range(self.num_features_in(ns)):
f = self.feature(ns, i)
v = self.feature_weight(ns, i)
yield f,v
def get_label(self, label_class=simple_label):
"""Given a known label class (default is simple_label), get
the corresponding label structure for this example."""
return label_class(self)
#help(example)
|
shanakaprageeth/ml_examples | gcloud_ai_keras/keras_model.py | import os
from six.moves import urllib
import tempfile
import numpy as np
import pandas as pd
import tensorflow as tf
from matplotlib import pyplot as plt
# Examine software versions
print(__import__('sys').version)
print(tf.__version__)
print(tf.keras.__version__)
### For downloading data ###
# Storage directory
DATA_DIR = os.path.join(tempfile.gettempdir(), 'census_data')
# Download options.
DATA_URL = 'https://storage.googleapis.com/cloud-samples-data/ai-platform' \
'/census/data'
TRAINING_FILE = 'adult.data.csv'
EVAL_FILE = 'adult.test.csv'
TRAINING_URL = '%s/%s' % (DATA_URL, TRAINING_FILE)
EVAL_URL = '%s/%s' % (DATA_URL, EVAL_FILE)
### For interpreting data ###
# These are the features in the dataset.
# Dataset information: https://archive.ics.uci.edu/ml/datasets/census+income
_CSV_COLUMNS = [
'age', 'workclass', 'fnlwgt', 'education', 'education_num',
'marital_status', 'occupation', 'relationship', 'race', 'gender',
'capital_gain', 'capital_loss', 'hours_per_week', 'native_country',
'income_bracket'
]
_CATEGORICAL_TYPES = {
'workclass': pd.api.types.CategoricalDtype(categories=[
'Federal-gov', 'Local-gov', 'Never-worked', 'Private', 'Self-emp-inc',
'Self-emp-not-inc', 'State-gov', 'Without-pay'
]),
'marital_status': pd.api.types.CategoricalDtype(categories=[
'Divorced', 'Married-AF-spouse', 'Married-civ-spouse',
'Married-spouse-absent', 'Never-married', 'Separated', 'Widowed'
]),
'occupation': pd.api.types.CategoricalDtype([
'Adm-clerical', 'Armed-Forces', 'Craft-repair', 'Exec-managerial',
'Farming-fishing', 'Handlers-cleaners', 'Machine-op-inspct',
'Other-service', 'Priv-house-serv', 'Prof-specialty', 'Protective-serv',
'Sales', 'Tech-support', 'Transport-moving'
]),
'relationship': pd.api.types.CategoricalDtype(categories=[
'Husband', 'Not-in-family', 'Other-relative', 'Own-child', 'Unmarried',
'Wife'
]),
'race': pd.api.types.CategoricalDtype(categories=[
'Amer-Indian-Eskimo', 'Asian-Pac-Islander', 'Black', 'Other', 'White'
]),
'native_country': pd.api.types.CategoricalDtype(categories=[
'Cambodia', 'Canada', 'China', 'Columbia', 'Cuba', 'Dominican-Republic',
'Ecuador', 'El-Salvador', 'England', 'France', 'Germany', 'Greece',
'Guatemala', 'Haiti', 'Holand-Netherlands', 'Honduras', 'Hong', 'Hungary',
'India', 'Iran', 'Ireland', 'Italy', 'Jamaica', 'Japan', 'Laos', 'Mexico',
'Nicaragua', 'Outlying-US(Guam-USVI-etc)', 'Peru', 'Philippines', 'Poland',
'Portugal', 'Puerto-Rico', 'Scotland', 'South', 'Taiwan', 'Thailand',
'Trinadad&Tobago', 'United-States', 'Vietnam', 'Yugoslavia'
]),
'income_bracket': pd.api.types.CategoricalDtype(categories=[
'<=50K', '>50K'
])
}
# This is the label (target) we want to predict.
_LABEL_COLUMN = 'income_bracket'
### Hyperparameters for training ###
# This the training batch size
BATCH_SIZE = 128
# This is the number of epochs (passes over the full training data)
NUM_EPOCHS = 20
# Define learning rate.
LEARNING_RATE = .01
def _download_and_clean_file(filename, url):
"""Downloads data from url, and makes changes to match the CSV format.
The CSVs may use spaces after the comma delimters (non-standard) or include
rows which do not represent well-formed examples. This function strips out
some of these problems.
Args:
filename: filename to save url to
url: URL of resource to download
"""
temp_file, _ = urllib.request.urlretrieve(url)
with tf.gfile.Open(temp_file, 'r') as temp_file_object:
with tf.gfile.Open(filename, 'w') as file_object:
for line in temp_file_object:
line = line.strip()
line = line.replace(', ', ',')
if not line or ',' not in line:
continue
if line[-1] == '.':
line = line[:-1]
line += '\n'
file_object.write(line)
tf.gfile.Remove(temp_file)
def download(data_dir):
"""Downloads census data if it is not already present.
Args:
data_dir: directory where we will access/save the census data
"""
tf.gfile.MakeDirs(data_dir)
training_file_path = os.path.join(data_dir, TRAINING_FILE)
if not tf.gfile.Exists(training_file_path):
_download_and_clean_file(training_file_path, TRAINING_URL)
eval_file_path = os.path.join(data_dir, EVAL_FILE)
if not tf.gfile.Exists(eval_file_path):
_download_and_clean_file(eval_file_path, EVAL_URL)
return training_file_path, eval_file_path
training_file_path, eval_file_path = download(DATA_DIR)
# This census data uses the value '?' for fields (column) that are missing data.
# We use na_values to find ? and set it to NaN values.
# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
train_df = pd.read_csv(training_file_path, names=_CSV_COLUMNS, na_values='?')
eval_df = pd.read_csv(eval_file_path, names=_CSV_COLUMNS, na_values='?')
UNUSED_COLUMNS = ['fnlwgt', 'education', 'gender']
def preprocess(dataframe):
"""Converts categorical features to numeric. Removes unused columns.
Args:
dataframe: Pandas dataframe with raw data
Returns:
Dataframe with preprocessed data
"""
dataframe = dataframe.drop(columns=UNUSED_COLUMNS)
# Convert integer valued (numeric) columns to floating point
numeric_columns = dataframe.select_dtypes(['int64']).columns
dataframe[numeric_columns] = dataframe[numeric_columns].astype('float32')
# Convert categorical columns to numeric
cat_columns = dataframe.select_dtypes(['object']).columns
dataframe[cat_columns] = dataframe[cat_columns].apply(lambda x: x.astype(
_CATEGORICAL_TYPES[x.name]))
dataframe[cat_columns] = dataframe[cat_columns].apply(lambda x: x.cat.codes)
return dataframe
prepped_train_df = preprocess(train_df)
prepped_eval_df = preprocess(eval_df)
# Split train and test data with labels.
# The pop() method will extract (copy) and remove the label column from the dataframe
train_x, train_y = prepped_train_df, prepped_train_df.pop(_LABEL_COLUMN)
eval_x, eval_y = prepped_eval_df, prepped_eval_df.pop(_LABEL_COLUMN)
# Reshape label columns for use with tf.data.Dataset
train_y = np.asarray(train_y).astype('float32').reshape((-1, 1))
eval_y = np.asarray(eval_y).astype('float32').reshape((-1, 1))
def standardize(dataframe):
"""Scales numerical columns using their means and standard deviation to get
z-scores: the mean of each numerical column becomes 0, and the standard
deviation becomes 1. This can help the model converge during training.
Args:
dataframe: Pandas dataframe
Returns:
Input dataframe with the numerical columns scaled to z-scores
"""
dtypes = list(zip(dataframe.dtypes.index, map(str, dataframe.dtypes)))
# Normalize numeric columns.
for column, dtype in dtypes:
if dtype == 'float32':
dataframe[column] -= dataframe[column].mean()
dataframe[column] /= dataframe[column].std()
return dataframe
# Join train_x and eval_x to normalize on overall means and standard
# deviations. Then separate them again.
all_x = pd.concat([train_x, eval_x], keys=['train', 'eval'])
all_x = standardize(all_x)
train_x, eval_x = all_x.xs('train'), all_x.xs('eval')
def input_fn(features, labels, shuffle, num_epochs, batch_size):
"""Generates an input function to be used for model training.
Args:
features: numpy array of features used for training or inference
labels: numpy array of labels for each example
shuffle: boolean for whether to shuffle the data or not (set True for
training, False for evaluation)
num_epochs: number of epochs to provide the data for
batch_size: batch size for training
Returns:
A tf.data.Dataset that can provide data to the Keras model for training or
evaluation
"""
if labels is None:
inputs = features
else:
inputs = (features, labels)
dataset = tf.data.Dataset.from_tensor_slices(inputs)
if shuffle:
dataset = dataset.shuffle(buffer_size=len(features))
# We call repeat after shuffling, rather than before, to prevent separate
# epochs from blending together.
dataset = dataset.repeat(num_epochs)
dataset = dataset.batch(batch_size)
return dataset
# Pass a numpy array by using DataFrame.values
training_dataset = input_fn(features=train_x.values,
labels=train_y,
shuffle=True,
num_epochs=NUM_EPOCHS,
batch_size=BATCH_SIZE)
num_eval_examples = eval_x.shape[0]
# Pass a numpy array by using DataFrame.values
validation_dataset = input_fn(features=eval_x.values,
labels=eval_y,
shuffle=False,
num_epochs=NUM_EPOCHS,
batch_size=num_eval_examples)
def create_keras_model(input_dim, learning_rate):
"""Creates Keras Model for Binary Classification.
Args:
input_dim: How many features the input has
learning_rate: Learning rate for training
Returns:
The compiled Keras model (still needs to be trained)
"""
Dense = tf.keras.layers.Dense
model = tf.keras.Sequential(
[
Dense(100, activation=tf.nn.relu, kernel_initializer='uniform',
input_shape=(input_dim,)),
Dense(75, activation=tf.nn.relu),
Dense(50, activation=tf.nn.relu),
Dense(25, activation=tf.nn.relu),
Dense(1, activation=tf.nn.sigmoid)
])
# Custom Optimizer:
# https://www.tensorflow.org/api_docs/python/tf/train/RMSPropOptimizer
optimizer = tf.keras.optimizers.RMSprop(
lr=learning_rate)
# Compile Keras model
model.compile(
loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
return model
num_train_examples, input_dim = train_x.shape
print('Number of features: {}'.format(input_dim))
print('Number of examples: {}'.format(num_train_examples))
keras_model = create_keras_model(
input_dim=input_dim,
learning_rate=LEARNING_RATE)
keras_model.summary()
# Setup Learning Rate decay.
lr_decay_cb = tf.keras.callbacks.LearningRateScheduler(
lambda epoch: LEARNING_RATE + 0.02 * (0.5 ** (1 + epoch)),
verbose=True)
# Setup TensorBoard callback.
JOB_DIR = os.getenv('JOB_DIR')
tensorboard_cb = tf.keras.callbacks.TensorBoard(
os.path.join(JOB_DIR, 'keras_tensorboard'),
histogram_freq=1)
history = keras_model.fit(training_dataset,
epochs=NUM_EPOCHS,
steps_per_epoch=int(num_train_examples/BATCH_SIZE),
validation_data=validation_dataset,
validation_steps=1,
callbacks=[lr_decay_cb, tensorboard_cb],
verbose=1)
# Visualize History for Loss.
plt.title('Keras model loss')
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['training', 'validation'], loc='upper right')
plt.show()
# Visualize History for Accuracy.
plt.title('Keras model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.legend(['training', 'validation'], loc='lower right')
plt.show()
# Export the model to a local SavedModel directory
export_path = tf.contrib.saved_model.save_keras_model(keras_model, 'keras_export')
print("Model exported to: ", export_path)
#JOB_DIR = os.getenv('JOB_DIR')
# Export the model to a SavedModel directory in Cloud Storage
#export_path = tf.contrib.saved_model.save_keras_model(keras_model, JOB_DIR + '/keras_export')
#print("Model exported to: ", export_path)
|
shanakaprageeth/ml_examples | gcloud_ai_keras/prefilter.py | <reponame>shanakaprageeth/ml_examples
from trainer import util
import pandas as pd
import json
# load prefiltered data
_, _, eval_x, eval_y = util.load_data()
prediction_input = eval_x.sample(20)
prediction_targets = eval_y[prediction_input.index]
#print sample
prediction_input
#download raw data
_, eval_file_path = util.download(util.DATA_DIR)
raw_eval_data = pd.read_csv(eval_file_path,
names=util._CSV_COLUMNS,
na_values='?')
raw_eval_data.iloc[prediction_input.index]
# write prefiltered raw data fro prediction
with open('prediction_input.json', 'w') as json_file:
for row in prediction_input.values.tolist():
json.dump(row, json_file)
json_file.write('\n')
|
Matteljay/clipcommander | setup.py | #!/usr/bin/env python3
# to install directly, invoke via pip: sudo pip3 install .
# packages for PyPI.org: ./setup.py sdist bdist_wheel && twine upload dist/*
import setuptools
import os, sys, re
from pathlib import Path
mainscript = 'clipcommander.py'
resources = []
for fil in (f for f in Path('data').rglob('*') if f.is_file()):
resources.append((str('share' / fil.parent.relative_to('data')), [str(fil)]))
with open('requirements.txt') as fh:
required = fh.read().strip().splitlines()
with open('README.md', 'r') as fh:
long_description = fh.read()
with open(mainscript) as fh:
for line in fh:
out = re.search(r'version = \u0027(.+?)\u0027$', line)
if out:
extracted_version = out.group(1)
break
try: extracted_version
except NameError:
print('ERROR: Could not extract version from ' + mainscript, file=sys.stderr)
sys.exit(1)
setuptools.setup(
name = 'clipcommander',
version = extracted_version,
author = 'Matteljay',
author_email = '<EMAIL>',
description = 'Clipboard selection monitor YouTube-dl GUI front-end',
long_description = long_description,
long_description_content_type = 'text/markdown',
url = 'https://github.com/Matteljay/clipcommander',
scripts = [ mainscript ],
install_requires = required,
packages = setuptools.find_packages(),
classifiers = [
'Programming Language :: Python :: 3',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
],
data_files = resources,
)
# End of file
|
Matteljay/clipcommander | clipcommander.py | <reponame>Matteljay/clipcommander
#!/usr/bin/env python3
# -*- mode: python -*-
#
# ClipCommander - Clipboard selection monitor YouTube-dl GUI front-end
# Copyright (C) 2018 Matteljay-at-pm-dot-me
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Donate if you find this app useful, educational or you like to motivate more projects like this.
#
# XMR: 4B6YQvbL9jqY3r1cD3ZvrDgGrRpKvifuLVb5cQnYZtapWUNovde7K5rc1LVGw3HhmTiijX21zHKSqjQtwxesBEe6FhufRGS
# BTC: 14VZcizduTvUTesw4T9yAHZ7GjDDmXZmVs
# ETH: 0x7C64707BD877f9cFBf0B304baf200cB1BB197354
# DASH: XnMLmmisNAyDMT3Sr1rhpfAPfkMjDyUiwJ
# NANO: nano_3yztgrd4exg16r6dwxwc64fasdipi81aoe8yindsin7o31trqsgqanfi9fym
#
# IMPORTS
# Kivy cross platform graphical user interface
from kivy import __version__ as KIVY_VERSION
from kivy.app import App
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.config import Config
Config.set('graphics', 'window_state', 'hidden') # start hidden, fix Window.hide()
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition
from kivy.clock import Clock
# Character string tricks
from distutils.version import StrictVersion
import re
# System
from subprocess import Popen, PIPE
import os, sys
from shutil import which
from pathlib import Path # find resources
import socket # Linux single instance check
import signal # graceful Ctrl+c (SIGINT, SIGTERM)
name = 'clipcommander'
version = '2019.01.12'
def_defaultcfg = {
'startmodus': 'normal',
'showbar': '1',
'welcome_msg': 'Ready! Select a YouTube video link (example: https://www.youtube.com/watch?v=-O5kNPlUV7w)',
'reflags': 'IGNORECASE',
'storewin': '0',
'storewindata' : '',
'scaninterval' : '0.5',
'btn1_text': 'Download best video',
'btn1_patt': '(https://www\.youtube\.com/watch\?v=[\w-]{11})',
'btn1_cmd': 'xterm -e youtube-dl $1',
'btn2_text': 'Download average mp4 video',
'btn2_patt': '(https://www\.youtube\.com/watch\?v=[\w-]{11})',
'btn2_cmd': 'xterm -e youtube-dl -f18 $1',
'btn3_text': 'Download best audio',
'btn3_patt': '(https://www\.youtube\.com/watch\?v=[\w-]{11})',
'btn3_cmd': 'xterm -e youtube-dl -fbestaudio $1',
}
def_jsondata = '''[
{ "type": "options", "title": "Window startup mode", "desc": "Visibility and daemonizing, select text !showyourself to override",
"section": "settings", "key": "startmodus", "options": ["normal", "hidden", "hidden_runfirst"] },
{ "type": "bool", "title": "Show edit bar", "desc": "When hidden, press F1 to access this menu",
"section": "settings", "key": "showbar" },
{ "type": "string", "title": "Welcome message", "desc": "Message to show at startup",
"section": "settings", "key": "welcome_msg" },
{ "type": "string", "title": "Python regex flags", "desc": "See docs.python.org could be: MULTILINE|DOTALL",
"section": "settings", "key": "reflags" },
{ "type": "bool", "title": "Store window pos & size", "desc": "Usage: 1: toggle OFF 2: move and drag window 3: toggle ON",
"section": "settings", "key": "storewin" },
{ "type": "numeric", "title": "Clipboard scan interval", "desc": "How fast the window will show up, lower value = faster",
"section": "settings", "key": "scaninterval" },
{ "type": "title", "title": "Release version: ''' + version + ''' - Matteljay" }
]'''
col_white = [1, 1, 1, 1]
col_good = [0.1, 0.5, 0.1, 1]
col_bad = [0.5, 0.1, 0.1, 1]
col_proximate = [0.3, 0.3, 0.5, 1]
# Global screen placeholders
Builder.load_string('''
<MainWidget>:
statuslabel: id_statuslabel
lab_hidden: id_lab_hidden
delarea: id_delarea
mainbox: id_mainbox
plusbtn: id_plusbtn
mybar: id_mybar
rootbox: id_rootbox
editbtn: id_editbtn
BoxLayout:
id: id_rootbox
canvas:
Color:
rgba: 0.9, 0.9, 0.9, 1
Rectangle:
pos: self.pos
size: self.size
padding: 0
spacing: 0
orientation: 'vertical'
BoxLayout:
id: id_mainbox
padding: 8
spacing: 2
orientation: 'vertical'
Label:
id: id_statuslabel
font_size: 20
size_hint: 1, 1.3
text_size: self.width, None
halign: 'center'
text: ''
BoxLayout:
id: id_mybar
canvas:
Color:
rgba: 0.84, 0.84, 0.84, 1
Rectangle:
pos: self.pos
size: self.size
size: self.width, 30
size_hint: 1, None
padding: 0
spacing: 0
orientation: 'horizontal'
Label:
size: 100, 30
size_hint: None, None
id: id_lab_hidden
text: ''
font_size: 16
halign: 'left'
text_size: self.width, None
padding_x: 8
Widget:
Label:
size: 100, 30
size_hint: None, None
id: id_delarea
text: '[delete]'
font_size: 20
Button:
size: 30, 30
size_hint: None, None
background_normal: ''
background_color: 0.84, 0.84, 0.84, 1
on_press: app.btn_plusbtn()
id: id_plusbtn
text: '+'
font_size: 20
ToggleButton:
id: id_editbtn
size: 30, 30
size_hint: None, None
background_normal: ''
background_color: 0.84, 0.84, 0.84, 1
on_press: app.btn_toggle_edit()
text: 'e'
font_size: 20
Button:
size: 30, 30
size_hint: None, None
background_normal: ''
background_color: 0.84, 0.84, 0.84, 1
on_press: app.open_settings()
text: '\u00B7\u00B7\u00B7'
font_size: 20
<ButtonEditor>:
on_enter: app.w_input_enter()
t_name: id_t_name
t_patt: id_t_patt
t_cmd: id_t_cmd
simmsg: id_simmsg
BoxLayout:
canvas:
Color:
rgba: 0.9, 0.9, 0.9, 1
Rectangle:
pos: self.pos
size: self.size
padding: 8
spacing: 2
orientation: 'vertical'
BoxLayout:
padding: 8
spacing: 2
orientation: 'vertical'
Label:
id: id_simmsg
font_size: 20
text: ''
Label:
color: 0, 0, 0, 1
font_size: 20
text: 'Button name:'
TextInput:
unfocus_on_touch: False
id: id_t_name
text: ''
multiline: False
font_size: 20
write_tab: False
on_text_validate: app.btn_ok()
text_validate_unfocus: False
Label:
color: 0, 0, 0, 1
font_size: 20
text: 'Clipboard Python-regex pattern:'
TextInput:
unfocus_on_touch: False
id: id_t_patt
text: ''
multiline: False
font_size: 20
write_tab: False
on_text_validate: app.btn_ok()
text_validate_unfocus: False
Label:
color: 0, 0, 0, 1
font_size: 20
text: 'Command reference to pattern ($1 $2..):'
TextInput:
unfocus_on_touch: False
id: id_t_cmd
text: ''
multiline: False
font_size: 20
write_tab: False
on_text_validate: app.btn_ok()
text_validate_unfocus: False
BoxLayout:
size_hint: 1, 0.2
Button:
on_press: app.btn_ok()
is_focusable: False
text: 'OK'
font_size: 20
Button:
on_press: root.manager.current = 'main'
is_focusable: False
text: 'CANCEL'
font_size: 20
''')
class MainWidget(Screen): pass
w_main = MainWidget(name='main')
class ButtonEditor(Screen): pass
w_input = ButtonEditor(name='input')
class ClipCommanderApp(App):
cmdline_process = None
scancmd = None
bad_lockdown = None
resource_rootpath = '' # examples: /path/to/data or /usr/local/share
edit_modus = False
confpath = '' # ini file
firstrun = False
usedbtn = None # differentiate pressing the '+' or selecting an existing button
reflags = 0 # regex
prevcliptext = None
btnslocked = False
startmodus = ''
def btn_ok(self):
# textbox input checks
w_input.t_name.text = w_input.t_name.text.strip()
w_input.t_patt.text = w_input.t_patt.text.strip()
w_input.t_cmd.text = w_input.t_cmd.text.strip()
for tbox in (w_input.t_name, w_input.t_patt, w_input.t_cmd):
if not tbox.text:
w_input.simmsg.color = col_bad
w_input.simmsg.text = 'Empty input not allowed'
tbox.focus = True
return
# regex checks on t_patt
try:
re.compile(w_input.t_patt.text)
except re.error as msg:
w_input.simmsg.color = col_bad
w_input.simmsg.text = 'Regex: ' + str(msg)
w_input.t_patt.focus = True
return
# command executable check here on t_cmd
cmd = w_input.t_cmd.text.split(maxsplit=1)
if which(cmd[0]) is None:
w_input.simmsg.color = col_bad
w_input.simmsg.text = 'Command not found!'
w_input.t_cmd.focus = True
return
# add button
if self.usedbtn: # clicked red button
self.usedbtn.text = w_input.t_name.text
self.usedbtn.patt = w_input.t_patt.text
self.usedbtn.cmd = w_input.t_cmd.text
else: # pressed '+'
# check if name already exists
for btn in (w for w in w_main.mainbox.children if type(w) is Button):
if btn.text == w_input.t_name.text:
w_input.simmsg.color = col_bad
w_input.simmsg.text = 'Cannot add, name already exists!'
w_input.t_name.focus = True
return
# add button widget
self.add_a_new_button(w_input.t_name.text, w_input.t_patt.text, w_input.t_cmd.text)
# write with correct ordering
self.write_button_widgets_to_config()
screenman.current = 'main'
def w_input_enter(self):
# Clear previous contents, initialize window with relevant data
if self.usedbtn:
w_input.t_name.text = self.usedbtn.text
w_input.t_patt.text = self.usedbtn.patt
w_input.t_cmd.text = self.usedbtn.cmd
w_input.simmsg.color = col_good
w_input.simmsg.text = 'Edit existing button'
else:
w_input.t_name.text = ''
w_input.t_patt.text = ''
w_input.t_cmd.text = ''
w_input.simmsg.color = col_good
w_input.simmsg.text = 'Add a new button'
w_input.t_name.focus = True
def btn_plusbtn(self):
self.usedbtn = None
screenman.current = 'input'
def btn_toggle_edit(self):
if w_main.editbtn.state == 'down':
self.edit_modus = True
for btn in (w for w in w_main.mainbox.children if type(w) is Button):
hide_widget(btn, False) # make all visible
btn.background_color = [2, 0, 0, 1]
btn.disabled = True
w_main.lab_hidden.text = 'Edit modus'
else:
self.edit_modus = False
for btn in (w for w in w_main.mainbox.children if type(w) is Button):
btn.background_color = col_white
btn.disabled = False
# do complete rescan
self.prevcliptext = None
self.myclock(0)
# Toggle showing 'add button' plus symbol
hide_widget(w_main.plusbtn, not self.edit_modus)
def swapbuttons(self, src, dest):
tempdestpos = list(dest.pos) # copy tuple content, prevent pointer assignment
dest.pos = src.pos
src.pos = tempdestpos
def touch_move_btn_DL(self, btn, touch):
if not btn.grabbed:
return
# check if the mouse left the initial button area
if not btn.collide_point(*touch.pos):
btn.triedswap = True
# check if dragging to another button
for widget in w_main.mainbox.children:
if type(widget) is Button and not widget == btn:
if widget.collide_point(*touch.pos):
# yes, swap button content
self.swapbuttons(btn, widget)
return
# check if dragging into delete area
if w_main.delarea.collide_point(*touch.pos):
w_main.delarea.color = col_proximate
else:
w_main.delarea.color = col_white
def touch_down_btn_DL(self, btn, touch):
if self.edit_modus and btn.collide_point(*touch.pos):
btn.grabbed = True
btn.triedswap = False
hide_widget(w_main.delarea, False)
def write_button_widgets_to_config(self):
# re-index/order buttons
poslist = [] # list of tuples containing all the info per button
for btn in (w for w in w_main.mainbox.children if type(w) is Button):
poslist.append((btn.y, btn.text, btn.patt, btn.cmd))
poslist.sort(key=lambda tup: tup[0], reverse=True) # sort by y-coordinate
# clear all btns from config
for setting in self.config['settings']:
if setting[:3] == 'btn':
del self.config['settings'][setting]
# store new btn setup to config
for i, tup in enumerate(poslist):
btnN = 'btn' + str(i + 1)
self.config['settings'].update({btnN + '_text': tup[1], btnN + '_patt': tup[2], btnN + '_cmd': tup[3]})
self.config.write()
def touch_up_btn_DL(self, btn, touch):
if not btn.grabbed:
return
btn.grabbed = False
# delete button
if w_main.delarea.collide_point(*touch.pos):
w_main.mainbox.remove_widget(btn)
# hide delete button
w_main.delarea.color = col_white
hide_widget(w_main.delarea, True)
# edit button
if not btn.triedswap:
self.usedbtn = btn
screenman.current = 'input'
return
# write with correct ordering
self.write_button_widgets_to_config()
def press_btn_DL(self, btn):
# spam control: alternative to Kivy's min_state_time button
if self.btnslocked: return
btn.background_color[1] = 2
self.btnslocked = True
def greenback(dt):
self.btnslocked = False
btn.background_color[1] = 1
self.on_request_close(None)
Clock.schedule_once(greenback, 0.5)
#print('"{}" "{}" "{}"'.format(btn.text, btn.patt, btn.cmd)) # debug
# replace into groups
command = btn.cmd # complete_selection = btn.matchobj.group(0)
for i, obj in enumerate(btn.matchobj.groups()):
i += 1
command = command.replace('$' + str(i), obj)
# execute command detached
print('[EXEC ] ' + command)
Popen(command.split())
def myclock(self, dt):
if self.edit_modus:
return
# get clipboard data
p = Popen(self.scancmd, stdout=PIPE, stderr=PIPE)
output, errors = p.communicate()
cliptext = output.decode('utf-8')
if cliptext == self.prevcliptext:
return
self.prevcliptext = cliptext
#print('cliptext: "{}"'.format(cliptext)) # debug
# match & grab clipboard text, see if button needs to be hidden
lastmatch = None
cnt = 0
for btn in (w for w in w_main.mainbox.children if type(w) is Button):
btn.matchobj = re.match(btn.patt, cliptext, flags=self.reflags)
if btn.matchobj:
hide_widget(btn, False) # show button
lastmatch = btn
else:
hide_widget(btn, True)
cnt += 1
w_main.lab_hidden.text = 'Hidden: ' + str(cnt)
if lastmatch and self.startmodus == 'hidden_runfirst':
self.press_btn_DL(lastmatch)
elif lastmatch or cliptext == '!showyourself':
SDL_fixed_window_show()
Window.raise_window()
def add_a_new_button(self, _text, patt, cmd):
btn = Button(text=_text, font_size=20)
btn.background_down = btn.background_normal
btn.patt = patt
btn.cmd = cmd
btn.grabbed = False
btn.bind(on_press=self.press_btn_DL, on_touch_down=self.touch_down_btn_DL, \
on_touch_move=self.touch_move_btn_DL, on_touch_up=self.touch_up_btn_DL)
w_main.mainbox.add_widget(btn)
if self.edit_modus:
btn.background_color = [2, 0, 0, 1]
btn.disabled = True
else:
btn.background_color = col_white
btn.disabled = False
return btn
def on_config_change(self, config, section, key, value):
if config is not self.config or self.bad_lockdown:
return # ignore config change of kivy itself
if key == 'welcome_msg':
w_main.statuslabel.text = value
elif key == 'showbar':
screenman.current = 'main'
if value == '0':
if self.edit_modus:
w_main.editbtn.state = 'normal'
self.btn_toggle_edit()
hide_widget(w_main.mybar)
else:
hide_widget(w_main.mybar, False)
elif key == 'reflags':
self.reflags = 0
flagslist = value.split('|')
for flagstr in flagslist:
if hasattr(re, flagstr):
self.reflags |= getattr(re, flagstr)
elif key == 'startmodus':
self.startmodus = value
elif key == 'storewin':
if value == '1':
winstr = ' '.join(str(n) for n in [Window.left, Window.top, Window.size[0], Window.size[1]])
config.set('settings', 'storewindata', winstr)
config.write()
elif key == 'scaninterval':
Clock.unschedule(self.myclock)
Clock.schedule_interval(self.myclock, float(value))
def on_start(self):
# Pre-run requirement tests
if which('xclip'):
self.scancmd = ['xclip', '-o']
elif which('xsel'):
self.scancmd = ['xsel', '-o']
if not self.scancmd:
self.bad_lockdown = 'Please install either "xclip" or "xsel" to use this app'
if not which('youtube-dl'):
self.bad_lockdown = 'Please install "youtube-dl" ("ffmpeg" is also recommended!)'
# See if app can function
cfg = self.config['settings']
statuslabel = w_main.statuslabel
if self.bad_lockdown:
statuslabel.color = col_bad
statuslabel.text = self.bad_lockdown
# hide mybar
Clock.schedule_once(lambda dt: hide_widget(w_main.mybar), 1) # doing this sooner seems defective
SDL_fixed_window_show()
Window.raise_window()
return
elif self.firstrun:
statuslabel.color = col_good
statuslabel.text = 'First time run, welcome! Wrote config {}\n Copy a YouTube video link into the clipboard'.format(self.confpath)
self.firstrun = False
else:
statuslabel.color = col_good
statuslabel.text = cfg['welcome_msg']
# Add command buttons from config
i = 1
while True:
btnN = 'btn' + str(i)
newtext = self.config.getdefault('settings', btnN + '_text', '')
if not newtext:
break
btn = self.add_a_new_button(newtext, cfg[btnN + '_patt'], cfg[btnN + '_cmd'])
i += 1
# Only show in edit modus
hide_widget(w_main.plusbtn)
hide_widget(w_main.delarea)
# showbar
if cfg['showbar'] == '0':
Clock.schedule_once(lambda dt: hide_widget(w_main.mybar), 1) # doing this sooner seems defective
# evaluate regex flags
self.reflags = 0
flagslist = cfg['reflags'].split('|')
for flagstr in flagslist:
if hasattr(re, flagstr):
self.reflags |= getattr(re, flagstr)
# Start responsive timer/scanner
self.myclock(0)
Clock.schedule_interval(self.myclock, float(cfg['scaninterval']))
def get_application_config(self):
self.confpath = super(type(self), self).get_application_config('~/.config/%(appname)s.ini')
return self.confpath
def build_config(self, config):
self.confpath = self.get_application_config()
if os.access(self.confpath, os.R_OK):
# remove 'btnX_...' keys from config, don't re-create buttons that may have been deleted
for key in list(def_defaultcfg.keys()):
if key[:3] == 'btn':
del def_defaultcfg[key]
else:
self.firstrun = True
config.setdefaults('settings', def_defaultcfg)
def build_settings(self, settings):
settings.add_json_panel('ClipCommander', self.config, data=def_jsondata)
def on_request_close(self, args):
if self.startmodus[:6] == 'hidden':
if self.edit_modus:
w_main.editbtn.state = 'normal'
self.btn_toggle_edit()
Window.hide()
print('[HIDDEN ]')
return True # daemon mode, impossible to close normally
def build(self):
# get icon and resource path
app_path = Path(__file__).resolve()
for tryroot in (str(app_path.parents[1]) + '/share', str(app_path.parents[0]) + '/data'):
tryicon = tryroot + '/pixmaps/' + name + '.png'
if os.access(tryicon, os.R_OK):
self.icon = tryicon
self.resource_rootpath = tryroot
break
else:
print('WARNING: Could not find application resource files', file=sys.stderr)
# storewin
cfg = self.config['settings']
if cfg['storewin'] == '1':
coords = cfg['storewindata'].split()
if len(coords) == 4:
Window.left, Window.top = int(coords[0]), int(coords[1])
Window.size = (int(coords[2]), int(coords[3]))
# determine startmodus
self.startmodus = cfg['startmodus']
if self.startmodus[:6] == 'hidden':
print('[HIDDEN ]')
else:
SDL_fixed_window_show()
Window.raise_window()
# wrap close request to handle startmodus
Window.bind(on_request_close=self.on_request_close)
return screenman
def SDL_fixed_window_show():
Window.show()
if SDL_needfix:
# doing this on >= 2.0.9 causes problems (lose Window focus)
# not doing this on lesser versions ignores Window.show() altogether
Window.maximize()
Window.restore()
#
########### NON-GUI Below
#
def hide_widget(wid, dohide=True):
if hasattr(wid, 'saved_attrs'):
if not dohide:
wid.height, wid.size_hint_y, wid.opacity, wid.disabled = wid.saved_attrs
del wid.saved_attrs
elif dohide:
wid.saved_attrs = wid.height, wid.size_hint_y, wid.opacity, wid.disabled
wid.height, wid.size_hint_y, wid.opacity, wid.disabled = 0, None, 0, True
def fatal_err(*args):
print('ERROR:', *args, file=sys.stderr)
sys.exit(1)
def pymod_versioncheck(module_name, module_version, required_version):
if StrictVersion(module_version) < StrictVersion(required_version):
fatal_err(module_name, 'requires version', required_version, 'current verion is', module_version)
else:
print('::', module_name, 'version is:', module_version)
def signal_intterm(sig, frame):
print('[EXITNOW]')
sys.exit(0)
def linux_SDL_getversion():
SDLpatt = 'libSDL\d*-(\d*).(\d*).so.0.(\d*).0'
for root, dirnames, filenames in os.walk('/usr/lib'):
for filename in filenames:
matchobj = re.match(SDLpatt, filename)
if matchobj:
return '.'.join(matchobj.groups())
return 0
#
##### Main program entry point (after reading all the functions above!)
#
if __name__ == '__main__':
# linux-specific check for app single instance
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind('\0{}_lock'.format(name))
except socket.error as err:
error_code, error_string = err.args[0], err.args[1]
print("Process already running ({}: {}). Exiting".format(error_code, error_string))
sys.exit(0)
# cross-platform check for app single instance, requires package 'tendo'
#from tendo import singleton
#me = singleton.SingleInstance()
# check module requirements
pymod_versioncheck('kivy', KIVY_VERSION, '1.10.1')
# SDL version/fix
linux_SDLver = linux_SDL_getversion()
if(linux_SDLver):
print(':: found Linux SDL version:', linux_SDLver)
SDL_needfix = StrictVersion(linux_SDLver) < StrictVersion('2.0.9')
else:
SDL_needfix = False
# handle signals more gracefully
signal.signal(signal.SIGINT, signal_intterm)
signal.signal(signal.SIGTERM, signal_intterm)
# Kivy config settings
Config.set('input', 'mouse', 'mouse,disable_multitouch') # right mouse behave like left button
Window.left, Window.top = 100, 0
Window.size = 600, 360
#Window.hide() # defective in Kivy, creates ugly artifacts
# Create the screen manager
screenman = ScreenManager(transition=NoTransition())
screenman.add_widget(w_main)
screenman.add_widget(w_input)
# Launch GUI
ClipCommanderApp().run()
# End of file
|
mchirico/Cipher | tests/test_advanced.py | # -*- coding: utf-8 -*-
from .context import clib
from clib.util.cipher import Cipher
from unittest import TestCase
class AdvancedTestSuite(TestCase):
"""Advanced test cases."""
def test_thoughts(self):
self.assertIsNone(clib.hmm())
def test_cipher(self):
cipher = Cipher()
shift = 7
expected_result = 'tvbzl pz jbal'
s = 'mouse is cute'
print(cipher.stringEncrypt(s, shift))
self.assertEqual(expected_result, cipher.stringEncrypt(s, shift))
|
YiminGao0113/MiniDiscord | test.py |
import smtplib, ssl
port = 465 # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "<EMAIL>" # Enter your address
receiver_email = "<EMAIL>" # Enter receiver address
password = "<PASSWORD>"
message = """\
Subject: Hi there
This message is sent from Python."""
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message) |
YiminGao0113/MiniDiscord | app.py | from flask import Flask, render_template, redirect, url_for, flash, request, session, jsonify
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import InputRequired, Email, Length, DataRequired
import email_validator
from werkzeug.security import generate_password_hash, check_password_hash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
import smtplib, ssl
from datetime import datetime
import time
from flask_socketio import SocketIO
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import json
import sqlite3
from sqlite3 import Error
FILE = "database.db"
LIMIT = 20
app = Flask(__name__)
clients = {}
app.config['SECRET_KEY'] = 'youwontguessthiskey'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
Bootstrap(app)
db = SQLAlchemy(app)
socketio = SocketIO(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(15), unique=True)
email = db.Column(db.String(50), unique=True)
password = db.Column(db.String(80))
email_confirmed = db.Column(db.Boolean(), nullable=False, default=False)
online = db.Column(db.Boolean(), nullable=False, default=False)
class Messages(db.Model):
id = db.Column(db.Integer, primary_key=True)
client = db.Column(db.String(15), unique=False)
message = db.Column(db.String(80))
time = db.Column(db.String(50))
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class LoginForm(FlaskForm):
username = StringField('username', validators=[InputRequired(), Length(min=4, max=15)])
password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])
remember = BooleanField('remember me')
class RegisterForm(FlaskForm):
email = StringField('email', validators=[InputRequired(), Email(message='Invalid email'), Length(max=50)])
username = StringField('username', validators=[InputRequired(), Length(min=4, max=15)])
password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])
# email_confirmed = BooleanField('email_confirmed', validators=[DataRequired(), ])
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login',methods=['GET','POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user=User.query.filter_by(username=form.username.data).first()
if user:
if user.email_confirmed:
if check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
user.online = True
db.session.commit()
session['name'] = user.username
return redirect(url_for('dashboard'))
flash("Wrong password!", "info")
else:
flash("The account is not confirmed!", "info")
else:
flash("Username doesn't exist!", "info")
return render_template('login.html', form=form)
# @app.route('/chat',methods=['GET','POST'])
# def chat():
# return render_template('chat.html')
@app.route('/signup',methods=['GET','POST'])
def signup():
form = RegisterForm()
if form.validate_on_submit():
try:
hashed_password = generate_password_hash(form.password.data, method='sha256')
new_user = User(username=form.username.data, email=form.email.data, password=<PASSWORD>, email_confirmed=0, online=0)
send_email(new_user)
db.session.add(new_user)
db.session.commit()
flash("Please click the link we sent to your email to activate the account!")
return redirect(url_for('login'))
except Exception as e:
print(e)
return render_template('signup.html', form=form)
@app.route('/dashboard',methods=['GET','POST'])
@login_required
def dashboard():
return render_template('dashboard.html', **{"session": session}, name= session['name'], users = get_users())
@app.route("/get_messages")
def get_messages():
conn = sqlite3.connect(FILE)
cursor = conn.cursor()
query = "SELECT * FROM Messages"
cursor.execute(query)
result = cursor.fetchall()
results = []
for r in sorted(result, key=lambda x: x[3], reverse=True)[:LIMIT]:
id, name, content, date = r
if (name == "host"):
continue
data = {"name":name, "message":content, "time":str(date)}
results.append(data)
msgs = remove_seconds_from_messages(results)
msgs = list(reversed(msgs))
return jsonify(msgs)
@app.route("/get_name")
def get_name():
"""
:return: a json object storing name of logged in user
"""
data = {"name": ""}
if 'name' in session:
data = {"name": session['name']}
return jsonify(data)
def get_users():
users = User.query.all()
return users
@app.route("/logout")
@login_required
def logout():
"""
logs the user out by popping name from session
:return: None
"""
data = {"name":"host", "message":f"{session['name']} has left the channel", "time":f"{datetime.now()}"}
s = json.dumps(data, indent=2)
print(s)
socketio.emit('message response', s)
user=User.query.filter_by(username=session['name']).first()
user.online = False
db.session.commit()
logout_user()
session.pop('name', None)
flash("You were logged out.")
return redirect(url_for("index"))
def send_email(user):
port = 465 # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "<EMAIL>" # Enter your address
receiver_email = user.email # Enter receiver address
password = "<PASSWORD>"
msg = MIMEMultipart('alternative')
msg['Subject'] = "Account acctivation(No-reply)"
msg['From'] = sender_email
msg['To'] = receiver_email
text = "Welcome to yimindiscord, please click the link here to acctivate your account:"
html = f"""\
<html>
<head>YiminDiscord</head>
<body>
<p>Welcome to yimindiscord! Please click the link here to activate your account: <p>
<a href="http://yimindiscord.com:5000/{user.username}">Activate</a></p>
</body>
</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg.as_string())
@app.route('/<name>')
def confirm_email(name):
user=User.query.filter_by(username=name).first()
if user:
user.email_confirmed = True
db.session.commit()
return render_template('mail.html', message="Your account has been activated!")
else:
return render_template('mail.html', message="No such account!")
# COMMUNICATION FUNCTIONS
@socketio.on('event')
def handle_my_custom_event(json, methods=['GET', 'POST']):
"""
handles saving messages once received from web server
and sending message to other clients
:param json: json
:param methods: POST GET
:return: None
"""
data = dict(json)
print(data)
if "name" in data:
new_message = Messages(client=data["name"], message=data["message"],time=datetime.now())
db.session.add(new_message)
db.session.commit()
socketio.emit('message response', json)
# UTILITIES
def remove_seconds_from_messages(msgs):
"""
removes the seconds from all messages
:param msgs: list
:return: list
"""
messages = []
for msg in msgs:
message = msg
message["time"] = remove_seconds(message["time"])
messages.append(message)
return messages
def remove_seconds(msg):
"""
:return: string with seconds trimmed off
"""
return msg.split(".")[0][:-3]
if __name__ == '__main__':
# db.create_all()
# app.run(debug=True)
# app.run(host='0.0.0.0')
socketio.run(app, debug=True, host='0.0.0.0')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.