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 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 ) self . axes . plot_wireframe ( x_dir , y_dir , z_dir , rstride = 5 , cstride = 5 , color = self . frame_color , alpha = self . frame_alpha ) 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 _filter_deprecation_warnings ( ) : deprecation_filter = ( 'always' , None , DeprecationWarning , re . compile ( r'^qiskit\.*' , re . UNICODE ) , 0 ) try : warnings . _add_filter ( * deprecation_filter , append = False ) except AttributeError : pass 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 : 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 : r 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 ] ] : r 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 : r 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

def default_pass_manager ( basis_gates , coupling_map , initial_layout , seed_transpiler ) : pass_manager = PassManager ( ) pass_manager . property_set [ 'layout' ] = initial_layout pass_manager . append ( Unroller ( basis_gates ) ) pass_manager . append ( TrivialLayout ( coupling_map ) , condition = lambda property_set : not property_set [ 'layout' ] ) pass_manager . append ( CheckMap ( coupling_map ) ) pass_manager . append ( DenseLayout ( coupling_map ) , condition = lambda property_set : not property_set [ 'is_swap_mapped' ] ) pass_manager . append ( FullAncillaAllocation ( coupling_map ) ) pass_manager . append ( EnlargeWithAncilla ( ) ) pass_manager . append ( Unroll3qOrMore ( ) ) pass_manager . append ( LegacySwap ( coupling_map , trials = 20 , seed = seed_transpiler ) ) pass_manager . append ( Decompose ( SwapGate ) ) pass_manager . append ( CXDirection ( coupling_map ) ) pass_manager . append ( Unroller ( [ 'u1' , 'u2' , 'u3' , 'id' , 'cx' ] ) ) 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 .


def _check_compatible_regs(self, rhs):
        """Raise exception if the circuits are defined on incompatible registers"""
        list1 = self.qregs + self.cregs
        list2 = rhs.qregs + rhs.cregs
        for element1 in list1:
            for element2 in list2:
                if element2.name == element1.name:
                    if element1 != element2:
                        raise QiskitError("circuits are not compatible")

def
_check_compatible_regs
(
self
,
rhs
)
:
list1
=
self
.
qregs
+
self
.
cregs
list2
=
rhs
.
qregs
+
rhs
.
cregs
for
element1
in
list1
:
for
element2
in
list2
:
if
element2
.
name
==
element1
.
name
:
if
element1
!=
element2
:
raise
QiskitError
(
"circuits are not compatible"
)


def qasm(self):
        """Return OpenQASM string."""
        string_temp = self.header + "\n"
        string_temp += self.extension_lib + "\n"
        for register in self.qregs:
            string_temp += register.qasm() + "\n"
        for register in self.cregs:
            string_temp += register.qasm() + "\n"
        for instruction, qargs, cargs in self.data:
            if instruction.name == 'measure':
                qubit = qargs[0]
                clbit = cargs[0]
                string_temp += "%s %s[%d] -> %s[%d];\n" % (instruction.qasm(),
                                                           qubit[0].name, qubit[1],
                                                           clbit[0].name, clbit[1])
            else:
                string_temp += "%s %s;\n" % (instruction.qasm(),
                                             ",".join(["%s[%d]" % (j[0].name, j[1])
                                                       for j in qargs + cargs]))
        return string_temp

def
qasm
(
self
)
:
string_temp
=
self
.
header
+
"\n"
string_temp
+=
self
.
extension_lib
+
"\n"
for
register
in
self
.
qregs
:
string_temp
+=
register
.
qasm
(
)
+
"\n"
for
register
in
self
.
cregs
:
string_temp
+=
register
.
qasm
(
)
+
"\n"
for
instruction
,
qargs
,
cargs
in
self
.
data
:
if
instruction
.
name
==
'measure'
:
qubit
=
qargs
[
0
]
clbit
=
cargs
[
0
]
string_temp
+=
"%s %s[%d] -> %s[%d];\n"
%
(
instruction
.
qasm
(
)
,
qubit
[
0
]
.
name
,
qubit
[
1
]
,
clbit
[
0
]
.
name
,
clbit
[
1
]
)
else
:
string_temp
+=
"%s %s;\n"
%
(
instruction
.
qasm
(
)
,
","
.
join
(
[
"%s[%d]"
%
(
j
[
0
]
.
name
,
j
[
1
]
)
for
j
in
qargs
+
cargs
]
)
)
return
string_temp


def draw(self, scale=0.7, filename=None, style=None, output='text',
             interactive=False, line_length=None, plot_barriers=True,
             reverse_bits=False, justify=None):
        """Draw the quantum circuit

        Using the output parameter you can specify the format. The choices are:
        0. text: ASCII art string
        1. latex: high-quality images, but heavy external software dependencies
        2. matplotlib: purely in Python with no external dependencies

        Defaults to an overcomplete basis, in order to not alter gates.

        Args:
            scale (float): scale of image to draw (shrink if < 1)
            filename (str): file path to save image to
            style (dict or str): dictionary of style or file name of style
                file. You can refer to the
                :ref:`Style Dict Doc <style-dict-doc>` for more information
                on the contents.
            output (str): Select the output method to use for drawing the
                circuit. Valid choices are `text`, `latex`, `latex_source`,
                `mpl`.
            interactive (bool): when set true show the circuit in a new window
                (for `mpl` this depends on the matplotlib backend being used
                supporting this). Note when used with either the `text` or the
                `latex_source` output type this has no effect and will be
                silently ignored.
            line_length (int): sets the length of the lines generated by `text`
            reverse_bits (bool): When set to True reverse the bit order inside
                registers for the output visualization.
            plot_barriers (bool): Enable/disable drawing barriers in the output
                circuit. Defaults to True.
            justify (string): Options are `left`, `right` or `none`, if anything
                else is supplied it defaults to left justified. It refers to where
                gates should be placed in the output circuit if there is an option.
                `none` results in each gate being placed in its own column. Currently
                only supported by text drawer.

        Returns:
            PIL.Image or matplotlib.figure or str or TextDrawing:
                * PIL.Image: (output `latex`) an in-memory representation of the
                  image of the circuit diagram.
                * matplotlib.figure: (output `mpl`) a matplotlib figure object
                  for the circuit diagram.
                * str: (output `latex_source`). The LaTeX source code.
                * TextDrawing: (output `text`). A drawing that can be printed as
                  ascii art

        Raises:
            VisualizationError: when an invalid output method is selected
        """
        from qiskit.tools import visualization
        return visualization.circuit_drawer(self, scale=scale,
                                            filename=filename, style=style,
                                            output=output,
                                            interactive=interactive,
                                            line_length=line_length,
                                            plot_barriers=plot_barriers,
                                            reverse_bits=reverse_bits,
                                            justify=justify)

def draw ( self , scale = 0.7 , filename = None , style = None , output = 'text' , interactive = False , line_length = None , plot_barriers = True , reverse_bits = False , justify = None ) : from qiskit . tools import visualization return visualization . circuit_drawer ( self , scale = scale , filename = filename , style = style , output = output , interactive = interactive , line_length = line_length , plot_barriers = plot_barriers , reverse_bits = reverse_bits , justify = justify )


def size(self):
        """Returns total number of gate operations in circuit.

        Returns:
            int: Total number of gate operations.
        """
        gate_ops = 0
        for instr, _, _ in self.data:
            if instr.name not in ['barrier', 'snapshot']:
                gate_ops += 1
        return gate_ops

def size ( self ) : gate_ops = 0 for instr , _ , _ in self . data : if instr . name not in [ 'barrier' , 'snapshot' ] : gate_ops += 1 return gate_ops

Returns total number of gate operations in circuit .


def width(self):
        """Return number of qubits plus clbits in circuit.

        Returns:
            int: Width of circuit.

        """
        return sum(reg.size for reg in self.qregs+self.cregs)

def width ( self ) : return sum ( reg . size for reg in self . qregs + self . cregs )

Return number of qubits plus clbits in circuit .


def count_ops(self):
        """Count each operation kind in the circuit.

        Returns:
            dict: a breakdown of how many operations of each kind.
        """
        count_ops = {}
        for instr, _, _ in self.data:
            if instr.name in count_ops.keys():
                count_ops[instr.name] += 1
            else:
                count_ops[instr.name] = 1
        return count_ops

def count_ops ( self ) : count_ops = { } for instr , _ , _ in self . data : if instr . name in count_ops . keys ( ) : count_ops [ instr . name ] += 1 else : count_ops [ instr . name ] = 1 return count_ops

Count each operation kind in the circuit .


def num_connected_components(self, unitary_only=False):
        """How many non-entangled subcircuits can the circuit be factored to.

        Args:
            unitary_only (bool): Compute only unitary part of graph.

        Returns:
            int: Number of connected components in circuit.
        """
        # Convert registers to ints (as done in depth).
        reg_offset = 0
        reg_map = {}

        if unitary_only:
            regs = self.qregs
        else:
            regs = self.qregs+self.cregs

        for reg in regs:
            reg_map[reg.name] = reg_offset
            reg_offset += reg.size
        # Start with each qubit or cbit being its own subgraph.
        sub_graphs = [[bit] for bit in range(reg_offset)]

        num_sub_graphs = len(sub_graphs)

        # Here we are traversing the gates and looking to see
        # which of the sub_graphs the gate joins together.
        for instr, qargs, cargs in self.data:
            if unitary_only:
                args = qargs
                num_qargs = len(args)
            else:
                args = qargs+cargs
                num_qargs = len(args) + (1 if instr.control else 0)

            if num_qargs >= 2 and instr.name not in ['barrier', 'snapshot']:
                graphs_touched = []
                num_touched = 0
                # Controls necessarily join all the cbits in the
                # register that they use.
                if instr.control and not unitary_only:
                    creg = instr.control[0]
                    creg_int = reg_map[creg.name]
                    for coff in range(creg.size):
                        temp_int = creg_int+coff
                        for k in range(num_sub_graphs):
                            if temp_int in sub_graphs[k]:
                                graphs_touched.append(k)
                                num_touched += 1
                                break

                for item in args:
                    reg_int = reg_map[item[0].name]+item[1]
                    for k in range(num_sub_graphs):
                        if reg_int in sub_graphs[k]:
                            if k not in graphs_touched:
                                graphs_touched.append(k)
                                num_touched += 1
                                break

                # If the gate touches more than one subgraph
                # join those graphs together and return
                # reduced number of subgraphs
                if num_touched > 1:
                    connections = []
                    for idx in graphs_touched:
                        connections.extend(sub_graphs[idx])
                    _sub_graphs = []
                    for idx in range(num_sub_graphs):
                        if idx not in graphs_touched:
                            _sub_graphs.append(sub_graphs[idx])
                    _sub_graphs.append(connections)
                    sub_graphs = _sub_graphs
                    num_sub_graphs -= (num_touched-1)
            # Cannot go lower than one so break
            if num_sub_graphs == 1:
                break
        return num_sub_graphs

def num_connected_components ( self , unitary_only = False ) : reg_offset = 0 reg_map = { } if unitary_only : regs = self . qregs else : regs = self . qregs + self . cregs for reg in regs : reg_map [ reg . name ] = reg_offset reg_offset += reg . size sub_graphs = [ [ bit ] for bit in range ( reg_offset ) ] num_sub_graphs = len ( sub_graphs ) for instr , qargs , cargs in self . data : if unitary_only : args = qargs num_qargs = len ( args ) else : args = qargs + cargs num_qargs = len ( args ) + ( 1 if instr . control else 0 ) if num_qargs >= 2 and instr . name not in [ 'barrier' , 'snapshot' ] : graphs_touched = [ ] num_touched = 0 if instr . control and not unitary_only : creg = instr . control [ 0 ] creg_int = reg_map [ creg . name ] for coff in range ( creg . size ) : temp_int = creg_int + coff for k in range ( num_sub_graphs ) : if temp_int in sub_graphs [ k ] : graphs_touched . append ( k ) num_touched += 1 break for item in args : reg_int = reg_map [ item [ 0 ] . name ] + item [ 1 ] for k in range ( num_sub_graphs ) : if reg_int in sub_graphs [ k ] : if k not in graphs_touched : graphs_touched . append ( k ) num_touched += 1 break if num_touched > 1 : connections = [ ] for idx in graphs_touched : connections . extend ( sub_graphs [ idx ] ) _sub_graphs = [ ] for idx in range ( num_sub_graphs ) : if idx not in graphs_touched : _sub_graphs . append ( sub_graphs [ idx ] ) _sub_graphs . append ( connections ) sub_graphs = _sub_graphs num_sub_graphs -= ( num_touched - 1 ) if num_sub_graphs == 1 : break return num_sub_graphs

How many non - entangled subcircuits can the circuit be factored to .


def bind_parameters(self, value_dict):
        """Assign parameters to values yielding a new circuit.

        Args:
            value_dict (dict): {parameter: value, ...}

        Raises:
            QiskitError: If value_dict contains parameters not present in the circuit

        Returns:
            QuantumCircuit: copy of self with assignment substitution.
        """
        new_circuit = self.copy()

        if value_dict.keys() > self.parameters:
            raise QiskitError('Cannot bind parameters ({}) not present in the circuit.'.format(
                [str(p) for p in value_dict.keys() - self.parameters]))

        for parameter, value in value_dict.items():
            new_circuit._bind_parameter(parameter, value)
        # clear evaluated expressions
        for parameter in value_dict:
            del new_circuit._parameter_table[parameter]
        return new_circuit

Assign parameters to values yielding a new circuit .


def _bind_parameter(self, parameter, value):
        """Assigns a parameter value to matching instructions in-place."""
        for (instr, param_index) in self._parameter_table[parameter]:
            instr.params[param_index] = value

def _bind_parameter ( self , parameter , value ) : for ( instr , param_index ) in self . _parameter_table [ parameter ] : instr . params [ param_index ] = value

Assigns a parameter value to matching instructions in - place .


def pulse_drawer(samples, duration, dt=None, interp_method='None',
                 filename=None, interactive=False,
                 dpi=150, nop=1000, size=(6, 5)):
    """Plot the interpolated envelope of pulse

    Args:
        samples (ndarray): Data points of complex pulse envelope.
        duration (int): Pulse length (number of points).
        dt (float): Time interval of samples.
        interp_method (str): Method of interpolation
            (set `None` for turn off the interpolation).
        filename (str): Name required to save pulse image.
        interactive (bool): When set true show the circuit in a new window
            (this depends on the matplotlib backend being used supporting this).
        dpi (int): Resolution of saved image.
        nop (int): Data points for interpolation.
        size (tuple): Size of figure.
    Returns:
        matplotlib.figure: A matplotlib figure object for the pulse envelope.
    Raises:
        ImportError: when the output methods requieres non-installed libraries.
        QiskitError: when invalid interpolation method is specified.
    """

    try:
        from matplotlib import pyplot as plt
    except ImportError:
        raise ImportError('pulse_drawer need matplotlib. '
                          'Run "pip install matplotlib" before.')

    if dt:
        _dt = dt
    else:
        _dt = 1

    re_y = np.real(samples)
    im_y = np.imag(samples)

    image = plt.figure(figsize=size)
    ax0 = image.add_subplot(111)

    if interp_method == 'CubicSpline':
        # spline interpolation, use mid-point of dt
        time = np.arange(0, duration + 1) * _dt + 0.5 * _dt
        cs_ry = CubicSpline(time[:-1], re_y)
        cs_iy = CubicSpline(time[:-1], im_y)

        _time = np.linspace(0, duration * _dt, nop)
        _re_y = cs_ry(_time)
        _im_y = cs_iy(_time)
    elif interp_method == 'None':
        # pseudo-DAC output
        time = np.arange(0, duration + 1) * _dt

        _time = np.r_[time[0], np.repeat(time[1:-1], 2), time[-1]]
        _re_y = np.repeat(re_y, 2)
        _im_y = np.repeat(im_y, 2)
    else:
        raise QiskitError('Invalid interpolation method "%s"' % interp_method)

    # plot
    ax0.fill_between(x=_time, y1=_re_y, y2=np.zeros_like(_time),
                     facecolor='red', alpha=0.3,
                     edgecolor='red', linewidth=1.5,
                     label='real part')
    ax0.fill_between(x=_time, y1=_im_y, y2=np.zeros_like(_time),
                     facecolor='blue', alpha=0.3,
                     edgecolor='blue', linewidth=1.5,
                     label='imaginary part')

    ax0.set_xlim(0, duration * _dt)
    ax0.grid(b=True, linestyle='-')
    ax0.legend(bbox_to_anchor=(0.5, 1.00), loc='lower center',
               ncol=2, frameon=False, fontsize=14)

    if filename:
        image.savefig(filename, dpi=dpi, bbox_inches='tight')

    plt.close(image)

    if image and interactive:
        plt.show(image)

    return image

def
pulse_drawer
(
samples
,
duration
,
dt
=
,
interp_method
=
'None'
,
filename
=
,
interactive
=
False
,
dpi
=
150
,
nop
=
1000
,
size
=
(
6
,
5
)
)
:
try
:
from
matplotlib
import
pyplot
as
plt
except
ImportError
:
raise
ImportError
(
'pulse_drawer need matplotlib. '
'Run "pip install matplotlib" before.'
)
if
dt
:
_dt
=
dt
else
:
_dt
=
1
re_y
=
np
.
real
(
samples
)
im_y
=
np
.
imag
(
samples
)
image
=
plt
.
figure
(
figsize
=
size
)
ax0
=
image
.
add_subplot
(
111
)
if
interp_method
==
'CubicSpline'
:
time
=
np
.
arange
(
0
,
duration
+
1
)
*
_dt
+
0.5
*
_dt
cs_ry
=
CubicSpline
(
time
[
:
1
]
,
re_y
)
cs_iy
=
CubicSpline
(
time
[
:
1
]
,
im_y
)
_time
=
np
.
linspace
(
0
,
duration
*
_dt
,
nop
)
_re_y
=
cs_ry
(
_time
)
_im_y
=
cs_iy
(
_time
)
elif
interp_method
==
'None'
:
time
=
np
.
arange
(
0
,
duration
+
1
)
*
_dt
_time
=
np
.
r_
[
time
[
0
]
,
np
.
repeat
(
time
[
1
:
1
]
,
2
)
,
time
[
1
]
]
_re_y
=
np
.
repeat
(
re_y
,
2
)
_im_y
=
np
.
repeat
(
im_y
,
2
)
else
:
raise
QiskitError
(
'Invalid interpolation method "%s"'
%
interp_method
)
ax0
.
fill_between
(
x
=
_time
,
y1
=
_re_y
,
y2
=
np
.
zeros_like
(
_time
)
,
facecolor
=
'red'
,
alpha
=
0.3
,
edgecolor
=
'red'
,
linewidth
=
1.5
,
label
=
'real part'
)
ax0
.
fill_between
(
x
=
_time
,
y1
=
_im_y
,
y2
=
np
.
zeros_like
(
_time
)
,
facecolor
=
'blue'
,
alpha
=
0.3
,
edgecolor
=
'blue'
,
linewidth
=
1.5
,
label
=
'imaginary part'
)
ax0
.
set_xlim
(
0
,
duration
*
_dt
)
ax0
.
grid
(
b
=
True
,
linestyle
=
'-'
)
ax0
.
legend
(
bbox_to_anchor
=
(
0.5
,
1.00
)
,
loc
=
'lower center'
,
ncol
=
2
,
frameon
=
False
,
fontsize
=
14
)
if
filename
:
image
.
savefig
(
filename
,
dpi
=
dpi
,
bbox_inches
=
'tight'
)
plt
.
close
(
image
)
if
image
and
interactive
:
plt
.
show
(
image
)
return
image


def _search_forward_n_swaps(layout, gates, coupling_map,
                            depth=SEARCH_DEPTH, width=SEARCH_WIDTH):
    """Search for SWAPs which allow for application of largest number of gates.

    Arguments:
        layout (Layout): Map from virtual qubit index to physical qubit index.
        gates (list): Gates to be mapped.
        coupling_map (CouplingMap): CouplingMap of the target backend.
        depth (int): Number of SWAP layers to search before choosing a result.
        width (int): Number of SWAPs to consider at each layer.
    Returns:
        dict: Describes solution step found.
            layout (Layout): Virtual to physical qubit map after SWAPs.
            gates_remaining (list): Gates that could not be mapped.
            gates_mapped (list): Gates that were mapped, including added SWAPs.

    """

    gates_mapped, gates_remaining = _map_free_gates(layout, gates, coupling_map)

    base_step = {'layout': layout,
                 'swaps_added': 0,
                 'gates_mapped': gates_mapped,
                 'gates_remaining': gates_remaining}

    if not gates_remaining or depth == 0:
        return base_step

    possible_swaps = coupling_map.get_edges()

    def _score_swap(swap):
        """Calculate the relative score for a given SWAP."""
        trial_layout = layout.copy()
        trial_layout.swap(*swap)
        return _calc_layout_distance(gates, coupling_map, trial_layout)

    ranked_swaps = sorted(possible_swaps, key=_score_swap)

    best_swap, best_step = None, None
    for swap in ranked_swaps[:width]:
        trial_layout = layout.copy()
        trial_layout.swap(*swap)
        next_step = _search_forward_n_swaps(trial_layout, gates_remaining,
                                            coupling_map, depth - 1, width)

        # ranked_swaps already sorted by distance, so distance is the tie-breaker.
        if best_swap is None or _score_step(next_step) > _score_step(best_step):
            best_swap, best_step = swap, next_step

    best_swap_gate = _swap_ops_from_edge(best_swap, layout)
    return {
        'layout': best_step['layout'],
        'swaps_added': 1 + best_step['swaps_added'],
        'gates_remaining': best_step['gates_remaining'],
        'gates_mapped': gates_mapped + best_swap_gate + best_step['gates_mapped'],
    }

def _search_forward_n_swaps ( layout , gates , coupling_map , depth = SEARCH_DEPTH , width = SEARCH_WIDTH ) : gates_mapped , gates_remaining = _map_free_gates ( layout , gates , coupling_map ) base_step = { 'layout' : layout , 'swaps_added' : 0 , 'gates_mapped' : gates_mapped , 'gates_remaining' : gates_remaining } if not gates_remaining or depth == 0 : return base_step possible_swaps = coupling_map . get_edges ( ) def _score_swap ( swap ) : trial_layout = layout . copy ( ) trial_layout . swap ( * swap ) return _calc_layout_distance ( gates , coupling_map , trial_layout ) ranked_swaps = sorted ( possible_swaps , key = _score_swap ) best_swap , best_step = None , None for swap in ranked_swaps [ : width ] : trial_layout = layout . copy ( ) trial_layout . swap ( * swap ) next_step = _search_forward_n_swaps ( trial_layout , gates_remaining , coupling_map , depth - 1 , width ) if best_swap is None or _score_step ( next_step ) > _score_step ( best_step ) : best_swap , best_step = swap , next_step best_swap_gate = _swap_ops_from_edge ( best_swap , layout ) return { 'layout' : best_step [ 'layout' ] , 'swaps_added' : 1 + best_step [ 'swaps_added' ] , 'gates_remaining' : best_step [ 'gates_remaining' ] , 'gates_mapped' : gates_mapped + best_swap_gate + best_step [ 'gates_mapped' ] , }

Search for SWAPs which allow for application of largest number of gates .


def _map_free_gates(layout, gates, coupling_map):
    """Map all gates that can be executed with the current layout.

    Args:
        layout (Layout): Map from virtual qubit index to physical qubit index.
        gates (list): Gates to be mapped.
        coupling_map (CouplingMap): CouplingMap for target device topology.

    Returns:
        tuple:
            mapped_gates (list): ops for gates that can be executed, mapped onto layout.
            remaining_gates (list): gates that cannot be executed on the layout.

    """

    blocked_qubits = set()

    mapped_gates = []
    remaining_gates = []

    for gate in gates:
        # Gates without a partition (barrier, snapshot, save, load, noise) may
        # still have associated qubits. Look for them in the qargs.
        if not gate['partition']:
            qubits = [n for n in gate['graph'].nodes() if n.type == 'op'][0].qargs

            if not qubits:
                continue

            if blocked_qubits.intersection(qubits):
                blocked_qubits.update(qubits)
                remaining_gates.append(gate)
            else:
                mapped_gate = _transform_gate_for_layout(gate, layout)
                mapped_gates.append(mapped_gate)
            continue

        qubits = gate['partition'][0]

        if blocked_qubits.intersection(qubits):
            blocked_qubits.update(qubits)
            remaining_gates.append(gate)
        elif len(qubits) == 1:
            mapped_gate = _transform_gate_for_layout(gate, layout)
            mapped_gates.append(mapped_gate)
        elif coupling_map.distance(*[layout[q] for q in qubits]) == 1:
            mapped_gate = _transform_gate_for_layout(gate, layout)
            mapped_gates.append(mapped_gate)
        else:
            blocked_qubits.update(qubits)
            remaining_gates.append(gate)

    return mapped_gates, remaining_gates

def _map_free_gates ( layout , gates , coupling_map ) : blocked_qubits = set ( ) mapped_gates = [ ] remaining_gates = [ ] for gate in gates : if not gate [ 'partition' ] : qubits = [ n for n in gate [ 'graph' ] . nodes ( ) if n . type == 'op' ] [ 0 ] . qargs if not qubits : continue if blocked_qubits . intersection ( qubits ) : blocked_qubits . update ( qubits ) remaining_gates . append ( gate ) else : mapped_gate = _transform_gate_for_layout ( gate , layout ) mapped_gates . append ( mapped_gate ) continue qubits = gate [ 'partition' ] [ 0 ] if blocked_qubits . intersection ( qubits ) : blocked_qubits . update ( qubits ) remaining_gates . append ( gate ) elif len ( qubits ) == 1 : mapped_gate = _transform_gate_for_layout ( gate , layout ) mapped_gates . append ( mapped_gate ) elif coupling_map . distance ( * [ layout [ q ] for q in qubits ] ) == 1 : mapped_gate = _transform_gate_for_layout ( gate , layout ) mapped_gates . append ( mapped_gate ) else : blocked_qubits . update ( qubits ) remaining_gates . append ( gate ) return mapped_gates , remaining_gates

Map all gates that can be executed with the current layout .


def _calc_layout_distance(gates, coupling_map, layout, max_gates=None):
    """Return the sum of the distances of two-qubit pairs in each CNOT in gates
    according to the layout and the coupling.
    """

    if max_gates is None:
        max_gates = 50 + 10 * len(coupling_map.physical_qubits)

    return sum(coupling_map.distance(*[layout[q] for q in gate['partition'][0]])
               for gate in gates[:max_gates]
               if gate['partition'] and len(gate['partition'][0]) == 2)

def _calc_layout_distance ( gates , coupling_map , layout , max_gates = None ) : if max_gates is None : max_gates = 50 + 10 * len ( coupling_map . physical_qubits ) return sum ( coupling_map . distance ( * [ layout [ q ] for q in gate [ 'partition' ] [ 0 ] ] ) for gate in gates [ : max_gates ] if gate [ 'partition' ] and len ( gate [ 'partition' ] [ 0 ] ) == 2 )

Return the sum of the distances of two - qubit pairs in each CNOT in gates according to the layout and the coupling .


def _score_step(step):

    """Count the mapped two-qubit gates, less the number of added SWAPs."""
    # Each added swap will add 3 ops to gates_mapped, so subtract 3.
    return len([g for g in step['gates_mapped']
                if len(g.qargs) == 2]) - 3 * step['swaps_added']

def _score_step ( step ) : return len ( [ g for g in step [ 'gates_mapped' ] if len ( g . qargs ) == 2 ] ) - 3 * step [ 'swaps_added' ]

Count the mapped two - qubit gates less the number of added SWAPs .


def _copy_circuit_metadata(source_dag, coupling_map):
    """Return a copy of source_dag with metadata but empty.
    Generate only a single qreg in the output DAG, matching the size of the
    coupling_map."""

    target_dag = DAGCircuit()
    target_dag.name = source_dag.name

    for creg in source_dag.cregs.values():
        target_dag.add_creg(creg)

    device_qreg = QuantumRegister(len(coupling_map.physical_qubits), 'q')
    target_dag.add_qreg(device_qreg)

    return target_dag

def _copy_circuit_metadata ( source_dag , coupling_map ) : target_dag = DAGCircuit ( ) target_dag . name = source_dag . name for creg in source_dag . cregs . values ( ) : target_dag . add_creg ( creg ) device_qreg = QuantumRegister ( len ( coupling_map . physical_qubits ) , 'q' ) target_dag . add_qreg ( device_qreg ) return target_dag

Return a copy of source_dag with metadata but empty . Generate only a single qreg in the output DAG matching the size of the coupling_map .


def _transform_gate_for_layout(gate, layout):
    """Return op implementing a virtual gate on given layout."""

    mapped_op_node = deepcopy([n for n in gate['graph'].nodes() if n.type == 'op'][0])

    # Workaround until #1816, apply mapped to qargs to both DAGNode and op
    device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
    mapped_qargs = [(device_qreg, layout[a]) for a in mapped_op_node.qargs]
    mapped_op_node.qargs = mapped_op_node.op.qargs = mapped_qargs

    mapped_op_node.pop('name')

    return mapped_op_node

def _transform_gate_for_layout ( gate , layout ) : mapped_op_node = deepcopy ( [ n for n in gate [ 'graph' ] . nodes ( ) if n . type == 'op' ] [ 0 ] ) device_qreg = QuantumRegister ( len ( layout . get_physical_bits ( ) ) , 'q' ) mapped_qargs = [ ( device_qreg , layout [ a ] ) for a in mapped_op_node . qargs ] mapped_op_node . qargs = mapped_op_node . op . qargs = mapped_qargs mapped_op_node . pop ( 'name' ) return mapped_op_node

Return op implementing a virtual gate on given layout .


def _swap_ops_from_edge(edge, layout):
    """Generate list of ops to implement a SWAP gate along a coupling edge."""

    device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
    qreg_edge = [(device_qreg, i) for i in edge]

    # TODO shouldn't be making other nodes not by the DAG!!
    return [
        DAGNode({'op': SwapGate(), 'qargs': qreg_edge, 'cargs': [], 'type': 'op'})
    ]

def _swap_ops_from_edge ( edge , layout ) : device_qreg = QuantumRegister ( len ( layout . get_physical_bits ( ) ) , 'q' ) qreg_edge = [ ( device_qreg , i ) for i in edge ] return [ DAGNode ( { 'op' : SwapGate ( ) , 'qargs' : qreg_edge , 'cargs' : [ ] , 'type' : 'op' } ) ]

Generate list of ops to implement a SWAP gate along a coupling edge .


def run(self, dag):
        """Run one pass of the lookahead mapper on the provided DAG.

        Args:
            dag (DAGCircuit): the directed acyclic graph to be mapped
        Returns:
            DAGCircuit: A dag mapped to be compatible with the coupling_map in
                the property_set.
        Raises:
            TranspilerError: if the coupling map or the layout are not
            compatible with the DAG
        """
        coupling_map = self._coupling_map
        ordered_virtual_gates = list(dag.serial_layers())

        if self.initial_layout is None:
            if self.property_set["layout"]:
                self.initial_layout = self.property_set["layout"]
            else:
                self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())

        if len(dag.qubits()) != len(self.initial_layout):
            raise TranspilerError('The layout does not match the amount of qubits in the DAG')

        if len(self._coupling_map.physical_qubits) != len(self.initial_layout):
            raise TranspilerError(
                "Mappers require to have the layout to be the same size as the coupling map")

        mapped_gates = []
        layout = self.initial_layout.copy()
        gates_remaining = ordered_virtual_gates.copy()

        while gates_remaining:
            best_step = _search_forward_n_swaps(layout, gates_remaining,
                                                coupling_map)

            layout = best_step['layout']
            gates_mapped = best_step['gates_mapped']
            gates_remaining = best_step['gates_remaining']

            mapped_gates.extend(gates_mapped)

        # Preserve input DAG's name, regs, wire_map, etc. but replace the graph.
        mapped_dag = _copy_circuit_metadata(dag, coupling_map)

        for node in mapped_gates:
            mapped_dag.apply_operation_back(op=node.op, qargs=node.qargs, cargs=node.cargs)

        return mapped_dag

Run one pass of the lookahead mapper on the provided DAG .


def add_physical_qubit(self, physical_qubit):
        """Add a physical qubit to the coupling graph as a node.

        physical_qubit (int): An integer representing a physical qubit.

        Raises:
            CouplingError: if trying to add duplicate qubit
        """
        if not isinstance(physical_qubit, int):
            raise CouplingError("Physical qubits should be integers.")
        if physical_qubit in self.physical_qubits:
            raise CouplingError(
                "The physical qubit %s is already in the coupling graph" % physical_qubit)
        self.graph.add_node(physical_qubit)
        self._dist_matrix = None  # invalidate
        self._qubit_list = None

Add a physical qubit to the coupling graph as a node .


def add_edge(self, src, dst):
        """
        Add directed edge to coupling graph.

        src (int): source physical qubit
        dst (int): destination physical qubit
        """
        if src not in self.physical_qubits:
            self.add_physical_qubit(src)
        if dst not in self.physical_qubits:
            self.add_physical_qubit(dst)
        self.graph.add_edge(src, dst)
        self._dist_matrix = None

def add_edge ( self , src , dst ) : if src not in self . physical_qubits : self . add_physical_qubit ( src ) if dst not in self . physical_qubits : self . add_physical_qubit ( dst ) self . graph . add_edge ( src , dst ) self . _dist_matrix = None


def subgraph(self, nodelist):
        """Return a CouplingMap object for a subgraph of self.

        nodelist (list): list of integer node labels
        """
        subcoupling = CouplingMap()
        subcoupling.graph = self.graph.subgraph(nodelist)
        for node in nodelist:
            if node not in subcoupling.physical_qubits:
                subcoupling.add_physical_qubit(node)
        return subcoupling

def subgraph ( self , nodelist ) : subcoupling = CouplingMap ( ) subcoupling . graph = self . graph . subgraph ( nodelist ) for node in nodelist : if node not in subcoupling . physical_qubits : subcoupling . add_physical_qubit ( node ) return subcoupling

Return a CouplingMap object for a subgraph of self .


def physical_qubits(self):
        """Returns a sorted list of physical_qubits"""
        if self._qubit_list is None:
            self._qubit_list = sorted([pqubit for pqubit in self.graph.nodes])
        return self._qubit_list

def physical_qubits ( self ) : if self . _qubit_list is None : self . _qubit_list = sorted ( [ pqubit for pqubit in self . graph . nodes ] ) return self . _qubit_list


def is_connected(self):
        """
        Test if the graph is connected.

        Return True if connected, False otherwise
        """
        try:
            return nx.is_weakly_connected(self.graph)
        except nx.exception.NetworkXException:
            return False

def is_connected ( self ) : try : return nx . is_weakly_connected ( self . graph ) except nx . exception . NetworkXException : return False


def _compute_distance_matrix(self):
        """Compute the full distance matrix on pairs of nodes.

        The distance map self._dist_matrix is computed from the graph using
        all_pairs_shortest_path_length.
        """
        if not self.is_connected():
            raise CouplingError("coupling graph not connected")
        lengths = nx.all_pairs_shortest_path_length(self.graph.to_undirected(as_view=True))
        lengths = dict(lengths)
        size = len(lengths)
        cmap = np.zeros((size, size))
        for idx in range(size):
            cmap[idx, np.fromiter(lengths[idx].keys(), dtype=int)] = np.fromiter(
                lengths[idx].values(), dtype=int)
        self._dist_matrix = cmap

def
_compute_distance_matrix
(
self
)
:
if
not
self
.
is_connected
(
)
:
raise
CouplingError
(
"coupling graph not connected"
)
lengths
=
nx
.
all_pairs_shortest_path_length
(
self
.
graph
.
to_undirected
(
as_view
=
True
)
)
lengths
=
dict
(
lengths
)
size
=
len
(
lengths
)
cmap
=
np
.
zeros
(
(
size
,
size
)
)
for
idx
in
range
(
size
)
:
cmap
[
idx
,
np
.
fromiter
(
lengths
[
idx
]
.
keys
(
)
,
dtype
=
int
)
]
=
np
.
fromiter
(
lengths
[
idx
]
.
values
(
)
,
dtype
=
int
)
self
.
_dist_matrix
=
cmap

Compute the full distance matrix on pairs of nodes .


def distance(self, physical_qubit1, physical_qubit2):
        """Returns the undirected distance between physical_qubit1 and physical_qubit2.

        Args:
            physical_qubit1 (int): A physical qubit
            physical_qubit2 (int): Another physical qubit

        Returns:
            int: The undirected distance

        Raises:
            CouplingError: if the qubits do not exist in the CouplingMap
        """
        if physical_qubit1 not in self.physical_qubits:
            raise CouplingError("%s not in coupling graph" % (physical_qubit1,))
        if physical_qubit2 not in self.physical_qubits:
            raise CouplingError("%s not in coupling graph" % (physical_qubit2,))
        if self._dist_matrix is None:
            self._compute_distance_matrix()
        return self._dist_matrix[physical_qubit1, physical_qubit2]

def
distance
(
self
,
physical_qubit1
,
physical_qubit2
)
:
if
physical_qubit1
not
in
self
.
physical_qubits
:
raise
CouplingError
(
"%s not in coupling graph"
%
(
physical_qubit1
,
)
)
if
physical_qubit2
not
in
self
.
physical_qubits
:
raise
CouplingError
(
"%s not in coupling graph"
%
(
physical_qubit2
,
)
)
if
self
.
_dist_matrix
is
:
self
.
_compute_distance_matrix
(
)
return
self
.
_dist_matrix
[
physical_qubit1
,
physical_qubit2
]

Returns the undirected distance between physical_qubit1 and physical_qubit2 .


def transpile(circuits, backend=None, basis_gates=None, coupling_map=None,
              initial_layout=None, seed_mapper=None, pass_manager=None):
    """transpile one or more circuits.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
        backend (BaseBackend): a backend to compile for
        basis_gates (list[str]): list of basis gate names supported by the
            target. Default: ['u1','u2','u3','cx','id']
        coupling_map (list): coupling map (perhaps custom) to target in mapping

        initial_layout (Layout or dict or list):
            Initial position of virtual qubits on physical qubits. The final
            layout is not guaranteed to be the same, as the transpiler may permute
            qubits through swaps or other means.

        seed_mapper (int): random seed for the swap_mapper
        pass_manager (PassManager): a pass_manager for the transpiler stages

    Returns:
        QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).

    Raises:
        TranspilerError: in case of bad inputs to transpiler or errors in passes
    """
    warnings.warn("qiskit.transpiler.transpile() has been deprecated and will be "
                  "removed in the 0.9 release. Use qiskit.compiler.transpile() instead.",
                  DeprecationWarning)
    return compiler.transpile(circuits=circuits, backend=backend,
                              basis_gates=basis_gates, coupling_map=coupling_map,
                              initial_layout=initial_layout, seed_transpiler=seed_mapper,
                              pass_manager=pass_manager)


def cu1(self, theta, ctl, tgt):
    """Apply cu1 from ctl to tgt with angle theta."""
    return self.append(Cu1Gate(theta), [ctl, tgt], [])

def cu1 ( self , theta , ctl , tgt ) : return self . append ( Cu1Gate ( theta ) , [ ctl , tgt ] , [ ] )

Apply cu1 from ctl to tgt with angle theta .


def inverse(self):
        """Invert all instructions."""
        for index, instruction in enumerate(self.instructions):
            self.instructions[index] = instruction.inverse()
        return self

def inverse ( self ) : for index , instruction in enumerate ( self . instructions ) : self . instructions [ index ] = instruction . inverse ( ) return self


def q_if(self, *qregs):
        """Add controls to all instructions."""
        for gate in self.instructions:
            gate.q_if(*qregs)
        return self

def q_if ( self , * qregs ) : for gate in self . instructions : gate . q_if ( * qregs ) return self


def c_if(self, classical, val):
        """Add classical control register to all instructions."""
        for gate in self.instructions:
            gate.c_if(classical, val)
        return self

def c_if ( self , classical , val ) : for gate in self . instructions : gate . c_if ( classical , val ) return self

Add classical control register to all instructions .


def subscribe(self, event, callback):
        """Subscribes to an event, so when it's emitted all the callbacks subscribed,
        will be executed. We are not allowing double registration.

        Args
            event (string): The event to subscribed in the form of:
                            "terra.<component>.<method>.<action>"
            callback (callable): The callback that will be executed when an event is
                                  emitted.
        """
        if not callable(callback):
            raise QiskitError("Callback is not a callable!")

        if event not in self._subscribers:
            self._subscribers[event] = []

        new_subscription = self._Subscription(event, callback)
        if new_subscription in self._subscribers[event]:
            # We are not allowing double subscription
            return False

        self._subscribers[event].append(new_subscription)
        return True

def
subscribe
(
self
,
event
,
callback
)
:
if
not
callable
(
callback
)
:
raise
QiskitError
(
"Callback is not a callable!"
)
if
event
not
in
self
.
_subscribers
:
self
.
_subscribers
[
event
]
=
[
]
new_subscription
=
self
.
_Subscription
(
event
,
callback
)
if
new_subscription
in
self
.
_subscribers
[
event
]
:
return
False
self
.
_subscribers
[
event
]
.
append
(
new_subscription
)
return
True

Subscribes to an event so when it s emitted all the callbacks subscribed will be executed . We are not allowing double registration .


def dispatch(self, event, *args, **kwargs):
        """Emits an event if there are any subscribers.

        Args
            event (String): The event to be emitted
            args: Arguments linked with the event
            kwargs: Named arguments linked with the event
        """
        # No event, no subscribers.
        if event not in self._subscribers:
            return

        for subscriber in self._subscribers[event]:
            subscriber.callback(*args, **kwargs)

def dispatch ( self , event , * args , ** kwargs ) : if event not in self . _subscribers : return for subscriber in self . _subscribers [ event ] : subscriber . callback ( * args , ** kwargs )

Emits an event if there are any subscribers .


def unsubscribe(self, event, callback):
        """ Unsubscribe the specific callback to the event.

        Args
            event (String): The event to unsubscribe
            callback (callable): The callback that won't be executed anymore

        Returns
            True: if we have successfully unsubscribed to the event
            False: if there's no callback previously registered
        """

        try:
            self._subscribers[event].remove(self._Subscription(event, callback))
        except KeyError:
            return False

        return True

def unsubscribe ( self , event , callback ) : try : self . _subscribers [ event ] . remove ( self . _Subscription ( event , callback ) ) except KeyError : return False return True

Unsubscribe the specific callback to the event .


def publish(self, event, *args, **kwargs):
        """ Triggers an event, and associates some data to it, so if there are any
        subscribers, their callback will be called synchronously. """
        return self._broker.dispatch(event, *args, **kwargs)

def publish ( self , event , * args , ** kwargs ) : return self . _broker . dispatch ( event , * args , ** kwargs )

Triggers an event and associates some data to it so if there are any subscribers their callback will be called synchronously .


def initialize(self, params, qubits):
    """Apply initialize to circuit."""
    if isinstance(qubits, QuantumRegister):
        qubits = qubits[:]
    else:
        qubits = _convert_to_bits([qubits], [qbit for qreg in self.qregs for qbit in qreg])[0]
    return self.append(Initialize(params), qubits)

def initialize ( self , params , qubits ) : if isinstance ( qubits , QuantumRegister ) : qubits = qubits [ : ] else : qubits = _convert_to_bits ( [ qubits ] , [ qbit for qreg in self . qregs for qbit in qreg ] ) [ 0 ] return self . append ( Initialize ( params ) , qubits )


def _define(self):
        """Calculate a subcircuit that implements this initialization

        Implements a recursive initialization algorithm, including optimizations,
        from "Synthesis of Quantum Logic Circuits" Shende, Bullock, Markov
        https://arxiv.org/abs/quant-ph/0406176v5

        Additionally implements some extra optimizations: remove zero rotations and
        double cnots.
        """
        # call to generate the circuit that takes the desired vector to zero
        disentangling_circuit = self.gates_to_uncompute()

        # invert the circuit to create the desired vector from zero (assuming
        # the qubits are in the zero state)
        initialize_instr = disentangling_circuit.to_instruction().inverse()

        q = QuantumRegister(self.num_qubits, 'q')
        initialize_circuit = QuantumCircuit(q, name='init_def')
        for qubit in q:
            initialize_circuit.append(Reset(), [qubit])
        initialize_circuit.append(initialize_instr, q[:])

        self.definition = initialize_circuit.data

def _define ( self ) : disentangling_circuit = self . gates_to_uncompute ( ) initialize_instr = disentangling_circuit . to_instruction ( ) . inverse ( ) q = QuantumRegister ( self . num_qubits , 'q' ) initialize_circuit = QuantumCircuit ( q , name = 'init_def' ) for qubit in q : initialize_circuit . append ( Reset ( ) , [ qubit ] ) initialize_circuit . append ( initialize_instr , q [ : ] ) self . definition = initialize_circuit . data


def gates_to_uncompute(self):
        """
        Call to create a circuit with gates that take the
        desired vector to zero.

        Returns:
            QuantumCircuit: circuit to take self.params vector to |00..0>
        """
        q = QuantumRegister(self.num_qubits)
        circuit = QuantumCircuit(q, name='disentangler')

        # kick start the peeling loop, and disentangle one-by-one from LSB to MSB
        remaining_param = self.params

        for i in range(self.num_qubits):
            # work out which rotations must be done to disentangle the LSB
            # qubit (we peel away one qubit at a time)
            (remaining_param,
             thetas,
             phis) = Initialize._rotations_to_disentangle(remaining_param)

            # perform the required rotations to decouple the LSB qubit (so that
            # it can be "factored" out, leaving a shorter amplitude vector to peel away)
            rz_mult = self._multiplex(RZGate, phis)
            ry_mult = self._multiplex(RYGate, thetas)
            circuit.append(rz_mult.to_instruction(), q[i:self.num_qubits])
            circuit.append(ry_mult.to_instruction(), q[i:self.num_qubits])
        return circuit

def gates_to_uncompute ( self ) : q = QuantumRegister ( self . num_qubits ) circuit = QuantumCircuit ( q , name = 'disentangler' ) remaining_param = self . params for i in range ( self . num_qubits ) : ( remaining_param , thetas , phis ) = Initialize . _rotations_to_disentangle ( remaining_param ) rz_mult = self . _multiplex ( RZGate , phis ) ry_mult = self . _multiplex ( RYGate , thetas ) circuit . append ( rz_mult . to_instruction ( ) , q [ i : self . num_qubits ] ) circuit . append ( ry_mult . to_instruction ( ) , q [ i : self . num_qubits ] ) return circuit

Call to create a circuit with gates that take the desired vector to zero .


def _bloch_angles(pair_of_complex):
        """
        Static internal method to work out rotation to create the passed in
        qubit from the zero vector.
        """
        [a_complex, b_complex] = pair_of_complex
        # Force a and b to be complex, as otherwise numpy.angle might fail.
        a_complex = complex(a_complex)
        b_complex = complex(b_complex)
        mag_a = np.absolute(a_complex)
        final_r = float(np.sqrt(mag_a ** 2 + np.absolute(b_complex) ** 2))
        if final_r < _EPS:
            theta = 0
            phi = 0
            final_r = 0
            final_t = 0
        else:
            theta = float(2 * np.arccos(mag_a / final_r))
            a_arg = np.angle(a_complex)
            b_arg = np.angle(b_complex)
            final_t = a_arg + b_arg
            phi = b_arg - a_arg

        return final_r * np.exp(1.J * final_t / 2), theta, phi

def _bloch_angles ( pair_of_complex ) : [ a_complex , b_complex ] = pair_of_complex a_complex = complex ( a_complex ) b_complex = complex ( b_complex ) mag_a = np . absolute ( a_complex ) final_r = float ( np . sqrt ( mag_a ** 2 + np . absolute ( b_complex ) ** 2 ) ) if final_r < _EPS : theta = 0 phi = 0 final_r = 0 final_t = 0 else : theta = float ( 2 * np . arccos ( mag_a / final_r ) ) a_arg = np . angle ( a_complex ) b_arg = np . angle ( b_complex ) final_t = a_arg + b_arg phi = b_arg - a_arg return final_r * np . exp ( 1.J * final_t / 2 ) , theta , phi

Static internal method to work out rotation to create the passed in qubit from the zero vector .


def _multiplex(self, target_gate, list_of_angles):
        """
        Return a recursive implementation of a multiplexor circuit,
        where each instruction itself has a decomposition based on
        smaller multiplexors.

        The LSB is the multiplexor "data" and the other bits are multiplexor "select".

        Args:
            target_gate (Gate): Ry or Rz gate to apply to target qubit, multiplexed
                over all other "select" qubits
            list_of_angles (list[float]): list of rotation angles to apply Ry and Rz

        Returns:
            DAGCircuit: the circuit implementing the multiplexor's action
        """
        list_len = len(list_of_angles)
        local_num_qubits = int(math.log2(list_len)) + 1

        q = QuantumRegister(local_num_qubits)
        circuit = QuantumCircuit(q, name="multiplex" + local_num_qubits.__str__())

        lsb = q[0]
        msb = q[local_num_qubits - 1]

        # case of no multiplexing: base case for recursion
        if local_num_qubits == 1:
            circuit.append(target_gate(list_of_angles[0]), [q[0]])
            return circuit

        # calc angle weights, assuming recursion (that is the lower-level
        # requested angles have been correctly implemented by recursion
        angle_weight = scipy.kron([[0.5, 0.5], [0.5, -0.5]],
                                  np.identity(2 ** (local_num_qubits - 2)))

        # calc the combo angles
        list_of_angles = angle_weight.dot(np.array(list_of_angles)).tolist()

        # recursive step on half the angles fulfilling the above assumption
        multiplex_1 = self._multiplex(target_gate, list_of_angles[0:(list_len // 2)])
        circuit.append(multiplex_1.to_instruction(), q[0:-1])

        # attach CNOT as follows, thereby flipping the LSB qubit
        circuit.append(CnotGate(), [msb, lsb])

        # implement extra efficiency from the paper of cancelling adjacent
        # CNOTs (by leaving out last CNOT and reversing (NOT inverting) the
        # second lower-level multiplex)
        multiplex_2 = self._multiplex(target_gate, list_of_angles[(list_len // 2):])
        if list_len > 1:
            circuit.append(multiplex_2.to_instruction().mirror(), q[0:-1])
        else:
            circuit.append(multiplex_2.to_instruction(), q[0:-1])

        # attach a final CNOT
        circuit.append(CnotGate(), [msb, lsb])

        return circuit

def _multiplex ( self , target_gate , list_of_angles ) : list_len = len ( list_of_angles ) local_num_qubits = int ( math . log2 ( list_len ) ) + 1 q = QuantumRegister ( local_num_qubits ) circuit = QuantumCircuit ( q , name = "multiplex" + local_num_qubits . __str__ ( ) ) lsb = q [ 0 ] msb = q [ local_num_qubits - 1 ] if local_num_qubits == 1 : circuit . append ( target_gate ( list_of_angles [ 0 ] ) , [ q [ 0 ] ] ) return circuit angle_weight = scipy . kron ( [ [ 0.5 , 0.5 ] , [ 0.5 , - 0.5 ] ] , np . identity ( 2 ** ( local_num_qubits - 2 ) ) ) list_of_angles = angle_weight . dot ( np . array ( list_of_angles ) ) . tolist ( ) multiplex_1 = self . _multiplex ( target_gate , list_of_angles [ 0 : ( list_len // 2 ) ] ) circuit . append ( multiplex_1 . to_instruction ( ) , q [ 0 : - 1 ] ) circuit . append ( CnotGate ( ) , [ msb , lsb ] ) multiplex_2 = self . _multiplex ( target_gate , list_of_angles [ ( list_len // 2 ) : ] ) if list_len > 1 : circuit . append ( multiplex_2 . to_instruction ( ) . mirror ( ) , q [ 0 : - 1 ] ) else : circuit . append ( multiplex_2 . to_instruction ( ) , q [ 0 : - 1 ] ) circuit . append ( CnotGate ( ) , [ msb , lsb ] ) return circuit

Return a recursive implementation of a multiplexor circuit where each instruction itself has a decomposition based on smaller multiplexors .


def is_virtual(value):
        """Checks if value has the format of a virtual qubit """
        return value is None or isinstance(value, tuple) and len(value) == 2 and isinstance(
            value[0], Register) and isinstance(value[1], int)

def is_virtual ( value ) : return value is None or isinstance ( value , tuple ) and len ( value ) == 2 and isinstance ( value [ 0 ] , Register ) and isinstance ( value [ 1 ] , int )


def copy(self):
        """Returns a copy of a Layout instance."""
        layout_copy = type(self)()

        layout_copy._p2v = self._p2v.copy()
        layout_copy._v2p = self._v2p.copy()

        return layout_copy

def copy ( self ) : layout_copy = type ( self ) ( ) layout_copy . _p2v = self . _p2v . copy ( ) layout_copy . _v2p = self . _v2p . copy ( ) return layout_copy


def combine_into_edge_map(self, another_layout):
        """Combines self and another_layout into an "edge map".

        For example::

              self       another_layout  resulting edge map
           qr_1 -> 0        0 <- q_2         qr_1 -> q_2
           qr_2 -> 2        2 <- q_1         qr_2 -> q_1
           qr_3 -> 3        3 <- q_0         qr_3 -> q_0

        The edge map is used to compose dags via, for example, compose_back.

        Args:
            another_layout (Layout): The other layout to combine.
        Returns:
            dict: A "edge map".
        Raises:
            LayoutError: another_layout can be bigger than self, but not smaller. Otherwise, raises.
        """
        edge_map = dict()

        for virtual, physical in self.get_virtual_bits().items():
            if physical not in another_layout._p2v:
                raise LayoutError('The wire_map_from_layouts() method does not support when the'
                                  ' other layout (another_layout) is smaller.')
            edge_map[virtual] = another_layout[physical]

        return edge_map

Combines self and another_layout into an edge map .


def ccx(self, ctl1, ctl2, tgt):
    """Apply Toffoli to from ctl1 and ctl2 to tgt."""
    return self.append(ToffoliGate(), [ctl1, ctl2, tgt], [])

def ccx ( self , ctl1 , ctl2 , tgt ) : return self . append ( ToffoliGate ( ) , [ ctl1 , ctl2 , tgt ] , [ ] )

Apply Toffoli to from ctl1 and ctl2 to tgt .


def insert(self, start_time: int, schedule: ScheduleComponent) -> 'ScheduleComponent':
        """Return a new schedule with `schedule` inserted within `self` at `start_time`.

        Args:
            start_time: time to be inserted
            schedule: schedule to be inserted
        """
        return ops.insert(self, start_time, schedule)

def insert ( self , start_time : int , schedule : ScheduleComponent ) -> 'ScheduleComponent' : return ops . insert ( self , start_time , schedule )

Return a new schedule with schedule inserted within self at start_time .


def _check_if_fenced(self, name):
        """
        Checks if the attribute name is in the list of attributes to protect. If so, raises
        TranspilerAccessError.

        Args:
            name (string): the attribute name to check

        Raises:
            TranspilerAccessError: when name is the list of attributes to protect.
        """
        if name in object.__getattribute__(self, '_attributes_to_fence'):
            raise TranspilerAccessError("The fenced %s has the property %s protected" %
                                        (type(object.__getattribute__(self, '_wrapped')), name))

Checks if the attribute name is in the list of attributes to protect . If so raises TranspilerAccessError .