def __init__(self, duration, discriminator=None, kernel=None):

super().__init__(duration=duration)<EOL>if discriminator:<EOL><INDENT>if isinstance(discriminator, Discriminator):<EOL><INDENT>self._discriminator = discriminator<EOL><DEDENT>else:<EOL><INDENT>raise PulseError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._discriminator = None<EOL><DEDENT>if kernel:<EOL><INDENT>if isinstance(kernel, Kernel):<EOL><INDENT>self._kernel = kernel<EOL><DEDENT>else:<EOL><INDENT>raise PulseError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._kernel = None<EOL><DEDENT>

Create new acquire command.

        Args:
            duration (int): Duration of acquisition.
            discriminator (Discriminator): Discriminators to be used
                (from the list of available discriminator) if the measurement level is 2.
            kernel (Kernel): The data structures defining the measurement kernels
                to be used (from the list of available kernels) and set of parameters
                (if applicable) if the measurement level is 1 or 2.

        Raises:
            PulseError: when invalid discriminator or kernel object is input.


return self._kernel<EOL>


return self._discriminator<EOL>


if type(self) is type(other) andself.kernel == other.kernel andself.discriminator == other.discriminator:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two Acquires are the same if they are of the same type
        and have the same kernel and discriminator.

        Args:
            other (Acquire): Other Acquire

        Returns:
            bool: are self and other equal.


return self._acquires<EOL>


return self._mem_slots<EOL>


return self._reg_slots<EOL>


@abstractmethod<EOL><INDENT>def __init__(self, duration: int = None, name: str = None):<DEDENT>

if isinstance(duration, int):<EOL><INDENT>self._duration = duration<EOL><DEDENT>else:<EOL><INDENT>raise PulseError('<STR_LIT>')<EOL><DEDENT>if name:<EOL><INDENT>self._name = name<EOL><DEDENT>else:<EOL><INDENT>self._name = '<STR_LIT>' % Command.pulseIndex<EOL>Command.pulseIndex += <NUM_LIT:1><EOL><DEDENT>

Create a new command.

        Args:
            duration (int): Duration of this command.
            name (str): Name of this command.
        Raises:
            PulseError: when duration is not number of points.


@property<EOL><INDENT>def duration(self) -> int:<DEDENT>

return self._duration<EOL>


@property<EOL><INDENT>def name(self) -> str:<DEDENT>

return self._name<EOL>


@abstractmethod<EOL><INDENT>def to_instruction(self, command, *channels, timeslots=None, name=None) -> Instruction:<DEDENT>

pass<EOL>


return self.to_instruction(*args, **kwargs)<EOL>

Creates an Instruction obtained from call to `to_instruction` wrapped in a Schedule.


if type(self) is type(other) andself._duration == other._duration andself._name == other._name:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two Commands are the same if they are of the same type
        and have the same duration and name.

        Args:
            other (Command): other Command.

        Returns:
            bool: are self and other equal.


@functools.wraps(func)<EOL>def to_pulse(duration, *args, name=None, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>if isinstance(duration, int) and duration > <NUM_LIT:0>:<EOL><INDENT>samples = func(duration, *args, **kwargs)<EOL>samples = np.asarray(samples, dtype=np.complex128)<EOL>return SamplePulse(samples=samples, name=name)<EOL><DEDENT>raise PulseError('<STR_LIT>')<EOL><DEDENT>return to_pulse<EOL>

A decorator for generating SamplePulse from python callable.
    Args:
        func (callable): A function describing pulse envelope.
    Raises:
        PulseError: when invalid function is specified.


super().__init__(duration=<NUM_LIT:0>)<EOL>if abs(value) > <NUM_LIT:1>:<EOL><INDENT>raise PulseError("<STR_LIT>")<EOL><DEDENT>self._value = complex(value)<EOL>

create new persistent value command.

        Args:
            value (complex): Complex value to apply, bounded by an absolute value of 1.
                The allowable precision is device specific.
        Raises:
            PulseError: when input value exceed 1.


return self._value<EOL>


if type(self) is type(other) andself.value == other.value:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two PersistentValues are the same if they are of the same type
        and have the same value.

        Args:
            other (PersistentValue): other PersistentValue

        Returns:
            bool: are self and other equal.


super().__init__(duration=len(samples), name=name)<EOL>if np.any(np.abs(samples) > <NUM_LIT:1>):<EOL><INDENT>raise PulseError('<STR_LIT>')<EOL><DEDENT>self._samples = samples<EOL>

Create new sample pulse command.

        Args:
            samples (ndarray): Complex array of pulse envelope.
            name (str): Unique name to identify the pulse.
        Raises:
            PulseError: when pulse envelope amplitude exceeds 1.


return self._samples<EOL>


from qiskit.tools.visualization import pulse_drawer<EOL>return pulse_drawer(self._samples, self.duration, **kwargs)<EOL>

Plot the interpolated envelope of pulse.

        Keyword Args:
            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.


if super().__eq__(other) and(self._samples == other._samples).all():<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two SamplePulses are the same if they are of the same type
        and have the same name and samples.

        Args:
            other (SamplePulse): other SamplePulse

        Returns:
            bool: are self and other equal.


return self._q_lo_freq<EOL>


return self._m_lo_freq<EOL>


def __init__(self, *schedules: List[Union[ScheduleComponent, Tuple[int, ScheduleComponent]]],<EOL>name: str = None):

self._name = name<EOL>try:<EOL><INDENT>timeslots = []<EOL>children = []<EOL>for sched_pair in schedules:<EOL><INDENT>if not isinstance(sched_pair, (list, tuple)):<EOL><INDENT>sched_pair = (<NUM_LIT:0>, sched_pair)<EOL><DEDENT>sched_pair = tuple(sched_pair)<EOL>insert_time, sched = sched_pair<EOL>sched_timeslots = sched.timeslots<EOL>if insert_time:<EOL><INDENT>sched_timeslots = sched_timeslots.shift(insert_time)<EOL><DEDENT>timeslots.append(sched_timeslots.timeslots)<EOL>children.append(sched_pair)<EOL><DEDENT>self._timeslots = TimeslotCollection(*itertools.chain(*timeslots))<EOL>self._children = tuple(children)<EOL><DEDENT>except PulseError as ts_err:<EOL><INDENT>raise PulseError('<STR_LIT>'.format(schedules)) from ts_err<EOL><DEDENT>

Create empty schedule.

        Args:
            *schedules: Child Schedules of this parent Schedule. May either be passed as
                the list of schedules, or a list of (start_time, schedule) pairs
            name: Name of this schedule

        Raises:
            PulseError: If timeslots intercept.


@property<EOL><INDENT>def channels(self) -> Tuple[Channel]:<DEDENT>

return self.timeslots.channels<EOL>

Returns channels that this schedule uses.


@property<EOL><INDENT>def instructions(self) -> Tuple[Tuple[int, '<STR_LIT>']]:<DEDENT>

return tuple(self._instructions())<EOL>

Iterable for getting instructions from Schedule tree.


def ch_duration(self, *channels: List[Channel]) -> int:

return self.timeslots.ch_duration(*channels)<EOL>

Return duration of supplied channels.

        Args:
            *channels: Supplied channels


def ch_start_time(self, *channels: List[Channel]) -> int:

return self.timeslots.ch_start_time(*channels)<EOL>

Return minimum start time for supplied channels.

        Args:
            *channels: Supplied channels


def ch_stop_time(self, *channels: List[Channel]) -> int:

return self.timeslots.ch_stop_time(*channels)<EOL>

Return maximum start time for supplied channels.

        Args:
            *channels: Supplied channels


def _instructions(self, time: int = <NUM_LIT:0>) -> Iterable[Tuple[int, '<STR_LIT>']]:

for insert_time, child_sched in self.children:<EOL><INDENT>yield from child_sched._instructions(time + insert_time)<EOL><DEDENT>

Iterable for flattening Schedule tree.

        Args:
            time: Shifted time due to parent

        Yields:
            Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts
                at and the flattened `ScheduleComponent`.


def union(self, *schedules: List[ScheduleComponent]) -> '<STR_LIT>':

return ops.union(self, *schedules)<EOL>

Return a new schedule which is the union of `self` and `schedule`.

        Args:
            *schedules: Schedules to be take the union with the parent `Schedule`.


def shift(self: ScheduleComponent, time: int) -> '<STR_LIT>':

return ops.shift(self, time)<EOL>

Return a new schedule shifted forward by `time`.

        Args:
            time: Time to shift by


def insert(self, start_time: int, schedule: ScheduleComponent) -> '<STR_LIT>':

return ops.insert(self, start_time, schedule)<EOL>

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

        Args:
            start_time: time to be inserted
            schedule: schedule to be inserted


def append(self, schedule: ScheduleComponent) -> '<STR_LIT>':

return ops.append(self, schedule)<EOL>

Return a new schedule with `schedule` inserted at the maximum time over
        all channels shared between `self` and `schedule`.

        Args:
            schedule: schedule to be appended


return ops.flatten(self)<EOL>

Return a new schedule which is the flattened schedule contained all `instructions`.


def __add__(self, schedule: ScheduleComponent) -> '<STR_LIT>':

return self.append(schedule)<EOL>

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


def __or__(self, schedule: ScheduleComponent) -> '<STR_LIT>':

return self.union(schedule)<EOL>

Return a new schedule which is the union of `self` and `schedule`.


def __lshift__(self, time: int) -> '<STR_LIT>':

return self.shift(time)<EOL>

Return a new schedule which is shifted forward by `time`.


def __init__(self, begin: int, end: int):

if begin < <NUM_LIT:0>:<EOL><INDENT>raise PulseError("<STR_LIT>")<EOL><DEDENT>if end < <NUM_LIT:0>:<EOL><INDENT>raise PulseError("<STR_LIT>")<EOL><DEDENT>self._begin = begin<EOL>self._end = end<EOL>

Create an interval = (begin, end))

        Args:
            begin: begin time of this interval
            end: end time of this interval

        Raises:
            PulseError: when invalid time or duration is specified


return self._begin<EOL>


return self._end<EOL>


return self._end - self._begin<EOL>


def has_overlap(self, interval: '<STR_LIT>') -> bool:

if self.begin < interval.end and interval.begin < self.end:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Check if self has overlap with `interval`.

        Args:
            interval: interval to be examined

        Returns:
            bool: True if self has overlap with `interval` otherwise False


def shift(self, time: int) -> '<STR_LIT>':

return Interval(self._begin + time, self._end + time)<EOL>

Return a new interval shifted by `time` from self

        Args:
            time: time to be shifted

        Returns:
            Interval: interval shifted by `time`


if self._begin == other._begin and self._end == other._end:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two intervals are the same if they have the same begin and end.

        Args:
            other (Interval): other Interval

        Returns:
            bool: are self and other equal.


return self._interval<EOL>


return self._channel<EOL>


return Timeslot(self.interval.shift(time), self.channel)<EOL>

Return a new Timeslot shifted by `time`.

        Args:
            time: time to be shifted


if self.interval == other.interval and self.channel == other.channel:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two time-slots are the same if they have the same interval and channel.

        Args:
            other (Timeslot): other Timeslot


def __init__(self, *timeslots: List[Timeslot]):

self._table = defaultdict(list)<EOL>for slot in timeslots:<EOL><INDENT>for interval in self._table[slot.channel]:<EOL><INDENT>if slot.interval.has_overlap(interval):<EOL><INDENT>raise PulseError("<STR_LIT>")<EOL><DEDENT><DEDENT>self._table[slot.channel].append(slot.interval)<EOL><DEDENT>self._timeslots = tuple(timeslots)<EOL>

Create a new time-slot collection.

        Args:
            *timeslots: list of time slots
        Raises:
            PulseError: when overlapped time slots are specified


@property<EOL><INDENT>def timeslots(self) -> Tuple[Timeslot]:<DEDENT>

return self._timeslots<EOL>


@property<EOL><INDENT>def channels(self) -> Tuple[Timeslot]:<DEDENT>

return tuple(self._table.keys())<EOL>

Channels within the timeslot collection.


@property<EOL><INDENT>def start_time(self) -> int:<DEDENT>

return self.ch_start_time(*self.channels)<EOL>

Return earliest start time in this collection.


@property<EOL><INDENT>def stop_time(self) -> int:<DEDENT>

return self.ch_stop_time(*self.channels)<EOL>

Return maximum time of timeslots over all channels.


@property<EOL><INDENT>def duration(self) -> int:<DEDENT>

return self.stop_time<EOL>

Return maximum duration of timeslots over all channels.


def ch_start_time(self, *channels: List[Channel]) -> int:

intervals = list(itertools.chain(*(self._table[chan] for chan in channels<EOL>if chan in self._table)))<EOL>if intervals:<EOL><INDENT>return min((interval.begin for interval in intervals))<EOL><DEDENT>return <NUM_LIT:0><EOL>

Return earliest start time in this collection.

        Args:
            *channels: Channels over which to obtain start_time.


def ch_stop_time(self, *channels: List[Channel]) -> int:

intervals = list(itertools.chain(*(self._table[chan] for chan in channels<EOL>if chan in self._table)))<EOL>if intervals:<EOL><INDENT>return max((interval.end for interval in intervals))<EOL><DEDENT>return <NUM_LIT:0><EOL>

Return maximum time of timeslots over all channels.

        Args:
            *channels: Channels over which to obtain stop time.


def ch_duration(self, *channels: List[Channel]) -> int:

return self.ch_stop_time(*channels)<EOL>

Return maximum duration of timeslots over all channels.

        Args:
            *channels: Channels over which to obtain the duration.


def is_mergeable_with(self, timeslots: '<STR_LIT>') -> bool:

for slot in timeslots.timeslots:<EOL><INDENT>for interval in self._table[slot.channel]:<EOL><INDENT>if slot.interval.has_overlap(interval):<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>return True<EOL>

Return if self is mergeable with `timeslots`.

        Args:
            timeslots: TimeslotCollection to be checked


def merged(self, timeslots: '<STR_LIT>') -> '<STR_LIT>':

slots = [Timeslot(slot.interval, slot.channel) for slot in self.timeslots]<EOL>slots.extend([Timeslot(slot.interval, slot.channel) for slot in timeslots.timeslots])<EOL>return TimeslotCollection(*slots)<EOL>

Return a new TimeslotCollection merged with a specified `timeslots`

        Args:
            timeslots: TimeslotCollection to be merged


slots = [Timeslot(slot.interval.shift(time), slot.channel) for slot in self.timeslots]<EOL>return TimeslotCollection(*slots)<EOL>

Return a new TimeslotCollection shifted by `time`.

        Args:
            time: time to be shifted by


if self.timeslots == other.timeslots:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two time-slot collections are the same if they have the same time-slots.

        Args:
            other (TimeslotCollection): other TimeslotCollection


super().__init__(*message)<EOL>self.message = '<STR_LIT:U+0020>'.join(message)<EOL>


return repr(self.message)<EOL>


<EOL>self.name = None<EOL>self.wires = []<EOL>self.input_map = OrderedDict()<EOL>self.output_map = OrderedDict()<EOL>self._max_node_id = <NUM_LIT:0><EOL>self._multi_graph = nx.MultiDiGraph()<EOL>self.qregs = OrderedDict()<EOL>self.cregs = OrderedDict()<EOL>self._id_to_node = {}<EOL>


warnings.warn('<STR_LIT>' +<EOL>'<STR_LIT>', DeprecationWarning)<EOL>return self._multi_graph<EOL>

Deprecated. Returns internal multi_graph.


warnings.warn('<STR_LIT>' +<EOL>'<STR_LIT>', DeprecationWarning)<EOL>self._multi_graph = multi_graph<EOL>


return copy.deepcopy(self._multi_graph)<EOL>

Returns a copy of the DAGCircuit in networkx format.


warnings.warn('<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>return self.qubits()<EOL>


return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]<EOL>

Return a list of qubits as (QuantumRegister, index) pairs.


warnings.warn('<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>return self.clbits()<EOL>


return [(v, i) for k, v in self.cregs.items() for i in range(v.size)]<EOL>

Return a list of bits as (ClassicalRegister, index) pairs.


warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>return len(self._multi_graph)<EOL>

Deprecated usage to return max node id, now returns size of DAG


def rename_register(self, regname, newname):

if regname == newname:<EOL><INDENT>return<EOL><DEDENT>if newname in self.qregs or newname in self.cregs:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % newname)<EOL><DEDENT>if regname not in self.qregs and regname not in self.cregs:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % regname)<EOL><DEDENT>if regname in self.qregs:<EOL><INDENT>reg = self.qregs[regname]<EOL>reg.name = newname<EOL>self.qregs[newname] = reg<EOL>self.qregs.pop(regname, None)<EOL><DEDENT>if regname in self.cregs:<EOL><INDENT>reg = self.cregs[regname]<EOL>reg.name = newname<EOL>self.qregs[newname] = reg<EOL>self.qregs.pop(regname, None)<EOL><DEDENT>for node in self._multi_graph.nodes():<EOL><INDENT>if node.type == "<STR_LIT>" or node.type == "<STR_LIT>":<EOL><INDENT>if node.name and regname in node.name:<EOL><INDENT>node.name = newname<EOL><DEDENT><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>qa = []<EOL>for a in node.qargs:<EOL><INDENT>if a[<NUM_LIT:0>] == regname:<EOL><INDENT>a = (newname, a[<NUM_LIT:1>])<EOL><DEDENT>qa.append(a)<EOL><DEDENT>node.qargs = qa<EOL>ca = []<EOL>for a in node.cargs:<EOL><INDENT>if a[<NUM_LIT:0>] == regname:<EOL><INDENT>a = (newname, a[<NUM_LIT:1>])<EOL><DEDENT>ca.append(a)<EOL><DEDENT>node.cargs = ca<EOL>if node.condition is not None:<EOL><INDENT>if node.condition[<NUM_LIT:0>] == regname:<EOL><INDENT>node.condition = (newname, node.condition[<NUM_LIT:1>])<EOL><DEDENT><DEDENT><DEDENT><DEDENT>for _, _, edge_data in self._multi_graph.edges(data=True):<EOL><INDENT>if regname in edge_data['<STR_LIT:name>']:<EOL><INDENT>edge_data['<STR_LIT:name>'] = re.sub(regname, newname, edge_data['<STR_LIT:name>'])<EOL><DEDENT><DEDENT>

Rename a classical or quantum register throughout the circuit.

        regname = existing register name string
        newname = replacement register name string


for n in self.named_nodes(opname):<EOL><INDENT>self.remove_op_node(n)<EOL><DEDENT>

Remove all operation nodes with the given name.


if not isinstance(qreg, QuantumRegister):<EOL><INDENT>raise DAGCircuitError("<STR_LIT>")<EOL><DEDENT>if qreg.name in self.qregs:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % qreg.name)<EOL><DEDENT>self.qregs[qreg.name] = qreg<EOL>for j in range(qreg.size):<EOL><INDENT>self._add_wire((qreg, j))<EOL><DEDENT>


if not isinstance(creg, ClassicalRegister):<EOL><INDENT>raise DAGCircuitError("<STR_LIT>")<EOL><DEDENT>if creg.name in self.cregs:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % creg.name)<EOL><DEDENT>self.cregs[creg.name] = creg<EOL>for j in range(creg.size):<EOL><INDENT>self._add_wire((creg, j))<EOL><DEDENT>


if wire not in self.wires:<EOL><INDENT>self.wires.append(wire)<EOL>self._max_node_id += <NUM_LIT:1><EOL>input_map_wire = self.input_map[wire] = self._max_node_id<EOL>self._max_node_id += <NUM_LIT:1><EOL>output_map_wire = self._max_node_id<EOL>wire_name = "<STR_LIT>" % (wire[<NUM_LIT:0>].name, wire[<NUM_LIT:1>])<EOL>inp_node = DAGNode(data_dict={'<STR_LIT:type>': '<STR_LIT>', '<STR_LIT:name>': wire_name, '<STR_LIT>': wire},<EOL>nid=input_map_wire)<EOL>outp_node = DAGNode(data_dict={'<STR_LIT:type>': '<STR_LIT>', '<STR_LIT:name>': wire_name, '<STR_LIT>': wire},<EOL>nid=output_map_wire)<EOL>self._id_to_node[input_map_wire] = inp_node<EOL>self._id_to_node[output_map_wire] = outp_node<EOL>self.input_map[wire] = inp_node<EOL>self.output_map[wire] = outp_node<EOL>self._multi_graph.add_node(inp_node)<EOL>self._multi_graph.add_node(outp_node)<EOL>self._multi_graph.add_edge(inp_node,<EOL>outp_node)<EOL>self._multi_graph.adj[inp_node][outp_node][<NUM_LIT:0>]["<STR_LIT:name>"]= "<STR_LIT>" % (wire[<NUM_LIT:0>].name, wire[<NUM_LIT:1>])<EOL>self._multi_graph.adj[inp_node][outp_node][<NUM_LIT:0>]["<STR_LIT>"]= wire<EOL><DEDENT>else:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % (wire,))<EOL><DEDENT>

Add a qubit or bit to the circuit.

        Args:
            wire (tuple): (Register,int) containing a register instance and index
            This adds a pair of in and out nodes connected by an edge.

        Raises:
            DAGCircuitError: if trying to add duplicate wire


def _check_condition(self, name, condition):

<EOL>if condition is not None and condition[<NUM_LIT:0>].name not in self.cregs:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % name)<EOL><DEDENT>

Verify that the condition is valid.

        Args:
            name (string): used for error reporting
            condition (tuple or None): a condition tuple (ClassicalRegister,int)

        Raises:
            DAGCircuitError: if conditioning on an invalid register


<EOL>for wire in args:<EOL><INDENT>if wire not in amap:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" %<EOL>(wire[<NUM_LIT:0>].name, wire[<NUM_LIT:1>]))<EOL><DEDENT><DEDENT>

Check the values of a list of (qu)bit arguments.

        For each element of args, check that amap contains it.

        Args:
            args (list): (register,idx) tuples
            amap (dict): a dictionary keyed on (register,idx) tuples

        Raises:
            DAGCircuitError: if a qubit is not contained in amap


all_bits = []<EOL>if cond is not None:<EOL><INDENT>all_bits.extend([(cond[<NUM_LIT:0>], j) for j in range(self.cregs[cond[<NUM_LIT:0>].name].size)])<EOL><DEDENT>return all_bits<EOL>

Return a list of bits in the given condition.

        Args:
            cond (tuple or None): optional condition (ClassicalRegister, int)

        Returns:
            list[(ClassicalRegister, idx)]: list of bits


def _add_op_node(self, op, qargs, cargs, condition=None):

node_properties = {<EOL>"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT>": op,<EOL>"<STR_LIT:name>": op.name,<EOL>"<STR_LIT>": qargs,<EOL>"<STR_LIT>": cargs,<EOL>"<STR_LIT>": condition<EOL>}<EOL>self._max_node_id += <NUM_LIT:1><EOL>new_node = DAGNode(data_dict=node_properties, nid=self._max_node_id)<EOL>self._multi_graph.add_node(new_node)<EOL>self._id_to_node[self._max_node_id] = new_node<EOL>

Add a new operation node to the graph and assign properties.

        Args:
            op (Instruction): the operation associated with the DAG node
            qargs (list): list of quantum wires to attach to.
            cargs (list): list of classical wires to attach to.
            condition (tuple or None): optional condition (ClassicalRegister, int)


def apply_operation_back(self, op, qargs=None, cargs=None, condition=None):

qargs = qargs or []<EOL>cargs = cargs or []<EOL>all_cbits = self._bits_in_condition(condition)<EOL>all_cbits.extend(cargs)<EOL>self._check_condition(op.name, condition)<EOL>self._check_bits(qargs, self.output_map)<EOL>self._check_bits(all_cbits, self.output_map)<EOL>self._add_op_node(op, qargs, cargs, condition)<EOL>al = [qargs, all_cbits]<EOL>for q in itertools.chain(*al):<EOL><INDENT>ie = list(self._multi_graph.predecessors(self.output_map[q]))<EOL>if len(ie) != <NUM_LIT:1>:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>")<EOL><DEDENT>self._multi_graph.add_edge(ie[<NUM_LIT:0>], self._id_to_node[self._max_node_id],<EOL>name="<STR_LIT>" % (q[<NUM_LIT:0>].name, q[<NUM_LIT:1>]), wire=q)<EOL>self._multi_graph.remove_edge(ie[<NUM_LIT:0>], self.output_map[q])<EOL>self._multi_graph.add_edge(self._id_to_node[self._max_node_id], self.output_map[q],<EOL>name="<STR_LIT>" % (q[<NUM_LIT:0>].name, q[<NUM_LIT:1>]), wire=q)<EOL><DEDENT>return self._id_to_node[self._max_node_id]<EOL>

Apply an operation to the output of the circuit.

        Args:
            op (Instruction): the operation associated with the DAG node
            qargs (list[tuple]): qubits that op will be applied to
            cargs (list[tuple]): cbits that op will be applied to
            condition (tuple or None): optional condition (ClassicalRegister, int)

        Returns:
            DAGNode: the current max node

        Raises:
            DAGCircuitError: if a leaf node is connected to multiple outputs


def apply_operation_front(self, op, qargs, cargs, condition=None):

all_cbits = self._bits_in_condition(condition)<EOL>all_cbits.extend(cargs)<EOL>self._check_condition(op.name, condition)<EOL>self._check_bits(qargs, self.input_map)<EOL>self._check_bits(all_cbits, self.input_map)<EOL>self._add_op_node(op, qargs, cargs, condition)<EOL>al = [qargs, all_cbits]<EOL>for q in itertools.chain(*al):<EOL><INDENT>ie = list(self._multi_graph.successors(self.input_map[q]))<EOL>if len(ie) != <NUM_LIT:1>:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>")<EOL><DEDENT>self._multi_graph.add_edge(self._id_to_node[self._max_node_id], ie[<NUM_LIT:0>],<EOL>name="<STR_LIT>" % (q[<NUM_LIT:0>].name, q[<NUM_LIT:1>]), wire=q)<EOL>self._multi_graph.remove_edge(self.input_map[q], ie[<NUM_LIT:0>])<EOL>self._multi_graph.add_edge(self.input_map[q], self._id_to_node[self._max_node_id],<EOL>name="<STR_LIT>" % (q[<NUM_LIT:0>].name, q[<NUM_LIT:1>]), wire=q)<EOL><DEDENT>return self._id_to_node[self._max_node_id]<EOL>

Apply an operation to the input of the circuit.

        Args:
            op (Instruction): the operation associated with the DAG node
            qargs (list[tuple]): qubits that op will be applied to
            cargs (list[tuple]): cbits that op will be applied to
            condition (tuple or None): optional condition (ClassicalRegister, value)

        Returns:
            DAGNode: the current max node

        Raises:
            DAGCircuitError: if initial nodes connected to multiple out edges


def _check_edgemap_registers(self, edge_map, keyregs, valregs, valreg=True):

<EOL>add_regs = set()<EOL>reg_frag_chk = {}<EOL>for v in keyregs.values():<EOL><INDENT>reg_frag_chk[v] = {j: False for j in range(len(v))}<EOL><DEDENT>for k in edge_map.keys():<EOL><INDENT>if k[<NUM_LIT:0>].name in keyregs:<EOL><INDENT>reg_frag_chk[k[<NUM_LIT:0>]][k[<NUM_LIT:1>]] = True<EOL><DEDENT><DEDENT>for k, v in reg_frag_chk.items():<EOL><INDENT>s = set(v.values())<EOL>if len(s) == <NUM_LIT:2>:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % k)<EOL><DEDENT>elif s == set([False]):<EOL><INDENT>if k in self.qregs.values() or k in self.cregs.values():<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % k)<EOL><DEDENT>else:<EOL><INDENT>add_regs.add(k)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if valreg:<EOL><INDENT>if not edge_map[(k, <NUM_LIT:0>)][<NUM_LIT:0>].name in valregs:<EOL><INDENT>size = max(map(lambda x: x[<NUM_LIT:1>],<EOL>filter(lambda x: x[<NUM_LIT:0>] == edge_map[(k, <NUM_LIT:0>)][<NUM_LIT:0>],<EOL>edge_map.values())))<EOL>qreg = QuantumRegister(size + <NUM_LIT:1>, edge_map[(k, <NUM_LIT:0>)][<NUM_LIT:0>].name)<EOL>add_regs.add(qreg)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return add_regs<EOL>

Check that wiremap neither fragments nor leaves duplicate registers.

        1. There are no fragmented registers. A register in keyregs
        is fragmented if not all of its (qu)bits are renamed by edge_map.
        2. There are no duplicate registers. A register is duplicate if
        it appears in both self and keyregs but not in edge_map.

        Args:
            edge_map (dict): map from (reg,idx) in keyregs to (reg,idx) in valregs
            keyregs (dict): a map from register names to Register objects
            valregs (dict): a map from register names to Register objects
            valreg (bool): if False the method ignores valregs and does not
                add regs for bits in the edge_map image that don't appear in valregs

        Returns:
            set(Register): the set of regs to add to self

        Raises:
            DAGCircuitError: if the wiremap fragments, or duplicates exist


def _check_wiremap_validity(self, wire_map, keymap, valmap):

for k, v in wire_map.items():<EOL><INDENT>kname = "<STR_LIT>" % (k[<NUM_LIT:0>].name, k[<NUM_LIT:1>])<EOL>vname = "<STR_LIT>" % (v[<NUM_LIT:0>].name, v[<NUM_LIT:1>])<EOL>if k not in keymap:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % kname)<EOL><DEDENT>if v not in valmap:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % vname)<EOL><DEDENT>if type(k) is not type(v):<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" %<EOL>(kname, vname))<EOL><DEDENT><DEDENT>

Check that the wiremap is consistent.

        Check that the wiremap refers to valid wires and that
        those wires have consistent types.

        Args:
            wire_map (dict): map from (register,idx) in keymap to
                (register,idx) in valmap
            keymap (dict): a map whose keys are wire_map keys
            valmap (dict): a map whose keys are wire_map values

        Raises:
            DAGCircuitError: if wire_map not valid


def _map_condition(self, wire_map, condition):

if condition is None:<EOL><INDENT>new_condition = None<EOL><DEDENT>else:<EOL><INDENT>bit0 = (condition[<NUM_LIT:0>], <NUM_LIT:0>)<EOL>new_condition = (wire_map.get(bit0, bit0)[<NUM_LIT:0>], condition[<NUM_LIT:1>])<EOL><DEDENT>return new_condition<EOL>

Use the wire_map dict to change the condition tuple's creg name.

        Args:
            wire_map (dict): a map from wires to wires
            condition (tuple): (ClassicalRegister,int)
        Returns:
            tuple(ClassicalRegister,int): new condition


def extend_back(self, dag, edge_map=None):

edge_map = edge_map or {}<EOL>for qreg in dag.qregs.values():<EOL><INDENT>if qreg.name not in self.qregs:<EOL><INDENT>self.add_qreg(QuantumRegister(qreg.size, qreg.name))<EOL><DEDENT>edge_map.update([(qbit, qbit) for qbit in qreg if qbit not in edge_map])<EOL><DEDENT>for creg in dag.cregs.values():<EOL><INDENT>if creg.name not in self.cregs:<EOL><INDENT>self.add_creg(ClassicalRegister(creg.size, creg.name))<EOL><DEDENT>edge_map.update([(cbit, cbit) for cbit in creg if cbit not in edge_map])<EOL><DEDENT>self.compose_back(dag, edge_map)<EOL>

Add `dag` at the end of `self`, using `edge_map`.


def compose_back(self, input_circuit, edge_map=None):

edge_map = edge_map or {}<EOL>if len(set(edge_map.values())) != len(edge_map):<EOL><INDENT>raise DAGCircuitError("<STR_LIT>")<EOL><DEDENT>add_qregs = self._check_edgemap_registers(edge_map,<EOL>input_circuit.qregs,<EOL>self.qregs)<EOL>for qreg in add_qregs:<EOL><INDENT>self.add_qreg(qreg)<EOL><DEDENT>add_cregs = self._check_edgemap_registers(edge_map,<EOL>input_circuit.cregs,<EOL>self.cregs)<EOL>for creg in add_cregs:<EOL><INDENT>self.add_creg(creg)<EOL><DEDENT>self._check_wiremap_validity(edge_map, input_circuit.input_map,<EOL>self.output_map)<EOL>for nd in input_circuit.topological_nodes():<EOL><INDENT>if nd.type == "<STR_LIT>":<EOL><INDENT>m_wire = edge_map.get(nd.wire, nd.wire)<EOL>if m_wire not in self.output_map:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % (m_wire[<NUM_LIT:0>].name, m_wire[<NUM_LIT:1>]))<EOL><DEDENT>if nd.wire not in input_circuit.wires:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>"<EOL>% (nd.wire[<NUM_LIT:0>].name, nd.wire[<NUM_LIT:1>]))<EOL><DEDENT><DEDENT>elif nd.type == "<STR_LIT>":<EOL><INDENT>pass<EOL><DEDENT>elif nd.type == "<STR_LIT>":<EOL><INDENT>condition = self._map_condition(edge_map, nd.condition)<EOL>self._check_condition(nd.name, condition)<EOL>m_qargs = list(map(lambda x: edge_map.get(x, x), nd.qargs))<EOL>m_cargs = list(map(lambda x: edge_map.get(x, x), nd.cargs))<EOL>self.apply_operation_back(nd.op, m_qargs, m_cargs, condition)<EOL><DEDENT>else:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % nd.type)<EOL><DEDENT><DEDENT>

Apply the input circuit to the output of this circuit.

        The two bases must be "compatible" or an exception occurs.
        A subset of input qubits of the input circuit are mapped
        to a subset of output qubits of this circuit.

        Args:
            input_circuit (DAGCircuit): circuit to append
            edge_map (dict): map {(Register, int): (Register, int)}
                from the output wires of input_circuit to input wires
                of self.

        Raises:
            DAGCircuitError: if missing, duplicate or incosistent wire


def compose_front(self, input_circuit, edge_map=None):

edge_map = edge_map or {}<EOL>if len(set(edge_map.values())) != len(edge_map):<EOL><INDENT>raise DAGCircuitError("<STR_LIT>")<EOL><DEDENT>add_qregs = self._check_edgemap_registers(edge_map,<EOL>input_circuit.qregs,<EOL>self.qregs)<EOL>for qreg in add_qregs:<EOL><INDENT>self.add_qreg(qreg)<EOL><DEDENT>add_cregs = self._check_edgemap_registers(edge_map,<EOL>input_circuit.cregs,<EOL>self.cregs)<EOL>for creg in add_cregs:<EOL><INDENT>self.add_creg(creg)<EOL><DEDENT>self._check_wiremap_validity(edge_map, input_circuit.output_map,<EOL>self.input_map)<EOL>for nd in reversed(list(input_circuit.topological_nodes())):<EOL><INDENT>if nd.type == "<STR_LIT>":<EOL><INDENT>m_name = edge_map.get(nd.wire, nd.wire)<EOL>if m_name not in self.input_map:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % (m_name[<NUM_LIT:0>].name, m_name[<NUM_LIT:1>]))<EOL><DEDENT>if nd.wire not in input_circuit.wires:<EOL><INDENT>raise DAGCircuitError(<EOL>"<STR_LIT>"<EOL>% (nd.wire[<NUM_LIT:0>].name, nd.wire[<NUM_LIT:1>]))<EOL><DEDENT><DEDENT>elif nd.type == "<STR_LIT>":<EOL><INDENT>pass<EOL><DEDENT>elif nd.type == "<STR_LIT>":<EOL><INDENT>condition = self._map_condition(edge_map, nd["<STR_LIT>"])<EOL>self._check_condition(nd.name, condition)<EOL>m_qargs = list(map(lambda x: edge_map.get(x, x), nd.qargs))<EOL>m_cargs = list(map(lambda x: edge_map.get(x, x), nd.cargs))<EOL>self.apply_operation_front(nd.op, m_qargs, m_cargs, condition)<EOL><DEDENT>else:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % nd.type)<EOL><DEDENT><DEDENT>

Apply the input circuit to the input of this circuit.

        The two bases must be "compatible" or an exception occurs.
        A subset of output qubits of the input circuit are mapped
        to a subset of input qubits of this circuit.

        Args:
            input_circuit (DAGCircuit): circuit to append
            edge_map (dict): map {(Register, int): (Register, int)}
                from the output wires of input_circuit to input wires
                of self.

        Raises:
            DAGCircuitError: missing, duplicate or inconsistent wire


return self._multi_graph.order() - <NUM_LIT:2> * len(self.wires)<EOL>


if not nx.is_directed_acyclic_graph(self._multi_graph):<EOL><INDENT>raise DAGCircuitError("<STR_LIT>")<EOL><DEDENT>depth = nx.dag_longest_path_length(self._multi_graph) - <NUM_LIT:1><EOL>return depth if depth != -<NUM_LIT:1> else <NUM_LIT:0><EOL>

Return the circuit depth.
        Returns:
            int: the circuit depth
        Raises:
            DAGCircuitError: if not a directed acyclic graph


return len(self.wires) - self.num_cbits()<EOL>

Return the total number of qubits used by the circuit.


return sum(creg.size for creg in self.cregs.values())<EOL>

Return the total number of bits used by the circuit.


return nx.number_weakly_connected_components(self._multi_graph)<EOL>

Compute how many components the circuit can decompose into.


warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>

Deprecated. use qiskit.converters.dag_to_circuit() then call
        qasm() on the obtained QuantumCircuit instance.


def _check_wires_list(self, wires, node):

if len(set(wires)) != len(wires):<EOL><INDENT>raise DAGCircuitError("<STR_LIT>")<EOL><DEDENT>wire_tot = len(node.qargs) + len(node.cargs)<EOL>if node.condition is not None:<EOL><INDENT>wire_tot += node.condition[<NUM_LIT:0>].size<EOL><DEDENT>if len(wires) != wire_tot:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>"<EOL>% (wire_tot, len(wires)))<EOL><DEDENT>

Check that a list of wires is compatible with a node to be replaced.

        - no duplicate names
        - correct length for operation
        Raise an exception otherwise.

        Args:
            wires (list[register, index]): gives an order for (qu)bits
                in the input circuit that is replacing the node.
            node (DAGNode): a node in the dag

        Raises:
            DAGCircuitError: if check doesn't pass.


pred_map = {e[<NUM_LIT:2>]['<STR_LIT>']: e[<NUM_LIT:0>] for e in<EOL>self._multi_graph.in_edges(nbunch=node, data=True)}<EOL>succ_map = {e[<NUM_LIT:2>]['<STR_LIT>']: e[<NUM_LIT:1>] for e in<EOL>self._multi_graph.out_edges(nbunch=node, data=True)}<EOL>return pred_map, succ_map<EOL>

Return predecessor and successor dictionaries.

        Args:
            node (DAGNode): reference to multi_graph node

        Returns:
            tuple(dict): tuple(predecessor_map, successor_map)
                These map from wire (Register, int) to predecessor (successor)
                nodes of n.


def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,<EOL>wire_map):

full_pred_map = {}<EOL>full_succ_map = {}<EOL>for w in input_circuit.input_map:<EOL><INDENT>if w in wire_map:<EOL><INDENT>full_pred_map[wire_map[w]] = pred_map[wire_map[w]]<EOL>full_succ_map[wire_map[w]] = succ_map[wire_map[w]]<EOL><DEDENT>else:<EOL><INDENT>full_succ_map[w] = self.output_map[w]<EOL>full_pred_map[w] = self._multi_graph.predecessors(<EOL>self.output_map[w])[<NUM_LIT:0>]<EOL>if len(list(self._multi_graph.predecessors(self.output_map[w]))) != <NUM_LIT:1>:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>"<EOL>"<STR_LIT>" % (w[<NUM_LIT:0>], w[<NUM_LIT:1>]))<EOL><DEDENT><DEDENT><DEDENT>return full_pred_map, full_succ_map<EOL>

Map all wires of the input circuit.

        Map all wires of the input circuit to predecessor and
        successor nodes in self, keyed on wires in self.

        Args:
            pred_map (dict): comes from _make_pred_succ_maps
            succ_map (dict): comes from _make_pred_succ_maps
            input_circuit (DAGCircuit): the input circuit
            wire_map (dict): the map from wires of input_circuit to wires of self

        Returns:
            tuple: full_pred_map, full_succ_map (dict, dict)

        Raises:
            DAGCircuitError: if more than one predecessor for output nodes


return nx.lexicographical_topological_sort(self._multi_graph,<EOL>key=lambda x: str(x.qargs))<EOL>

Yield nodes in topological order.

Returns:
    generator(DAGNode): node in topological order


return (nd for nd in self.topological_nodes() if nd.type == '<STR_LIT>')<EOL>

Yield op nodes in topological order.

Returns:
    generator(DAGnode): op node in topological order


def substitute_node_with_dag(self, node, input_dag, wires=None):

if isinstance(node, int):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>node = self._id_to_node[node]<EOL><DEDENT>condition = node.condition<EOL>if condition:<EOL><INDENT>input_dag.add_creg(condition[<NUM_LIT:0>])<EOL>to_replay = []<EOL>for sorted_node in input_dag.topological_nodes():<EOL><INDENT>if sorted_node.type == "<STR_LIT>":<EOL><INDENT>sorted_node.op.control = condition<EOL>to_replay.append(sorted_node)<EOL><DEDENT><DEDENT>for input_node in input_dag.op_nodes():<EOL><INDENT>input_dag.remove_op_node(input_node)<EOL><DEDENT>for replay_node in to_replay:<EOL><INDENT>input_dag.apply_operation_back(replay_node.op, replay_node.qargs,<EOL>replay_node.cargs, condition=condition)<EOL><DEDENT><DEDENT>if wires is None:<EOL><INDENT>qwires = [w for w in input_dag.wires if isinstance(w[<NUM_LIT:0>], QuantumRegister)]<EOL>cwires = [w for w in input_dag.wires if isinstance(w[<NUM_LIT:0>], ClassicalRegister)]<EOL>wires = qwires + cwires<EOL><DEDENT>self._check_wires_list(wires, node)<EOL>proxy_map = {w: QuantumRegister(<NUM_LIT:1>, '<STR_LIT>') for w in wires}<EOL>add_qregs = self._check_edgemap_registers(proxy_map,<EOL>input_dag.qregs,<EOL>{}, False)<EOL>for qreg in add_qregs:<EOL><INDENT>self.add_qreg(qreg)<EOL><DEDENT>add_cregs = self._check_edgemap_registers(proxy_map,<EOL>input_dag.cregs,<EOL>{}, False)<EOL>for creg in add_cregs:<EOL><INDENT>self.add_creg(creg)<EOL><DEDENT>if node.type != "<STR_LIT>":<EOL><INDENT>raise DAGCircuitError("<STR_LIT>"<EOL>% node.type)<EOL><DEDENT>condition_bit_list = self._bits_in_condition(node.condition)<EOL>wire_map = {k: v for k, v in zip(wires,<EOL>[i for s in [node.qargs,<EOL>node.cargs,<EOL>condition_bit_list]<EOL>for i in s])}<EOL>self._check_wiremap_validity(wire_map, wires, self.input_map)<EOL>pred_map, succ_map = self._make_pred_succ_maps(node)<EOL>full_pred_map, full_succ_map = self._full_pred_succ_maps(pred_map, succ_map,<EOL>input_dag, wire_map)<EOL>self._multi_graph.remove_node(node)<EOL>for sorted_node in input_dag.topological_op_nodes():<EOL><INDENT>condition = self._map_condition(wire_map, sorted_node.condition)<EOL>m_qargs = list(map(lambda x: wire_map.get(x, x),<EOL>sorted_node.qargs))<EOL>m_cargs = list(map(lambda x: wire_map.get(x, x),<EOL>sorted_node.cargs))<EOL>self._add_op_node(sorted_node.op, m_qargs, m_cargs, condition)<EOL>all_cbits = self._bits_in_condition(condition)<EOL>all_cbits.extend(m_cargs)<EOL>al = [m_qargs, all_cbits]<EOL>for q in itertools.chain(*al):<EOL><INDENT>self._multi_graph.add_edge(full_pred_map[q],<EOL>self._id_to_node[self._max_node_id],<EOL>name="<STR_LIT>" % (q[<NUM_LIT:0>].name, q[<NUM_LIT:1>]),<EOL>wire=q)<EOL>full_pred_map[q] = self._id_to_node[self._max_node_id]<EOL><DEDENT><DEDENT>for w in full_pred_map:<EOL><INDENT>self._multi_graph.add_edge(full_pred_map[w],<EOL>full_succ_map[w],<EOL>name="<STR_LIT>" % (w[<NUM_LIT:0>].name, w[<NUM_LIT:1>]),<EOL>wire=w)<EOL>o_pred = list(self._multi_graph.predecessors(self.output_map[w]))<EOL>if len(o_pred) > <NUM_LIT:1>:<EOL><INDENT>if len(o_pred) != <NUM_LIT:2>:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>")<EOL><DEDENT>p = [x for x in o_pred if x != full_pred_map[w]]<EOL>if len(p) != <NUM_LIT:1>:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>")<EOL><DEDENT>self._multi_graph.remove_edge(p[<NUM_LIT:0>], self.output_map[w])<EOL><DEDENT><DEDENT>

Replace one node with dag.

        Args:
            node (DAGNode): node to substitute
            input_dag (DAGCircuit): circuit that will substitute the node
            wires (list[(Register, index)]): gives an order for (qu)bits
                in the input circuit. This order gets matched to the node wires
                by qargs first, then cargs, then conditions.

        Raises:
            DAGCircuitError: if met with unexpected predecessor/successors


return self._multi_graph.nodes[node_id]<EOL>

Get the node in the dag.

        Args:
            node_id(int): Node identifier.

        Returns:
            node: the node.


for node in self._multi_graph.nodes:<EOL><INDENT>yield node<EOL><DEDENT>

Iterator for node values.

        Yield:
            node: the node.


for source_node, dest_node, edge_data in self._multi_graph.edges(nodes, data=True):<EOL><INDENT>yield source_node, dest_node, edge_data<EOL><DEDENT>


def get_op_nodes(self, op=None, data=False):

warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>if data:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL><DEDENT>nodes = []<EOL>for node in self._multi_graph.nodes():<EOL><INDENT>if node.type == "<STR_LIT>":<EOL><INDENT>if op is None or isinstance(node.op, op):<EOL><INDENT>nodes.append((node._node_id, node.data_dict))<EOL><DEDENT><DEDENT><DEDENT>if not data:<EOL><INDENT>nodes = [n[<NUM_LIT:0>] for n in nodes]<EOL><DEDENT>return nodes<EOL>


nodes = []<EOL>for node in self._multi_graph.nodes():<EOL><INDENT>if node.type == "<STR_LIT>":<EOL><INDENT>if op is None or isinstance(node.op, op):<EOL><INDENT>nodes.append(node)<EOL><DEDENT><DEDENT><DEDENT>return nodes<EOL>

Get the list of "op" nodes in the dag.

        Args:
            op (Type): Instruction subclass op nodes to return. if op=None, return
                all op nodes.
        Returns:
            list[DAGNode]: the list of node ids containing the given op.


warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>if data:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL><DEDENT>nodes = []<EOL>for node in self.op_nodes():<EOL><INDENT>if isinstance(node.op, Gate):<EOL><INDENT>nodes.append((node._node_id, node))<EOL><DEDENT><DEDENT>if not data:<EOL><INDENT>nodes = [n[<NUM_LIT:0>] for n in nodes]<EOL><DEDENT>return nodes<EOL>


nodes = []<EOL>for node in self.op_nodes():<EOL><INDENT>if isinstance(node.op, Gate):<EOL><INDENT>nodes.append(node)<EOL><DEDENT><DEDENT>return nodes<EOL>

Get the list of gate nodes in the dag.

        Returns:
            list: the list of node ids that represent gates.


warnings.warn('<STR_LIT>',<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>named_nodes = []<EOL>for node in self._multi_graph.nodes():<EOL><INDENT>if node.type == '<STR_LIT>' and node.op.name in names:<EOL><INDENT>named_nodes.append(node._node_id)<EOL><DEDENT><DEDENT>return named_nodes<EOL>


named_nodes = []<EOL>for node in self._multi_graph.nodes():<EOL><INDENT>if node.type == '<STR_LIT>' and node.op.name in names:<EOL><INDENT>named_nodes.append(node)<EOL><DEDENT><DEDENT>return named_nodes<EOL>

Get the set of "op" nodes with the given name.


warnings.warn('<STR_LIT>',<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>two_q_nodes = []<EOL>for node in self._multi_graph.nodes():<EOL><INDENT>if node.type == '<STR_LIT>' and len(node.qargs) == <NUM_LIT:2>:<EOL><INDENT>two_q_nodes.append(node.data_dict)<EOL><DEDENT><DEDENT>return two_q_nodes<EOL>


two_q_gates = []<EOL>for node in self.gate_nodes():<EOL><INDENT>if len(node.qargs) == <NUM_LIT:2>:<EOL><INDENT>two_q_gates.append(node)<EOL><DEDENT><DEDENT>return two_q_gates<EOL>

Get list of 2-qubit gates. Ignore snapshot, barriers, and the like.


warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>three_q_nodes = []<EOL>for node in self._multi_graph.nodes():<EOL><INDENT>if node.type == '<STR_LIT>' and len(node.qargs) >= <NUM_LIT:3>:<EOL><INDENT>three_q_nodes.append((node._node_id, node.data_dict))<EOL><DEDENT><DEDENT>return three_q_nodes<EOL>


three_q_gates = []<EOL>for node in self.gate_nodes():<EOL><INDENT>if len(node.qargs) >= <NUM_LIT:3>:<EOL><INDENT>three_q_gates.append(node)<EOL><DEDENT><DEDENT>return three_q_gates<EOL>

Get list of 3-or-more-qubit gates: (id, data).


if isinstance(node, int):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>node = self._id_to_node[node]<EOL><DEDENT>return self._multi_graph.successors(node)<EOL>

Returns list of the successors of a node as DAGNodes.


if isinstance(node, int):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>node = self._id_to_node[node]<EOL><DEDENT>return self._multi_graph.predecessors(node)<EOL>

Returns list of the predecessors of a node as DAGNodes.


predecessors = []<EOL>for predecessor in self.predecessors(node):<EOL><INDENT>if isinstance(self._multi_graph.get_edge_data(predecessor, node, key=<NUM_LIT:0>)['<STR_LIT>'][<NUM_LIT:0>],<EOL>QuantumRegister):<EOL><INDENT>predecessors.append(predecessor)<EOL><DEDENT><DEDENT>return predecessors<EOL>

Returns list of the predecessors of a node that are
        connected by a quantum edge as DAGNodes.


if isinstance(node, int):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>node = self._id_to_node[node]<EOL><DEDENT>return nx.ancestors(self._multi_graph, node)<EOL>

Returns set of the ancestors of a node as DAGNodes.


if isinstance(node, int):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>node = self._id_to_node[node]<EOL><DEDENT>return nx.descendants(self._multi_graph, node)<EOL>

Returns set of the descendants of a node as DAGNodes.


if isinstance(node, int):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>node = self._id_to_node[node]<EOL><DEDENT>return nx.bfs_successors(self._multi_graph, node)<EOL>

Returns an iterator of tuples of (DAGNode, [DAGNodes]) where the DAGNode is the current node
and [DAGNode] is its successors in  BFS order.


if isinstance(node, int):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>node = self._id_to_node[node]<EOL><DEDENT>successors = []<EOL>for successor in self.successors(node):<EOL><INDENT>if isinstance(self._multi_graph.get_edge_data(<EOL>node, successor, key=<NUM_LIT:0>)['<STR_LIT>'][<NUM_LIT:0>],<EOL>QuantumRegister):<EOL><INDENT>successors.append(successor)<EOL><DEDENT><DEDENT>return successors<EOL>

Returns list of the successors of a node that are
        connected by a quantum edge as DAGNodes.


if isinstance(node, int):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>node = self._id_to_node[node]<EOL><DEDENT>if node.type != '<STR_LIT>':<EOL><INDENT>raise DAGCircuitError('<STR_LIT>'<EOL>'<STR_LIT>' % node.type)<EOL><DEDENT>pred_map, succ_map = self._make_pred_succ_maps(node)<EOL>self._multi_graph.remove_node(node)<EOL>for w in pred_map.keys():<EOL><INDENT>self._multi_graph.add_edge(pred_map[w], succ_map[w],<EOL>name="<STR_LIT>" % (w[<NUM_LIT:0>].name, w[<NUM_LIT:1>]), wire=w)<EOL><DEDENT>

Remove an operation node n.

        Add edges from predecessors to successors.


if isinstance(node, int):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>node = self._id_to_node[node]<EOL><DEDENT>anc = nx.ancestors(self._multi_graph, node)<EOL>for anc_node in anc:<EOL><INDENT>if anc_node.type == "<STR_LIT>":<EOL><INDENT>self.remove_op_node(anc_node)<EOL><DEDENT><DEDENT>

Remove all of the ancestor operation nodes of node.


if isinstance(node, int):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>node = self._id_to_node[node]<EOL><DEDENT>desc = nx.descendants(self._multi_graph, node)<EOL>for desc_node in desc:<EOL><INDENT>if desc_node.type == "<STR_LIT>":<EOL><INDENT>self.remove_op_node(desc_node)<EOL><DEDENT><DEDENT>

Remove all of the descendant operation nodes of node.


if isinstance(node, int):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>node = self._id_to_node[node]<EOL><DEDENT>anc = nx.ancestors(self._multi_graph, node)<EOL>comp = list(set(self._multi_graph.nodes()) - set(anc))<EOL>for n in comp:<EOL><INDENT>if n.type == "<STR_LIT>":<EOL><INDENT>self.remove_op_node(n)<EOL><DEDENT><DEDENT>

Remove all of the non-ancestors operation nodes of node.


if isinstance(node, int):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>node = self._id_to_node[node]<EOL><DEDENT>dec = nx.descendants(self._multi_graph, node)<EOL>comp = list(set(self._multi_graph.nodes()) - set(dec))<EOL>for n in comp:<EOL><INDENT>if n.type == "<STR_LIT>":<EOL><INDENT>self.remove_op_node(n)<EOL><DEDENT><DEDENT>

Remove all of the non-descendants operation nodes of node.


graph_layers = self.multigraph_layers()<EOL>try:<EOL><INDENT>next(graph_layers)  <EOL><DEDENT>except StopIteration:<EOL><INDENT>return<EOL><DEDENT>def add_nodes_from(layer, nodes):<EOL><INDENT>"""<STR_LIT>"""<EOL>layer._multi_graph.add_nodes_from(nodes)<EOL><DEDENT>for graph_layer in graph_layers:<EOL><INDENT>op_nodes = [node for node in graph_layer if node.type == "<STR_LIT>"]<EOL>if not op_nodes:<EOL><INDENT>return<EOL><DEDENT>new_layer = DAGCircuit()<EOL>new_layer.name = self.name<EOL>for creg in self.cregs.values():<EOL><INDENT>new_layer.add_creg(creg)<EOL><DEDENT>for qreg in self.qregs.values():<EOL><INDENT>new_layer.add_qreg(qreg)<EOL><DEDENT>add_nodes_from(new_layer, self.input_map.values())<EOL>add_nodes_from(new_layer, self.output_map.values())<EOL>add_nodes_from(new_layer, op_nodes)<EOL>support_list = [<EOL>op_node.qargs<EOL>for op_node in op_nodes<EOL>if op_node.name not in {"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"}<EOL>]<EOL>wires = {self.input_map[wire]: self.output_map[wire]<EOL>for wire in self.wires}<EOL>for op_node in op_nodes:<EOL><INDENT>args = self._bits_in_condition(op_node.condition)+ op_node.cargs + op_node.qargs<EOL>arg_ids = (self.input_map[(arg[<NUM_LIT:0>], arg[<NUM_LIT:1>])] for arg in args)<EOL>for arg_id in arg_ids:<EOL><INDENT>wires[arg_id], wires[op_node] = op_node, wires[arg_id]<EOL><DEDENT><DEDENT>new_layer._multi_graph.add_edges_from(wires.items())<EOL>yield {"<STR_LIT>": new_layer, "<STR_LIT>": support_list}<EOL><DEDENT>

Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.

        A layer is a circuit whose gates act on disjoint qubits, i.e.
        a layer has depth 1. The total number of layers equals the
        circuit depth d. The layers are indexed from 0 to d-1 with the
        earliest layer at index 0. The layers are constructed using a
        greedy algorithm. Each returned layer is a dict containing
        {"graph": circuit graph, "partition": list of qubit lists}.

        TODO: Gates that use the same cbits will end up in different
        layers as this is currently implemented. This may not be
        the desired behavior.


for next_node in self.topological_op_nodes():<EOL><INDENT>new_layer = DAGCircuit()<EOL>for qreg in self.qregs.values():<EOL><INDENT>new_layer.add_qreg(qreg)<EOL><DEDENT>for creg in self.cregs.values():<EOL><INDENT>new_layer.add_creg(creg)<EOL><DEDENT>support_list = []<EOL>op = copy.copy(next_node.op)<EOL>qa = copy.copy(next_node.qargs)<EOL>ca = copy.copy(next_node.cargs)<EOL>co = copy.copy(next_node.condition)<EOL>_ = self._bits_in_condition(co)<EOL>new_layer.apply_operation_back(op, qa, ca, co)<EOL>if next_node.name not in ["<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>support_list.append(list(qa))<EOL><DEDENT>l_dict = {"<STR_LIT>": new_layer, "<STR_LIT>": support_list}<EOL>yield l_dict<EOL><DEDENT>

Yield a layer for all gates of this circuit.

        A serial layer is a circuit with one gate. The layers have the
        same structure as in layers().


predecessor_count = dict()  <EOL>cur_layer = [node for node in self.input_map.values()]<EOL>yield cur_layer<EOL>next_layer = []<EOL>while cur_layer:<EOL><INDENT>for node in cur_layer:<EOL><INDENT>for successor in self._multi_graph.successors(node):<EOL><INDENT>multiplicity = self._multi_graph.number_of_edges(node, successor)<EOL>if successor in predecessor_count:<EOL><INDENT>predecessor_count[successor] -= multiplicity<EOL><DEDENT>else:<EOL><INDENT>predecessor_count[successor] =self._multi_graph.in_degree(successor) - multiplicity<EOL><DEDENT>if predecessor_count[successor] == <NUM_LIT:0>:<EOL><INDENT>next_layer.append(successor)<EOL>del predecessor_count[successor]<EOL><DEDENT><DEDENT><DEDENT>yield next_layer<EOL>cur_layer = next_layer<EOL>next_layer = []<EOL><DEDENT>


group_list = []<EOL>topo_ops = list(self.topological_op_nodes())<EOL>nodes_seen = dict(zip(topo_ops, [False] * len(topo_ops)))<EOL>for node in topo_ops:<EOL><INDENT>if node.name in namelist and node.condition is Noneand not nodes_seen[node]:<EOL><INDENT>group = [node]<EOL>nodes_seen[node] = True<EOL>s = list(self._multi_graph.successors(node))<EOL>while len(s) == <NUM_LIT:1> ands[<NUM_LIT:0>].type == "<STR_LIT>" ands[<NUM_LIT:0>].name in namelist:<EOL><INDENT>group.append(s[<NUM_LIT:0>])<EOL>nodes_seen[s[<NUM_LIT:0>]] = True<EOL>s = list(self._multi_graph.successors(s[<NUM_LIT:0>]))<EOL><DEDENT>if len(group) >= <NUM_LIT:1>:<EOL><INDENT>group_list.append(tuple(group))<EOL><DEDENT><DEDENT><DEDENT>return set(group_list)<EOL>

Return a set of non-conditional runs of "op" nodes with the given names.

        For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
        would produce the tuple of cx nodes as an element of the set returned
        from a call to collect_runs(["cx"]). If instead the cx nodes were
        "cx q[0],q[1]; cx q[1],q[0];", the method would still return the
        pair in a tuple. The namelist can contain names that are not
        in the circuit's basis.

        Nodes must have only one successor to continue the run.


def nodes_on_wire(self, wire, only_ops=False):

current_node = self.input_map.get(wire, None)<EOL>if not current_node:<EOL><INDENT>raise DAGCircuitError('<STR_LIT>'<EOL>% str(wire))<EOL><DEDENT>more_nodes = True<EOL>while more_nodes:<EOL><INDENT>more_nodes = False<EOL>if current_node.type == '<STR_LIT>' or not only_ops:<EOL><INDENT>yield current_node<EOL><DEDENT>for node, edges in self._multi_graph.adj[current_node].items():<EOL><INDENT>if any(wire == edge['<STR_LIT>'] for edge in edges.values()):<EOL><INDENT>current_node = node<EOL>more_nodes = True<EOL>break<EOL><DEDENT><DEDENT><DEDENT>

Iterator for nodes that affect a given wire

Args:
    wire (tuple(Register, index)): the wire to be looked at.
    only_ops (bool): True if only the ops nodes are wanted
                otherwise all nodes are returned.
Yield:
     DAGNode: the successive ops on the given wire

Raises:
    DAGCircuitError: if the given wire doesn't exist in the DAG


op_dict = {}<EOL>for node in self.topological_op_nodes():<EOL><INDENT>name = node.name<EOL>if name not in op_dict:<EOL><INDENT>op_dict[name] = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>op_dict[name] += <NUM_LIT:1><EOL><DEDENT><DEDENT>return op_dict<EOL>

Count the occurrences of operation names.

        Returns a dictionary of counts keyed on the operation name.


summary = {"<STR_LIT:size>": self.size(),<EOL>"<STR_LIT>": self.depth(),<EOL>"<STR_LIT:width>": self.width(),<EOL>"<STR_LIT>": self.num_cbits(),<EOL>"<STR_LIT>": self.num_tensor_factors(),<EOL>"<STR_LIT>": self.count_ops()}<EOL>return summary<EOL>

Return a dictionary of circuit properties.


def __init__(self, data_dict, nid=-<NUM_LIT:1>):

self._node_id = nid<EOL>self.data_dict = data_dict<EOL>


return self.data_dict.get('<STR_LIT:type>')<EOL>

Returns a str which is the type of the node else None


if '<STR_LIT:type>' not in self.data_dict or self.data_dict['<STR_LIT:type>'] != '<STR_LIT>':<EOL><INDENT>raise QiskitError("<STR_LIT>" % (str(self)))<EOL><DEDENT>return self.data_dict.get('<STR_LIT>')<EOL>

Returns the Instruction object corresponding to the op for the node else None


return self.data_dict.get('<STR_LIT:name>')<EOL>

Returns a str which is the name of the node else None


self.data_dict['<STR_LIT:name>'] = new_name<EOL>

Sets the name of the node to be the given value


return self.data_dict.get('<STR_LIT>', [])<EOL>

Returns list of (QuantumRegister, int) tuples where the int is the index
of the qubit else an empty list


self.data_dict['<STR_LIT>'] = new_qargs<EOL>

Sets the qargs to be the given list of qargs


Returns list of (ClassicalRegister, int) tuples where the int is the index
of the cbit else an empty list


return self.data_dict.get('<STR_LIT>')<EOL>

Returns a tuple (ClassicalRegister, int) where the int is the
value of the condition else None


if self.data_dict['<STR_LIT:type>'] not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise QiskitError('<STR_LIT>' % str(self))<EOL><DEDENT>return self.data_dict.get('<STR_LIT>')<EOL>

Returns (Register, int) tuple where the int is the index of
the wire else None


return hash(id(self))<EOL>

Needed for ancestors function, which returns a set
        to be in a set requires the object to be hashable


del self.data_dict[val]<EOL>

Remove the provided value from the dictionary


<EOL>if '<STR_LIT>' == node1.name == node2.name:<EOL><INDENT>return set(node1.qargs) == set(node2.qargs)<EOL><DEDENT>return node1.data_dict == node2.data_dict<EOL>

Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.

Args:
    node1 (DAGNode): A node to compare.
    node2 (DAGNode): The other node to compare.

Return:
    Bool: If node1 == node2


super().__init__(*msg)<EOL>self.msg = '<STR_LIT:U+0020>'.join(msg)<EOL>


return repr(self.msg)<EOL>


qregs = collections.OrderedDict()<EOL>for qreg in dag.qregs.values():<EOL><INDENT>qreg_tmp = QuantumRegister(qreg.size, name=qreg.name)<EOL>qregs[qreg.name] = qreg_tmp<EOL><DEDENT>cregs = collections.OrderedDict()<EOL>for creg in dag.cregs.values():<EOL><INDENT>creg_tmp = ClassicalRegister(creg.size, name=creg.name)<EOL>cregs[creg.name] = creg_tmp<EOL><DEDENT>name = dag.name or None<EOL>circuit = QuantumCircuit(*qregs.values(), *cregs.values(), name=name)<EOL>for node in dag.topological_op_nodes():<EOL><INDENT>qubits = []<EOL>for qubit in node.qargs:<EOL><INDENT>qubits.append(qregs[qubit[<NUM_LIT:0>].name][qubit[<NUM_LIT:1>]])<EOL><DEDENT>clbits = []<EOL>for clbit in node.cargs:<EOL><INDENT>clbits.append(cregs[clbit[<NUM_LIT:0>].name][clbit[<NUM_LIT:1>]])<EOL><DEDENT>if node.condition is None:<EOL><INDENT>control = None<EOL><DEDENT>else:<EOL><INDENT>control = (node.condition[<NUM_LIT:0>], node.condition[<NUM_LIT:1>])<EOL><DEDENT>inst = node.op.copy()<EOL>inst.control = control<EOL>circuit.append(inst, qubits, clbits)<EOL><DEDENT>return circuit<EOL>

Build a ``QuantumCircuit`` object from a ``DAGCircuit``.

    Args:
        dag (DAGCircuit): the input dag.

    Return:
        QuantumCircuit: the circuit representing the input dag.


def circuits_to_qobj(circuits, qobj_header=None,<EOL>qobj_id=None, backend_name=None,<EOL>config=None, shots=None, max_credits=None,<EOL>basis_gates=None,<EOL>coupling_map=None, seed=None, memory=None):

warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning)<EOL>qobj_header = qobj_header or QobjHeader()<EOL>if backend_name:<EOL><INDENT>qobj_header.backend_name = backend_name<EOL><DEDENT>if basis_gates:<EOL><INDENT>warnings.warn('<STR_LIT>', DeprecationWarning)<EOL><DEDENT>if coupling_map:<EOL><INDENT>warnings.warn('<STR_LIT>', DeprecationWarning)<EOL><DEDENT>qobj = assemble(experiments=circuits,<EOL>qobj_id=qobj_id,<EOL>qobj_header=qobj_header,<EOL>shots=shots,<EOL>memory=memory,<EOL>max_credits=max_credits,<EOL>seed_simulator=seed,<EOL>config=config)<EOL>return qobj<EOL>

Convert a list of circuits into a qobj.

    Args:
        circuits (list[QuantumCircuits] or QuantumCircuit): circuits to compile
        qobj_header (QobjHeader): header to pass to the results
        qobj_id (int): TODO: delete after qiskit-terra 0.8
        backend_name (str): TODO: delete after qiskit-terra 0.8
        config (dict): TODO: delete after qiskit-terra 0.8
        shots (int): TODO: delete after qiskit-terra 0.8
        max_credits (int): TODO: delete after qiskit-terra 0.8
        basis_gates (str): TODO: delete after qiskit-terra 0.8
        coupling_map (list): TODO: delete after qiskit-terra 0.8
        seed (int): TODO: delete after qiskit-terra 0.8
        memory (bool): TODO: delete after qiskit-terra 0.8

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


warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>', DeprecationWarning)<EOL>return disassembler._experiments_to_circuits(qobj)<EOL>

Return a list of QuantumCircuit object(s) from a qobj

    Args:
        qobj (Qobj): The Qobj object to convert to QuantumCircuits
    Returns:
        list: A list of QuantumCircuit objects from the qobj


instruction = Instruction(name=circuit.name,<EOL>num_qubits=sum([qreg.size for qreg in circuit.qregs]),<EOL>num_clbits=sum([creg.size for creg in circuit.cregs]),<EOL>params=[])<EOL>instruction.control = None<EOL>def find_bit_position(bit):<EOL><INDENT>"""<STR_LIT>"""<EOL>if isinstance(bit[<NUM_LIT:0>], QuantumRegister):<EOL><INDENT>ordered_regs = circuit.qregs<EOL><DEDENT>else:<EOL><INDENT>ordered_regs = circuit.cregs<EOL><DEDENT>reg_index = ordered_regs.index(bit[<NUM_LIT:0>])<EOL>return sum([reg.size for reg in ordered_regs[:reg_index]]) + bit[<NUM_LIT:1>]<EOL><DEDENT>definition = circuit.data.copy()<EOL>if instruction.num_qubits > <NUM_LIT:0>:<EOL><INDENT>q = QuantumRegister(instruction.num_qubits, '<STR_LIT:q>')<EOL><DEDENT>if instruction.num_clbits > <NUM_LIT:0>:<EOL><INDENT>c = ClassicalRegister(instruction.num_clbits, '<STR_LIT:c>')<EOL><DEDENT>definition = list(map(lambda x:<EOL>(x[<NUM_LIT:0>],<EOL>list(map(lambda y: (q, find_bit_position(y)), x[<NUM_LIT:1>])),<EOL>list(map(lambda y: (c, find_bit_position(y)), x[<NUM_LIT:2>]))), definition))<EOL>instruction.definition = definition<EOL>return instruction<EOL>

Build an ``Instruction`` object from a ``QuantumCircuit``.

    The instruction is anonymous (not tied to a named quantum register),
    and so can be inserted into another circuit. The instruction will
    have the same string name as the circuit.

    Args:
        circuit (QuantumCircuit): the input circuit.

    Return:
        Instruction: an instruction equivalent to the action of the
            input circuit. Upon decomposition, this instruction will
            yield the components comprising the original circuit.


dag = DAGCircuit()<EOL>AstInterpreter(dag)._process_node(ast)<EOL>return dag<EOL>

Build a ``DAGCircuit`` object from an AST ``Node`` object.

    Args:
        ast (Program): a Program Node of an AST (parser's output)

    Return:
        DAGCircuit: the DAG representing an OpenQASM's AST

    Raises:
        QiskitError: if the AST is malformed.


<EOL>self.dag = dag<EOL>self.version = <NUM_LIT:0.0><EOL>self.gates = OrderedDict()<EOL>self.condition = None<EOL>self.arg_stack = [{}]<EOL>self.bit_stack = [{}]<EOL>


<EOL>reg = None<EOL>if node.name in self.dag.qregs:<EOL><INDENT>reg = self.dag.qregs[node.name]<EOL><DEDENT>elif node.name in self.dag.cregs:<EOL><INDENT>reg = self.dag.cregs[node.name]<EOL><DEDENT>else:<EOL><INDENT>raise QiskitError("<STR_LIT>",<EOL>"<STR_LIT>" % node.line,<EOL>"<STR_LIT>" % node.file)<EOL><DEDENT>if node.type == "<STR_LIT>":<EOL><INDENT>return [(reg, node.index)]<EOL><DEDENT>elif node.type == "<STR_LIT:id>":<EOL><INDENT>if not self.bit_stack[-<NUM_LIT:1>]:<EOL><INDENT>return [(reg, j) for j in range(reg.size)]<EOL><DEDENT>else:<EOL><INDENT>if node.name in self.bit_stack[-<NUM_LIT:1>]:<EOL><INDENT>return [self.bit_stack[-<NUM_LIT:1>][node.name]]<EOL><DEDENT>raise QiskitError("<STR_LIT>",<EOL>"<STR_LIT>" % node.line,<EOL>"<STR_LIT>" % node.file)<EOL><DEDENT><DEDENT>return None<EOL>

Process an Id or IndexedId node as a bit or register type.

        Return a list of tuples (Register,index).


name = node.name<EOL>if node.arguments is not None:<EOL><INDENT>args = self._process_node(node.arguments)<EOL><DEDENT>else:<EOL><INDENT>args = []<EOL><DEDENT>bits = [self._process_bit_id(node_element)<EOL>for node_element in node.bitlist.children]<EOL>if name in self.gates:<EOL><INDENT>gargs = self.gates[name]["<STR_LIT:args>"]<EOL>gbits = self.gates[name]["<STR_LIT>"]<EOL>maxidx = max(map(len, bits))<EOL>for idx in range(maxidx):<EOL><INDENT>self.arg_stack.append({gargs[j]: args[j]<EOL>for j in range(len(gargs))})<EOL>element = [idx*x for x in<EOL>[len(bits[j]) > <NUM_LIT:1> for j in range(len(bits))]]<EOL>self.bit_stack.append({gbits[j]: bits[j][element[j]]<EOL>for j in range(len(gbits))})<EOL>self._create_dag_op(name,<EOL>[self.arg_stack[-<NUM_LIT:1>][s].sym() for s in gargs],<EOL>[self.bit_stack[-<NUM_LIT:1>][s] for s in gbits])<EOL>self.arg_stack.pop()<EOL>self.bit_stack.pop()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise QiskitError("<STR_LIT>",<EOL>"<STR_LIT>" % node.line, "<STR_LIT>" % node.file)<EOL><DEDENT>


def _process_gate(self, node, opaque=False):

self.gates[node.name] = {}<EOL>de_gate = self.gates[node.name]<EOL>de_gate["<STR_LIT>"] = True  <EOL>de_gate["<STR_LIT>"] = opaque<EOL>de_gate["<STR_LIT>"] = node.n_args()<EOL>de_gate["<STR_LIT>"] = node.n_bits()<EOL>if node.n_args() > <NUM_LIT:0>:<EOL><INDENT>de_gate["<STR_LIT:args>"] = [element.name for element in node.arguments.children]<EOL><DEDENT>else:<EOL><INDENT>de_gate["<STR_LIT:args>"] = []<EOL><DEDENT>de_gate["<STR_LIT>"] = [c.name for c in node.bitlist.children]<EOL>if opaque:<EOL><INDENT>de_gate["<STR_LIT:body>"] = None<EOL><DEDENT>else:<EOL><INDENT>de_gate["<STR_LIT:body>"] = node.body<EOL><DEDENT>

Process a gate node.

        If opaque is True, process the node as an opaque gate node.


id0 = self._process_bit_id(node.children[<NUM_LIT:0>])<EOL>id1 = self._process_bit_id(node.children[<NUM_LIT:1>])<EOL>if not(len(id0) == len(id1) or len(id0) == <NUM_LIT:1> or len(id1) == <NUM_LIT:1>):<EOL><INDENT>raise QiskitError("<STR_LIT>",<EOL>"<STR_LIT>" % node.line, "<STR_LIT>" % node.file)<EOL><DEDENT>maxidx = max([len(id0), len(id1)])<EOL>for idx in range(maxidx):<EOL><INDENT>if len(id0) > <NUM_LIT:1> and len(id1) > <NUM_LIT:1>:<EOL><INDENT>self.dag.apply_operation_back(CXBase(), [id0[idx], id1[idx]], [], self.condition)<EOL><DEDENT>elif len(id0) > <NUM_LIT:1>:<EOL><INDENT>self.dag.apply_operation_back(CXBase(), [id0[idx], id1[<NUM_LIT:0>]], [], self.condition)<EOL><DEDENT>else:<EOL><INDENT>self.dag.apply_operation_back(CXBase(), [id0[<NUM_LIT:0>], id1[idx]], [], self.condition)<EOL><DEDENT><DEDENT>


id0 = self._process_bit_id(node.children[<NUM_LIT:0>])<EOL>id1 = self._process_bit_id(node.children[<NUM_LIT:1>])<EOL>if len(id0) != len(id1):<EOL><INDENT>raise QiskitError("<STR_LIT>",<EOL>"<STR_LIT>" % node.line, "<STR_LIT>" % node.file)<EOL><DEDENT>for idx, idy in zip(id0, id1):<EOL><INDENT>self.dag.apply_operation_back(Measure(), [idx], [idy], self.condition)<EOL><DEDENT>


creg_name = node.children[<NUM_LIT:0>].name<EOL>creg = self.dag.cregs[creg_name]<EOL>cval = node.children[<NUM_LIT:1>].value<EOL>self.condition = (creg, cval)<EOL>self._process_node(node.children[<NUM_LIT:2>])<EOL>self.condition = None<EOL>


for kid in node.children:<EOL><INDENT>self._process_node(kid)<EOL><DEDENT>

Call process_node for all children of node.


if node.type == "<STR_LIT>":<EOL><INDENT>self._process_children(node)<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>qreg = QuantumRegister(node.index, node.name)<EOL>self.dag.add_qreg(qreg)<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>creg = ClassicalRegister(node.index, node.name)<EOL>self.dag.add_creg(creg)<EOL><DEDENT>elif node.type == "<STR_LIT:id>":<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>elif node.type == "<STR_LIT:int>":<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>return [self._process_bit_id(node_children)<EOL>for node_children in node.children]<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>return [self._process_bit_id(m) for m in node.children]<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>self._process_gate(node)<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>self._process_custom_unitary(node)<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>args = self._process_node(node.children[<NUM_LIT:0>])<EOL>qid = self._process_bit_id(node.children[<NUM_LIT:1>])<EOL>for element in qid:<EOL><INDENT>self.dag.apply_operation_back(UBase(*args, element), self.condition)<EOL><DEDENT><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>self._process_cnot(node)<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>return node.children<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>self._process_measure(node)<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>self.version = node.version()<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>ids = self._process_node(node.children[<NUM_LIT:0>])<EOL>qubits = []<EOL>for qubit in ids:<EOL><INDENT>for j, _ in enumerate(qubit):<EOL><INDENT>qubits.append(qubit[j])<EOL><DEDENT><DEDENT>self.dag.apply_operation_back(Barrier(len(qubits)), qubits, [])<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>id0 = self._process_bit_id(node.children[<NUM_LIT:0>])<EOL>for i, _ in enumerate(id0):<EOL><INDENT>self.dag.apply_operation_back(Reset(), [id0[i]], [], self.condition)<EOL><DEDENT><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>self._process_if(node)<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>self._process_gate(node, opaque=True)<EOL><DEDENT>elif node.type == "<STR_LIT>":<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>raise QiskitError("<STR_LIT>",<EOL>node.type, "<STR_LIT>" % node.line,<EOL>"<STR_LIT>" % node.file)<EOL><DEDENT>return None<EOL>

Carry out the action associated with a node.


def _create_dag_op(self, name, params, qargs):

if name == "<STR_LIT>":<EOL><INDENT>op_class = U0Gate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = U1Gate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = U2Gate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = U3Gate<EOL><DEDENT>elif name == "<STR_LIT:x>":<EOL><INDENT>op_class = XGate<EOL><DEDENT>elif name == "<STR_LIT:y>":<EOL><INDENT>op_class = YGate<EOL><DEDENT>elif name == "<STR_LIT:z>":<EOL><INDENT>op_class = ZGate<EOL><DEDENT>elif name == "<STR_LIT:t>":<EOL><INDENT>op_class = TGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = TdgGate<EOL><DEDENT>elif name == "<STR_LIT:s>":<EOL><INDENT>op_class = SGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = SdgGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = SwapGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = RXGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = RYGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = RZGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = RZZGate<EOL><DEDENT>elif name == "<STR_LIT:id>":<EOL><INDENT>op_class = IdGate<EOL><DEDENT>elif name == "<STR_LIT:h>":<EOL><INDENT>op_class = HGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = CnotGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = CyGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = CzGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = CHGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = CrzGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = Cu1Gate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = Cu3Gate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = ToffoliGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = FredkinGate<EOL><DEDENT>else:<EOL><INDENT>raise QiskitError("<STR_LIT>" % name)<EOL><DEDENT>op = op_class(*params)<EOL>self.dag.apply_operation_back(op, qargs, [], condition=self.condition)<EOL>

Create a DAG node out of a parsed AST op node.

Args:
    name (str): operation name to apply to the dag.
    params (list): op parameters
    qargs (list(QuantumRegister, int)): qubits to attach to

Raises:
    QiskitError: if encountering a non-basis opaque gate


dagcircuit = DAGCircuit()<EOL>dagcircuit.name = circuit.name<EOL>for register in circuit.qregs:<EOL><INDENT>dagcircuit.add_qreg(register)<EOL><DEDENT>for register in circuit.cregs:<EOL><INDENT>dagcircuit.add_creg(register)<EOL><DEDENT>for instruction, qargs, cargs in circuit.data:<EOL><INDENT>if instruction.control is None:<EOL><INDENT>control = None<EOL><DEDENT>else:<EOL><INDENT>control = (instruction.control[<NUM_LIT:0>], instruction.control[<NUM_LIT:1>])<EOL><DEDENT>dagcircuit.apply_operation_back(instruction.copy(),<EOL>qargs, cargs, control)<EOL><DEDENT>return dagcircuit<EOL>

Build a ``DAGCircuit`` object from a ``QuantumCircuit``.

    Args:
        circuit (QuantumCircuit): the input circuit.

    Return:
        DAGCircuit: the DAG representing the input circuit.


n = int(str_state, <NUM_LIT:2>)<EOL>if num >= len(str_state):<EOL><INDENT>state = np.zeros(<NUM_LIT:1> << num, dtype=complex)<EOL>state[n] = <NUM_LIT:1><EOL>return state<EOL><DEDENT>else:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>

Return a basis state ndarray.

Args:
    str_state (string): a string representing the state.
    num (int): the number of qubits
Returns:
    ndarray:  state(2**num) a quantum state with basis basis state.
 Raises:
    QiskitError: if the dimensions is wrong


density_matrix = np.outer(state.conjugate(), state)<EOL>if flatten:<EOL><INDENT>return density_matrix.flatten(order='<STR_LIT:F>')<EOL><DEDENT>return density_matrix<EOL>

maps a pure state to a state matrix

Args:
    state (ndarray): the number of qubits
    flatten (bool): determine if state matrix of column work
Returns:
    ndarray:  state_mat(2**num, 2**num) if flatten is false
    ndarray:  state_mat(4**num) if flatten is true stacked on by the column


rho = np.array(state)<EOL>if rho.ndim == <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:1.0><EOL><DEDENT>return np.real(np.trace(rho.dot(rho)))<EOL>

Calculate the purity of a quantum state.

    Args:
        state (ndarray): a quantum state
    Returns:
        float: purity.


<EOL>s1 = np.array(state1)<EOL>s2 = np.array(state2)<EOL>if s1.ndim == <NUM_LIT:1> and s2.ndim == <NUM_LIT:1>:<EOL><INDENT>return np.abs(s2.conj().dot(s1)) ** <NUM_LIT:2><EOL><DEDENT>elif s1.ndim == <NUM_LIT:1>:<EOL><INDENT>return np.abs(s1.conj().dot(s2).dot(s1))<EOL><DEDENT>elif s2.ndim == <NUM_LIT:1>:<EOL><INDENT>return np.abs(s2.conj().dot(s1).dot(s2))<EOL><DEDENT>s1sq = _funm_svd(s1, np.sqrt)<EOL>s2sq = _funm_svd(s2, np.sqrt)<EOL>return np.linalg.norm(s1sq.dot(s2sq), ord='<STR_LIT>') ** <NUM_LIT:2><EOL>

Return the state fidelity between two quantum states.

    Either input may be a state vector, or a density matrix. The state
    fidelity (F) for two density matrices is defined as::

        F(rho1, rho2) = Tr[sqrt(sqrt(rho1).rho2.sqrt(rho1))] ^ 2

    For a pure state and mixed state the fidelity is given by::

        F(|psi1>, rho2) = <psi1|rho2|psi1>

    For two pure states the fidelity is given by::

        F(|psi1>, |psi2>) = |<psi1|psi2>|^2

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

    Returns:
        array_like: The state fidelity F(state1, state2).


U, s, Vh = la.svd(a, lapack_driver='<STR_LIT>')<EOL>S = np.diag(func(s))<EOL>return U.dot(S).dot(Vh)<EOL>

Apply real scalar function to singular values of a matrix.

    Args:
        a (array_like): (N, N) Matrix at which to evaluate the function.
        func (callable): Callable object that evaluates a scalar function f.

    Returns:
        ndarray: funm (N, N) Value of the matrix function specified by func
        evaluated at `A`.


if seed is None:<EOL><INDENT>seed = np.random.randint(<NUM_LIT:0>, np.iinfo(np.int32).max)<EOL><DEDENT>rng = np.random.RandomState(seed)<EOL>x = rng.rand(dim)<EOL>x += x == <NUM_LIT:0><EOL>x = -np.log(x)<EOL>sumx = sum(x)<EOL>phases = rng.rand(dim)*<NUM_LIT>*np.pi<EOL>return np.sqrt(x/sumx)*np.exp(<NUM_LIT>*phases)<EOL>

Return a random quantum state from the uniform (Haar) measure on
state space.

Args:
    dim (int): the dim of the state spaxe
    seed (int): Optional. To set a random seed.

Returns:
    ndarray:  state(2**num) a random quantum state.


if dim == <NUM_LIT:0> or not math.log2(dim).is_integer():<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>matrix = np.zeros([dim, dim], dtype=complex)<EOL>for j in range(dim):<EOL><INDENT>if j == <NUM_LIT:0>:<EOL><INDENT>a = random_state(dim, seed)<EOL><DEDENT>else:<EOL><INDENT>a = random_state(dim)<EOL><DEDENT>matrix[:, j] = np.copy(a)<EOL>i = j-<NUM_LIT:1><EOL>while i >= <NUM_LIT:0>:<EOL><INDENT>dc = np.vdot(matrix[:, i], a)<EOL>matrix[:, j] = matrix[:, j]-dc*matrix[:, i]<EOL>i = i - <NUM_LIT:1><EOL><DEDENT>matrix[:, j] = matrix[:, j] * (<NUM_LIT:1.0> / np.sqrt(np.vdot(matrix[:, j], matrix[:, j])))<EOL><DEDENT>return Operator(matrix)<EOL>

Return a random dim x dim unitary Operator from the Haar measure.

Args:
    dim (int): the dim of the state space.
    seed (int): Optional. To set a random seed.

Returns:
    Operator: (dim, dim) unitary operator.

Raises:
    QiskitError: if dim is not a positive power of 2.


def random_density_matrix(length, rank=None, method='<STR_LIT>', seed=None):

if method == '<STR_LIT>':<EOL><INDENT>return __random_density_hs(length, rank, seed)<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>return __random_density_bures(length, rank, seed)<EOL><DEDENT>else:<EOL><INDENT>raise QiskitError('<STR_LIT>'.format(method))<EOL><DEDENT>

Generate a random density matrix rho.

Args:
    length (int): the length of the density matrix.
    rank (int or None): the rank of the density matrix. The default
        value is full-rank.
    method (string): the method to use.
        'Hilbert-Schmidt': sample rho from the Hilbert-Schmidt metric.
        'Bures': sample rho from the Bures metric.
    seed (int): Optional. To set a random seed.
Returns:
    ndarray: rho (length, length) a density matrix.
Raises:
    QiskitError: if the method is not valid.


def __ginibre_matrix(nrow, ncol=None, seed=None):

if ncol is None:<EOL><INDENT>ncol = nrow<EOL><DEDENT>if seed is not None:<EOL><INDENT>np.random.seed(seed)<EOL><DEDENT>G = np.random.normal(size=(nrow, ncol)) +np.random.normal(size=(nrow, ncol)) * <NUM_LIT><EOL>return G<EOL>

Return a normally distributed complex random matrix.

Args:
    nrow (int): number of rows in output matrix.
    ncol (int): number of columns in output matrix.
    seed (int): Optional. To set a random seed.
Returns:
    ndarray: A complex rectangular matrix where each real and imaginary
        entry is sampled from the normal distribution.


def __random_density_hs(N, rank=None, seed=None):

G = __ginibre_matrix(N, rank, seed)<EOL>G = G.dot(G.conj().T)<EOL>return G / np.trace(G)<EOL>

Generate a random density matrix from the Hilbert-Schmidt metric.

Args:
    N (int): the length of the density matrix.
    rank (int or None): the rank of the density matrix. The default
        value is full-rank.
    seed (int): Optional. To set a random seed.
Returns:
    ndarray: rho (N,N  a density matrix.


def __random_density_bures(N, rank=None, seed=None):

P = np.eye(N) + random_unitary(N).data<EOL>G = P.dot(__ginibre_matrix(N, rank, seed))<EOL>G = G.dot(G.conj().T)<EOL>return G / np.trace(G)<EOL>

Generate a random density matrix from the Bures metric.

Args:
    N (int): the length of the density matrix.
    rank (int or None): the rank of the density matrix. The default
        value is full-rank.
    seed (int): Optional. To set a random seed.
Returns:
    ndarray: rho (N,N) a density matrix.


if unitary_matrix.shape != (<NUM_LIT:2>, <NUM_LIT:2>):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>phase = la.det(unitary_matrix)**(-<NUM_LIT:1.0>/<NUM_LIT>)<EOL>U = phase * unitary_matrix  <EOL>if abs(U[<NUM_LIT:0>, <NUM_LIT:0>]) > _CUTOFF_PRECISION:<EOL><INDENT>theta = <NUM_LIT:2> * math.acos(abs(U[<NUM_LIT:0>, <NUM_LIT:0>]))<EOL><DEDENT>else:<EOL><INDENT>theta = <NUM_LIT:2> * math.asin(abs(U[<NUM_LIT:1>, <NUM_LIT:0>]))<EOL><DEDENT>phase11 = <NUM_LIT:0.0><EOL>phase10 = <NUM_LIT:0.0><EOL>if abs(math.cos(theta/<NUM_LIT>)) > _CUTOFF_PRECISION:<EOL><INDENT>phase11 = U[<NUM_LIT:1>, <NUM_LIT:1>] / math.cos(theta/<NUM_LIT>)<EOL><DEDENT>if abs(math.sin(theta/<NUM_LIT>)) > _CUTOFF_PRECISION:<EOL><INDENT>phase10 = U[<NUM_LIT:1>, <NUM_LIT:0>] / math.sin(theta/<NUM_LIT>)<EOL><DEDENT>phiplambda = <NUM_LIT:2> * math.atan2(np.imag(phase11), np.real(phase11))<EOL>phimlambda = <NUM_LIT:2> * math.atan2(np.imag(phase10), np.real(phase10))<EOL>phi = <NUM_LIT:0.0><EOL>if abs(U[<NUM_LIT:0>, <NUM_LIT:0>]) > _CUTOFF_PRECISION and abs(U[<NUM_LIT:1>, <NUM_LIT:0>]) > _CUTOFF_PRECISION:<EOL><INDENT>phi = (phiplambda + phimlambda) / <NUM_LIT><EOL>lamb = (phiplambda - phimlambda) / <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>if abs(U[<NUM_LIT:0>, <NUM_LIT:0>]) < _CUTOFF_PRECISION:<EOL><INDENT>lamb = -phimlambda<EOL><DEDENT>else:<EOL><INDENT>lamb = phiplambda<EOL><DEDENT><DEDENT>Rzphi = np.array([[np.exp(-<NUM_LIT>*phi/<NUM_LIT>), <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, np.exp(<NUM_LIT>*phi/<NUM_LIT>)]], dtype=complex)<EOL>Rytheta = np.array([[np.cos(theta/<NUM_LIT>), -np.sin(theta/<NUM_LIT>)],<EOL>[np.sin(theta/<NUM_LIT>), np.cos(theta/<NUM_LIT>)]], dtype=complex)<EOL>Rzlambda = np.array([[np.exp(-<NUM_LIT>*lamb/<NUM_LIT>), <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, np.exp(<NUM_LIT>*lamb/<NUM_LIT>)]], dtype=complex)<EOL>V = np.dot(Rzphi, np.dot(Rytheta, Rzlambda))<EOL>if la.norm(V - U) > _CUTOFF_PRECISION:<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>return theta, phi, lamb<EOL>

Compute Euler angles for a single-qubit gate.

    Find angles (theta, phi, lambda) such that
    unitary_matrix = phase * Rz(phi) * Ry(theta) * Rz(lambda)

    Args:
        unitary_matrix (ndarray): 2x2 unitary matrix

    Returns:
        tuple: (theta, phi, lambda) Euler angles of SU(2)

    Raises:
        QiskitError: if unitary_matrix not 2x2, or failure


gate = U3Gate(theta, phi, lam)<EOL>if abs(gate.params[<NUM_LIT:0>] % (<NUM_LIT> * math.pi)) < _CUTOFF_PRECISION:<EOL><INDENT>gate = U1Gate(gate.params[<NUM_LIT:0>] + gate.params[<NUM_LIT:1>] + gate.params[<NUM_LIT:2>])<EOL><DEDENT>if isinstance(gate, U3Gate):<EOL><INDENT>if abs((gate.params[<NUM_LIT:0>] - math.pi / <NUM_LIT:2>) % (<NUM_LIT> * math.pi)) < _CUTOFF_PRECISION:<EOL><INDENT>gate = U2Gate(gate.params[<NUM_LIT:1>],<EOL>gate.params[<NUM_LIT:2>] + (gate.params[<NUM_LIT:0>] - math.pi / <NUM_LIT:2>))<EOL><DEDENT>if abs((gate.params[<NUM_LIT:0>] + math.pi / <NUM_LIT:2>) % (<NUM_LIT> * math.pi)) < _CUTOFF_PRECISION:<EOL><INDENT>gate = U2Gate(gate.params[<NUM_LIT:1>] + math.pi,<EOL>gate.params[<NUM_LIT:2>] - math.pi + (gate.params[<NUM_LIT:0>] + math.pi / <NUM_LIT:2>))<EOL><DEDENT><DEDENT>if isinstance(gate, U1Gate) and abs(gate.params[<NUM_LIT:0>] % (<NUM_LIT> * math.pi)) < _CUTOFF_PRECISION:<EOL><INDENT>gate = IdGate()<EOL><DEDENT>return gate<EOL>

Return the gate u1, u2, or u3 implementing U with the fewest pulses.

    The returned gate implements U exactly, not up to a global phase.

    Args:
        theta, phi, lam: input Euler rotation angles for a general U gate

    Returns:
        Gate: one of IdGate, U1Gate, U2Gate, U3Gate.


if hasattr(unitary, '<STR_LIT>'):<EOL><INDENT>unitary = unitary.to_operator().data<EOL><DEDENT>if hasattr(unitary, '<STR_LIT>'):<EOL><INDENT>unitary = unitary.to_matrix()<EOL><DEDENT>unitary_matrix = np.array(unitary, dtype=complex)<EOL>if unitary_matrix.shape != (<NUM_LIT:4>, <NUM_LIT:4>):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>if not is_unitary_matrix(unitary_matrix):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>phase = la.det(unitary_matrix)**(-<NUM_LIT:1.0>/<NUM_LIT>)<EOL>U = phase * unitary_matrix<EOL>B = (<NUM_LIT:1.0>/math.sqrt(<NUM_LIT:2>)) * np.array([[<NUM_LIT:1>, <NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:1>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT>, -<NUM_LIT:1>],<EOL>[<NUM_LIT:1>, -<NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:0>]], dtype=complex)<EOL>Bdag = B.conj().T<EOL>Uprime = Bdag.dot(U.dot(B))<EOL>M2 = Uprime.T.dot(Uprime)<EOL>D, P = la.eig(M2)<EOL>D = np.diag(D)<EOL>if abs(la.det(P)+<NUM_LIT:1>) < <NUM_LIT>:<EOL><INDENT>swap = np.array([[<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]], dtype=complex)<EOL>P = P.dot(swap)<EOL>D = swap.dot(D.dot(swap))<EOL><DEDENT>Q = np.sqrt(D)  <EOL>if abs(la.det(Q)+<NUM_LIT:1>) < <NUM_LIT>:<EOL><INDENT>Q[<NUM_LIT:0>, <NUM_LIT:0>] = -Q[<NUM_LIT:0>, <NUM_LIT:0>]<EOL><DEDENT>Pprime = la.solve(Q, P.T)<EOL>Kprime = Uprime.dot(P.dot(Pprime))<EOL>K1 = B.dot(Kprime.dot(P.dot(Bdag)))<EOL>A = B.dot(Q.dot(Bdag))<EOL>K2 = B.dot(P.T.dot(Bdag))<EOL>KAK = K1.dot(A.dot(K2))<EOL>if la.norm(KAK - U) > <NUM_LIT>:<EOL><INDENT>raise QiskitError("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>xx = np.array([[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>]], dtype=complex)<EOL>yy = np.array([[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, -<NUM_LIT:1>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[-<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>]], dtype=complex)<EOL>zz = np.array([[<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, -<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, -<NUM_LIT:1>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]], dtype=complex)<EOL>A_real_tr = A.real.trace()<EOL>alpha = math.atan2(A.dot(xx).imag.trace(), A_real_tr)<EOL>beta = math.atan2(A.dot(yy).imag.trace(), A_real_tr)<EOL>gamma = math.atan2(A.dot(zz).imag.trace(), A_real_tr)<EOL>L = K1[<NUM_LIT:0>:<NUM_LIT:2>, <NUM_LIT:0>:<NUM_LIT:2>]<EOL>if la.norm(L) < <NUM_LIT>:<EOL><INDENT>L = K1[<NUM_LIT:0>:<NUM_LIT:2>, <NUM_LIT:2>:<NUM_LIT:4>]<EOL>if la.norm(L) < <NUM_LIT>:<EOL><INDENT>L = K1[<NUM_LIT:2>:<NUM_LIT:4>, <NUM_LIT:2>:<NUM_LIT:4>]<EOL><DEDENT><DEDENT>Q = L.dot(L.conj().T)<EOL>U2 = L / math.sqrt(Q[<NUM_LIT:0>, <NUM_LIT:0>].real)<EOL>R = K1.dot(np.kron(np.identity(<NUM_LIT:2>), U2.conj().T))<EOL>U1 = np.zeros((<NUM_LIT:2>, <NUM_LIT:2>), dtype=complex)<EOL>U1[<NUM_LIT:0>, <NUM_LIT:0>] = R[<NUM_LIT:0>, <NUM_LIT:0>]<EOL>U1[<NUM_LIT:0>, <NUM_LIT:1>] = R[<NUM_LIT:0>, <NUM_LIT:2>]<EOL>U1[<NUM_LIT:1>, <NUM_LIT:0>] = R[<NUM_LIT:2>, <NUM_LIT:0>]<EOL>U1[<NUM_LIT:1>, <NUM_LIT:1>] = R[<NUM_LIT:2>, <NUM_LIT:2>]<EOL>L = K2[<NUM_LIT:0>:<NUM_LIT:2>, <NUM_LIT:0>:<NUM_LIT:2>]<EOL>if la.norm(L) < <NUM_LIT>:<EOL><INDENT>L = K2[<NUM_LIT:0>:<NUM_LIT:2>, <NUM_LIT:2>:<NUM_LIT:4>]<EOL>if la.norm(L) < <NUM_LIT>:<EOL><INDENT>L = K2[<NUM_LIT:2>:<NUM_LIT:4>, <NUM_LIT:2>:<NUM_LIT:4>]<EOL><DEDENT><DEDENT>Q = np.dot(L, np.transpose(L.conjugate()))<EOL>V2 = L / np.sqrt(Q[<NUM_LIT:0>, <NUM_LIT:0>])<EOL>R = np.dot(K2, np.kron(np.identity(<NUM_LIT:2>), np.transpose(V2.conjugate())))<EOL>V1 = np.zeros_like(U1)<EOL>V1[<NUM_LIT:0>, <NUM_LIT:0>] = R[<NUM_LIT:0>, <NUM_LIT:0>]<EOL>V1[<NUM_LIT:0>, <NUM_LIT:1>] = R[<NUM_LIT:0>, <NUM_LIT:2>]<EOL>V1[<NUM_LIT:1>, <NUM_LIT:0>] = R[<NUM_LIT:2>, <NUM_LIT:0>]<EOL>V1[<NUM_LIT:1>, <NUM_LIT:1>] = R[<NUM_LIT:2>, <NUM_LIT:2>]<EOL>if la.norm(np.kron(U1, U2) - K1) > <NUM_LIT>:<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>if la.norm(np.kron(V1, V2) - K2) > <NUM_LIT>:<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>test = la.expm(<NUM_LIT>*(alpha * xx + beta * yy + gamma * zz))<EOL>if la.norm(A - test) > <NUM_LIT>:<EOL><INDENT>raise QiskitError("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>V2 = np.array([[np.exp(<NUM_LIT>*np.pi/<NUM_LIT:4>), <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, np.exp(-<NUM_LIT>*np.pi/<NUM_LIT:4>)]], dtype=complex).dot(V2)<EOL>U1 = U1.dot(np.array([[np.exp(-<NUM_LIT>*np.pi/<NUM_LIT:4>), <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, np.exp(<NUM_LIT>*np.pi/<NUM_LIT:4>)]], dtype=complex))<EOL>U1 = U1.dot(np.array([[np.exp(<NUM_LIT>*np.pi/<NUM_LIT:4>), <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, np.exp(<NUM_LIT>*np.pi/<NUM_LIT:4>)]], dtype=complex))<EOL>U1 = phase.conjugate() * U1<EOL>g1 = np.kron(V1, V2)<EOL>g2 = np.array([[<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>]], dtype=complex)<EOL>theta = <NUM_LIT:2>*gamma - np.pi/<NUM_LIT:2><EOL>Ztheta = np.array([[np.exp(<NUM_LIT>*theta/<NUM_LIT:2>), <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, np.exp(-<NUM_LIT>*theta/<NUM_LIT:2>)]], dtype=complex)<EOL>kappa = np.pi/<NUM_LIT:2> - <NUM_LIT:2>*alpha<EOL>Ykappa = np.array([[math.cos(kappa/<NUM_LIT:2>), math.sin(kappa/<NUM_LIT:2>)],<EOL>[-math.sin(kappa/<NUM_LIT:2>), math.cos(kappa/<NUM_LIT:2>)]], dtype=complex)<EOL>g3 = np.kron(Ztheta, Ykappa)<EOL>g4 = np.array([[<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>]], dtype=complex)<EOL>zeta = <NUM_LIT:2>*beta - np.pi/<NUM_LIT:2><EOL>Yzeta = np.array([[math.cos(zeta/<NUM_LIT:2>), math.sin(zeta/<NUM_LIT:2>)],<EOL>[-math.sin(zeta/<NUM_LIT:2>), math.cos(zeta/<NUM_LIT:2>)]], dtype=complex)<EOL>g5 = np.kron(np.identity(<NUM_LIT:2>), Yzeta)<EOL>g6 = g2<EOL>g7 = np.kron(U1, U2)<EOL>V = g2.dot(g1)<EOL>V = g3.dot(V)<EOL>V = g4.dot(V)<EOL>V = g5.dot(V)<EOL>V = g6.dot(V)<EOL>V = g7.dot(V)<EOL>if la.norm(V - U*phase.conjugate()) > <NUM_LIT>:<EOL><INDENT>raise QiskitError("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>v1_param = euler_angles_1q(V1)<EOL>v2_param = euler_angles_1q(V2)<EOL>u1_param = euler_angles_1q(U1)<EOL>u2_param = euler_angles_1q(U2)<EOL>v1_gate = U3Gate(v1_param[<NUM_LIT:0>], v1_param[<NUM_LIT:1>], v1_param[<NUM_LIT:2>])<EOL>v2_gate = U3Gate(v2_param[<NUM_LIT:0>], v2_param[<NUM_LIT:1>], v2_param[<NUM_LIT:2>])<EOL>u1_gate = U3Gate(u1_param[<NUM_LIT:0>], u1_param[<NUM_LIT:1>], u1_param[<NUM_LIT:2>])<EOL>u2_gate = U3Gate(u2_param[<NUM_LIT:0>], u2_param[<NUM_LIT:1>], u2_param[<NUM_LIT:2>])<EOL>q = QuantumRegister(<NUM_LIT:2>)<EOL>return_circuit = QuantumCircuit(q)<EOL>return_circuit.append(v1_gate, [q[<NUM_LIT:1>]])<EOL>return_circuit.append(v2_gate, [q[<NUM_LIT:0>]])<EOL>return_circuit.append(CnotGate(), [q[<NUM_LIT:0>], q[<NUM_LIT:1>]])<EOL>gate = U3Gate(<NUM_LIT:0.0>, <NUM_LIT:0.0>, -<NUM_LIT>*gamma + np.pi/<NUM_LIT>)<EOL>return_circuit.append(gate, [q[<NUM_LIT:1>]])<EOL>gate = U3Gate(-np.pi/<NUM_LIT> + <NUM_LIT>*alpha, <NUM_LIT:0.0>, <NUM_LIT:0.0>)<EOL>return_circuit.append(gate, [q[<NUM_LIT:0>]])<EOL>return_circuit.append(CnotGate(), [q[<NUM_LIT:1>], q[<NUM_LIT:0>]])<EOL>gate = U3Gate(-<NUM_LIT>*beta + np.pi/<NUM_LIT>, <NUM_LIT:0.0>, <NUM_LIT:0.0>)<EOL>return_circuit.append(gate, [q[<NUM_LIT:0>]])<EOL>return_circuit.append(CnotGate(), [q[<NUM_LIT:0>], q[<NUM_LIT:1>]])<EOL>return_circuit.append(u1_gate, [q[<NUM_LIT:1>]])<EOL>return_circuit.append(u2_gate, [q[<NUM_LIT:0>]])<EOL>return return_circuit<EOL>

Decompose a two-qubit gate over SU(2)+CNOT using the KAK decomposition.

    Args:
        unitary (Operator): a 4x4 unitary operator to decompose.

    Returns:
        QuantumCircuit: a circuit implementing the unitary over SU(2)+CNOT

    Raises:
        QiskitError: input not a unitary, or error in KAK decomposition.


dict_observable = {}<EOL>observable = np.array(matrix_observable)<EOL>observable_size = len(observable)<EOL>observable_bits = int(np.ceil(np.log2(observable_size)))<EOL>binary_formater = '<STR_LIT>'.format(observable_bits)<EOL>if observable.ndim == <NUM_LIT:2>:<EOL><INDENT>observable = observable.diagonal()<EOL><DEDENT>for state_no in range(observable_size):<EOL><INDENT>state_str = format(state_no, binary_formater)<EOL>dict_observable[state_str] = observable[state_no]<EOL><DEDENT>return dict_observable<EOL>

Convert an observable in matrix form to dictionary form.

    Takes in a diagonal observable as a matrix and converts it to a dictionary
    form. Can also handle a list sorted of the diagonal elements.

    Args:
        matrix_observable (list): The observable to be converted to dictionary
        form. Can be a matrix or just an ordered list of observed values

    Returns:
        Dict: A dictionary with all observable states as keys, and corresponding
        values being the observed value for that state


if not isinstance(observable, dict):<EOL><INDENT>observable = make_dict_observable(observable)<EOL><DEDENT>temp = <NUM_LIT:0><EOL>tot = sum(counts.values())<EOL>for key in counts:<EOL><INDENT>if key in observable:<EOL><INDENT>temp += counts[key] * observable[key] / tot<EOL><DEDENT><DEDENT>return temp<EOL>

Compute the mean value of an diagonal observable.

    Takes in a diagonal observable in dictionary, list or matrix format and then
    calculates the sum_i value(i) P(i) where value(i) is the value of the
    observable for state i.

    Args:
        counts (dict): a dict of outcomes from an experiment
        observable (dict or matrix or list): The observable to be averaged over.
        As an example, ZZ on qubits can be given as:
        * dict: {"00": 1, "11": 1, "01": -1, "10": -1}
        * matrix: [[1, 0, 0, 0], [0, -1, 0, 0, ], [0, 0, -1, 0], [0, 0, 0, 1]]
        * matrix diagonal (list): [1, -1, -1, 1]

    Returns:
        Double: Average of the observable


def process_fidelity(channel1, channel2, require_cptp=True):

<EOL>is_cptp1 = None<EOL>is_cptp2 = None<EOL>if isinstance(channel1, (list, np.ndarray)):<EOL><INDENT>channel1 = Operator(channel1)<EOL>if require_cptp:<EOL><INDENT>is_cptp1 = channel1.is_unitary()<EOL><DEDENT><DEDENT>if isinstance(channel2, (list, np.ndarray)):<EOL><INDENT>channel2 = Operator(channel2)<EOL>if require_cptp:<EOL><INDENT>is_cptp2 = channel2.is_unitary()<EOL><DEDENT><DEDENT>s1 = SuperOp(channel1)<EOL>s2 = SuperOp(channel2)<EOL>if require_cptp:<EOL><INDENT>if is_cptp1 is None:<EOL><INDENT>is_cptp1 = s1.is_cptp()<EOL><DEDENT>if not is_cptp1:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>if is_cptp2 is None:<EOL><INDENT>is_cptp2 = s2.is_cptp()<EOL><DEDENT>if not is_cptp2:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT><DEDENT>input_dim1, output_dim1 = s1.dim<EOL>input_dim2, output_dim2 = s2.dim<EOL>if input_dim1 != output_dim1 or input_dim2 != output_dim2:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>if input_dim1 != input_dim2:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>fidelity = np.trace(s1.compose(s2.adjoint()).data) / (input_dim1 ** <NUM_LIT:2>)<EOL>return fidelity<EOL>

Return the process fidelity between two quantum channels.

    This is given by

        F_p(E1, E2) = Tr[S2^dagger.S1])/dim^2

    where S1 and S2 are the SuperOp matrices for channels E1 and E2,
    and dim is the dimension of the input output statespace.

    Args:
        channel1 (QuantumChannel or matrix): a quantum channel or unitary matrix.
        channel2 (QuantumChannel or matrix): a quantum channel or unitary matrix.
        require_cptp (bool): require input channels to be CPTP [Default: True].

    Returns:
        array_like: The state fidelity F(state1, state2).

    Raises:
        QiskitError: if inputs channels do not have the same dimensions,
        have different input and output dimensions, or are not CPTP with
        `require_cptp=True`.