def __partial_trace_vec(vec, trace_systems, dimensions, reverse=True):
    """
    Partial trace over subsystems of multi-partite vector.

    Args:
        vec (vector_like): complex vector N
        trace_systems (list(int)): a list of subsystems (starting from 0) to
                                  trace over.
        dimensions (list(int)): a list of the dimensions of the subsystems.
                                If this is not set it will assume all
                                subsystems are qubits.
        reverse (bool): ordering of systems in operator.
            If True system-0 is the right most system in tensor product.
            If False system-0 is the left most system in tensor product.

    Returns:
        ndarray: A density matrix with the appropriate subsystems traced over.
    """

    # trace sys positions
    if reverse:
        dimensions = dimensions[::-1]
        trace_systems = len(dimensions) - 1 - np.array(trace_systems)

    rho = vec.reshape(dimensions)
    rho = np.tensordot(rho, rho.conj(), axes=(trace_systems, trace_systems))
    d = int(np.sqrt(np.product(rho.shape)))

    return rho.reshape(d, d)

def
__partial_trace_vec
(
vec
,
trace_systems
,
dimensions
,
reverse
=
True
)
:
# trace sys positions
if
reverse
:
dimensions
=
dimensions
[
:
:
1
]
trace_systems
=
len
(
dimensions
)
1
np
.
array
(
trace_systems
)
rho
=
vec
.
reshape
(
dimensions
)
rho
=
np
.
tensordot
(
rho
,
rho
.
conj
(
)
,
axes
=
(
trace_systems
,
trace_systems
)
)
d
=
int
(
np
.
sqrt
(
np
.
product
(
rho
.
shape
)
)
)
return
rho
.
reshape
(
d
,
d
)

Partial trace over subsystems of multi - partite vector .


def vectorize(density_matrix, method='col'):
    """Flatten an operator to a vector in a specified basis.

    Args:
        density_matrix (ndarray): a density matrix.
        method (str): the method of vectorization. Allowed values are
            - 'col' (default) flattens to column-major vector.
            - 'row' flattens to row-major vector.
            - 'pauli'flattens in the n-qubit Pauli basis.
            - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by
               weight.

    Returns:
        ndarray: the resulting vector.
    Raises:
        Exception: if input state is not a n-qubit state
    """
    density_matrix = np.array(density_matrix)
    if method == 'col':
        return density_matrix.flatten(order='F')
    elif method == 'row':
        return density_matrix.flatten(order='C')
    elif method in ['pauli', 'pauli_weights']:
        num = int(np.log2(len(density_matrix)))  # number of qubits
        if len(density_matrix) != 2**num:
            raise Exception('Input state must be n-qubit state')
        if method == 'pauli_weights':
            pgroup = pauli_group(num, case='weight')
        else:
            pgroup = pauli_group(num, case='tensor')
        vals = [np.trace(np.dot(p.to_matrix(), density_matrix))
                for p in pgroup]
        return np.array(vals)
    return None

def
vectorize
(
density_matrix
,
method
=
'col'
)
:
density_matrix
=
np
.
array
(
density_matrix
)
if
method
==
'col'
:
return
density_matrix
.
flatten
(
order
=
'F'
)
elif
method
==
'row'
:
return
density_matrix
.
flatten
(
order
=
'C'
)
elif
method
in
[
'pauli'
,
'pauli_weights'
]
:
num
=
int
(
np
.
log2
(
len
(
density_matrix
)
)
)
# number of qubits
if
len
(
density_matrix
)
!=
2
**
num
:
raise
Exception
(
'Input state must be n-qubit state'
)
if
method
==
'pauli_weights'
:
pgroup
=
pauli_group
(
num
,
case
=
'weight'
)
else
:
pgroup
=
pauli_group
(
num
,
case
=
'tensor'
)
vals
=
[
np
.
trace
(
np
.
dot
(
p
.
to_matrix
(
)
,
density_matrix
)
)
for
p
in
pgroup
]
return
np
.
array
(
vals
)
return

Flatten an operator to a vector in a specified basis .


def devectorize(vectorized_mat, method='col'):
    """Devectorize a vectorized square matrix.

    Args:
        vectorized_mat (ndarray): a vectorized density matrix.
        method (str): the method of devectorization. Allowed values are
            - 'col' (default): flattens to column-major vector.
            - 'row': flattens to row-major vector.
            - 'pauli': flattens in the n-qubit Pauli basis.
            - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by
               weight.

    Returns:
        ndarray: the resulting matrix.
    Raises:
        Exception: if input state is not a n-qubit state
    """
    vectorized_mat = np.array(vectorized_mat)
    dimension = int(np.sqrt(vectorized_mat.size))
    if len(vectorized_mat) != dimension * dimension:
        raise Exception('Input is not a vectorized square matrix')

    if method == 'col':
        return vectorized_mat.reshape(dimension, dimension, order='F')
    elif method == 'row':
        return vectorized_mat.reshape(dimension, dimension, order='C')
    elif method in ['pauli', 'pauli_weights']:
        num_qubits = int(np.log2(dimension))  # number of qubits
        if dimension != 2 ** num_qubits:
            raise Exception('Input state must be n-qubit state')
        if method == 'pauli_weights':
            pgroup = pauli_group(num_qubits, case='weight')
        else:
            pgroup = pauli_group(num_qubits, case='tensor')
        pbasis = np.array([p.to_matrix() for p in pgroup]) / 2 ** num_qubits
        return np.tensordot(vectorized_mat, pbasis, axes=1)
    return None

Devectorize a vectorized square matrix .


def choi_to_rauli(choi, order=1):
    """
    Convert a Choi-matrix to a Pauli-basis superoperator.

    Note that this function assumes that the Choi-matrix
    is defined in the standard column-stacking convention
    and is normalized to have trace 1. For a channel E this
    is defined as: choi = (I \\otimes E)(bell_state).

    The resulting 'rauli' R acts on input states as
    |rho_out>_p = R.|rho_in>_p
    where |rho> = vectorize(rho, method='pauli') for order=1
    and |rho> = vectorize(rho, method='pauli_weights') for order=0.

    Args:
        choi (matrix): the input Choi-matrix.
        order (int): ordering of the Pauli group vector.
            order=1 (default) is standard lexicographic ordering.
                Eg: [II, IX, IY, IZ, XI, XX, XY,...]
            order=0 is ordered by weights.
                Eg. [II, IX, IY, IZ, XI, XY, XZ, XX, XY,...]

    Returns:
        np.array: A superoperator in the Pauli basis.
    """
    if order == 0:
        order = 'weight'
    elif order == 1:
        order = 'tensor'

    # get number of qubits'
    num_qubits = int(np.log2(np.sqrt(len(choi))))
    pgp = pauli_group(num_qubits, case=order)
    rauli = []
    for i in pgp:
        for j in pgp:
            pauliop = np.kron(j.to_matrix().T, i.to_matrix())
            rauli += [np.trace(np.dot(choi, pauliop))]
    return np.array(rauli).reshape(4 ** num_qubits, 4 ** num_qubits)

def
choi_to_rauli
(
choi
,
order
=
1
)
:
if
order
==
0
:
order
=
'weight'
elif
order
==
1
:
order
=
'tensor'
# get number of qubits'
num_qubits
=
int
(
np
.
log2
(
np
.
sqrt
(
len
(
choi
)
)
)
)
pgp
=
pauli_group
(
num_qubits
,
case
=
order
)
rauli
=
[
]
for
i
in
pgp
:
for
j
in
pgp
:
pauliop
=
np
.
kron
(
j
.
to_matrix
(
)
.
T
,
i
.
to_matrix
(
)
)
rauli
+=
[
np
.
trace
(
np
.
dot
(
choi
,
pauliop
)
)
]
return
np
.
array
(
rauli
)
.
reshape
(
4
**
num_qubits
,
4
**
num_qubits
)

Convert a Choi - matrix to a Pauli - basis superoperator .


def chop(array, epsilon=1e-10):
    """
    Truncate small values of a complex array.

    Args:
        array (array_like): array to truncte small values.
        epsilon (float): threshold.

    Returns:
        np.array: A new operator with small values set to zero.
    """
    ret = np.array(array)

    if np.isrealobj(ret):
        ret[abs(ret) < epsilon] = 0.0
    else:
        ret.real[abs(ret.real) < epsilon] = 0.0
        ret.imag[abs(ret.imag) < epsilon] = 0.0
    return ret

def chop ( array , epsilon = 1e-10 ) : ret = np . array ( array ) if np . isrealobj ( ret ) : ret [ abs ( ret ) < epsilon ] = 0.0 else : ret . real [ abs ( ret . real ) < epsilon ] = 0.0 ret . imag [ abs ( ret . imag ) < epsilon ] = 0.0 return ret

Truncate small values of a complex array .


def outer(vector1, vector2=None):
    """
    Construct the outer product of two vectors.

    The second vector argument is optional, if absent the projector
    of the first vector will be returned.

    Args:
        vector1 (ndarray): the first vector.
        vector2 (ndarray): the (optional) second vector.

    Returns:
        np.array: The matrix |v1><v2|.

    """
    if vector2 is None:
        vector2 = np.array(vector1).conj()
    else:
        vector2 = np.array(vector2).conj()
    return np.outer(vector1, vector2)

def outer ( vector1 , vector2 = None ) : if vector2 is None : vector2 = np . array ( vector1 ) . conj ( ) else : vector2 = np . array ( vector2 ) . conj ( ) return np . outer ( vector1 , vector2 )

Construct the outer product of two vectors .


def concurrence(state):
    """Calculate the concurrence.

    Args:
        state (np.array): a quantum state (1x4 array) or a density matrix (4x4
                          array)
    Returns:
        float: concurrence.
    Raises:
        Exception: if attempted on more than two qubits.
    """
    rho = np.array(state)
    if rho.ndim == 1:
        rho = outer(state)
    if len(state) != 4:
        raise Exception("Concurrence is only defined for more than two qubits")

    YY = np.fliplr(np.diag([-1, 1, 1, -1]))
    A = rho.dot(YY).dot(rho.conj()).dot(YY)
    w = la.eigh(A, eigvals_only=True)
    w = np.sqrt(np.maximum(w, 0))
    return max(0.0, w[-1] - np.sum(w[0:-1]))


def shannon_entropy(pvec, base=2):
    """
    Compute the Shannon entropy of a probability vector.

    The shannon entropy of a probability vector pv is defined as
    $H(pv) = - \\sum_j pv[j] log_b (pv[j])$ where $0 log_b 0 = 0$.

    Args:
        pvec (array_like): a probability vector.
        base (int): the base of the logarith

    Returns:
        float: The Shannon entropy H(pvec).
    """
    # pylint: disable=missing-docstring
    if base == 2:
        def logfn(x):
            return - x * np.log2(x)
    elif base == np.e:
        def logfn(x):
            return - x * np.log(x)
    else:
        def logfn(x):
            return -x * np.log(x) / np.log(base)

    h = 0.
    for x in pvec:
        if 0 < x < 1:
            h += logfn(x)
    return h

def
shannon_entropy
(
pvec
,
base
=
2
)
:
# pylint: disable=missing-docstring
if
base
==
2
:
def
logfn
(
x
)
:
return
x
*
np
.
log2
(
x
)
elif
base
==
np
.
e
:
def
logfn
(
x
)
:
return
x
*
np
.
log
(
x
)
else
:
def
logfn
(
x
)
:
return
x
*
np
.
log
(
x
)
/
np
.
log
(
base
)
h
=
0.
for
x
in
pvec
:
if
0
<
x
<
1
:
h
+=
logfn
(
x
)
return
h

Compute the Shannon entropy of a probability vector .


def entropy(state):
    """
    Compute the von-Neumann entropy of a quantum state.

    Args:
        state (array_like): a density matrix or state vector.

    Returns:
        float: The von-Neumann entropy S(rho).
    """

    rho = np.array(state)
    if rho.ndim == 1:
        return 0
    evals = np.maximum(np.linalg.eigvalsh(state), 0.)
    return shannon_entropy(evals, base=np.e)

def entropy ( state ) : rho = np . array ( state ) if rho . ndim == 1 : return 0 evals = np . maximum ( np . linalg . eigvalsh ( state ) , 0. ) return shannon_entropy ( evals , base = np . e )

Compute the von - Neumann entropy of a quantum state .


def mutual_information(state, d0, d1=None):
    """
    Compute the mutual information of a bipartite state.

    Args:
        state (array_like): a bipartite state-vector or density-matrix.
        d0 (int): dimension of the first subsystem.
        d1 (int or None): dimension of the second subsystem.

    Returns:
        float: The mutual information S(rho_A) + S(rho_B) - S(rho_AB).
    """
    if d1 is None:
        d1 = int(len(state) / d0)
    mi = entropy(partial_trace(state, [0], dimensions=[d0, d1]))
    mi += entropy(partial_trace(state, [1], dimensions=[d0, d1]))
    mi -= entropy(state)
    return mi

def mutual_information ( state , d0 , d1 = None ) : if d1 is None : d1 = int ( len ( state ) / d0 ) mi = entropy ( partial_trace ( state , [ 0 ] , dimensions = [ d0 , d1 ] ) ) mi += entropy ( partial_trace ( state , [ 1 ] , dimensions = [ d0 , d1 ] ) ) mi -= entropy ( state ) return mi

Compute the mutual information of a bipartite state .


def entanglement_of_formation(state, d0, d1=None):
    """
    Compute the entanglement of formation of quantum state.

    The input quantum state must be either a bipartite state vector, or a
    2-qubit density matrix.

    Args:
        state (array_like): (N) array_like or (4,4) array_like, a
            bipartite quantum state.
        d0 (int): the dimension of the first subsystem.
        d1 (int or None): the dimension of the second subsystem.

    Returns:
        float: The entanglement of formation.
    """
    state = np.array(state)

    if d1 is None:
        d1 = int(len(state) / d0)

    if state.ndim == 2 and len(state) == 4 and d0 == 2 and d1 == 2:
        return __eof_qubit(state)
    elif state.ndim == 1:
        # trace out largest dimension
        if d0 < d1:
            tr = [1]
        else:
            tr = [0]
        state = partial_trace(state, tr, dimensions=[d0, d1])
        return entropy(state)
    else:
        print('Input must be a state-vector or 2-qubit density matrix.')
    return None

Compute the entanglement of formation of quantum state .


def __eof_qubit(rho):
    """
    Compute the Entanglement of Formation of a 2-qubit density matrix.

    Args:
        rho ((array_like): (4,4) array_like, input density matrix.

    Returns:
        float: The entanglement of formation.
    """
    c = concurrence(rho)
    c = 0.5 + 0.5 * np.sqrt(1 - c * c)
    return shannon_entropy([c, 1 - c])

def __eof_qubit ( rho ) : c = concurrence ( rho ) c = 0.5 + 0.5 * np . sqrt ( 1 - c * c ) return shannon_entropy ( [ c , 1 - c ] )

Compute the Entanglement of Formation of a 2 - qubit density matrix .


def flatten(schedule: ScheduleComponent, name: str = None) -> Schedule:
    """Create a flattened schedule.

    Args:
        schedule: Schedules to flatten
        name: Name of the new schedule. Defaults to first element of `schedules`
    """
    if name is None:
        name = schedule.name

    return Schedule(*schedule.instructions, name=name)

def flatten ( schedule : ScheduleComponent , name : str = None ) -> Schedule : if name is None : name = schedule . name return Schedule ( * schedule . instructions , name = name )


def shift(schedule: ScheduleComponent, time: int, name: str = None) -> Schedule:
    """Return schedule shifted by `time`.

    Args:
        schedule: The schedule to shift
        time: The time to shift by
        name: Name of shifted schedule. Defaults to name of `schedule`
    """
    if name is None:
        name = schedule.name
    return union((time, schedule), name=name)

def shift ( schedule : ScheduleComponent , time : int , name : str = None ) -> Schedule : if name is None : name = schedule . name return union ( ( time , schedule ) , name = name )


def insert(parent: ScheduleComponent, time: int, child: ScheduleComponent,
           name: str = None) -> Schedule:
    """Return a new schedule with the `child` schedule inserted into the `parent` at `start_time`.

    Args:
        parent: Schedule to be inserted into
        time: Time to be inserted defined with respect to `parent`
        child: Schedule to insert
        name: Name of the new schedule. Defaults to name of parent
    """
    return union(parent, (time, child), name=name)

def insert ( parent : ScheduleComponent , time : int , child : ScheduleComponent , name : str = None ) -> Schedule : return union ( parent , ( time , child ) , name = name )

Return a new schedule with the child schedule inserted into the parent at start_time .


def append(parent: ScheduleComponent, child: ScheduleComponent,
           name: str = None) -> Schedule:
    r"""Return a new schedule with by appending `child` to `parent` at
       the last time of the `parent` schedule's channels
       over the intersection of the parent and child schedule's channels.

       $t = \textrm{max}({x.stop\_time |x \in parent.channels \cap child.channels})$

    Args:
        parent: The schedule to be inserted into
        child: The schedule to insert
        name: Name of the new schedule. Defaults to name of parent
    """
    common_channels = set(parent.channels) & set(child.channels)
    insertion_time = parent.ch_stop_time(*common_channels)
    return insert(parent, insertion_time, child, name=name)

def append ( parent : ScheduleComponent , child : ScheduleComponent , name : str = None ) -> Schedule : common_channels = set ( parent . channels ) & set ( child . channels ) insertion_time = parent . ch_stop_time ( * common_channels ) return insert ( parent , insertion_time , child , name = name )

r Return a new schedule with by appending child to parent at the last time of the parent schedule s channels over the intersection of the parent and child schedule s channels .


def u3(self, theta, phi, lam, q):
    """Apply u3 to q."""
    return self.append(U3Gate(theta, phi, lam), [q], [])

def u3 ( self , theta , phi , lam , q ) : return self . append ( U3Gate ( theta , phi , lam ) , [ q ] , [ ] )


def status(self):
        """Return backend status.

        Returns:
            BackendStatus: the status of the backend.
        """
        return BackendStatus(backend_name=self.name(),
                             backend_version=__version__,
                             operational=True,
                             pending_jobs=0,
                             status_msg='')

def status ( self ) : return BackendStatus ( backend_name = self . name ( ) , backend_version = __version__ , operational = True , pending_jobs = 0 , status_msg = '' )


def start(self, iterations):
        """Start the progress bar.

        Parameters:
            iterations (int): Number of iterations.
        """
        self.touched = True
        self.iter = int(iterations)
        self.t_start = time.time()

def start ( self , iterations ) : self . touched = True self . iter = int ( iterations ) self . t_start = time . time ( )


def time_remaining_est(self, completed_iter):
        """Estimate the remaining time left.

        Parameters:
            completed_iter (int): Number of iterations completed.

        Returns:
            est_time: Estimated time remaining.
        """
        if completed_iter:
            t_r_est = (time.time() - self.t_start) / \
                completed_iter*(self.iter-completed_iter)
        else:
            t_r_est = 0
        date_time = datetime.datetime(1, 1, 1) + datetime.timedelta(seconds=t_r_est)
        time_string = "%02d:%02d:%02d:%02d" % \
            (date_time.day - 1, date_time.hour, date_time.minute, date_time.second)

        return time_string

def time_remaining_est ( self , completed_iter ) : if completed_iter : t_r_est = ( time . time ( ) - self . t_start ) / completed_iter * ( self . iter - completed_iter ) else : t_r_est = 0 date_time = datetime . datetime ( 1 , 1 , 1 ) + datetime . timedelta ( seconds = t_r_est ) time_string = "%02d:%02d:%02d:%02d" % ( date_time . day - 1 , date_time . hour , date_time . minute , date_time . second ) return time_string


def disassemble(qobj):
    """Dissasemble a qobj and return the circuits, run_config, and user header

    Args:
        qobj (Qobj): The input qobj object to dissasemble
    Returns:
        circuits (list): A list of quantum circuits
        run_config (dict): The dist of the run config
        user_qobj_header (dict): The dict of any user headers in the qobj

    """
    run_config = qobj.config.to_dict()
    user_qobj_header = qobj.header.to_dict()
    circuits = _experiments_to_circuits(qobj)

    return circuits, run_config, user_qobj_header

def disassemble ( qobj ) : run_config = qobj . config . to_dict ( ) user_qobj_header = qobj . header . to_dict ( ) circuits = _experiments_to_circuits ( qobj ) return circuits , run_config , user_qobj_header

Dissasemble a qobj and return the circuits run_config and user header


def hamming_distance(str1, str2):
    """Calculate the Hamming distance between two bit strings

    Args:
        str1 (str): First string.
        str2 (str): Second string.
    Returns:
        int: Distance between strings.
    Raises:
        VisualizationError: Strings not same length
    """
    if len(str1) != len(str2):
        raise VisualizationError('Strings not same length.')
    return sum(s1 != s2 for s1, s2 in zip(str1, str2))

def
hamming_distance
(
str1
,
str2
)
:
if
len
(
str1
)
!=
len
(
str2
)
:
raise
VisualizationError
(
'Strings not same length.'
)
return
sum
(
s1
!=
s2
for
s1
,
s2
in
zip
(
str1
,
str2
)
)


def quaternion_from_axis_rotation(angle, axis):
    """Return quaternion for rotation about given axis.

    Args:
        angle (float): Angle in radians.
        axis (str): Axis for rotation

    Returns:
        Quaternion: Quaternion for axis rotation.

    Raises:
        ValueError: Invalid input axis.
    """
    out = np.zeros(4, dtype=float)
    if axis == 'x':
        out[1] = 1
    elif axis == 'y':
        out[2] = 1
    elif axis == 'z':
        out[3] = 1
    else:
        raise ValueError('Invalid axis input.')
    out *= math.sin(angle/2.0)
    out[0] = math.cos(angle/2.0)
    return Quaternion(out)

def
quaternion_from_axis_rotation
(
angle
,
axis
)
:
out
=
np
.
zeros
(
4
,
dtype
=
float
)
if
axis
==
'x'
:
out
[
1
]
=
1
elif
axis
==
'y'
:
out
[
2
]
=
1
elif
axis
==
'z'
:
out
[
3
]
=
1
else
:
raise
ValueError
(
'Invalid axis input.'
)
out
*=
math
.
sin
(
angle
/
2.0
)
out
[
0
]
=
math
.
cos
(
angle
/
2.0
)
return
Quaternion
(
out
)

Return quaternion for rotation about given axis .


def quaternion_from_euler(angles, order='yzy'):
    """Generate a quaternion from a set of Euler angles.

    Args:
        angles (array_like): Array of Euler angles.
        order (str): Order of Euler rotations.  'yzy' is default.

    Returns:
        Quaternion: Quaternion representation of Euler rotation.
    """
    angles = np.asarray(angles, dtype=float)
    quat = quaternion_from_axis_rotation(angles[0], order[0])\
        * (quaternion_from_axis_rotation(angles[1], order[1])
           * quaternion_from_axis_rotation(angles[2], order[2]))
    quat.normalize(inplace=True)
    return quat

def quaternion_from_euler ( angles , order = 'yzy' ) : angles = np . asarray ( angles , dtype = float ) quat = quaternion_from_axis_rotation ( angles [ 0 ] , order [ 0 ] ) * ( quaternion_from_axis_rotation ( angles [ 1 ] , order [ 1 ] ) * quaternion_from_axis_rotation ( angles [ 2 ] , order [ 2 ] ) ) quat . normalize ( inplace = True ) return quat

Generate a quaternion from a set of Euler angles .


def normalize(self, inplace=False):
        """Normalizes a Quaternion to unit length
        so that it represents a valid rotation.

        Args:
            inplace (bool): Do an inplace normalization.

        Returns:
            Quaternion: Normalized quaternion.
        """
        if inplace:
            nrm = self.norm()
            self.data /= nrm
            return None
        nrm = self.norm()
        data_copy = np.array(self.data, copy=True)
        data_copy /= nrm
        return Quaternion(data_copy)

def normalize ( self , inplace = False ) : if inplace : nrm = self . norm ( ) self . data /= nrm return None nrm = self . norm ( ) data_copy = np . array ( self . data , copy = True ) data_copy /= nrm return Quaternion ( data_copy )

Normalizes a Quaternion to unit length so that it represents a valid rotation .


def to_matrix(self):
        """Converts a unit-length quaternion to a rotation matrix.

        Returns:
            ndarray: Rotation matrix.
        """
        w, x, y, z = self.normalize().data  # pylint: disable=C0103
        mat = np.array([
            [1-2*y**2-2*z**2, 2*x*y-2*z*w, 2*x*z+2*y*w],
            [2*x*y+2*z*w, 1-2*x**2-2*z**2, 2*y*z-2*x*w],
            [2*x*z-2*y*w, 2*y*z+2*x*w, 1-2*x**2-2*y**2]
        ], dtype=float)
        return mat

Converts a unit - length quaternion to a rotation matrix .


def to_zyz(self):
        """Converts a unit-length quaternion to a sequence
        of ZYZ Euler angles.

        Returns:
            ndarray: Array of Euler angles.
        """
        mat = self.to_matrix()
        euler = np.zeros(3, dtype=float)
        if mat[2, 2] < 1:
            if mat[2, 2] > -1:
                euler[0] = math.atan2(mat[1, 2], mat[0, 2])
                euler[1] = math.acos(mat[2, 2])
                euler[2] = math.atan2(mat[2, 1], -mat[2, 0])
            else:
                euler[0] = -math.atan2(mat[1, 0], mat[1, 1])
                euler[1] = np.pi
        else:
            euler[0] = math.atan2(mat[1, 0], mat[1, 1])
        return euler

def to_zyz ( self ) : mat = self . to_matrix ( ) euler = np . zeros ( 3 , dtype = float ) if mat [ 2 , 2 ] < 1 : if mat [ 2 , 2 ] > - 1 : euler [ 0 ] = math . atan2 ( mat [ 1 , 2 ] , mat [ 0 , 2 ] ) euler [ 1 ] = math . acos ( mat [ 2 , 2 ] ) euler [ 2 ] = math . atan2 ( mat [ 2 , 1 ] , - mat [ 2 , 0 ] ) else : euler [ 0 ] = - math . atan2 ( mat [ 1 , 0 ] , mat [ 1 , 1 ] ) euler [ 1 ] = np . pi else : euler [ 0 ] = math . atan2 ( mat [ 1 , 0 ] , mat [ 1 , 1 ] ) return euler

Converts a unit - length quaternion to a sequence of ZYZ Euler angles .


def process_data(data, number_to_keep):
    """ Prepare received data for representation.

        Args:
            data (dict): values to represent (ex. {'001' : 130})
            number_to_keep (int): number of elements to show individually.

        Returns:
            dict: processed data to show.
    """

    result = dict()

    if number_to_keep != 0:
        data_temp = dict(Counter(data).most_common(number_to_keep))
        data_temp['rest'] = sum(data.values()) - sum(data_temp.values())
        data = data_temp

    labels = data
    values = np.array([data[key] for key in labels], dtype=float)
    pvalues = values / sum(values)
    for position, label in enumerate(labels):
        result[label] = round(pvalues[position], 5)

    return result

def process_data ( data , number_to_keep ) : result = dict ( ) if number_to_keep != 0 : data_temp = dict ( Counter ( data ) . most_common ( number_to_keep ) ) data_temp [ 'rest' ] = sum ( data . values ( ) ) - sum ( data_temp . values ( ) ) data = data_temp labels = data values = np . array ( [ data [ key ] for key in labels ] , dtype = float ) pvalues = values / sum ( values ) for position , label in enumerate ( labels ) : result [ label ] = round ( pvalues [ position ] , 5 ) return result

Prepare received data for representation .


def iplot_histogram(data, figsize=None, number_to_keep=None,
                    sort='asc', legend=None):
    """ Create a histogram representation.

        Graphical representation of the input array using a vertical bars
        style graph.

        Args:
            data (list or dict):  This is either a list of dicts or a single
                dict containing the values to represent (ex. {'001' : 130})
            figsize (tuple): Figure size in pixels.
            number_to_keep (int): The number of terms to plot and
                rest is made into a single bar called other values
            sort (string): Could be 'asc' or 'desc'
            legend (list): A list of strings to use for labels of the data.
                The number of entries must match the length of data.
        Raises:
            VisualizationError: When legend is provided and the length doesn't
                match the input data.
    """

    # HTML
    html_template = Template("""

    """)

    # JavaScript
    javascript_template = Template("""

    """)

    # Process data and execute
    div_number = str(time.time())
    div_number = re.sub('[.]', '', div_number)

    # set default figure size if none provided
    if figsize is None:
        figsize = (7, 5)

    options = {'number_to_keep': 0 if number_to_keep is None else number_to_keep,
               'sort': sort,
               'show_legend': 0,
               'width': int(figsize[0]),
               'height': int(figsize[1])}
    if legend:
        options['show_legend'] = 1

    data_to_plot = []
    if isinstance(data, dict):
        data = [data]

    if legend and len(legend) != len(data):
        raise VisualizationError("Length of legendL (%s) doesn't match number "
                                 "of input executions: %s" %
                                 (len(legend), len(data)))

    for item, execution in enumerate(data):
        exec_data = process_data(execution, options['number_to_keep'])
        out_dict = {'data': exec_data}
        if legend:
            out_dict['name'] = legend[item]
        data_to_plot.append(out_dict)

    html = html_template.substitute({
        'divNumber': div_number
    })

    javascript = javascript_template.substitute({
        'divNumber': div_number,
        'executions': data_to_plot,
        'options': options
    })

    display(HTML(html + javascript))

"""
    <script>
        requirejs.config({
            paths: {
                qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
            }
        });

        require(["qVisualization"], function(qVisualizations) {
            qVisualizations.plotState("histogram_$divNumber",
                                      "histogram",
                                      $executions,
                                      $options);
        });
    </script>
    """


def check_type(self, value, attr, data):
        """Customize check_type for handling containers."""
        # Check the type in the standard way first, in order to fail quickly
        # in case of invalid values.
        root_value = super(InstructionParameter, self).check_type(
            value, attr, data)

        if is_collection(value):
            _ = [super(InstructionParameter, self).check_type(item, attr, data)
                 for item in value]

        return root_value

Customize check_type for handling containers .


def check_range(self, j):
        """Check that j is a valid index into self."""
        if isinstance(j, int):
            if j < 0 or j >= self.size:
                raise QiskitIndexError("register index out of range")
            elif isinstance(j, slice):
                if j.start < 0 or j.stop >= self.size or (j.step is not None and
                                                          j.step <= 0):
                    raise QiskitIndexError("register index slice out of range")

def
check_range
(
self
,
j
)
:
if
isinstance
(
j
,
int
)
:
if
j
<
0
or
j
>=
self
.
size
:
raise
QiskitIndexError
(
"register index out of range"
)
elif
isinstance
(
j
,
slice
)
:
if
j
.
start
<
0
or
j
.
stop
>=
self
.
size
or
(
j
.
step
is
not
and
j
.
step
<=
0
)
:
raise
QiskitIndexError
(
"register index slice out of range"
)

Check that j is a valid index into self .


def is_square_matrix(mat):
    """Test if an array is a square matrix."""
    mat = np.array(mat)
    if mat.ndim != 2:
        return False
    shape = mat.shape
    return shape[0] == shape[1]

def is_square_matrix ( mat ) : mat = np . array ( mat ) if mat . ndim != 2 : return False shape = mat . shape return shape [ 0 ] == shape [ 1 ]


def is_diagonal_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
    """Test if an array is a diagonal matrix"""
    if atol is None:
        atol = ATOL_DEFAULT
    if rtol is None:
        rtol = RTOL_DEFAULT
    mat = np.array(mat)
    if mat.ndim != 2:
        return False
    return np.allclose(mat, np.diag(np.diagonal(mat)), rtol=rtol, atol=atol)

def is_diagonal_matrix ( mat , rtol = RTOL_DEFAULT , atol = ATOL_DEFAULT ) : if atol is None : atol = ATOL_DEFAULT if rtol is None : rtol = RTOL_DEFAULT mat = np . array ( mat ) if mat . ndim != 2 : return False return np . allclose ( mat , np . diag ( np . diagonal ( mat ) ) , rtol = rtol , atol = atol )


def is_symmetric_matrix(op, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
    """Test if an array is a symmetrix matrix"""
    if atol is None:
        atol = ATOL_DEFAULT
    if rtol is None:
        rtol = RTOL_DEFAULT
    mat = np.array(op)
    if mat.ndim != 2:
        return False
    return np.allclose(mat, mat.T, rtol=rtol, atol=atol)

def is_symmetric_matrix ( op , rtol = RTOL_DEFAULT , atol = ATOL_DEFAULT ) : if atol is None : atol = ATOL_DEFAULT if rtol is None : rtol = RTOL_DEFAULT mat = np . array ( op ) if mat . ndim != 2 : return False return np . allclose ( mat , mat . T , rtol = rtol , atol = atol )


def is_hermitian_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
    """Test if an array is a Hermitian matrix"""
    if atol is None:
        atol = ATOL_DEFAULT
    if rtol is None:
        rtol = RTOL_DEFAULT
    mat = np.array(mat)
    if mat.ndim != 2:
        return False
    return np.allclose(mat, np.conj(mat.T), rtol=rtol, atol=atol)

def is_hermitian_matrix ( mat , rtol = RTOL_DEFAULT , atol = ATOL_DEFAULT ) : if atol is None : atol = ATOL_DEFAULT if rtol is None : rtol = RTOL_DEFAULT mat = np . array ( mat ) if mat . ndim != 2 : return False return np . allclose ( mat , np . conj ( mat . T ) , rtol = rtol , atol = atol )


def is_positive_semidefinite_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
    """Test if a matrix is positive semidefinite"""
    if atol is None:
        atol = ATOL_DEFAULT
    if rtol is None:
        rtol = RTOL_DEFAULT
    if not is_hermitian_matrix(mat, rtol=rtol, atol=atol):
        return False
    # Check eigenvalues are all positive
    vals = np.linalg.eigvalsh(mat)
    for v in vals:
        if v < -atol:
            return False
    return True

def
is_positive_semidefinite_matrix
(
mat
,
rtol
=
RTOL_DEFAULT
,
atol
=
ATOL_DEFAULT
)
:
if
atol
is
:
atol
=
ATOL_DEFAULT
if
rtol
is
:
rtol
=
RTOL_DEFAULT
if
not
is_hermitian_matrix
(
mat
,
rtol
=
rtol
,
atol
=
atol
)
:
return
False
# Check eigenvalues are all positive
vals
=
np
.
linalg
.
eigvalsh
(
mat
)
for
v
in
vals
:
if
v
<
atol
:
return
False
return
True


def is_identity_matrix(mat,
                       ignore_phase=False,
                       rtol=RTOL_DEFAULT,
                       atol=ATOL_DEFAULT):
    """Test if an array is an identity matrix."""
    if atol is None:
        atol = ATOL_DEFAULT
    if rtol is None:
        rtol = RTOL_DEFAULT
    mat = np.array(mat)
    if mat.ndim != 2:
        return False
    if ignore_phase:
        # If the matrix is equal to an identity up to a phase, we can
        # remove the phase by multiplying each entry by the complex
        # conjugate of the phase of the [0, 0] entry.
        theta = np.angle(mat[0, 0])
        mat = np.exp(-1j * theta) * mat
    # Check if square identity
    iden = np.eye(len(mat))
    return np.allclose(mat, iden, rtol=rtol, atol=atol)

Test if an array is an identity matrix .


def is_unitary_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
    """Test if an array is a unitary matrix."""
    if atol is None:
        atol = ATOL_DEFAULT
    if rtol is None:
        rtol = RTOL_DEFAULT
    mat = np.array(mat)
    # Compute A^dagger.A and see if it is identity matrix
    mat = np.conj(mat.T).dot(mat)
    return is_identity_matrix(mat, ignore_phase=False, rtol=rtol, atol=atol)


def _to_choi(rep, data, input_dim, output_dim):
    """Transform a QuantumChannel to the Choi representation."""
    if rep == 'Choi':
        return data
    if rep == 'Operator':
        return _from_operator('Choi', data, input_dim, output_dim)
    if rep == 'SuperOp':
        return _superop_to_choi(data, input_dim, output_dim)
    if rep == 'Kraus':
        return _kraus_to_choi(data, input_dim, output_dim)
    if rep == 'Chi':
        return _chi_to_choi(data, input_dim, output_dim)
    if rep == 'PTM':
        data = _ptm_to_superop(data, input_dim, output_dim)
        return _superop_to_choi(data, input_dim, output_dim)
    if rep == 'Stinespring':
        return _stinespring_to_choi(data, input_dim, output_dim)
    raise QiskitError('Invalid QuantumChannel {}'.format(rep))

def
_to_choi
(
rep
,
data
,
input_dim
,
output_dim
)
:
if
rep
==
'Choi'
:
return
data
if
rep
==
'Operator'
:
return
_from_operator
(
'Choi'
,
data
,
input_dim
,
output_dim
)
if
rep
==
'SuperOp'
:
return
_superop_to_choi
(
data
,
input_dim
,
output_dim
)
if
rep
==
'Kraus'
:
return
_kraus_to_choi
(
data
,
input_dim
,
output_dim
)
if
rep
==
'Chi'
:
return
_chi_to_choi
(
data
,
input_dim
,
output_dim
)
if
rep
==
'PTM'
:
data
=
_ptm_to_superop
(
data
,
input_dim
,
output_dim
)
return
_superop_to_choi
(
data
,
input_dim
,
output_dim
)
if
rep
==
'Stinespring'
:
return
_stinespring_to_choi
(
data
,
input_dim
,
output_dim
)
raise
QiskitError
(
'Invalid QuantumChannel {}'
.
format
(
rep
)
)

Transform a QuantumChannel to the Choi representation .


def _to_superop(rep, data, input_dim, output_dim):
    """Transform a QuantumChannel to the SuperOp representation."""
    if rep == 'SuperOp':
        return data
    if rep == 'Operator':
        return _from_operator('SuperOp', data, input_dim, output_dim)
    if rep == 'Choi':
        return _choi_to_superop(data, input_dim, output_dim)
    if rep == 'Kraus':
        return _kraus_to_superop(data, input_dim, output_dim)
    if rep == 'Chi':
        data = _chi_to_choi(data, input_dim, output_dim)
        return _choi_to_superop(data, input_dim, output_dim)
    if rep == 'PTM':
        return _ptm_to_superop(data, input_dim, output_dim)
    if rep == 'Stinespring':
        return _stinespring_to_superop(data, input_dim, output_dim)
    raise QiskitError('Invalid QuantumChannel {}'.format(rep))

def
_to_superop
(
rep
,
data
,
input_dim
,
output_dim
)
:
if
rep
==
'SuperOp'
:
return
data
if
rep
==
'Operator'
:
return
_from_operator
(
'SuperOp'
,
data
,
input_dim
,
output_dim
)
if
rep
==
'Choi'
:
return
_choi_to_superop
(
data
,
input_dim
,
output_dim
)
if
rep
==
'Kraus'
:
return
_kraus_to_superop
(
data
,
input_dim
,
output_dim
)
if
rep
==
'Chi'
:
data
=
_chi_to_choi
(
data
,
input_dim
,
output_dim
)
return
_choi_to_superop
(
data
,
input_dim
,
output_dim
)
if
rep
==
'PTM'
:
return
_ptm_to_superop
(
data
,
input_dim
,
output_dim
)
if
rep
==
'Stinespring'
:
return
_stinespring_to_superop
(
data
,
input_dim
,
output_dim
)
raise
QiskitError
(
'Invalid QuantumChannel {}'
.
format
(
rep
)
)

Transform a QuantumChannel to the SuperOp representation .


def _to_kraus(rep, data, input_dim, output_dim):
    """Transform a QuantumChannel to the Kraus representation."""
    if rep == 'Kraus':
        return data
    if rep == 'Stinespring':
        return _stinespring_to_kraus(data, input_dim, output_dim)
    if rep == 'Operator':
        return _from_operator('Kraus', data, input_dim, output_dim)
    # Convert via Choi and Kraus
    if rep != 'Choi':
        data = _to_choi(rep, data, input_dim, output_dim)
    return _choi_to_kraus(data, input_dim, output_dim)

def
_to_kraus
(
rep
,
data
,
input_dim
,
output_dim
)
:
if
rep
==
'Kraus'
:
return
data
if
rep
==
'Stinespring'
:
return
_stinespring_to_kraus
(
data
,
input_dim
,
output_dim
)
if
rep
==
'Operator'
:
return
_from_operator
(
'Kraus'
,
data
,
input_dim
,
output_dim
)
# Convert via Choi and Kraus
if
rep
!=
'Choi'
:
data
=
_to_choi
(
rep
,
data
,
input_dim
,
output_dim
)
return
_choi_to_kraus
(
data
,
input_dim
,
output_dim
)

Transform a QuantumChannel to the Kraus representation .


def _to_chi(rep, data, input_dim, output_dim):
    """Transform a QuantumChannel to the Chi representation."""
    if rep == 'Chi':
        return data
    # Check valid n-qubit input
    _check_nqubit_dim(input_dim, output_dim)
    if rep == 'Operator':
        return _from_operator('Chi', data, input_dim, output_dim)
    # Convert via Choi representation
    if rep != 'Choi':
        data = _to_choi(rep, data, input_dim, output_dim)
    return _choi_to_chi(data, input_dim, output_dim)

def
_to_chi
(
rep
,
data
,
input_dim
,
output_dim
)
:
if
rep
==
'Chi'
:
return
data
# Check valid n-qubit input
_check_nqubit_dim
(
input_dim
,
output_dim
)
if
rep
==
'Operator'
:
return
_from_operator
(
'Chi'
,
data
,
input_dim
,
output_dim
)
# Convert via Choi representation
if
rep
!=
'Choi'
:
data
=
_to_choi
(
rep
,
data
,
input_dim
,
output_dim
)
return
_choi_to_chi
(
data
,
input_dim
,
output_dim
)

Transform a QuantumChannel to the Chi representation .


def _to_ptm(rep, data, input_dim, output_dim):
    """Transform a QuantumChannel to the PTM representation."""
    if rep == 'PTM':
        return data
    # Check valid n-qubit input
    _check_nqubit_dim(input_dim, output_dim)
    if rep == 'Operator':
        return _from_operator('PTM', data, input_dim, output_dim)
    # Convert via Superoperator representation
    if rep != 'SuperOp':
        data = _to_superop(rep, data, input_dim, output_dim)
    return _superop_to_ptm(data, input_dim, output_dim)

Transform a QuantumChannel to the PTM representation .


def _to_stinespring(rep, data, input_dim, output_dim):
    """Transform a QuantumChannel to the Stinespring representation."""
    if rep == 'Stinespring':
        return data
    if rep == 'Operator':
        return _from_operator('Stinespring', data, input_dim, output_dim)
    # Convert via Superoperator representation
    if rep != 'Kraus':
        data = _to_kraus(rep, data, input_dim, output_dim)
    return _kraus_to_stinespring(data, input_dim, output_dim)

Transform a QuantumChannel to the Stinespring representation .


def _to_operator(rep, data, input_dim, output_dim):
    """Transform a QuantumChannel to the Operator representation."""
    if rep == 'Operator':
        return data
    if rep == 'Stinespring':
        return _stinespring_to_operator(data, input_dim, output_dim)
    # Convert via Kraus representation
    if rep != 'Kraus':
        data = _to_kraus(rep, data, input_dim, output_dim)
    return _kraus_to_operator(data, input_dim, output_dim)

def
_to_operator
(
rep
,
data
,
input_dim
,
output_dim
)
:
if
rep
==
'Operator'
:
return
data
if
rep
==
'Stinespring'
:
return
_stinespring_to_operator
(
data
,
input_dim
,
output_dim
)
# Convert via Kraus representation
if
rep
!=
'Kraus'
:
data
=
_to_kraus
(
rep
,
data
,
input_dim
,
output_dim
)
return
_kraus_to_operator
(
data
,
input_dim
,
output_dim
)

Transform a QuantumChannel to the Operator representation .


def _from_operator(rep, data, input_dim, output_dim):
    """Transform Operator representation to other representation."""
    if rep == 'Operator':
        return data
    if rep == 'SuperOp':
        return np.kron(np.conj(data), data)
    if rep == 'Choi':
        vec = np.ravel(data, order='F')
        return np.outer(vec, np.conj(vec))
    if rep == 'Kraus':
        return ([data], None)
    if rep == 'Stinespring':
        return (data, None)
    if rep == 'Chi':
        _check_nqubit_dim(input_dim, output_dim)
        data = _from_operator('Choi', data, input_dim, output_dim)
        return _choi_to_chi(data, input_dim, output_dim)
    if rep == 'PTM':
        _check_nqubit_dim(input_dim, output_dim)
        data = _from_operator('SuperOp', data, input_dim, output_dim)
        return _superop_to_ptm(data, input_dim, output_dim)
    raise QiskitError('Invalid QuantumChannel {}'.format(rep))

def
_from_operator
(
rep
,
data
,
input_dim
,
output_dim
)
:
if
rep
==
'Operator'
:
return
data
if
rep
==
'SuperOp'
:
return
np
.
kron
(
np
.
conj
(
data
)
,
data
)
if
rep
==
'Choi'
:
vec
=
np
.
ravel
(
data
,
order
=
'F'
)
return
np
.
outer
(
vec
,
np
.
conj
(
vec
)
)
if
rep
==
'Kraus'
:
return
(
[
data
]
,
)
if
rep
==
'Stinespring'
:
return
(
data
,
)
if
rep
==
'Chi'
:
_check_nqubit_dim
(
input_dim
,
output_dim
)
data
=
_from_operator
(
'Choi'
,
data
,
input_dim
,
output_dim
)
return
_choi_to_chi
(
data
,
input_dim
,
output_dim
)
if
rep
==
'PTM'
:
_check_nqubit_dim
(
input_dim
,
output_dim
)
data
=
_from_operator
(
'SuperOp'
,
data
,
input_dim
,
output_dim
)
return
_superop_to_ptm
(
data
,
input_dim
,
output_dim
)
raise
QiskitError
(
'Invalid QuantumChannel {}'
.
format
(
rep
)
)

Transform Operator representation to other representation .


def _stinespring_to_operator(data, input_dim, output_dim):
    """Transform Stinespring representation to Operator representation."""
    trace_dim = data[0].shape[0] // output_dim
    if data[1] is not None or trace_dim != 1:
        raise QiskitError(
            'Channel cannot be converted to Operator representation')
    return data[0]

Transform Stinespring representation to Operator representation .


def _superop_to_choi(data, input_dim, output_dim):
    """Transform SuperOp representation to Choi representation."""
    shape = (output_dim, output_dim, input_dim, input_dim)
    return _reshuffle(data, shape)

def _superop_to_choi ( data , input_dim , output_dim ) : shape = ( output_dim , output_dim , input_dim , input_dim ) return _reshuffle ( data , shape )

Transform SuperOp representation to Choi representation .


def _choi_to_superop(data, input_dim, output_dim):
    """Transform Choi to SuperOp representation."""
    shape = (input_dim, output_dim, input_dim, output_dim)
    return _reshuffle(data, shape)

def _choi_to_superop ( data , input_dim , output_dim ) : shape = ( input_dim , output_dim , input_dim , output_dim ) return _reshuffle ( data , shape )

Transform Choi to SuperOp representation .


def _kraus_to_choi(data, input_dim, output_dim):
    """Transform Kraus representation to Choi representation."""
    choi = 0
    kraus_l, kraus_r = data
    if kraus_r is None:
        for i in kraus_l:
            vec = i.ravel(order='F')
            choi += np.outer(vec, vec.conj())
    else:
        for i, j in zip(kraus_l, kraus_r):
            choi += np.outer(i.ravel(order='F'), j.ravel(order='F').conj())
    return choi

def _kraus_to_choi ( data , input_dim , output_dim ) : choi = 0 kraus_l , kraus_r = data if kraus_r is None : for i in kraus_l : vec = i . ravel ( order = 'F' ) choi += np . outer ( vec , vec . conj ( ) ) else : for i , j in zip ( kraus_l , kraus_r ) : choi += np . outer ( i . ravel ( order = 'F' ) , j . ravel ( order = 'F' ) . conj ( ) ) return choi

Transform Kraus representation to Choi representation .


def _choi_to_kraus(data, input_dim, output_dim, atol=ATOL_DEFAULT):
    """Transform Choi representation to Kraus representation."""
    # Check if hermitian matrix
    if is_hermitian_matrix(data, atol=atol):
        # Get eigen-decomposition of Choi-matrix
        w, v = la.eigh(data)
        # Check eigenvaleus are non-negative
        if len(w[w < -atol]) == 0:
            # CP-map Kraus representation
            kraus = []
            for val, vec in zip(w, v.T):
                if abs(val) > atol:
                    k = np.sqrt(val) * vec.reshape(
                        (output_dim, input_dim), order='F')
                    kraus.append(k)
            # If we are converting a zero matrix, we need to return a Kraus set
            # with a single zero-element Kraus matrix
            if not kraus:
                kraus.append(np.zeros((output_dim, input_dim), dtype=complex))
            return (kraus, None)
    # Non-CP-map generalized Kraus representation
    mat_u, svals, mat_vh = la.svd(data)
    kraus_l = []
    kraus_r = []
    for val, vec_l, vec_r in zip(svals, mat_u.T, mat_vh.conj()):
        kraus_l.append(
            np.sqrt(val) * vec_l.reshape((output_dim, input_dim), order='F'))
        kraus_r.append(
            np.sqrt(val) * vec_r.reshape((output_dim, input_dim), order='F'))
    return (kraus_l, kraus_r)

Transform Choi representation to Kraus representation .


def _stinespring_to_kraus(data, input_dim, output_dim):
    """Transform Stinespring representation to Kraus representation."""
    kraus_pair = []
    for stine in data:
        if stine is None:
            kraus_pair.append(None)
        else:
            trace_dim = stine.shape[0] // output_dim
            iden = np.eye(output_dim)
            kraus = []
            for j in range(trace_dim):
                vec = np.zeros(trace_dim)
                vec[j] = 1
                kraus.append(np.kron(iden, vec[None, :]).dot(stine))
            kraus_pair.append(kraus)
    return tuple(kraus_pair)

def _stinespring_to_kraus ( data , input_dim , output_dim ) : kraus_pair = [ ] for stine in data : if stine is None : kraus_pair . append ( None ) else : trace_dim = stine . shape [ 0 ] // output_dim iden = np . eye ( output_dim ) kraus = [ ] for j in range ( trace_dim ) : vec = np . zeros ( trace_dim ) vec [ j ] = 1 kraus . append ( np . kron ( iden , vec [ None , : ] ) . dot ( stine ) ) kraus_pair . append ( kraus ) return tuple ( kraus_pair )

Transform Stinespring representation to Kraus representation .


def _stinespring_to_choi(data, input_dim, output_dim):
    """Transform Stinespring representation to Choi representation."""
    trace_dim = data[0].shape[0] // output_dim
    stine_l = np.reshape(data[0], (output_dim, trace_dim, input_dim))
    if data[1] is None:
        stine_r = stine_l
    else:
        stine_r = np.reshape(data[1], (output_dim, trace_dim, input_dim))
    return np.reshape(
        np.einsum('iAj,kAl->jilk', stine_l, stine_r.conj()),
        2 * [input_dim * output_dim])

def _stinespring_to_choi ( data , input_dim , output_dim ) : trace_dim = data [ 0 ] . shape [ 0 ] // output_dim stine_l = np . reshape ( data [ 0 ] , ( output_dim , trace_dim , input_dim ) ) if data [ 1 ] is None : stine_r = stine_l else : stine_r = np . reshape ( data [ 1 ] , ( output_dim , trace_dim , input_dim ) ) return np . reshape ( np . einsum ( 'iAj,kAl->jilk' , stine_l , stine_r . conj ( ) ) , 2 * [ input_dim * output_dim ] )

Transform Stinespring representation to Choi representation .


def _kraus_to_stinespring(data, input_dim, output_dim):
    """Transform Kraus representation to Stinespring representation."""
    stine_pair = [None, None]
    for i, kraus in enumerate(data):
        if kraus is not None:
            num_kraus = len(kraus)
            stine = np.zeros((output_dim * num_kraus, input_dim),
                             dtype=complex)
            for j, mat in enumerate(kraus):
                vec = np.zeros(num_kraus)
                vec[j] = 1
                stine += np.kron(mat, vec[:, None])
            stine_pair[i] = stine
    return tuple(stine_pair)

def _kraus_to_stinespring ( data , input_dim , output_dim ) : stine_pair = [ None , None ] for i , kraus in enumerate ( data ) : if kraus is not None : num_kraus = len ( kraus ) stine = np . zeros ( ( output_dim * num_kraus , input_dim ) , dtype = complex ) for j , mat in enumerate ( kraus ) : vec = np . zeros ( num_kraus ) vec [ j ] = 1 stine += np . kron ( mat , vec [ : , None ] ) stine_pair [ i ] = stine return tuple ( stine_pair )

Transform Kraus representation to Stinespring representation .


def _kraus_to_superop(data, input_dim, output_dim):
    """Transform Kraus representation to SuperOp representation."""
    kraus_l, kraus_r = data
    superop = 0
    if kraus_r is None:
        for i in kraus_l:
            superop += np.kron(np.conj(i), i)
    else:
        for i, j in zip(kraus_l, kraus_r):
            superop += np.kron(np.conj(j), i)
    return superop

def _kraus_to_superop ( data , input_dim , output_dim ) : kraus_l , kraus_r = data superop = 0 if kraus_r is None : for i in kraus_l : superop += np . kron ( np . conj ( i ) , i ) else : for i , j in zip ( kraus_l , kraus_r ) : superop += np . kron ( np . conj ( j ) , i ) return superop

Transform Kraus representation to SuperOp representation .


def _chi_to_choi(data, input_dim, output_dim):
    """Transform Chi representation to a Choi representation."""
    num_qubits = int(np.log2(input_dim))
    return _transform_from_pauli(data, num_qubits)

def _chi_to_choi ( data , input_dim , output_dim ) : num_qubits = int ( np . log2 ( input_dim ) ) return _transform_from_pauli ( data , num_qubits )

Transform Chi representation to a Choi representation .


def _choi_to_chi(data, input_dim, output_dim):
    """Transform Choi representation to the Chi representation."""
    num_qubits = int(np.log2(input_dim))
    return _transform_to_pauli(data, num_qubits)

def _choi_to_chi ( data , input_dim , output_dim ) : num_qubits = int ( np . log2 ( input_dim ) ) return _transform_to_pauli ( data , num_qubits )

Transform Choi representation to the Chi representation .


def _reravel(mat1, mat2, shape1, shape2):
    """Reravel two bipartite matrices."""
    # Reshuffle indicies
    left_dims = shape1[:2] + shape2[:2]
    right_dims = shape1[2:] + shape2[2:]
    tensor_shape = left_dims + right_dims
    final_shape = (np.product(left_dims), np.product(right_dims))
    # Tensor product matrices
    data = np.kron(mat1, mat2)
    data = np.reshape(
        np.transpose(np.reshape(data, tensor_shape), (0, 2, 1, 3, 4, 6, 5, 7)),
        final_shape)
    return data

def
_reravel
(
mat1
,
mat2
,
shape1
,
shape2
)
:
# Reshuffle indicies
left_dims
=
shape1
[
:
2
]
+
shape2
[
:
2
]
right_dims
=
shape1
[
2
:
]
+
shape2
[
2
:
]
tensor_shape
=
left_dims
+
right_dims
final_shape
=
(
np
.
product
(
left_dims
)
,
np
.
product
(
right_dims
)
)
# Tensor product matrices
data
=
np
.
kron
(
mat1
,
mat2
)
data
=
np
.
reshape
(
np
.
transpose
(
np
.
reshape
(
data
,
tensor_shape
)
,
(
0
,
2
,
1
,
3
,
4
,
6
,
5
,
7
)
)
,
final_shape
)
return
data


def _transform_from_pauli(data, num_qubits):
    """Change of basis of bipartite matrix represenation."""
    # Change basis: sum_{i=0}^3 =|\sigma_i>><i|
    basis_mat = np.array(
        [[1, 0, 0, 1], [0, 1, 1j, 0], [0, 1, -1j, 0], [1, 0j, 0, -1]],
        dtype=complex)
    # Note that we manually renormalized after change of basis
    # to avoid rounding errors from square-roots of 2.
    cob = basis_mat
    for _ in range(num_qubits - 1):
        dim = int(np.sqrt(len(cob)))
        cob = np.reshape(
            np.transpose(
                np.reshape(
                    np.kron(basis_mat, cob), (2, 2, dim, dim, 4, dim * dim)),
                (0, 2, 1, 3, 4, 5)), (4 * dim * dim, 4 * dim * dim))
    return np.dot(np.dot(cob, data), cob.conj().T) / 2**num_qubits

Change of basis of bipartite matrix represenation .


def _check_nqubit_dim(input_dim, output_dim):
    """Return true if dims correspond to an n-qubit channel."""
    if input_dim != output_dim:
        raise QiskitError(
            'Not an n-qubit channel: input_dim' +
            ' ({}) != output_dim ({})'.format(input_dim, output_dim))
    num_qubits = int(np.log2(input_dim))
    if 2**num_qubits != input_dim:
        raise QiskitError('Not an n-qubit channel: input_dim != 2 ** n')

Return true if dims correspond to an n - qubit channel .


def _hide_tick_lines_and_labels(axis):
    """
    Set visible property of ticklines and ticklabels of an axis to False
    """
    for item in axis.get_ticklines() + axis.get_ticklabels():
        item.set_visible(False)

def _hide_tick_lines_and_labels ( axis ) : for item in axis . get_ticklines ( ) + axis . get_ticklabels ( ) : item . set_visible ( False )


def set_label_convention(self, convention):
        """Set x, y and z labels according to one of conventions.

        Args:
            convention (str):
                One of the following:
                    - "original"
                    - "xyz"
                    - "sx sy sz"
                    - "01"
                    - "polarization jones"
                    - "polarization jones letters"
                    see also: http://en.wikipedia.org/wiki/Jones_calculus
                    - "polarization stokes"
                    see also: http://en.wikipedia.org/wiki/Stokes_parameters
        Raises:
            Exception: If convention is not valid.
        """
        ketex = "$\\left.|%s\\right\\rangle$"
        # \left.| is on purpose, so that every ket has the same size

        if convention == "original":
            self.xlabel = ['$x$', '']
            self.ylabel = ['$y$', '']
            self.zlabel = ['$\\left|0\\right>$', '$\\left|1\\right>$']
        elif convention == "xyz":
            self.xlabel = ['$x$', '']
            self.ylabel = ['$y$', '']
            self.zlabel = ['$z$', '']
        elif convention == "sx sy sz":
            self.xlabel = ['$s_x$', '']
            self.ylabel = ['$s_y$', '']
            self.zlabel = ['$s_z$', '']
        elif convention == "01":
            self.xlabel = ['', '']
            self.ylabel = ['', '']
            self.zlabel = ['$\\left|0\\right>$', '$\\left|1\\right>$']
        elif convention == "polarization jones":
            self.xlabel = [ketex % "\\nearrow\\hspace{-1.46}\\swarrow",
                           ketex % "\\nwarrow\\hspace{-1.46}\\searrow"]
            self.ylabel = [ketex % "\\circlearrowleft", ketex %
                           "\\circlearrowright"]
            self.zlabel = [ketex % "\\leftrightarrow", ketex % "\\updownarrow"]
        elif convention == "polarization jones letters":
            self.xlabel = [ketex % "D", ketex % "A"]
            self.ylabel = [ketex % "L", ketex % "R"]
            self.zlabel = [ketex % "H", ketex % "V"]
        elif convention == "polarization stokes":
            self.ylabel = ["$\\nearrow\\hspace{-1.46}\\swarrow$",
                           "$\\nwarrow\\hspace{-1.46}\\searrow$"]
            self.zlabel = ["$\\circlearrowleft$", "$\\circlearrowright$"]
            self.xlabel = ["$\\leftrightarrow$", "$\\updownarrow$"]
        else:
            raise Exception("No such convention.")

Set x y and z labels according to one of conventions .


def clear(self):
        """Resets Bloch sphere data sets to empty.
        """
        self.points = []
        self.vectors = []
        self.point_style = []
        self.annotations = []

def clear ( self ) : self . points = [ ] self . vectors = [ ] self . point_style = [ ] self . annotations = [ ]

Resets Bloch sphere data sets to empty .


def add_vectors(self, vectors):
        """Add a list of vectors to Bloch sphere.

        Args:
            vectors (array_like):
                Array with vectors of unit length or smaller.
        """
        if isinstance(vectors[0], (list, np.ndarray)):
            for vec in vectors:
                self.vectors.append(vec)
        else:
            self.vectors.append(vectors)

def add_vectors ( self , vectors ) : if isinstance ( vectors [ 0 ] , ( list , np . ndarray ) ) : for vec in vectors : self . vectors . append ( vec ) else : self . vectors . append ( vectors )


def add_annotation(self, state_or_vector, text, **kwargs):
        """Add a text or LaTeX annotation to Bloch sphere,
        parametrized by a qubit state or a vector.

        Args:
            state_or_vector (array_like):
                Position for the annotation.
                Qobj of a qubit or a vector of 3 elements.
            text (str):
                Annotation text.
                You can use LaTeX, but remember to use raw string
                e.g. r"$\\langle x \\rangle$"
                or escape backslashes
                e.g. "$\\\\langle x \\\\rangle$".
            **kwargs:
                Options as for mplot3d.axes3d.text, including:
                fontsize, color, horizontalalignment, verticalalignment.
        Raises:
            Exception: If input not array_like or tuple.
        """
        if isinstance(state_or_vector, (list, np.ndarray, tuple)) \
                and len(state_or_vector) == 3:
            vec = state_or_vector
        else:
            raise Exception("Position needs to be specified by a qubit " +
                            "state or a 3D vector.")
        self.annotations.append({'position': vec,
                                 'text': text,
                                 'opts': kwargs})

Add a text or LaTeX annotation to Bloch sphere parametrized by a qubit state or a vector .


def render(self, title=''):
        """
        Render the Bloch sphere and its data sets in on given figure and axes.
        """
        if self._rendered:
            self.axes.clear()

        self._rendered = True

        # Figure instance for Bloch sphere plot
        if not self._ext_fig:
            self.fig = plt.figure(figsize=self.figsize)

        if not self._ext_axes:
            self.axes = Axes3D(self.fig, azim=self.view[0], elev=self.view[1])

        if self.background:
            self.axes.clear()
            self.axes.set_xlim3d(-1.3, 1.3)
            self.axes.set_ylim3d(-1.3, 1.3)
            self.axes.set_zlim3d(-1.3, 1.3)
        else:
            self.plot_axes()
            self.axes.set_axis_off()
            self.axes.set_xlim3d(-0.7, 0.7)
            self.axes.set_ylim3d(-0.7, 0.7)
            self.axes.set_zlim3d(-0.7, 0.7)

        self.axes.grid(False)
        self.plot_back()
        self.plot_points()
        self.plot_vectors()
        self.plot_front()
        self.plot_axes_labels()
        self.plot_annotations()
        self.axes.set_title(title, fontsize=self.font_size, y=1.08)

def
render
(
self
,
title
=
''
)
:
if
self
.
_rendered
:
self
.
axes
.
clear
(
)
self
.
_rendered
=
True
# Figure instance for Bloch sphere plot
if
not
self
.
_ext_fig
:
self
.
fig
=
plt
.
figure
(
figsize
=
self
.
figsize
)
if
not
self
.
_ext_axes
:
self
.
axes
=
Axes3D
(
self
.
fig
,
azim
=
self
.
view
[
0
]
,
elev
=
self
.
view
[
1
]
)
if
self
.
background
:
self
.
axes
.
clear
(
)
self
.
axes
.
set_xlim3d
(
1.3
,
1.3
)
self
.
axes
.
set_ylim3d
(
1.3
,
1.3
)
self
.
axes
.
set_zlim3d
(
1.3
,
1.3
)
else
:
self
.
plot_axes
(
)
self
.
axes
.
set_axis_off
(
)
self
.
axes
.
set_xlim3d
(
0.7
,
0.7
)
self
.
axes
.
set_ylim3d
(
0.7
,
0.7
)
self
.
axes
.
set_zlim3d
(
0.7
,
0.7
)
self
.
axes
.
grid
(
False
)
self
.
plot_back
(
)
self
.
plot_points
(
)
self
.
plot_vectors
(
)
self
.
plot_front
(
)
self
.
plot_axes_labels
(
)
self
.
plot_annotations
(
)
self
.
axes
.
set_title
(
title
,
fontsize
=
self
.
font_size
,
y
=
1.08
)

Render the Bloch sphere and its data sets in on given figure and axes .


def plot_front(self):
        """front half of sphere"""
        u_angle = np.linspace(-np.pi, 0, 25)
        v_angle = np.linspace(0, np.pi, 25)
        x_dir = np.outer(np.cos(u_angle), np.sin(v_angle))
        y_dir = np.outer(np.sin(u_angle), np.sin(v_angle))
        z_dir = np.outer(np.ones(u_angle.shape[0]), np.cos(v_angle))
        self.axes.plot_surface(x_dir, y_dir, z_dir, rstride=2, cstride=2,
                               color=self.sphere_color, linewidth=0,
                               alpha=self.sphere_alpha)
        # wireframe
        self.axes.plot_wireframe(x_dir, y_dir, z_dir, rstride=5, cstride=5,
                                 color=self.frame_color,
                                 alpha=self.frame_alpha)
        # equator
        self.axes.plot(1.0 * np.cos(u_angle), 1.0 * np.sin(u_angle),
                       zs=0, zdir='z', lw=self.frame_width,
                       color=self.frame_color)
        self.axes.plot(1.0 * np.cos(u_angle), 1.0 * np.sin(u_angle),
                       zs=0, zdir='x', lw=self.frame_width,
                       color=self.frame_color)

def
plot_front
(
self
)
:
u_angle
=
np
.
linspace
(
np
.
pi
,
0
,
25
)
v_angle
=
np
.
linspace
(
0
,
np
.
pi
,
25
)
x_dir
=
np
.
outer
(
np
.
cos
(
u_angle
)
,
np
.
sin
(
v_angle
)
)
y_dir
=
np
.
outer
(
np
.
sin
(
u_angle
)
,
np
.
sin
(
v_angle
)
)
z_dir
=
np
.
outer
(
np
.
ones
(
u_angle
.
shape
[
0
]
)
,
np
.
cos
(
v_angle
)
)
self
.
axes
.
plot_surface
(
x_dir
,
y_dir
,
z_dir
,
rstride
=
2
,
cstride
=
2
,
color
=
self
.
sphere_color
,
linewidth
=
0
,
alpha
=
self
.
sphere_alpha
)
# wireframe
self
.
axes
.
plot_wireframe
(
x_dir
,
y_dir
,
z_dir
,
rstride
=
5
,
cstride
=
5
,
color
=
self
.
frame_color
,
alpha
=
self
.
frame_alpha
)
# equator
self
.
axes
.
plot
(
1.0
*
np
.
cos
(
u_angle
)
,
1.0
*
np
.
sin
(
u_angle
)
,
zs
=
0
,
zdir
=
'z'
,
lw
=
self
.
frame_width
,
color
=
self
.
frame_color
)
self
.
axes
.
plot
(
1.0
*
np
.
cos
(
u_angle
)
,
1.0
*
np
.
sin
(
u_angle
)
,
zs
=
0
,
zdir
=
'x'
,
lw
=
self
.
frame_width
,
color
=
self
.
frame_color
)


def show(self, title=''):
        """
        Display Bloch sphere and corresponding data sets.
        """
        self.render(title=title)
        if self.fig:
            plt.show(self.fig)

def show ( self , title = '' ) : self . render ( title = title ) if self . fig : plt . show ( self . fig )

Display Bloch sphere and corresponding data sets .


def two_qubit_kak(unitary_matrix, verify_gate_sequence=False):
    """Deprecated after 0.8
    """
    warnings.warn("two_qubit_kak function is now accessible under "
                  "qiskit.quantum_info.synthesis", DeprecationWarning)
    return synthesis.two_qubit_kak(unitary_matrix)


def top(self):
        """ Constructs the top line of the element"""
        ret = self.top_format % self.top_connect.center(
            self.width, self.top_pad)
        if self.right_fill:
            ret = ret.ljust(self.right_fill, self.top_pad)
        if self.left_fill:
            ret = ret.rjust(self.left_fill, self.top_pad)
        ret = ret.center(self.layer_width, self.top_bck)
        return ret

def top ( self ) : ret = self . top_format % self . top_connect . center ( self . width , self . top_pad ) if self . right_fill : ret = ret . ljust ( self . right_fill , self . top_pad ) if self . left_fill : ret = ret . rjust ( self . left_fill , self . top_pad ) ret = ret . center ( self . layer_width , self . top_bck ) return ret


def mid(self):
        """ Constructs the middle line of the element"""
        ret = self.mid_format % self.mid_content.center(
            self.width, self._mid_padding)
        if self.right_fill:
            ret = ret.ljust(self.right_fill, self._mid_padding)
        if self.left_fill:
            ret = ret.rjust(self.left_fill, self._mid_padding)
        ret = ret.center(self.layer_width, self.mid_bck)
        return ret

def mid ( self ) : ret = self . mid_format % self . mid_content . center ( self . width , self . _mid_padding ) if self . right_fill : ret = ret . ljust ( self . right_fill , self . _mid_padding ) if self . left_fill : ret = ret . rjust ( self . left_fill , self . _mid_padding ) ret = ret . center ( self . layer_width , self . mid_bck ) return ret


def bot(self):
        """ Constructs the bottom line of the element"""
        ret = self.bot_format % self.bot_connect.center(
            self.width, self.bot_pad)
        if self.right_fill:
            ret = ret.ljust(self.right_fill, self.bot_pad)
        if self.left_fill:
            ret = ret.rjust(self.left_fill, self.bot_pad)
        ret = ret.center(self.layer_width, self.bot_bck)
        return ret

def bot ( self ) : ret = self . bot_format % self . bot_connect . center ( self . width , self . bot_pad ) if self . right_fill : ret = ret . ljust ( self . right_fill , self . bot_pad ) if self . left_fill : ret = ret . rjust ( self . left_fill , self . bot_pad ) ret = ret . center ( self . layer_width , self . bot_bck ) return ret


def length(self):
        """ Returns the length of the element, including the box around."""
        return max(len(self.top), len(self.mid), len(self.bot))

def length ( self ) : return max ( len ( self . top ) , len ( self . mid ) , len ( self . bot ) )

Returns the length of the element including the box around .


def params_for_label(instruction):
        """Get the params and format them to add them to a label. None if there
         are no params of if the params are numpy.ndarrays."""

        if not hasattr(instruction.op, 'params'):
            return None
        if all([isinstance(param, ndarray) for param in instruction.op.params]):
            return None

        ret = []
        for param in instruction.op.params:
            if isinstance(param, (sympy.Number, float)):
                ret.append('%.5g' % param)
            else:
                ret.append('%s' % param)
        return ret

def params_for_label ( instruction ) : if not hasattr ( instruction . op , 'params' ) : return None if all ( [ isinstance ( param , ndarray ) for param in instruction . op . params ] ) : return None ret = [ ] for param in instruction . op . params : if isinstance ( param , ( sympy . Number , float ) ) : ret . append ( '%.5g' % param ) else : ret . append ( '%s' % param ) return ret

Get the params and format them to add them to a label . None if there are no params of if the params are numpy . ndarrays .


def label_for_box(instruction):
        """ Creates the label for a box."""
        label = instruction.name.capitalize()
        params = TextDrawing.params_for_label(instruction)
        if params:
            label += "(%s)" % ','.join(params)
        return label

def label_for_box ( instruction ) : label = instruction . name . capitalize ( ) params = TextDrawing . params_for_label ( instruction ) if params : label += "(%s)" % ',' . join ( params ) return label


def latex(self, prec=15, nested_scope=None):
        """Return the correspond math mode latex string."""
        if not nested_scope:
            return "\textrm{" + self.name + "}"
        else:
            if self.name not in nested_scope[-1]:
                raise NodeException("Expected local parameter name: ",
                                    "name=%s, " % self.name,
                                    "line=%s, " % self.line,
                                    "file=%s" % self.file)
            else:
                return nested_scope[-1][self.name].latex(prec,
                                                         nested_scope[0:-1])

def
latex
(
self
,
prec
=
15
,
nested_scope
=
)
:
if
not
nested_scope
:
return
"\textrm{"
+
self
.
name
+
"}"
else
:
if
self
.
name
not
in
nested_scope
[
1
]
:
raise
NodeException
(
"Expected local parameter name: "
,
"name=%s, "
%
self
.
name
,
"line=%s, "
%
self
.
line
,
"file=%s"
%
self
.
file
)
else
:
return
nested_scope
[
1
]
[
self
.
name
]
.
latex
(
prec
,
nested_scope
[
0
:
1
]
)

Return the correspond math mode latex string .


def compile(circuits, backend,
            config=None, basis_gates=None, coupling_map=None, initial_layout=None,
            shots=1024, max_credits=10, seed=None, qobj_id=None, seed_mapper=None,
            pass_manager=None, memory=False):
    """Compile a list of circuits into a qobj.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
        backend (BaseBackend): a backend to compile for
        config (dict): dictionary of parameters (e.g. noise) used by runner
        basis_gates (list[str]): list of basis gates names supported by the
            target. Default: ['u1','u2','u3','cx','id']
        coupling_map (list): coupling map (perhaps custom) to target in mapping
        initial_layout (list): initial layout of qubits in mapping
        shots (int): number of repetitions of each circuit, for sampling
        max_credits (int): maximum credits to use
        seed (int): random seed for simulators
        seed_mapper (int): random seed for swapper mapper
        qobj_id (int): identifier for the generated qobj
        pass_manager (PassManager): a pass manger for the transpiler pipeline
        memory (bool): if True, per-shot measurement bitstrings are returned as well

    Returns:
        Qobj: the qobj to be run on the backends

    Raises:
        QiskitError: if the desired options are not supported by backend
    """
    warnings.warn('qiskit.compile() is deprecated and will be removed in Qiskit Terra 0.9. '
                  'Please use qiskit.compiler.transpile() to transform circuits '
                  'and qiskit.compiler.assemble() to produce a runnable qobj.',
                  DeprecationWarning)

    new_circuits = transpile(circuits,
                             basis_gates=basis_gates,
                             coupling_map=coupling_map,
                             initial_layout=initial_layout,
                             seed_transpiler=seed_mapper,
                             backend=backend,
                             pass_manager=pass_manager)

    qobj = assemble(new_circuits,
                    qobj_header=None,
                    shots=shots,
                    max_credits=max_credits,
                    seed_simulator=seed,
                    memory=memory,
                    qobj_id=qobj_id,
                    config=config)  # deprecated

    return qobj

Compile a list of circuits into a qobj .


def _filter_deprecation_warnings():
    """Apply filters to deprecation warnings.

    Force the `DeprecationWarning` warnings to be displayed for the qiskit
    module, overriding the system configuration as they are ignored by default
    [1] for end-users. Additionally, silence the `ChangedInMarshmallow3Warning`
    messages.

    TODO: on Python 3.7, this might not be needed due to PEP-0565 [2].

    [1] https://docs.python.org/3/library/warnings.html#default-warning-filters
    [2] https://www.python.org/dev/peps/pep-0565/
    """
    deprecation_filter = ('always', None, DeprecationWarning,
                          re.compile(r'^qiskit\.*', re.UNICODE), 0)

    # Instead of using warnings.simple_filter() directly, the internal
    # _add_filter() function is used for being able to match against the
    # module.
    try:
        warnings._add_filter(*deprecation_filter, append=False)
    except AttributeError:
        # ._add_filter is internal and not available in some Python versions.
        pass

    # Add a filter for ignoring ChangedInMarshmallow3Warning, as we depend on
    # marhsmallow 2 explicitly. 2.17.0 introduced new deprecation warnings that
    # are useful for eventually migrating, but too verbose for our purposes.
    warnings.simplefilter('ignore', category=ChangedInMarshmallow3Warning)


def local_hardware_info():
    """Basic hardware information about the local machine.

    Gives actual number of CPU's in the machine, even when hyperthreading is
    turned on. CPU count defaults to 1 when true count can't be determined.

    Returns:
        dict: The hardware information.
    """
    results = {
        'os': platform.system(),
        'memory': psutil.virtual_memory().total / (1024 ** 3),
        'cpus': psutil.cpu_count(logical=False) or 1
    }
    return results

def local_hardware_info ( ) : results = { 'os' : platform . system ( ) , 'memory' : psutil . virtual_memory ( ) . total / ( 1024 ** 3 ) , 'cpus' : psutil . cpu_count ( logical = False ) or 1 } return results

Basic hardware information about the local machine .


def _has_connection(hostname, port):
    """Checks if internet connection exists to host via specified port.

    If any exception is raised while trying to open a socket this will return
    false.

    Args:
        hostname (str): Hostname to connect to.
        port (int): Port to connect to

    Returns:
        bool: Has connection or not

    """
    try:
        host = socket.gethostbyname(hostname)
        socket.create_connection((host, port), 2)
        return True
    except Exception:  # pylint: disable=broad-except
        return False

def
_has_connection
(
hostname
,
port
)
:
try
:
host
=
socket
.
gethostbyname
(
hostname
)
socket
.
create_connection
(
(
host
,
port
)
,
2
)
return
True
except
Exception
:
# pylint: disable=broad-except
return
False

Checks if internet connection exists to host via specified port .


def _html_checker(job_var, interval, status, header,
                  _interval_set=False):
    """Internal function that updates the status
    of a HTML job monitor.

    Args:
        job_var (BaseJob): The job to keep track of.
        interval (int): The status check interval
        status (widget): HTML ipywidget for output ot screen
        header (str): String representing HTML code for status.
        _interval_set (bool): Was interval set by user?
    """
    job_status = job_var.status()
    job_status_name = job_status.name
    job_status_msg = job_status.value
    status.value = header % (job_status_msg)
    while job_status_name not in ['DONE', 'CANCELLED']:
        time.sleep(interval)
        job_status = job_var.status()
        job_status_name = job_status.name
        job_status_msg = job_status.value
        if job_status_name == 'ERROR':
            break
        else:
            if job_status_name == 'QUEUED':
                job_status_msg += ' (%s)' % job_var.queue_position()
                if not _interval_set:
                    interval = max(job_var.queue_position(), 2)
            else:
                if not _interval_set:
                    interval = 2
            status.value = header % (job_status_msg)

    status.value = header % (job_status_msg)

def
_html_checker
(
job_var
,
interval
,
status
,
header
,
_interval_set
=
False
)
:
job_status
=
job_var
.
status
(
)
job_status_name
=
job_status
.
name
job_status_msg
=
job_status
.
value
status
.
value
=
header
%
(
job_status_msg
)
while
job_status_name
not
in
[
'DONE'
,
'CANCELLED'
]
:
time
.
sleep
(
interval
)
job_status
=
job_var
.
status
(
)
job_status_name
=
job_status
.
name
job_status_msg
=
job_status
.
value
if
job_status_name
==
'ERROR'
:
break
else
:
if
job_status_name
==
'QUEUED'
:
job_status_msg
+=
' (%s)'
%
job_var
.
queue_position
(
)
if
not
_interval_set
:
interval
=
max
(
job_var
.
queue_position
(
)
,
2
)
else
:
if
not
_interval_set
:
interval
=
2
status
.
value
=
header
%
(
job_status_msg
)
status
.
value
=
header
%
(
job_status_msg
)

Internal function that updates the status of a HTML job monitor .


def constant(times: np.ndarray, amp: complex) -> np.ndarray:
    """Continuous constant pulse.

    Args:
        times: Times to output pulse for.
        amp: Complex pulse amplitude.
    """
    return np.full(len(times), amp, dtype=np.complex_)

def constant ( times : np . ndarray , amp : complex ) -> np . ndarray : return np . full ( len ( times ) , amp , dtype = np . complex_ )


def square(times: np.ndarray, amp: complex, period: float, phase: float = 0) -> np.ndarray:
    """Continuous square wave.

    Args:
        times: Times to output wave for.
        amp: Pulse amplitude. Wave range is [-amp, amp].
        period: Pulse period, units of dt.
        phase: Pulse phase.
    """
    x = times/period+phase/np.pi
    return amp*(2*(2*np.floor(x) - np.floor(2*x)) + 1).astype(np.complex_)

def square ( times : np . ndarray , amp : complex , period : float , phase : float = 0 ) -> np . ndarray : x = times / period + phase / np . pi return amp * ( 2 * ( 2 * np . floor ( x ) - np . floor ( 2 * x ) ) + 1 ) . astype ( np . complex_ )


def triangle(times: np.ndarray, amp: complex, period: float, phase: float = 0) -> np.ndarray:
    """Continuous triangle wave.

    Args:
        times: Times to output wave for.
        amp: Pulse amplitude. Wave range is [-amp, amp].
        period: Pulse period, units of dt.
        phase: Pulse phase.
    """
    return amp*(-2*np.abs(sawtooth(times, 1, period, (phase-np.pi/2)/2)) + 1).astype(np.complex_)

def triangle ( times : np . ndarray , amp : complex , period : float , phase : float = 0 ) -> np . ndarray : return amp * ( - 2 * np . abs ( sawtooth ( times , 1 , period , ( phase - np . pi / 2 ) / 2 ) ) + 1 ) . astype ( np . complex_ )


def cos(times: np.ndarray, amp: complex, freq: float, phase: float = 0) -> np.ndarray:
    """Continuous cosine wave.

    Args:
        times: Times to output wave for.
        amp: Pulse amplitude.
        freq: Pulse frequency, units of 1/dt.
        phase: Pulse phase.
    """
    return amp*np.cos(2*np.pi*freq*times+phase).astype(np.complex_)

def cos ( times : np . ndarray , amp : complex , freq : float , phase : float = 0 ) -> np . ndarray : return amp * np . cos ( 2 * np . pi * freq * times + phase ) . astype ( np . complex_ )


def _fix_gaussian_width(gaussian_samples, amp: float, center: float, sigma: float,
                        zeroed_width: Union[None, float] = None, rescale_amp: bool = False,
                        ret_scale_factor: bool = False) -> np.ndarray:
    r"""Enforce that the supplied gaussian pulse is zeroed at a specific width.

    This is acheived by subtracting $\Omega_g(center \pm zeroed_width/2)$ from all samples.

    amp: Pulse amplitude at `2\times center+1`.
    center: Center (mean) of pulse.
    sigma: Width (standard deviation) of pulse.
    zeroed_width: Subtract baseline to gaussian pulses to make sure
             $\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
             large discontinuities at the start of a gaussian pulse. If unsupplied,
             defaults to $2*(center+1)$ such that the samples are zero at $\Omega_g(-1)$.
    rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
                 be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.
    ret_scale_factor: Return amplitude scale factor.
    """
    if zeroed_width is None:
        zeroed_width = 2*(center+1)

    zero_offset = gaussian(np.array([-zeroed_width/2]), amp, center, sigma)
    gaussian_samples -= zero_offset
    amp_scale_factor = 1.
    if rescale_amp:
        amp_scale_factor = amp/(amp-zero_offset)
        gaussian_samples *= amp_scale_factor

    if ret_scale_factor:
        return gaussian_samples, amp_scale_factor
    return gaussian_samples

def _fix_gaussian_width ( gaussian_samples , amp : float , center : float , sigma : float , zeroed_width : Union [ None , float ] = None , rescale_amp : bool = False , ret_scale_factor : bool = False ) -> np . ndarray : if zeroed_width is None : zeroed_width = 2 * ( center + 1 ) zero_offset = gaussian ( np . array ( [ - zeroed_width / 2 ] ) , amp , center , sigma ) gaussian_samples -= zero_offset amp_scale_factor = 1. if rescale_amp : amp_scale_factor = amp / ( amp - zero_offset ) gaussian_samples *= amp_scale_factor if ret_scale_factor : return gaussian_samples , amp_scale_factor return gaussian_samples

r Enforce that the supplied gaussian pulse is zeroed at a specific width .


def gaussian(times: np.ndarray, amp: complex, center: float, sigma: float,
             zeroed_width: Union[None, float] = None, rescale_amp: bool = False,
             ret_x: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
    r"""Continuous unnormalized gaussian pulse.

    Integrated area under curve is $\Omega_g(amp, sigma) = amp \times np.sqrt(2\pi \sigma^2)$

    Args:
        times: Times to output pulse for.
        amp: Pulse amplitude at `center`. If `zeroed_width` is set pulse amplitude at center
            will be $amp-\Omega_g(center\pm zeroed_width/2)$ unless `rescale_amp` is set,
            in which case all samples will be rescaled such that the center
            amplitude will be `amp`.
        center: Center (mean) of pulse.
        sigma: Width (standard deviation) of pulse.
        zeroed_width: Subtract baseline to gaussian pulses to make sure
                 $\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
                 large discontinuities at the start of a gaussian pulse.
        rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
                     be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.
        ret_x: Return centered and standard deviation normalized pulse location.
               $x=(times-center)/sigma.
    """
    times = np.asarray(times, dtype=np.complex_)
    x = (times-center)/sigma
    gauss = amp*np.exp(-x**2/2).astype(np.complex_)

    if zeroed_width is not None:
        gauss = _fix_gaussian_width(gauss, amp=amp, center=center, sigma=sigma,
                                    zeroed_width=zeroed_width, rescale_amp=rescale_amp)

    if ret_x:
        return gauss, x
    return gauss

def gaussian ( times : np . ndarray , amp : complex , center : float , sigma : float , zeroed_width : Union [ None , float ] = None , rescale_amp : bool = False , ret_x : bool = False ) -> Union [ np . ndarray , Tuple [ np . ndarray , np . ndarray ] ] : times = np . asarray ( times , dtype = np . complex_ ) x = ( times - center ) / sigma gauss = amp * np . exp ( - x ** 2 / 2 ) . astype ( np . complex_ ) if zeroed_width is not None : gauss = _fix_gaussian_width ( gauss , amp = amp , center = center , sigma = sigma , zeroed_width = zeroed_width , rescale_amp = rescale_amp ) if ret_x : return gauss , x return gauss

r Continuous unnormalized gaussian pulse .


def gaussian_deriv(times: np.ndarray, amp: complex, center: float, sigma: float,
                   ret_gaussian: bool = False) -> np.ndarray:
    """Continuous unnormalized gaussian derivative pulse.

    Args:
        times: Times to output pulse for.
        amp: Pulse amplitude at `center`.
        center: Center (mean) of pulse.
        sigma: Width (standard deviation) of pulse.
        ret_gaussian: Return gaussian with which derivative was taken with.
    """
    gauss, x = gaussian(times, amp=amp, center=center, sigma=sigma, ret_x=True)
    gauss_deriv = -x/sigma*gauss
    if ret_gaussian:
        return gauss_deriv, gauss
    return gauss_deriv

def gaussian_deriv ( times : np . ndarray , amp : complex , center : float , sigma : float , ret_gaussian : bool = False ) -> np . ndarray : gauss , x = gaussian ( times , amp = amp , center = center , sigma = sigma , ret_x = True ) gauss_deriv = - x / sigma * gauss if ret_gaussian : return gauss_deriv , gauss return gauss_deriv

Continuous unnormalized gaussian derivative pulse .


def gaussian_square(times: np.ndarray, amp: complex, center: float, width: float,
                    sigma: float, zeroed_width: Union[None, float] = None) -> np.ndarray:
    r"""Continuous gaussian square pulse.

    Args:
        times: Times to output pulse for.
        amp: Pulse amplitude.
        center: Center of the square pulse component.
        width: Width of the square pulse component.
        sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse.
        zeroed_width: Subtract baseline of gaussian square pulse
                      to enforce $\OmegaSquare(center \pm zeroed_width/2)=0$.
    """
    square_start = center-width/2
    square_stop = center+width/2
    if zeroed_width:
        zeroed_width = min(width, zeroed_width)
        gauss_zeroed_width = zeroed_width-width
    else:
        gauss_zeroed_width = None

    funclist = [functools.partial(gaussian, amp=amp, center=square_start, sigma=sigma,
                                  zeroed_width=gauss_zeroed_width, rescale_amp=True),
                functools.partial(gaussian, amp=amp, center=square_stop, sigma=sigma,
                                  zeroed_width=gauss_zeroed_width, rescale_amp=True),
                functools.partial(constant, amp=amp)]
    condlist = [times <= square_start, times >= square_stop]
    return np.piecewise(times.astype(np.complex_), condlist, funclist)

def gaussian_square ( times : np . ndarray , amp : complex , center : float , width : float , sigma : float , zeroed_width : Union [ None , float ] = None ) -> np . ndarray : square_start = center - width / 2 square_stop = center + width / 2 if zeroed_width : zeroed_width = min ( width , zeroed_width ) gauss_zeroed_width = zeroed_width - width else : gauss_zeroed_width = None funclist = [ functools . partial ( gaussian , amp = amp , center = square_start , sigma = sigma , zeroed_width = gauss_zeroed_width , rescale_amp = True ) , functools . partial ( gaussian , amp = amp , center = square_stop , sigma = sigma , zeroed_width = gauss_zeroed_width , rescale_amp = True ) , functools . partial ( constant , amp = amp ) ] condlist = [ times <= square_start , times >= square_stop ] return np . piecewise ( times . astype ( np . complex_ ) , condlist , funclist )


def default_pass_manager(basis_gates, coupling_map, initial_layout, seed_transpiler):
    """
    The default pass manager that maps to the coupling map.

    Args:
        basis_gates (list[str]): list of basis gate names supported by the target.
        coupling_map (CouplingMap): coupling map to target in mapping.
        initial_layout (Layout or None): initial layout of virtual qubits on physical qubits
        seed_transpiler (int or None): random seed for stochastic passes.

    Returns:
        PassManager: A pass manager to map and optimize.
    """
    pass_manager = PassManager()
    pass_manager.property_set['layout'] = initial_layout

    pass_manager.append(Unroller(basis_gates))

    # Use the trivial layout if no layout is found
    pass_manager.append(TrivialLayout(coupling_map),
                        condition=lambda property_set: not property_set['layout'])

    # if the circuit and layout already satisfy the coupling_constraints, use that layout
    # otherwise layout on the most densely connected physical qubit subset
    pass_manager.append(CheckMap(coupling_map))
    pass_manager.append(DenseLayout(coupling_map),
                        condition=lambda property_set: not property_set['is_swap_mapped'])

    # Extend the the dag/layout with ancillas using the full coupling map
    pass_manager.append(FullAncillaAllocation(coupling_map))
    pass_manager.append(EnlargeWithAncilla())

    # Circuit must only contain 1- or 2-qubit interactions for swapper to work
    pass_manager.append(Unroll3qOrMore())

    # Swap mapper
    pass_manager.append(LegacySwap(coupling_map, trials=20, seed=seed_transpiler))

    # Expand swaps
    pass_manager.append(Decompose(SwapGate))

    # Change CX directions
    pass_manager.append(CXDirection(coupling_map))

    # Unroll to the basis
    pass_manager.append(Unroller(['u1', 'u2', 'u3', 'id', 'cx']))

    # Simplify single qubit gates and CXs
    simplification_passes = [Optimize1qGates(), CXCancellation(), RemoveResetInZeroState()]

    pass_manager.append(simplification_passes + [Depth(), FixedPoint('depth')],
                        do_while=lambda property_set: not property_set['depth_fixed_point'])

    return pass_manager

The default pass manager that maps to the coupling map .


def default_pass_manager_simulator(basis_gates):
    """
    The default pass manager without a coupling map.

    Args:
        basis_gates (list[str]): list of basis gate names to unroll to.

    Returns:
        PassManager: A passmanager that just unrolls, without any optimization.
    """
    pass_manager = PassManager()

    pass_manager.append(Unroller(basis_gates))

    pass_manager.append([RemoveResetInZeroState(), Depth(), FixedPoint('depth')],
                        do_while=lambda property_set: not property_set['depth_fixed_point'])

    return pass_manager

def default_pass_manager_simulator ( basis_gates ) : pass_manager = PassManager ( ) pass_manager . append ( Unroller ( basis_gates ) ) pass_manager . append ( [ RemoveResetInZeroState ( ) , Depth ( ) , FixedPoint ( 'depth' ) ] , do_while = lambda property_set : not property_set [ 'depth_fixed_point' ] ) return pass_manager

The default pass manager without a coupling map .


def has_register(self, register):
        """
        Test if this circuit has the register r.

        Args:
            register (Register): a quantum or classical register.

        Returns:
            bool: True if the register is contained in this circuit.
        """
        has_reg = False
        if (isinstance(register, QuantumRegister) and
                register in self.qregs):
            has_reg = True
        elif (isinstance(register, ClassicalRegister) and
              register in self.cregs):
            has_reg = True
        return has_reg

def has_register ( self , register ) : has_reg = False if ( isinstance ( register , QuantumRegister ) and register in self . qregs ) : has_reg = True elif ( isinstance ( register , ClassicalRegister ) and register in self . cregs ) : has_reg = True return has_reg

Test if this circuit has the register r .


def mirror(self):
        """Mirror the circuit by reversing the instructions.

        This is done by recursively mirroring all instructions.
        It does not invert any gate.

        Returns:
            QuantumCircuit: the mirrored circuit
        """
        reverse_circ = self.copy(name=self.name+'_mirror')
        reverse_circ.data = []
        for inst, qargs, cargs in reversed(self.data):
            reverse_circ.data.append((inst.mirror(), qargs, cargs))
        return reverse_circ

def mirror ( self ) : reverse_circ = self . copy ( name = self . name + '_mirror' ) reverse_circ . data = [ ] for inst , qargs , cargs in reversed ( self . data ) : reverse_circ . data . append ( ( inst . mirror ( ) , qargs , cargs ) ) return reverse_circ

Mirror the circuit by reversing the instructions .


def inverse(self):
        """Invert this circuit.

        This is done by recursively inverting all gates.

        Returns:
            QuantumCircuit: the inverted circuit

        Raises:
            QiskitError: if the circuit cannot be inverted.
        """
        inverse_circ = self.copy(name=self.name+'_dg')
        inverse_circ.data = []
        for inst, qargs, cargs in reversed(self.data):
            inverse_circ.data.append((inst.inverse(), qargs, cargs))
        return inverse_circ

def inverse ( self ) : inverse_circ = self . copy ( name = self . name + '_dg' ) inverse_circ . data = [ ] for inst , qargs , cargs in reversed ( self . data ) : inverse_circ . data . append ( ( inst . inverse ( ) , qargs , cargs ) ) return inverse_circ


def append(self, instruction, qargs=None, cargs=None):
        """Append an instruction to the end of the circuit, modifying
        the circuit in place.

        Args:
            instruction (Instruction or Operator): Instruction instance to append
            qargs (list(tuple)): qubits to attach instruction to
            cargs (list(tuple)): clbits to attach instruction to

        Returns:
            Instruction: a handle to the instruction that was just added

        Raises:
            QiskitError: if the gate is of a different shape than the wires
                it is being attached to.
        """
        qargs = qargs or []
        cargs = cargs or []

        # Convert input to instruction
        if not isinstance(instruction, Instruction) and hasattr(instruction, 'to_instruction'):
            instruction = instruction.to_instruction()
        if not isinstance(instruction, Instruction):
            raise QiskitError('object is not an Instruction.')

        # do some compatibility checks
        self._check_dups(qargs)
        self._check_qargs(qargs)
        self._check_cargs(cargs)
        if instruction.num_qubits != len(qargs) or \
                instruction.num_clbits != len(cargs):
            raise QiskitError("instruction %s with %d qubits and %d clbits "
                              "cannot be appended onto %d qubits and %d clbits." %
                              (instruction.name,
                               instruction.num_qubits, instruction.num_clbits,
                               len(qargs), len(cargs)))

        # add the instruction onto the given wires
        instruction_context = instruction, qargs, cargs
        self.data.append(instruction_context)

        # track variable parameters in instruction
        for param_index, param in enumerate(instruction.params):
            if isinstance(param, Parameter):
                current_symbols = self.parameters

                if param in current_symbols:
                    self._parameter_table[param].append((instruction, param_index))
                else:
                    self._parameter_table[param] = [(instruction, param_index)]

        return instruction

Append an instruction to the end of the circuit modifying the circuit in place .


def _attach(self, instruction, qargs, cargs):
        """DEPRECATED after 0.8"""
        self.append(instruction, qargs, cargs)

def _attach ( self , instruction , qargs , cargs ) : self . append ( instruction , qargs , cargs )


def add_register(self, *regs):
        """Add registers."""
        if not regs:
            return

        if any([isinstance(reg, int) for reg in regs]):
            # QuantumCircuit defined without registers
            if len(regs) == 1 and isinstance(regs[0], int):
                # QuantumCircuit with anonymous quantum wires e.g. QuantumCircuit(2)
                regs = (QuantumRegister(regs[0], 'q'),)
            elif len(regs) == 2 and all([isinstance(reg, int) for reg in regs]):
                # QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3)
                regs = (QuantumRegister(regs[0], 'q'), ClassicalRegister(regs[1], 'c'))
            else:
                raise QiskitError("QuantumCircuit parameters can be Registers or Integers."
                                  " If Integers, up to 2 arguments. QuantumCircuit was called"
                                  " with %s." % (regs,))

        for register in regs:
            if register in self.qregs or register in self.cregs:
                raise QiskitError("register name \"%s\" already exists"
                                  % register.name)
            if isinstance(register, QuantumRegister):
                self.qregs.append(register)
            elif isinstance(register, ClassicalRegister):
                self.cregs.append(register)
            else:
                raise QiskitError("expected a register")


def _check_dups(self, qubits):
        """Raise exception if list of qubits contains duplicates."""
        squbits = set(qubits)
        if len(squbits) != len(qubits):
            raise QiskitError("duplicate qubit arguments")

def
_check_dups
(
self
,
qubits
)
:
squbits
=
set
(
qubits
)
if
len
(
squbits
)
!=
len
(
qubits
)
:
raise
QiskitError
(
"duplicate qubit arguments"
)

Raise exception if list of qubits contains duplicates .


def _check_qargs(self, qargs):
        """Raise exception if a qarg is not in this circuit or bad format."""
        if not all(isinstance(i, tuple) and
                   isinstance(i[0], QuantumRegister) and
                   isinstance(i[1], int) for i in qargs):
            raise QiskitError("qarg not (QuantumRegister, int) tuple")
        if not all(self.has_register(i[0]) for i in qargs):
            raise QiskitError("register not in this circuit")
        for qubit in qargs:
            qubit[0].check_range(qubit[1])

def
_check_qargs
(
self
,
qargs
)
:
if
not
all
(
isinstance
(
i
,
tuple
)
and
isinstance
(
i
[
0
]
,
QuantumRegister
)
and
isinstance
(
i
[
1
]
,
int
)
for
i
in
qargs
)
:
raise
QiskitError
(
"qarg not (QuantumRegister, int) tuple"
)
if
not
all
(
self
.
has_register
(
i
[
0
]
)
for
i
in
qargs
)
:
raise
QiskitError
(
"register not in this circuit"
)
for
qubit
in
qargs
:
qubit
[
0
]
.
check_range
(
qubit
[
1
]
)

Raise exception if a qarg is not in this circuit or bad format .


def _check_cargs(self, cargs):
        """Raise exception if clbit is not in this circuit or bad format."""
        if not all(isinstance(i, tuple) and
                   isinstance(i[0], ClassicalRegister) and
                   isinstance(i[1], int) for i in cargs):
            raise QiskitError("carg not (ClassicalRegister, int) tuple")
        if not all(self.has_register(i[0]) for i in cargs):
            raise QiskitError("register not in this circuit")
        for clbit in cargs:
            clbit[0].check_range(clbit[1])

Raise exception if clbit is not in this circuit or bad format .