def _layer_update(self, i, first_layer, best_layout, best_depth,<EOL>best_circuit, layer_list):

layout = best_layout<EOL>logger.debug("<STR_LIT>", pformat(layout))<EOL>logger.debug("<STR_LIT>", pformat(self.initial_layout))<EOL>dagcircuit_output = DAGCircuit()<EOL>for register in layout.get_virtual_bits().keys():<EOL><INDENT>if register[<NUM_LIT:0>] not in dagcircuit_output.qregs.values():<EOL><INDENT>dagcircuit_output.add_qreg(register[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>if first_layer:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>for j in range(i + <NUM_LIT:1>):<EOL><INDENT>edge_map = layout.combine_into_edge_map(self.initial_layout)<EOL>for bit in dagcircuit_output.clbits():<EOL><INDENT>edge_map[bit] = bit<EOL><DEDENT>dagcircuit_output.compose_back(layer_list[j]["<STR_LIT>"], edge_map)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if best_depth > <NUM_LIT:0>:<EOL><INDENT>logger.debug("<STR_LIT>"<EOL>"<STR_LIT>", best_depth)<EOL>dagcircuit_output.extend_back(best_circuit)<EOL><DEDENT>else:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL><DEDENT>edge_map = layout.combine_into_edge_map(self.initial_layout)<EOL>for bit in dagcircuit_output.clbits():<EOL><INDENT>edge_map[bit] = bit<EOL><DEDENT>dagcircuit_output.compose_back(layer_list[i]["<STR_LIT>"], edge_map)<EOL><DEDENT>return dagcircuit_output<EOL>

Provide a DAGCircuit for a new mapped layer.

        i (int) = layer number
        first_layer (bool) = True if this is the first layer in the
            circuit with any multi-qubit gates
        best_layout (Layout) = layout returned from _layer_permutation
        best_depth (int) = depth returned from _layer_permutation
        best_circuit (DAGCircuit) = swap circuit returned
            from _layer_permutation
        layer_list (list) = list of DAGCircuit objects for each layer,
            output of DAGCircuit layers() method

        Return a DAGCircuit object to append to the output DAGCircuit
        that the _mapper method is building.


def _mapper(self, circuit_graph, coupling_graph,<EOL>trials=<NUM_LIT:20>):

<EOL>layerlist = list(circuit_graph.layers())<EOL>logger.debug("<STR_LIT>")<EOL>for i, v in enumerate(layerlist):<EOL><INDENT>logger.debug("<STR_LIT>", i, v["<STR_LIT>"])<EOL><DEDENT>if self.initial_layout is not None:<EOL><INDENT>qubit_subset = self.initial_layout.get_virtual_bits().keys()<EOL><DEDENT>else:<EOL><INDENT>self.initial_layout = Layout()<EOL>physical_qubit = <NUM_LIT:0><EOL>for qreg in circuit_graph.qregs.values():<EOL><INDENT>for index in range(qreg.size):<EOL><INDENT>self.initial_layout[(qreg, index)] = physical_qubit<EOL>physical_qubit += <NUM_LIT:1><EOL><DEDENT><DEDENT>qubit_subset = self.initial_layout.get_virtual_bits().keys()<EOL>coupling_graph = coupling_graph.subgraph(<EOL>self.initial_layout.get_physical_bits().keys())<EOL>if coupling_graph.size() < len(self.initial_layout):<EOL><INDENT>raise TranspilerError("<STR_LIT>")<EOL><DEDENT>self.input_layout = self.initial_layout.copy()<EOL><DEDENT>layout = self.initial_layout.copy()<EOL>dagcircuit_output = DAGCircuit()<EOL>dagcircuit_output.name = circuit_graph.name<EOL>for qreg in circuit_graph.qregs.values():<EOL><INDENT>dagcircuit_output.add_qreg(qreg)<EOL><DEDENT>for creg in circuit_graph.cregs.values():<EOL><INDENT>dagcircuit_output.add_creg(creg)<EOL><DEDENT>identity_wire_map = {}<EOL>for qubit in circuit_graph.qubits():<EOL><INDENT>identity_wire_map[qubit] = qubit<EOL><DEDENT>for bit in circuit_graph.clbits():<EOL><INDENT>identity_wire_map[bit] = bit<EOL><DEDENT>first_layer = True  <EOL>logger.debug("<STR_LIT>", layout)<EOL>for i, layer in enumerate(layerlist):<EOL><INDENT>success_flag, best_circuit, best_depth, best_layout, trivial_flag= self._layer_permutation(layer["<STR_LIT>"], layout,<EOL>qubit_subset, coupling_graph,<EOL>trials)<EOL>logger.debug("<STR_LIT>", i)<EOL>logger.debug("<STR_LIT>",<EOL>success_flag, str(best_depth), trivial_flag)<EOL>if not success_flag:<EOL><INDENT>logger.debug("<STR_LIT>"<EOL>"<STR_LIT>", i)<EOL>serial_layerlist = list(layer["<STR_LIT>"].serial_layers())<EOL>for j, serial_layer in enumerate(serial_layerlist):<EOL><INDENT>success_flag, best_circuit, best_depth, best_layout, trivial_flag =self._layer_permutation(<EOL>serial_layer["<STR_LIT>"],<EOL>layout, qubit_subset,<EOL>coupling_graph,<EOL>trials)<EOL>logger.debug("<STR_LIT>", i, j)<EOL>logger.debug("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>success_flag, str(best_depth), trivial_flag)<EOL>if not success_flag:<EOL><INDENT>raise TranspilerError("<STR_LIT>" +<EOL>"<STR_LIT>" % (i, j))<EOL><DEDENT>if trivial_flag and first_layer:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>continue<EOL><DEDENT>if first_layer:<EOL><INDENT>self.initial_layout = layout<EOL><DEDENT>layout = best_layout<EOL>dagcircuit_output.extend_back(<EOL>self._layer_update(j,<EOL>first_layer,<EOL>best_layout,<EOL>best_depth,<EOL>best_circuit,<EOL>serial_layerlist),<EOL>identity_wire_map)<EOL>if first_layer:<EOL><INDENT>first_layer = False<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>layout = best_layout<EOL>if first_layer:<EOL><INDENT>self.initial_layout = layout<EOL><DEDENT>dagcircuit_output.extend_back(<EOL>self._layer_update(i,<EOL>first_layer,<EOL>best_layout,<EOL>best_depth,<EOL>best_circuit,<EOL>layerlist),<EOL>identity_wire_map)<EOL>if first_layer:<EOL><INDENT>first_layer = False<EOL><DEDENT><DEDENT><DEDENT>logger.debug("<STR_LIT>", pformat(self.initial_layout))<EOL>logger.debug("<STR_LIT>", pformat(layout))<EOL>last_edgemap = layout.combine_into_edge_map(self.initial_layout)<EOL>logger.debug("<STR_LIT>", pformat(last_edgemap))<EOL>if first_layer:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>layout = self.initial_layout<EOL>for i, layer in enumerate(layerlist):<EOL><INDENT>edge_map = layout.combine_into_edge_map(self.initial_layout)<EOL>dagcircuit_output.compose_back(layer["<STR_LIT>"], edge_map)<EOL><DEDENT><DEDENT>return dagcircuit_output<EOL>

Map a DAGCircuit onto a CouplingMap using swap gates.

        Use self.initial_layout for the initial layout.

        Args:
            circuit_graph (DAGCircuit): input DAG circuit
            coupling_graph (CouplingMap): coupling graph to map onto
            trials (int): number of trials.

        Returns:
            DAGCircuit: object containing a circuit equivalent to
                circuit_graph that respects couplings in coupling_graph
            Layout: a layout object mapping qubits of circuit_graph into
                qubits of coupling_graph. The layout may differ from the
                initial_layout if the first layer of gates cannot be
                executed on the initial_layout, since in this case
                it is more efficient to modify the layout instead of swapping
            Dict: a final-layer qubit permutation

        Raises:
            TranspilerError: if there was any error during the mapping
                or with the parameters.


super().__init__()<EOL>self.backend_prop = backend_prop<EOL>self.swap_graph = nx.DiGraph()<EOL>self.cx_errors = {}<EOL>self.readout_errors = {}<EOL>self.available_hw_qubits = []<EOL>self.gate_list = []<EOL>self.gate_cost = {}<EOL>self.swap_paths = {}<EOL>self.swap_costs = {}<EOL>self.prog_graph = nx.Graph()<EOL>self.qarg_to_id = {}<EOL>self.pending_program_edges = []<EOL>self.prog2hw = {}<EOL>

Chooses a Noise Adaptive Layout

Args:
    backend_prop (BackendProperties): backend properties object

Raises:
    TranspilerError: if invalid options


backend_prop = self.backend_prop<EOL>for ginfo in backend_prop.gates:<EOL><INDENT>if ginfo.gate == '<STR_LIT>':<EOL><INDENT>for item in ginfo.parameters:<EOL><INDENT>if item.name == '<STR_LIT>':<EOL><INDENT>g_reliab = <NUM_LIT:1.0> - item.value<EOL>break<EOL><DEDENT>else:<EOL><INDENT>g_reliab = <NUM_LIT:1.0><EOL><DEDENT><DEDENT>swap_reliab = -math.log(pow(g_reliab, <NUM_LIT:3>))<EOL>self.swap_graph.add_edge(ginfo.qubits[<NUM_LIT:0>], ginfo.qubits[<NUM_LIT:1>], weight=swap_reliab)<EOL>self.swap_graph.add_edge(ginfo.qubits[<NUM_LIT:1>], ginfo.qubits[<NUM_LIT:0>], weight=swap_reliab)<EOL>self.cx_errors[(ginfo.qubits[<NUM_LIT:0>], ginfo.qubits[<NUM_LIT:1>])] = g_reliab<EOL>self.gate_list.append((ginfo.qubits[<NUM_LIT:0>], ginfo.qubits[<NUM_LIT:1>]))<EOL><DEDENT><DEDENT>idx = <NUM_LIT:0><EOL>for q in backend_prop.qubits:<EOL><INDENT>for nduv in q:<EOL><INDENT>if nduv.name == '<STR_LIT>':<EOL><INDENT>self.readout_errors[idx] = <NUM_LIT:1.0> - nduv.value<EOL>self.available_hw_qubits.append(idx)<EOL><DEDENT><DEDENT>idx += <NUM_LIT:1><EOL><DEDENT>for edge in self.cx_errors:<EOL><INDENT>self.gate_cost[edge] = self.cx_errors[edge] * self.readout_errors[edge[<NUM_LIT:0>]] *self.readout_errors[edge[<NUM_LIT:1>]]<EOL><DEDENT>self.swap_paths, swap_costs_temp = nx.algorithms.shortest_paths.dense.floyd_warshall_predecessor_and_distance(self.swap_graph, weight='<STR_LIT>')<EOL>for i in swap_costs_temp:<EOL><INDENT>self.swap_costs[i] = {}<EOL>for j in swap_costs_temp[i]:<EOL><INDENT>if (i, j) in self.cx_errors:<EOL><INDENT>self.swap_costs[i][j] = self.cx_errors[(i, j)]<EOL><DEDENT>elif (j, i) in self.cx_errors:<EOL><INDENT>self.swap_costs[i][j] = self.cx_errors[(j, i)]<EOL><DEDENT>else:<EOL><INDENT>best_reliab = <NUM_LIT:0.0><EOL>for n in self.swap_graph.neighbors(j):<EOL><INDENT>if (n, j) in self.cx_errors:<EOL><INDENT>reliab = math.exp(-swap_costs_temp[i][n])*self.cx_errors[(n, j)]<EOL><DEDENT>else:<EOL><INDENT>reliab = math.exp(-swap_costs_temp[i][n])*self.cx_errors[(j, n)]<EOL><DEDENT>if reliab > best_reliab:<EOL><INDENT>best_reliab = reliab<EOL><DEDENT><DEDENT>self.swap_costs[i][j] = best_reliab<EOL><DEDENT><DEDENT><DEDENT>

Extract readout and CNOT errors and compute swap costs.


return self.qarg_to_id[qubit[<NUM_LIT:0>].name + str(qubit[<NUM_LIT:1>])]<EOL>

Converts qarg with name and value to an integer id


idx = <NUM_LIT:0><EOL>for q in dag.qubits():<EOL><INDENT>self.qarg_to_id[q[<NUM_LIT:0>].name + str(q[<NUM_LIT:1>])] = idx<EOL>idx += <NUM_LIT:1><EOL><DEDENT>for gate in dag.twoQ_gates():<EOL><INDENT>qid1 = self._qarg_to_id(gate.qargs[<NUM_LIT:0>])<EOL>qid2 = self._qarg_to_id(gate.qargs[<NUM_LIT:1>])<EOL>min_q = min(qid1, qid2)<EOL>max_q = max(qid1, qid2)<EOL>edge_weight = <NUM_LIT:1><EOL>if self.prog_graph.has_edge(min_q, max_q):<EOL><INDENT>edge_weight = self.prog_graph[min_q][max_q]['<STR_LIT>'] + <NUM_LIT:1><EOL><DEDENT>self.prog_graph.add_edge(min_q, max_q, weight=edge_weight)<EOL><DEDENT>return idx<EOL>

Program graph has virtual qubits as nodes.
Two nodes have an edge if the corresponding virtual qubits
participate in a 2-qubit gate. The edge is weighted by the
number of CNOTs between the pair.


for edge in self.pending_program_edges:<EOL><INDENT>q1_mapped = edge[<NUM_LIT:0>] in self.prog2hw<EOL>q2_mapped = edge[<NUM_LIT:1>] in self.prog2hw<EOL>assert not (q1_mapped and q2_mapped)<EOL>if q1_mapped or q2_mapped:<EOL><INDENT>return edge<EOL><DEDENT><DEDENT>return self.pending_program_edges[<NUM_LIT:0>]<EOL>

If there is an edge with one endpoint mapped, return it.
Else return in the first edge


candidates = []<EOL>for gate in self.gate_list:<EOL><INDENT>chk1 = gate[<NUM_LIT:0>] in self.available_hw_qubits<EOL>chk2 = gate[<NUM_LIT:1>] in self.available_hw_qubits<EOL>if chk1 and chk2:<EOL><INDENT>candidates.append(gate)<EOL><DEDENT><DEDENT>best_reliab = <NUM_LIT:0><EOL>best_item = None<EOL>for item in candidates:<EOL><INDENT>if self.gate_cost[item] > best_reliab:<EOL><INDENT>best_reliab = self.gate_cost[item]<EOL>best_item = item<EOL><DEDENT><DEDENT>return best_item<EOL>

Select best remaining CNOT in the hardware for the next program edge.


reliab_store = {}<EOL>for hw_qubit in self.available_hw_qubits:<EOL><INDENT>reliab = <NUM_LIT:1><EOL>for n in self.prog_graph.neighbors(prog_qubit):<EOL><INDENT>if n in self.prog2hw:<EOL><INDENT>reliab *= self.swap_costs[self.prog2hw[n]][hw_qubit]<EOL><DEDENT><DEDENT>reliab *= self.readout_errors[hw_qubit]<EOL>reliab_store[hw_qubit] = reliab<EOL><DEDENT>max_reliab = <NUM_LIT:0><EOL>best_hw_qubit = None<EOL>for hw_qubit in reliab_store:<EOL><INDENT>if reliab_store[hw_qubit] > max_reliab:<EOL><INDENT>max_reliab = reliab_store[hw_qubit]<EOL>best_hw_qubit = hw_qubit<EOL><DEDENT><DEDENT>return best_hw_qubit<EOL>

Select the best remaining hardware qubit for the next program qubit.


self._initialize_backend_prop()<EOL>num_qubits = self._create_program_graph(dag)<EOL>if num_qubits > len(self.swap_graph):<EOL><INDENT>raise TranspilerError('<STR_LIT>')<EOL><DEDENT>for end1, end2, _ in sorted(self.prog_graph.edges(data=True),<EOL>key=lambda x: x[<NUM_LIT:2>]['<STR_LIT>'], reverse=True):<EOL><INDENT>self.pending_program_edges.append((end1, end2))<EOL><DEDENT>while self.pending_program_edges:<EOL><INDENT>edge = self._select_next_edge()<EOL>q1_mapped = edge[<NUM_LIT:0>] in self.prog2hw<EOL>q2_mapped = edge[<NUM_LIT:1>] in self.prog2hw<EOL>if (not q1_mapped) and (not q2_mapped):<EOL><INDENT>best_hw_edge = self._select_best_remaining_cx()<EOL>self.prog2hw[edge[<NUM_LIT:0>]] = best_hw_edge[<NUM_LIT:0>]<EOL>self.prog2hw[edge[<NUM_LIT:1>]] = best_hw_edge[<NUM_LIT:1>]<EOL>self.available_hw_qubits.remove(best_hw_edge[<NUM_LIT:0>])<EOL>self.available_hw_qubits.remove(best_hw_edge[<NUM_LIT:1>])<EOL><DEDENT>elif not q1_mapped:<EOL><INDENT>best_hw_qubit = self._select_best_remaining_qubit(edge[<NUM_LIT:0>])<EOL>self.prog2hw[edge[<NUM_LIT:0>]] = best_hw_qubit<EOL>self.available_hw_qubits.remove(best_hw_qubit)<EOL><DEDENT>else:<EOL><INDENT>best_hw_qubit = self._select_best_remaining_qubit(edge[<NUM_LIT:1>])<EOL>self.prog2hw[edge[<NUM_LIT:1>]] = best_hw_qubit<EOL>self.available_hw_qubits.remove(best_hw_qubit)<EOL><DEDENT>new_edges = [x for x in self.pending_program_edges<EOL>if not (x[<NUM_LIT:0>] in self.prog2hw and x[<NUM_LIT:1>] in self.prog2hw)]<EOL>self.pending_program_edges = new_edges<EOL><DEDENT>for qid in self.qarg_to_id.values():<EOL><INDENT>if qid not in self.prog2hw:<EOL><INDENT>self.prog2hw[qid] = self.available_hw_qubits[<NUM_LIT:0>]<EOL>self.available_hw_qubits.remove(self.prog2hw[qid])<EOL><DEDENT><DEDENT>layout = Layout()<EOL>for q in dag.qubits():<EOL><INDENT>pid = self._qarg_to_id(q)<EOL>hwid = self.prog2hw[pid]<EOL>layout[(q[<NUM_LIT:0>], q[<NUM_LIT:1>])] = hwid<EOL><DEDENT>self.property_set['<STR_LIT>'] = layout<EOL>

Main run method for the noise adaptive layout.


def __init__(self, coupling_map, initial_layout=None):

super().__init__()<EOL>self.layout = initial_layout<EOL>self.coupling_map = coupling_map<EOL>

Checks if the CNOTs in DAGCircuit are in the allowed direction with
respect to `coupling_map`.
Args:
    coupling_map (CouplingMap): Directed graph representing a coupling map.
    initial_layout (Layout): The initial layout of the DAG to analyze.


if self.layout is None:<EOL><INDENT>if self.property_set["<STR_LIT>"]:<EOL><INDENT>self.layout = self.property_set["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>self.layout = Layout.generate_trivial_layout(*dag.qregs.values())<EOL><DEDENT><DEDENT>self.property_set['<STR_LIT>'] = True<EOL>edges = self.coupling_map.get_edges()<EOL>for gate in dag.twoQ_gates():<EOL><INDENT>physical_q0 = self.layout[gate.qargs[<NUM_LIT:0>]]<EOL>physical_q1 = self.layout[gate.qargs[<NUM_LIT:1>]]<EOL>if isinstance(gate.op, (CXBase, CnotGate)) and (<EOL>physical_q0, physical_q1) not in edges:<EOL><INDENT>self.property_set['<STR_LIT>'] = False<EOL>return<EOL><DEDENT><DEDENT>

If `dag` is mapped and the direction is correct the property
`is_direction_mapped` is set to True (or to False otherwise).

Args:
    dag (DAGCircuit): DAG to check.


super().__init__()<EOL>self.coupling_map = coupling_map<EOL>self.initial_layout = initial_layout<EOL>self.trials = trials<EOL>self.seed = seed<EOL>self.requires.append(BarrierBeforeFinalMeasurements())<EOL>

Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
    coupling_map (CouplingMap): Directed graph represented a coupling map.
    initial_layout (Layout): initial layout of qubits in mapping
    trials (int): the number of attempts the randomized algorithm makes.
    seed (int): initial seed.


if dag.width() > self.coupling_map.size():<EOL><INDENT>raise TranspilerError("<STR_LIT>")<EOL><DEDENT>layerlist = list(dag.layers())<EOL>if self.initial_layout is None and self.property_set["<STR_LIT>"]:<EOL><INDENT>self.initial_layout = self.property_set["<STR_LIT>"]<EOL><DEDENT>if self.initial_layout is not None:<EOL><INDENT>virtual_qubits = self.initial_layout.get_virtual_bits()<EOL>self.initial_layout = {(v[<NUM_LIT:0>].name, v[<NUM_LIT:1>]): ('<STR_LIT:q>', self.initial_layout[v]) for v in<EOL>virtual_qubits}<EOL>device_register = QuantumRegister(self.coupling_map.size(), '<STR_LIT:q>')<EOL>initial_layout = {(dag.qregs[k[<NUM_LIT:0>]], k[<NUM_LIT:1>]): (device_register, v[<NUM_LIT:1>])<EOL>for k, v in self.initial_layout.items()}<EOL>circ_qubits = dag.qubits()<EOL>coup_qubits = [(QuantumRegister(self.coupling_map.size(), '<STR_LIT:q>'), wire) for wire in<EOL>self.coupling_map.physical_qubits]<EOL>qubit_subset = []<EOL>for k, v in initial_layout.items():<EOL><INDENT>qubit_subset.append(v)<EOL>if k not in circ_qubits:<EOL><INDENT>raise TranspilerError("<STR_LIT>"<EOL>"<STR_LIT>" % (k[<NUM_LIT:0>].name, k[<NUM_LIT:1>]))<EOL><DEDENT>if v not in coup_qubits:<EOL><INDENT>raise TranspilerError("<STR_LIT>"<EOL>"<STR_LIT>" % (v[<NUM_LIT:0>].name, v[<NUM_LIT:1>]))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>qubit_subset = [(QuantumRegister(self.coupling_map.size(), '<STR_LIT:q>'), wire) for wire in<EOL>self.coupling_map.physical_qubits]<EOL>qubit_subset = qubit_subset[<NUM_LIT:0>:dag.width()]<EOL>initial_layout = {a: b for a, b in zip(dag.qubits(), qubit_subset)}<EOL><DEDENT>layout = initial_layout.copy()<EOL>dagcircuit_output = DAGCircuit()<EOL>dagcircuit_output.name = dag.name<EOL>dagcircuit_output.add_qreg(QuantumRegister(self.coupling_map.size(), "<STR_LIT:q>"))<EOL>for creg in dag.cregs.values():<EOL><INDENT>dagcircuit_output.add_creg(creg)<EOL><DEDENT>identity_wire_map = {}<EOL>q = QuantumRegister(self.coupling_map.size(), '<STR_LIT:q>')<EOL>for j in range(self.coupling_map.size()):<EOL><INDENT>identity_wire_map[(q, j)] = (q, j)<EOL><DEDENT>for creg in dag.cregs.values():<EOL><INDENT>for j in range(creg.size):<EOL><INDENT>identity_wire_map[(creg, j)] = (creg, j)<EOL><DEDENT><DEDENT>first_layer = True  <EOL>for i, layer in enumerate(layerlist):<EOL><INDENT>success_flag, best_circ, best_d, best_layout, trivial_flag= self.layer_permutation(layer["<STR_LIT>"], layout, qubit_subset)<EOL>if not success_flag:<EOL><INDENT>serial_layerlist = list(layer["<STR_LIT>"].serial_layers())<EOL>for j, serial_layer in enumerate(serial_layerlist):<EOL><INDENT>success_flag, best_circ, best_d, best_layout, trivial_flag= self.layer_permutation(serial_layer["<STR_LIT>"], layout, qubit_subset)<EOL>if not success_flag:<EOL><INDENT>raise TranspilerError("<STR_LIT>" +<EOL>"<STR_LIT>" % (i, j))<EOL><DEDENT>if trivial_flag and first_layer:<EOL><INDENT>continue<EOL><DEDENT>layout = best_layout<EOL>dagcircuit_output.compose_back(<EOL>self.swap_mapper_layer_update(j,<EOL>first_layer,<EOL>best_layout,<EOL>best_d,<EOL>best_circ,<EOL>serial_layerlist),<EOL>identity_wire_map)<EOL>if first_layer:<EOL><INDENT>initial_layout = layout<EOL>first_layer = False<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>layout = best_layout<EOL>dagcircuit_output.compose_back(<EOL>self.swap_mapper_layer_update(i,<EOL>first_layer,<EOL>best_layout,<EOL>best_d,<EOL>best_circ,<EOL>layerlist),<EOL>identity_wire_map)<EOL>if first_layer:<EOL><INDENT>initial_layout = layout<EOL>first_layer = False<EOL><DEDENT><DEDENT><DEDENT>if first_layer:<EOL><INDENT>layout = initial_layout<EOL>for i, layer in enumerate(layerlist):<EOL><INDENT>dagcircuit_output.compose_back(layer["<STR_LIT>"], layout)<EOL><DEDENT><DEDENT>return dagcircuit_output<EOL>

Map a DAGCircuit onto a CouplingGraph using swap gates.

        Args:
            dag (DAGCircuit): input DAG circuit

        Returns:
            DAGCircuit: object containing a circuit equivalent to
            circuit_graph that respects couplings in coupling_map, and
            a layout dict mapping qubits of circuit_graph into qubits
            of coupling_map. The layout may differ from the initial_layout
            if the first layer of gates cannot be executed on the
            initial_layout.

        Raises:
            TranspilerError: if there was any error during the mapping or with the
                parameters.


def layer_permutation(self, layer_partition, layout, qubit_subset):

if self.seed is None:<EOL><INDENT>self.seed = np.random.randint(<NUM_LIT:0>, np.iinfo(np.int32).max)<EOL><DEDENT>rng = np.random.RandomState(self.seed)<EOL>rev_layout = {b: a for a, b in layout.items()}<EOL>gates = []<EOL>for layer in layer_partition:<EOL><INDENT>if len(layer) > <NUM_LIT:2>:<EOL><INDENT>raise TranspilerError("<STR_LIT>")<EOL><DEDENT>elif len(layer) == <NUM_LIT:2>:<EOL><INDENT>gates.append(tuple(layer))<EOL><DEDENT><DEDENT>dist = sum([self.coupling_map.distance(layout[g[<NUM_LIT:0>]][<NUM_LIT:1>], layout[g[<NUM_LIT:1>]][<NUM_LIT:1>]) for g in gates])<EOL>if dist == len(gates):<EOL><INDENT>circ = DAGCircuit()<EOL>circ.add_qreg(QuantumRegister(self.coupling_map.size(), "<STR_LIT:q>"))<EOL>return True, circ, <NUM_LIT:0>, layout, bool(gates)<EOL><DEDENT>n = self.coupling_map.size()<EOL>best_d = sys.maxsize  <EOL>best_circ = None  <EOL>best_layout = None  <EOL>QR = QuantumRegister(self.coupling_map.size(), "<STR_LIT:q>")<EOL>for _ in range(self.trials):<EOL><INDENT>trial_layout = layout.copy()<EOL>rev_trial_layout = rev_layout.copy()<EOL>trial_circ = DAGCircuit()<EOL>trial_circ.add_qreg(QR)<EOL>xi = {}<EOL>for i in self.coupling_map.physical_qubits:<EOL><INDENT>xi[(QR, i)] = {}<EOL><DEDENT>for i in self.coupling_map.physical_qubits:<EOL><INDENT>i = (QR, i)<EOL>for j in self.coupling_map.physical_qubits:<EOL><INDENT>j = (QR, j)<EOL>scale = <NUM_LIT:1> + rng.normal(<NUM_LIT:0>, <NUM_LIT:1> / n)<EOL>xi[i][j] = scale * self.coupling_map.distance(i[<NUM_LIT:1>], j[<NUM_LIT:1>]) ** <NUM_LIT:2><EOL>xi[j][i] = xi[i][j]<EOL><DEDENT><DEDENT>d = <NUM_LIT:1><EOL>circ = DAGCircuit()<EOL>circ.add_qreg(QR)<EOL>identity_wire_map = {(QR, j): (QR, j) for j in range(n)}<EOL>while d < <NUM_LIT:2> * n + <NUM_LIT:1>:<EOL><INDENT>qubit_set = set(qubit_subset)<EOL>while qubit_set:<EOL><INDENT>min_cost = sum([xi[trial_layout[g[<NUM_LIT:0>]]][trial_layout[g[<NUM_LIT:1>]]]<EOL>for g in gates])<EOL>progress_made = False<EOL>for e in self.coupling_map.get_edges():<EOL><INDENT>e = [(QR, edge) for edge in e]<EOL>if e[<NUM_LIT:0>] in qubit_set and e[<NUM_LIT:1>] in qubit_set:<EOL><INDENT>new_layout = trial_layout.copy()<EOL>new_layout[rev_trial_layout[e[<NUM_LIT:0>]]] = e[<NUM_LIT:1>]<EOL>new_layout[rev_trial_layout[e[<NUM_LIT:1>]]] = e[<NUM_LIT:0>]<EOL>rev_new_layout = rev_trial_layout.copy()<EOL>rev_new_layout[e[<NUM_LIT:0>]] = rev_trial_layout[e[<NUM_LIT:1>]]<EOL>rev_new_layout[e[<NUM_LIT:1>]] = rev_trial_layout[e[<NUM_LIT:0>]]<EOL>new_cost = sum([xi[new_layout[g[<NUM_LIT:0>]]][new_layout[g[<NUM_LIT:1>]]]<EOL>for g in gates])<EOL>if new_cost < min_cost:<EOL><INDENT>progress_made = True<EOL>min_cost = new_cost<EOL>opt_layout = new_layout<EOL>rev_opt_layout = rev_new_layout<EOL>opt_edge = e<EOL><DEDENT><DEDENT><DEDENT>if progress_made:<EOL><INDENT>qubit_set.remove(opt_edge[<NUM_LIT:0>])<EOL>qubit_set.remove(opt_edge[<NUM_LIT:1>])<EOL>trial_layout = opt_layout<EOL>rev_trial_layout = rev_opt_layout<EOL>circ.apply_operation_back(<EOL>SwapGate(),<EOL>[(opt_edge[<NUM_LIT:0>][<NUM_LIT:0>], opt_edge[<NUM_LIT:0>][<NUM_LIT:1>]), (opt_edge[<NUM_LIT:1>][<NUM_LIT:0>], opt_edge[<NUM_LIT:1>][<NUM_LIT:1>])],<EOL>[])<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>dist = sum([self.coupling_map.distance(trial_layout[g[<NUM_LIT:0>]][<NUM_LIT:1>],<EOL>trial_layout[g[<NUM_LIT:1>]][<NUM_LIT:1>]) for g in gates])<EOL>if dist == len(gates):<EOL><INDENT>trial_circ.compose_back(circ, identity_wire_map)<EOL>break<EOL><DEDENT>d += <NUM_LIT:1><EOL><DEDENT>dist = sum([self.coupling_map.distance(trial_layout[g[<NUM_LIT:0>]][<NUM_LIT:1>],<EOL>trial_layout[g[<NUM_LIT:1>]][<NUM_LIT:1>]) for g in gates])<EOL>if dist == len(gates):<EOL><INDENT>if d < best_d:<EOL><INDENT>best_circ = trial_circ<EOL>best_layout = trial_layout<EOL><DEDENT>best_d = min(best_d, d)<EOL><DEDENT><DEDENT>if best_circ is None:<EOL><INDENT>return False, None, None, None, False<EOL><DEDENT>return True, best_circ, best_d, best_layout, False<EOL>

Find a swap circuit that implements a permutation for this layer.

        The goal is to swap qubits such that qubits in the same two-qubit gates
        are adjacent.

        Based on Sergey Bravyi's algorithm.

        The layer_partition is a list of (qu)bit lists and each qubit is a
        tuple (qreg, index).
        The layout is a dict mapping qubits in the circuit to qubits in the
        coupling graph and represents the current positions of the data.
        The qubit_subset is the subset of qubits in the coupling graph that
        we have chosen to map into.
        The coupling is a CouplingGraph.
        TRIALS is the number of attempts the randomized algorithm makes.

        Returns: success_flag, best_circ, best_d, best_layout, trivial_flag

        If success_flag is True, then best_circ contains a DAGCircuit with
        the swap circuit, best_d contains the depth of the swap circuit, and
        best_layout contains the new positions of the data qubits after the
        swap circuit has been applied. The trivial_flag is set if the layer
        has no multi-qubit gates.


def swap_mapper_layer_update(self, i, first_layer, best_layout, best_d,<EOL>best_circ, layer_list):

layout = best_layout<EOL>dagcircuit_output = DAGCircuit()<EOL>QR = QuantumRegister(self.coupling_map.size(), '<STR_LIT:q>')<EOL>dagcircuit_output.add_qreg(QR)<EOL>identity_wire_map = {(QR, j): (QR, j) for j in range(self.coupling_map.size())}<EOL>if first_layer:<EOL><INDENT>for j in range(i + <NUM_LIT:1>):<EOL><INDENT>dagcircuit_output.compose_back(layer_list[j]["<STR_LIT>"], layout)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if best_d > <NUM_LIT:0>:<EOL><INDENT>dagcircuit_output.compose_back(best_circ, identity_wire_map)<EOL><DEDENT>dagcircuit_output.compose_back(layer_list[i]["<STR_LIT>"], layout)<EOL><DEDENT>return dagcircuit_output<EOL>

Update the QASM string for an iteration of swap_mapper.

        i = layer number
        first_layer = True if this is the first layer with multi-qubit gates
        best_layout = layout returned from swap algorithm
        best_d = depth returned from swap algorithm
        best_circ = swap circuit returned from swap algorithm
        layer_list = list of circuit objects for each layer

        Return DAGCircuit object to append to the output DAGCircuit.


super().__init__()<EOL>self.coupling_map = coupling_map<EOL>self.layout = initial_layout<EOL>

Args:
    coupling_map (CouplingMap): Directed graph represented a coupling map.
    initial_layout (Layout): The initial layout of the DAG.


new_dag = DAGCircuit()<EOL>if self.layout is None:<EOL><INDENT>self.layout = Layout.generate_trivial_layout(*dag.qregs.values())<EOL><DEDENT>for layer in dag.serial_layers():<EOL><INDENT>subdag = layer['<STR_LIT>']<EOL>for cnot_node in subdag.named_nodes('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>control = cnot_node.qargs[<NUM_LIT:0>]<EOL>target = cnot_node.qargs[<NUM_LIT:1>]<EOL>physical_q0 = self.layout[control]<EOL>physical_q1 = self.layout[target]<EOL>if self.coupling_map.distance(physical_q0, physical_q1) != <NUM_LIT:1>:<EOL><INDENT>raise TranspilerError('<STR_LIT>'<EOL>'<STR_LIT>' % (physical_q0, physical_q1))<EOL><DEDENT>if (physical_q0, physical_q1) not in self.coupling_map.get_edges():<EOL><INDENT>if control[<NUM_LIT:0>] not in subdag.qregs.values():<EOL><INDENT>subdag.add_qreg(control[<NUM_LIT:0>])<EOL><DEDENT>if target[<NUM_LIT:0>] not in subdag.qregs.values():<EOL><INDENT>subdag.add_qreg(target[<NUM_LIT:0>])<EOL><DEDENT>subdag.apply_operation_back(HGate(), [target], [])<EOL>subdag.apply_operation_back(HGate(), [control], [])<EOL>subdag.apply_operation_front(HGate(), [target], [])<EOL>subdag.apply_operation_front(HGate(), [control], [])<EOL>cnot_node.qargs[<NUM_LIT:0>], cnot_node.qargs[<NUM_LIT:1>] = target, control<EOL><DEDENT><DEDENT>new_dag.extend_back(subdag)<EOL><DEDENT>return new_dag<EOL>

Flips the cx nodes to match the directed coupling map.
Args:
    dag (DAGCircuit): DAG to map.
Returns:
    DAGCircuit: The rearranged dag for the coupling map

Raises:
    TranspilerError: If the circuit cannot be mapped just by flipping the
        cx nodes.


<EOL>final_op_types = ['<STR_LIT>', '<STR_LIT>']<EOL>final_ops = []<EOL>for candidate_node in dag.named_nodes(*final_op_types):<EOL><INDENT>is_final_op = True<EOL>for _, child_successors in dag.bfs_successors(candidate_node):<EOL><INDENT>if any(suc.type == '<STR_LIT>' and suc.name not in final_op_types<EOL>for suc in child_successors):<EOL><INDENT>is_final_op = False<EOL>break<EOL><DEDENT><DEDENT>if is_final_op:<EOL><INDENT>final_ops.append(candidate_node)<EOL><DEDENT><DEDENT>if not final_ops:<EOL><INDENT>return dag<EOL><DEDENT>barrier_layer = DAGCircuit()<EOL>for qreg in dag.qregs.values():<EOL><INDENT>barrier_layer.add_qreg(qreg)<EOL><DEDENT>for creg in dag.cregs.values():<EOL><INDENT>barrier_layer.add_creg(creg)<EOL><DEDENT>final_qubits = set(final_op.qargs[<NUM_LIT:0>] for final_op in final_ops)<EOL>barrier_layer.apply_operation_back(<EOL>Barrier(len(final_qubits)), list(final_qubits), [])<EOL>ordered_final_nodes = [node for node in dag.topological_op_nodes()<EOL>if node in set(final_ops)]<EOL>for final_node in ordered_final_nodes:<EOL><INDENT>barrier_layer.apply_operation_back(final_node.op,<EOL>final_node.qargs,<EOL>final_node.cargs)<EOL><DEDENT>for final_op in final_ops:<EOL><INDENT>dag.remove_op_node(final_op)<EOL><DEDENT>dag.extend_back(barrier_layer)<EOL>adjacent_pass = MergeAdjacentBarriers()<EOL>return adjacent_pass.run(dag)<EOL>

Return a circuit with a barrier before last measurements.


def __init__(self, coupling_map, layout=None):

super().__init__()<EOL>self.coupling_map = coupling_map<EOL>self.layout = layout<EOL>self.ancilla_name = '<STR_LIT>'<EOL>

Extends a Layout with the idle nodes from coupling_map.

Args:
    coupling_map (Coupling): directed graph representing a coupling map.
    layout (Layout): an existing layout. ancilla allocation occurs if
        the layout is smaller than the coupling_map.


self.layout = self.layout or self.property_set.get('<STR_LIT>')<EOL>if self.layout is None:<EOL><INDENT>raise TranspilerError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>layout_physical_qubits = self.layout.get_physical_bits().keys()<EOL>coupling_physical_qubits = self.coupling_map.physical_qubits<EOL>idle_physical_qubits = [q for q in coupling_physical_qubits<EOL>if q not in layout_physical_qubits]<EOL>if idle_physical_qubits:<EOL><INDENT>if self.ancilla_name in dag.qregs:<EOL><INDENT>save_prefix = QuantumRegister.prefix<EOL>QuantumRegister.prefix = self.ancilla_name<EOL>qreg = QuantumRegister(len(idle_physical_qubits))<EOL>QuantumRegister.prefix = save_prefix<EOL><DEDENT>else:<EOL><INDENT>qreg = QuantumRegister(len(idle_physical_qubits), name=self.ancilla_name)<EOL><DEDENT><DEDENT>for idx, idle_q in enumerate(idle_physical_qubits):<EOL><INDENT>self.property_set['<STR_LIT>'][idle_q] = qreg[idx]<EOL><DEDENT>return dag<EOL>

Extend the layout with new (physical qubit, virtual qubit) pairs.

The dag signals which virtual qubits are already in the circuit.
This pass will allocate new virtual qubits such that no collision occurs
(i.e. Layout bijectivity is preserved)

The coupling_map and layout together determine which physical qubits are free.

Args:
    dag (DAGCircuit): circuit to analyze

Returns:
    DAGCircuit: returns the same dag circuit, unmodified

Raises:
    TranspilerError: If there is not layout in the property set or not set at init time.


super().__init__()<EOL>self.coupling_map = coupling_map<EOL>

Chooses a DenseLayout

Args:
    coupling_map (Coupling): directed graph representing a coupling map.

Raises:
    TranspilerError: if invalid options


num_dag_qubits = sum([qreg.size for qreg in dag.qregs.values()])<EOL>if num_dag_qubits > self.coupling_map.size():<EOL><INDENT>raise TranspilerError('<STR_LIT>')<EOL><DEDENT>best_sub = self._best_subset(num_dag_qubits)<EOL>layout = Layout()<EOL>map_iter = <NUM_LIT:0><EOL>for qreg in dag.qregs.values():<EOL><INDENT>for i in range(qreg.size):<EOL><INDENT>layout[(qreg, i)] = int(best_sub[map_iter])<EOL>map_iter += <NUM_LIT:1><EOL><DEDENT><DEDENT>self.property_set['<STR_LIT>'] = layout<EOL>

Pick a convenient layout depending on the best matching
qubit connectivity, and set the property `layout`.

Args:
    dag (DAGCircuit): DAG to find layout for.

Raises:
    TranspilerError: if dag wider than self.coupling_map


if n_qubits == <NUM_LIT:1>:<EOL><INDENT>return np.array([<NUM_LIT:0>])<EOL><DEDENT>device_qubits = self.coupling_map.size()<EOL>cmap = np.asarray(self.coupling_map.get_edges())<EOL>data = np.ones_like(cmap[:, <NUM_LIT:0>])<EOL>sp_cmap = sp.coo_matrix((data, (cmap[:, <NUM_LIT:0>], cmap[:, <NUM_LIT:1>])),<EOL>shape=(device_qubits, device_qubits)).tocsr()<EOL>best = <NUM_LIT:0><EOL>best_map = None<EOL>for k in range(sp_cmap.shape[<NUM_LIT:0>]):<EOL><INDENT>bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False,<EOL>return_predecessors=False)<EOL>connection_count = <NUM_LIT:0><EOL>sub_graph = []<EOL>for i in range(n_qubits):<EOL><INDENT>node_idx = bfs[i]<EOL>for j in range(sp_cmap.indptr[node_idx],<EOL>sp_cmap.indptr[node_idx + <NUM_LIT:1>]):<EOL><INDENT>node = sp_cmap.indices[j]<EOL>for counter in range(n_qubits):<EOL><INDENT>if node == bfs[counter]:<EOL><INDENT>connection_count += <NUM_LIT:1><EOL>sub_graph.append([node_idx, node])<EOL>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if connection_count > best:<EOL><INDENT>best = connection_count<EOL>best_map = bfs[<NUM_LIT:0>:n_qubits]<EOL>mapping = {}<EOL>for edge in range(best_map.shape[<NUM_LIT:0>]):<EOL><INDENT>mapping[best_map[edge]] = edge<EOL><DEDENT>new_cmap = [[mapping[c[<NUM_LIT:0>]], mapping[c[<NUM_LIT:1>]]] for c in sub_graph]<EOL>rows = [edge[<NUM_LIT:0>] for edge in new_cmap]<EOL>cols = [edge[<NUM_LIT:1>] for edge in new_cmap]<EOL>data = [<NUM_LIT:1>]*len(rows)<EOL>sp_sub_graph = sp.coo_matrix((data, (rows, cols)),<EOL>shape=(n_qubits, n_qubits)).tocsr()<EOL>perm = cs.reverse_cuthill_mckee(sp_sub_graph)<EOL>best_map = best_map[perm]<EOL><DEDENT><DEDENT>return best_map<EOL>

Computes the qubit mapping with the best connectivity.

        Args:
            n_qubits (int): Number of subset qubits to consider.

        Returns:
            ndarray: Array of qubits to use for best connectivity mapping.


def _search_forward_n_swaps(layout, gates, coupling_map,<EOL>depth=SEARCH_DEPTH, width=SEARCH_WIDTH):

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

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

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


def _map_free_gates(layout, gates, coupling_map):

blocked_qubits = set()<EOL>mapped_gates = []<EOL>remaining_gates = []<EOL>for gate in gates:<EOL><INDENT>if not gate['<STR_LIT>']:<EOL><INDENT>qubits = [n for n in gate['<STR_LIT>'].nodes() if n.type == '<STR_LIT>'][<NUM_LIT:0>].qargs<EOL>if not qubits:<EOL><INDENT>continue<EOL><DEDENT>if blocked_qubits.intersection(qubits):<EOL><INDENT>blocked_qubits.update(qubits)<EOL>remaining_gates.append(gate)<EOL><DEDENT>else:<EOL><INDENT>mapped_gate = _transform_gate_for_layout(gate, layout)<EOL>mapped_gates.append(mapped_gate)<EOL><DEDENT>continue<EOL><DEDENT>qubits = gate['<STR_LIT>'][<NUM_LIT:0>]<EOL>if blocked_qubits.intersection(qubits):<EOL><INDENT>blocked_qubits.update(qubits)<EOL>remaining_gates.append(gate)<EOL><DEDENT>elif len(qubits) == <NUM_LIT:1>:<EOL><INDENT>mapped_gate = _transform_gate_for_layout(gate, layout)<EOL>mapped_gates.append(mapped_gate)<EOL><DEDENT>elif coupling_map.distance(*[layout[q] for q in qubits]) == <NUM_LIT:1>:<EOL><INDENT>mapped_gate = _transform_gate_for_layout(gate, layout)<EOL>mapped_gates.append(mapped_gate)<EOL><DEDENT>else:<EOL><INDENT>blocked_qubits.update(qubits)<EOL>remaining_gates.append(gate)<EOL><DEDENT><DEDENT>return mapped_gates, remaining_gates<EOL>

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

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

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


def _calc_layout_distance(gates, coupling_map, layout, max_gates=None):

if max_gates is None:<EOL><INDENT>max_gates = <NUM_LIT:50> + <NUM_LIT:10> * len(coupling_map.physical_qubits)<EOL><DEDENT>return sum(coupling_map.distance(*[layout[q] for q in gate['<STR_LIT>'][<NUM_LIT:0>]])<EOL>for gate in gates[:max_gates]<EOL>if gate['<STR_LIT>'] and len(gate['<STR_LIT>'][<NUM_LIT:0>]) == <NUM_LIT:2>)<EOL>

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


<EOL>return len([g for g in step['<STR_LIT>']<EOL>if len(g.qargs) == <NUM_LIT:2>]) - <NUM_LIT:3> * step['<STR_LIT>']<EOL>

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


target_dag = DAGCircuit()<EOL>target_dag.name = source_dag.name<EOL>for creg in source_dag.cregs.values():<EOL><INDENT>target_dag.add_creg(creg)<EOL><DEDENT>device_qreg = QuantumRegister(len(coupling_map.physical_qubits), '<STR_LIT:q>')<EOL>target_dag.add_qreg(device_qreg)<EOL>return target_dag<EOL>

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


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

Return op implementing a virtual gate on given layout.


device_qreg = QuantumRegister(len(layout.get_physical_bits()), '<STR_LIT:q>')<EOL>qreg_edge = [(device_qreg, i) for i in edge]<EOL>return [<EOL>DAGNode({'<STR_LIT>': SwapGate(), '<STR_LIT>': qreg_edge, '<STR_LIT>': [], '<STR_LIT:type>': '<STR_LIT>'})<EOL>]<EOL>

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


super().__init__()<EOL>self._coupling_map = coupling_map<EOL>self.initial_layout = initial_layout<EOL>self.requires.append(BarrierBeforeFinalMeasurements())<EOL>

Initialize a LookaheadSwap instance.

        Arguments:
            coupling_map (CouplingMap): CouplingMap of the target backend.
            initial_layout (Layout): The initial layout of the DAG to analyze.


coupling_map = self._coupling_map<EOL>ordered_virtual_gates = list(dag.serial_layers())<EOL>if self.initial_layout is None:<EOL><INDENT>if self.property_set["<STR_LIT>"]:<EOL><INDENT>self.initial_layout = self.property_set["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())<EOL><DEDENT><DEDENT>if len(dag.qubits()) != len(self.initial_layout):<EOL><INDENT>raise TranspilerError('<STR_LIT>')<EOL><DEDENT>if len(self._coupling_map.physical_qubits) != len(self.initial_layout):<EOL><INDENT>raise TranspilerError(<EOL>"<STR_LIT>")<EOL><DEDENT>mapped_gates = []<EOL>layout = self.initial_layout.copy()<EOL>gates_remaining = ordered_virtual_gates.copy()<EOL>while gates_remaining:<EOL><INDENT>best_step = _search_forward_n_swaps(layout, gates_remaining,<EOL>coupling_map)<EOL>layout = best_step['<STR_LIT>']<EOL>gates_mapped = best_step['<STR_LIT>']<EOL>gates_remaining = best_step['<STR_LIT>']<EOL>mapped_gates.extend(gates_mapped)<EOL><DEDENT>mapped_dag = _copy_circuit_metadata(dag, coupling_map)<EOL>for node in mapped_gates:<EOL><INDENT>mapped_dag.apply_operation_back(op=node.op, qargs=node.qargs, cargs=node.cargs)<EOL><DEDENT>return mapped_dag<EOL>

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

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


super().__init__()<EOL>self.coupling_map = coupling_map<EOL>self.initial_layout = initial_layout<EOL>self.requires.append(BarrierBeforeFinalMeasurements())<EOL>

Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
    coupling_map (CouplingMap): Directed graph represented a coupling map.
    initial_layout (Layout): initial layout of qubits in mapping


new_dag = DAGCircuit()<EOL>if self.initial_layout is None:<EOL><INDENT>if self.property_set["<STR_LIT>"]:<EOL><INDENT>self.initial_layout = self.property_set["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())<EOL><DEDENT><DEDENT>if len(dag.qubits()) != len(self.initial_layout):<EOL><INDENT>raise TranspilerError('<STR_LIT>')<EOL><DEDENT>if len(self.coupling_map.physical_qubits) != len(self.initial_layout):<EOL><INDENT>raise TranspilerError(<EOL>"<STR_LIT>")<EOL><DEDENT>current_layout = self.initial_layout.copy()<EOL>for layer in dag.serial_layers():<EOL><INDENT>subdag = layer['<STR_LIT>']<EOL>for gate in subdag.twoQ_gates():<EOL><INDENT>physical_q0 = current_layout[gate.qargs[<NUM_LIT:0>]]<EOL>physical_q1 = current_layout[gate.qargs[<NUM_LIT:1>]]<EOL>if self.coupling_map.distance(physical_q0, physical_q1) != <NUM_LIT:1>:<EOL><INDENT>swap_layer = DAGCircuit()<EOL>path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1)<EOL>for swap in range(len(path) - <NUM_LIT:2>):<EOL><INDENT>connected_wire_1 = path[swap]<EOL>connected_wire_2 = path[swap + <NUM_LIT:1>]<EOL>qubit_1 = current_layout[connected_wire_1]<EOL>qubit_2 = current_layout[connected_wire_2]<EOL>for qreg in current_layout.get_registers():<EOL><INDENT>if qreg not in swap_layer.qregs.values():<EOL><INDENT>swap_layer.add_qreg(qreg)<EOL><DEDENT><DEDENT>swap_layer.apply_operation_back(SwapGate(),<EOL>qargs=[qubit_1, qubit_2],<EOL>cargs=[])<EOL><DEDENT>edge_map = current_layout.combine_into_edge_map(self.initial_layout)<EOL>new_dag.compose_back(swap_layer, edge_map)<EOL>for swap in range(len(path) - <NUM_LIT:2>):<EOL><INDENT>current_layout.swap(path[swap], path[swap + <NUM_LIT:1>])<EOL><DEDENT><DEDENT><DEDENT>edge_map = current_layout.combine_into_edge_map(self.initial_layout)<EOL>new_dag.extend_back(subdag, edge_map)<EOL><DEDENT>return new_dag<EOL>

Runs the BasicSwap pass on `dag`.
Args:
    dag (DAGCircuit): DAG to map.

Returns:
    DAGCircuit: A mapped DAG.

Raises:
    TranspilerError: if the coupling map or the layout are not
    compatible with the DAG


super().__init__()<EOL>self.layout = initial_layout<EOL>self.coupling_map = coupling_map<EOL>

Checks if a DAGCircuit is mapped to `coupling_map`.
Args:
    coupling_map (CouplingMap): Directed graph representing a coupling map.
    initial_layout (Layout): The initial layout of the DAG to analyze.


if self.layout is None:<EOL><INDENT>if self.property_set["<STR_LIT>"]:<EOL><INDENT>self.layout = self.property_set["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>self.layout = Layout.generate_trivial_layout(*dag.qregs.values())<EOL><DEDENT><DEDENT>self.property_set['<STR_LIT>'] = True<EOL>for gate in dag.twoQ_gates():<EOL><INDENT>physical_q0 = self.layout[gate.qargs[<NUM_LIT:0>]]<EOL>physical_q1 = self.layout[gate.qargs[<NUM_LIT:1>]]<EOL>if self.coupling_map.distance(physical_q0, physical_q1) != <NUM_LIT:1>:<EOL><INDENT>self.property_set['<STR_LIT>'] = False<EOL>return<EOL><DEDENT><DEDENT>

If `dag` is mapped to `coupling_map`, the property
`is_swap_mapped` is set to True (or to False otherwise).

Args:
    dag (DAGCircuit): DAG to map.


super().__init__()<EOL>self.layout = layout<EOL>

Args:
    layout (Layout): layout of qubits to consider


self.layout = self.layout or self.property_set['<STR_LIT>']<EOL>if self.layout is None:<EOL><INDENT>raise TranspilerError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>layout_virtual_qubits = self.layout.get_virtual_bits().keys()<EOL>new_qregs = set(virtual_qubit[<NUM_LIT:0>] for virtual_qubit in layout_virtual_qubits<EOL>if virtual_qubit not in dag.wires)<EOL>for qreg in new_qregs:<EOL><INDENT>dag.add_qreg(qreg)<EOL><DEDENT>return dag<EOL>

Extends dag with virtual qubits that are in layout but not in the circuit yet.

Args:
    dag (DAGCircuit): DAG to extend.

Returns:
    DAGCircuit: An extended DAG.

Raises:
    TranspilerError: If there is not layout in the property set or not set at init time.


swaps = dag.op_nodes(SwapGate)<EOL>for swap in swaps:<EOL><INDENT>final_successor = []<EOL>for successor in dag.successors(swap):<EOL><INDENT>final_successor.append(successor.type == '<STR_LIT>' or (successor.type == '<STR_LIT>' and<EOL>successor.op.name == '<STR_LIT>'))<EOL><DEDENT>if all(final_successor):<EOL><INDENT>swap_qargs = swap.qargs<EOL>measure_layer = DAGCircuit()<EOL>for qreg in dag.qregs.values():<EOL><INDENT>measure_layer.add_qreg(qreg)<EOL><DEDENT>for creg in dag.cregs.values():<EOL><INDENT>measure_layer.add_creg(creg)<EOL><DEDENT>for successor in dag.successors(swap):<EOL><INDENT>if successor.type == '<STR_LIT>' and successor.op.name == '<STR_LIT>':<EOL><INDENT>dag.remove_op_node(successor)<EOL>old_measure_qarg = successor.qargs[<NUM_LIT:0>]<EOL>new_measure_qarg = swap_qargs[swap_qargs.index(old_measure_qarg) - <NUM_LIT:1>]<EOL>measure_layer.apply_operation_back(Measure(), [new_measure_qarg],<EOL>[successor.cargs[<NUM_LIT:0>]])<EOL><DEDENT><DEDENT>dag.extend_back(measure_layer)<EOL>dag.remove_op_node(swap)<EOL><DEDENT><DEDENT>return dag<EOL>

Return a new circuit that has been optimized.


for node in dag.threeQ_or_more_gates():<EOL><INDENT>rule = node.op.definition<EOL>if not rule:<EOL><INDENT>raise QiskitError("<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>node.op.name)<EOL><DEDENT>decomposition = DAGCircuit()<EOL>decomposition.add_qreg(rule[<NUM_LIT:0>][<NUM_LIT:1>][<NUM_LIT:0>][<NUM_LIT:0>])<EOL>for inst in rule:<EOL><INDENT>decomposition.apply_operation_back(*inst)<EOL><DEDENT>decomposition = self.run(decomposition)  <EOL>dag.substitute_node_with_dag(node, decomposition)<EOL><DEDENT>return dag<EOL>

Expand 3+ qubit gates using their decomposition rules.

        Args:
            dag(DAGCircuit): input dag
        Returns:
            DAGCircuit: output dag with maximum node degrees of 2
        Raises:
            QiskitError: if a 3q+ gate is not decomposable


def _is_dagnode_parameterized(node):<EOL><INDENT>return any(isinstance(param, Parameter) for param in node.op.params)<EOL><DEDENT>out = []<EOL>for run in runs:<EOL><INDENT>groups = groupby(run, _is_dagnode_parameterized)<EOL>for group_is_parameterized, gates in groups:<EOL><INDENT>if not group_is_parameterized:<EOL><INDENT>out.append(list(gates))<EOL><DEDENT><DEDENT><DEDENT>return out<EOL>

Finds runs containing parameterized gates and splits them into sequential
    runs excluding the parameterized gates.


runs = dag.collect_runs(["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT:id>"])<EOL>runs = _split_runs_on_parameters(runs)<EOL>for run in runs:<EOL><INDENT>right_name = "<STR_LIT>"<EOL>right_parameters = (<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>)  <EOL>for current_node in run:<EOL><INDENT>left_name = current_node.name<EOL>if (current_node.condition is not None<EOL>or len(current_node.qargs) != <NUM_LIT:1><EOL>or left_name not in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT:id>"]):<EOL><INDENT>raise TranspilerError("<STR_LIT>")<EOL><DEDENT>if left_name == "<STR_LIT>":<EOL><INDENT>left_parameters = (<NUM_LIT:0>, <NUM_LIT:0>, current_node.op.params[<NUM_LIT:0>])<EOL><DEDENT>elif left_name == "<STR_LIT>":<EOL><INDENT>left_parameters = (np.pi / <NUM_LIT:2>, current_node.op.params[<NUM_LIT:0>],<EOL>current_node.op.params[<NUM_LIT:1>])<EOL><DEDENT>elif left_name == "<STR_LIT>":<EOL><INDENT>left_parameters = tuple(current_node.op.params)<EOL><DEDENT>else:<EOL><INDENT>left_name = "<STR_LIT>"  <EOL>left_parameters = (<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>)<EOL><DEDENT>left_parameters = tuple([float(x) for x in left_parameters])<EOL>name_tuple = (left_name, right_name)<EOL>if name_tuple == ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>right_parameters = (<NUM_LIT:0>, <NUM_LIT:0>, right_parameters[<NUM_LIT:2>] +<EOL>left_parameters[<NUM_LIT:2>])<EOL><DEDENT>elif name_tuple == ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>right_parameters = (np.pi / <NUM_LIT:2>, right_parameters[<NUM_LIT:1>] +<EOL>left_parameters[<NUM_LIT:2>], right_parameters[<NUM_LIT:2>])<EOL><DEDENT>elif name_tuple == ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>right_name = "<STR_LIT>"<EOL>right_parameters = (np.pi / <NUM_LIT:2>, left_parameters[<NUM_LIT:1>],<EOL>right_parameters[<NUM_LIT:2>] + left_parameters[<NUM_LIT:2>])<EOL><DEDENT>elif name_tuple == ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>right_parameters = (right_parameters[<NUM_LIT:0>], right_parameters[<NUM_LIT:1>] +<EOL>left_parameters[<NUM_LIT:2>], right_parameters[<NUM_LIT:2>])<EOL><DEDENT>elif name_tuple == ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>right_name = "<STR_LIT>"<EOL>right_parameters = (left_parameters[<NUM_LIT:0>], left_parameters[<NUM_LIT:1>],<EOL>right_parameters[<NUM_LIT:2>] + left_parameters[<NUM_LIT:2>])<EOL><DEDENT>elif name_tuple == ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>right_name = "<STR_LIT>"<EOL>right_parameters = (np.pi - left_parameters[<NUM_LIT:2>] -<EOL>right_parameters[<NUM_LIT:1>], left_parameters[<NUM_LIT:1>] +<EOL>np.pi / <NUM_LIT:2>, right_parameters[<NUM_LIT:2>] +<EOL>np.pi / <NUM_LIT:2>)<EOL><DEDENT>elif name_tuple[<NUM_LIT:1>] == "<STR_LIT>":<EOL><INDENT>right_name = left_name<EOL>right_parameters = left_parameters<EOL><DEDENT>else:<EOL><INDENT>right_name = "<STR_LIT>"<EOL>right_parameters = Optimize1qGates.compose_u3(left_parameters[<NUM_LIT:0>],<EOL>left_parameters[<NUM_LIT:1>],<EOL>left_parameters[<NUM_LIT:2>],<EOL>right_parameters[<NUM_LIT:0>],<EOL>right_parameters[<NUM_LIT:1>],<EOL>right_parameters[<NUM_LIT:2>])<EOL><DEDENT>if np.mod(right_parameters[<NUM_LIT:0>], (<NUM_LIT:2> * np.pi)) == <NUM_LIT:0>and right_name != "<STR_LIT>":<EOL><INDENT>right_name = "<STR_LIT>"<EOL>right_parameters = (<NUM_LIT:0>, <NUM_LIT:0>, right_parameters[<NUM_LIT:1>] +<EOL>right_parameters[<NUM_LIT:2>] +<EOL>right_parameters[<NUM_LIT:0>])<EOL><DEDENT>if right_name == "<STR_LIT>":<EOL><INDENT>if np.mod((right_parameters[<NUM_LIT:0>] - np.pi / <NUM_LIT:2>), (<NUM_LIT:2> * np.pi)) == <NUM_LIT:0>:<EOL><INDENT>right_name = "<STR_LIT>"<EOL>right_parameters = (np.pi / <NUM_LIT:2>, right_parameters[<NUM_LIT:1>],<EOL>right_parameters[<NUM_LIT:2>] +<EOL>(right_parameters[<NUM_LIT:0>] - np.pi / <NUM_LIT:2>))<EOL><DEDENT>if np.mod((right_parameters[<NUM_LIT:0>] + np.pi / <NUM_LIT:2>), (<NUM_LIT:2> * np.pi)) == <NUM_LIT:0>:<EOL><INDENT>right_name = "<STR_LIT>"<EOL>right_parameters = (np.pi / <NUM_LIT:2>, right_parameters[<NUM_LIT:1>] +<EOL>np.pi, right_parameters[<NUM_LIT:2>] -<EOL>np.pi + (right_parameters[<NUM_LIT:0>] +<EOL>np.pi / <NUM_LIT:2>))<EOL><DEDENT><DEDENT>if right_name == "<STR_LIT>" and np.mod(right_parameters[<NUM_LIT:2>], (<NUM_LIT:2> * np.pi)) == <NUM_LIT:0>:<EOL><INDENT>right_name = "<STR_LIT>"<EOL><DEDENT><DEDENT>run_qarg = (QuantumRegister(<NUM_LIT:1>, '<STR_LIT:q>'), <NUM_LIT:0>)<EOL>new_op = Gate(name="<STR_LIT>", num_qubits=<NUM_LIT:1>, params=[])<EOL>if right_name == "<STR_LIT>":<EOL><INDENT>new_op = U1Gate(right_parameters[<NUM_LIT:2>])<EOL><DEDENT>if right_name == "<STR_LIT>":<EOL><INDENT>new_op = U2Gate(right_parameters[<NUM_LIT:1>], right_parameters[<NUM_LIT:2>])<EOL><DEDENT>if right_name == "<STR_LIT>":<EOL><INDENT>new_op = U3Gate(*right_parameters)<EOL><DEDENT>if right_name != '<STR_LIT>':<EOL><INDENT>new_dag = DAGCircuit()<EOL>new_dag.add_qreg(run_qarg[<NUM_LIT:0>])<EOL>new_dag.apply_operation_back(new_op, [run_qarg], [])<EOL>dag.substitute_node_with_dag(run[<NUM_LIT:0>], new_dag)<EOL><DEDENT>for current_node in run[<NUM_LIT:1>:]:<EOL><INDENT>dag.remove_op_node(current_node)<EOL><DEDENT>if right_name == "<STR_LIT>":<EOL><INDENT>dag.remove_op_node(run[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>return dag<EOL>


@staticmethod<EOL><INDENT>def compose_u3(theta1, phi1, lambda1, theta2, phi2, lambda2):<DEDENT>

<EOL>thetap, phip, lambdap = Optimize1qGates.yzy_to_zyz((lambda1 + phi2), theta1, theta2)<EOL>(theta, phi, lamb) = (thetap, phi1 + phip, lambda2 + lambdap)<EOL>return (theta, phi, lamb)<EOL>

Return a triple theta, phi, lambda for the product.

        u3(theta, phi, lambda)
           = u3(theta1, phi1, lambda1).u3(theta2, phi2, lambda2)
           = Rz(phi1).Ry(theta1).Rz(lambda1+phi2).Ry(theta2).Rz(lambda2)
           = Rz(phi1).Rz(phi').Ry(theta').Rz(lambda').Rz(lambda2)
           = u3(theta', phi1 + phi', lambda2 + lambda')

        Return theta, phi, lambda.


@staticmethod<EOL><INDENT>def yzy_to_zyz(xi, theta1, theta2, eps=<NUM_LIT>):  <DEDENT>

quaternion_yzy = quaternion_from_euler([theta1, xi, theta2], '<STR_LIT>')<EOL>euler = quaternion_yzy.to_zyz()<EOL>quaternion_zyz = quaternion_from_euler(euler, '<STR_LIT>')<EOL>out_angles = (euler[<NUM_LIT:1>], euler[<NUM_LIT:0>], euler[<NUM_LIT:2>])<EOL>abs_inner = abs(quaternion_zyz.data.dot(quaternion_yzy.data))<EOL>if not np.allclose(abs_inner, <NUM_LIT:1>, eps):<EOL><INDENT>raise TranspilerError('<STR_LIT>')<EOL><DEDENT>out_angles = tuple(<NUM_LIT:0> if np.abs(angle) < _CHOP_THRESHOLD else angle<EOL>for angle in out_angles)<EOL>return out_angles<EOL>

Express a Y.Z.Y single qubit gate as a Z.Y.Z gate.

        Solve the equation

        .. math::

        Ry(theta1).Rz(xi).Ry(theta2) = Rz(phi).Ry(theta).Rz(lambda)

        for theta, phi, and lambda.

        Return a solution theta, phi, and lambda.


def _add_unitary_single(self, gate, qubit):

<EOL>gate_tensor = np.array(gate, dtype=complex)<EOL>indexes = einsum_matmul_index([qubit], self._number_of_qubits)<EOL>self._unitary = np.einsum(indexes, gate_tensor, self._unitary,<EOL>dtype=complex, casting='<STR_LIT>')<EOL>

Apply an arbitrary 1-qubit unitary matrix.

        Args:
            gate (matrix_like): a single qubit gate matrix
            qubit (int): the qubit to apply gate to


def _add_unitary_two(self, gate, qubit0, qubit1):

<EOL>gate_tensor = np.reshape(np.array(gate, dtype=complex), <NUM_LIT:4> * [<NUM_LIT:2>])<EOL>indexes = einsum_matmul_index([qubit0, qubit1], self._number_of_qubits)<EOL>self._unitary = np.einsum(indexes, gate_tensor, self._unitary,<EOL>dtype=complex, casting='<STR_LIT>')<EOL>

Apply a two-qubit unitary matrix.

        Args:
            gate (matrix_like): a the two-qubit gate matrix
            qubit0 (int): gate qubit-0
            qubit1 (int): gate qubit-1


<EOL>if self._initial_unitary is None:<EOL><INDENT>return<EOL><DEDENT>shape = np.shape(self._initial_unitary)<EOL>required_shape = (<NUM_LIT:2> ** self._number_of_qubits,<EOL><NUM_LIT:2> ** self._number_of_qubits)<EOL>if shape != required_shape:<EOL><INDENT>raise BasicAerError('<STR_LIT>' +<EOL>'<STR_LIT>'.format(shape, required_shape))<EOL><DEDENT>


def _set_options(self, qobj_config=None, backend_options=None):

<EOL>self._initial_unitary = self.DEFAULT_OPTIONS["<STR_LIT>"]<EOL>self._chop_threshold = self.DEFAULT_OPTIONS["<STR_LIT>"]<EOL>if backend_options is None:<EOL><INDENT>backend_options = {}<EOL><DEDENT>if '<STR_LIT>' in backend_options:<EOL><INDENT>self._initial_unitary = np.array(backend_options['<STR_LIT>'],<EOL>dtype=complex)<EOL><DEDENT>elif hasattr(qobj_config, '<STR_LIT>'):<EOL><INDENT>self._initial_unitary = np.array(qobj_config.initial_unitary,<EOL>dtype=complex)<EOL><DEDENT>if self._initial_unitary is not None:<EOL><INDENT>shape = np.shape(self._initial_unitary)<EOL>if len(shape) != <NUM_LIT:2> or shape[<NUM_LIT:0>] != shape[<NUM_LIT:1>]:<EOL><INDENT>raise BasicAerError("<STR_LIT>")<EOL><DEDENT>iden = np.eye(len(self._initial_unitary))<EOL>u_dagger_u = np.dot(self._initial_unitary.T.conj(),<EOL>self._initial_unitary)<EOL>norm = np.linalg.norm(u_dagger_u - iden)<EOL>if round(norm, <NUM_LIT:10>) != <NUM_LIT:0>:<EOL><INDENT>raise BasicAerError("<STR_LIT>")<EOL><DEDENT><DEDENT>if '<STR_LIT>' in backend_options:<EOL><INDENT>self._chop_threshold = backend_options['<STR_LIT>']<EOL><DEDENT>elif hasattr(qobj_config, '<STR_LIT>'):<EOL><INDENT>self._chop_threshold = qobj_config.chop_threshold<EOL><DEDENT>

Set the backend options for all experiments in a qobj


self._validate_initial_unitary()<EOL>if self._initial_unitary is None:<EOL><INDENT>self._unitary = np.eye(<NUM_LIT:2> ** self._number_of_qubits,<EOL>dtype=complex)<EOL><DEDENT>else:<EOL><INDENT>self._unitary = self._initial_unitary.copy()<EOL><DEDENT>self._unitary = np.reshape(self._unitary,<EOL>self._number_of_qubits * [<NUM_LIT:2>, <NUM_LIT:2>])<EOL>


unitary = np.reshape(self._unitary, <NUM_LIT:2> * [<NUM_LIT:2> ** self._number_of_qubits])<EOL>unitary = np.stack((unitary.real, unitary.imag), axis=-<NUM_LIT:1>)<EOL>unitary[abs(unitary) < self._chop_threshold] = <NUM_LIT:0.0><EOL>return unitary<EOL>

Return the current unitary in JSON Result spec format


def run(self, qobj, backend_options=None):

self._set_options(qobj_config=qobj.config,<EOL>backend_options=backend_options)<EOL>job_id = str(uuid.uuid4())<EOL>job = BasicAerJob(self, job_id, self._run_job, qobj)<EOL>job.submit()<EOL>return job<EOL>

Run qobj asynchronously.

        Args:
            qobj (Qobj): payload of the experiment
            backend_options (dict): backend options

        Returns:
            BasicAerJob: derived from BaseJob

        Additional Information::

            backend_options: Is a dict of options for the backend. It may contain
                * "initial_unitary": matrix_like
                * "chop_threshold": double

            The "initial_unitary" option specifies a custom initial unitary
            matrix for the simulator to be used instead of the identity
            matrix. This size of this matrix must be correct for the number
            of qubits inall experiments in the qobj.

            The "chop_threshold" option specifies a trunctation value for
            setting small values to zero in the output unitary. The default
            value is 1e-15.

            Example::

                backend_options = {
                    "initial_unitary": np.array([[1, 0, 0, 0],
                                                 [0, 0, 0, 1],
                                                 [0, 0, 1, 0],
                                                 [0, 1, 0, 0]])
                    "chop_threshold": 1e-15
                }


self._validate(qobj)<EOL>result_list = []<EOL>start = time.time()<EOL>for experiment in qobj.experiments:<EOL><INDENT>result_list.append(self.run_experiment(experiment))<EOL><DEDENT>end = time.time()<EOL>result = {'<STR_LIT>': self.name(),<EOL>'<STR_LIT>': self._configuration.backend_version,<EOL>'<STR_LIT>': qobj.qobj_id,<EOL>'<STR_LIT>': job_id,<EOL>'<STR_LIT>': result_list,<EOL>'<STR_LIT:status>': '<STR_LIT>',<EOL>'<STR_LIT:success>': True,<EOL>'<STR_LIT>': (end - start),<EOL>'<STR_LIT>': qobj.header.as_dict()}<EOL>return Result.from_dict(result)<EOL>

Run experiments in qobj.

        Args:
            job_id (str): unique id for the job.
            qobj (Qobj): job description

        Returns:
            Result: Result object


start = time.time()<EOL>self._number_of_qubits = experiment.header.n_qubits<EOL>self._validate_initial_unitary()<EOL>self._initialize_unitary()<EOL>for operation in experiment.instructions:<EOL><INDENT>if operation.name in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>params = getattr(operation, '<STR_LIT>', None)<EOL>qubit = operation.qubits[<NUM_LIT:0>]<EOL>gate = single_gate_matrix(operation.name, params)<EOL>self._add_unitary_single(gate, qubit)<EOL><DEDENT>elif operation.name in ('<STR_LIT:id>', '<STR_LIT>'):<EOL><INDENT>pass<EOL><DEDENT>elif operation.name in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>qubit0 = operation.qubits[<NUM_LIT:0>]<EOL>qubit1 = operation.qubits[<NUM_LIT:1>]<EOL>gate = cx_gate_matrix()<EOL>self._add_unitary_two(gate, qubit0, qubit1)<EOL><DEDENT>elif operation.name == '<STR_LIT>':<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>backend = self.name()<EOL>err_msg = '<STR_LIT>'<EOL>raise BasicAerError(err_msg.format(backend, operation.name))<EOL><DEDENT><DEDENT>data = {'<STR_LIT>': self._get_unitary()}<EOL>end = time.time()<EOL>return {'<STR_LIT:name>': experiment.header.name,<EOL>'<STR_LIT>': <NUM_LIT:1>,<EOL>'<STR_LIT:data>': data,<EOL>'<STR_LIT:status>': '<STR_LIT>',<EOL>'<STR_LIT:success>': True,<EOL>'<STR_LIT>': (end - start),<EOL>'<STR_LIT>': experiment.header.as_dict()}<EOL>

Run an experiment (circuit) and return a single experiment result.

        Args:
            experiment (QobjExperiment): experiment from qobj experiments list

        Returns:
            dict: A result dictionary which looks something like::

                {
                "name": name of this experiment (obtained from qobj.experiment header)
                "seed": random seed used for simulation
                "shots": number of shots used in the simulation
                "data":
                    {
                    "unitary": [[[0.0, 0.0], [1.0, 0.0]],
                                [[1.0, 0.0], [0.0, 0.0]]]
                    },
                "status": status string for the simulation
                "success": boolean
                "time taken": simulation time of this single experiment
                }

        Raises:
            BasicAerError: if the number of qubits in the circuit is greater than 24.
            Note that the practical qubit limit is much lower than 24.


n_qubits = qobj.config.n_qubits<EOL>max_qubits = self.configuration().n_qubits<EOL>if n_qubits > max_qubits:<EOL><INDENT>raise BasicAerError('<STR_LIT>'.format(n_qubits) +<EOL>'<STR_LIT>'.format(max_qubits) +<EOL>'<STR_LIT>'.format(self.name()))<EOL><DEDENT>if hasattr(qobj.config, '<STR_LIT>') and qobj.config.shots != <NUM_LIT:1>:<EOL><INDENT>logger.info('<STR_LIT>',<EOL>self.name())<EOL>qobj.config.shots = <NUM_LIT:1><EOL><DEDENT>for experiment in qobj.experiments:<EOL><INDENT>name = experiment.header.name<EOL>if getattr(experiment.config, '<STR_LIT>', <NUM_LIT:1>) != <NUM_LIT:1>:<EOL><INDENT>logger.info('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>self.name(), name)<EOL>experiment.config.shots = <NUM_LIT:1><EOL><DEDENT>for operation in experiment.instructions:<EOL><INDENT>if operation.name in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise BasicAerError('<STR_LIT>' +<EOL>'<STR_LIT>', self.name(),<EOL>operation.name, name)<EOL><DEDENT><DEDENT><DEDENT>

Semantic validations of the qobj which cannot be done via schemas.
        Some of these may later move to backend schemas.
        1. No shots
        2. No measurements in the middle


<EOL>indexes = einsum_vecmul_index([qubit], self._number_of_qubits)<EOL>gate_tensor = np.array(gate, dtype=complex)<EOL>self._statevector = np.einsum(indexes, gate_tensor,<EOL>self._statevector,<EOL>dtype=complex,<EOL>casting='<STR_LIT>')<EOL>


<EOL>indexes = einsum_vecmul_index([qubit0, qubit1], self._number_of_qubits)<EOL>gate_tensor = np.reshape(np.array(gate, dtype=complex), <NUM_LIT:4> * [<NUM_LIT:2>])<EOL>self._statevector = np.einsum(indexes, gate_tensor,<EOL>self._statevector,<EOL>dtype=complex,<EOL>casting='<STR_LIT>')<EOL>


<EOL>axis = list(range(self._number_of_qubits))<EOL>axis.remove(self._number_of_qubits - <NUM_LIT:1> - qubit)<EOL>probabilities = np.sum(np.abs(self._statevector) ** <NUM_LIT:2>, axis=tuple(axis))<EOL>random_number = self._local_random.rand()<EOL>if random_number < probabilities[<NUM_LIT:0>]:<EOL><INDENT>return '<STR_LIT:0>', probabilities[<NUM_LIT:0>]<EOL><DEDENT>return '<STR_LIT:1>', probabilities[<NUM_LIT:1>]<EOL>

Simulate the outcome of measurement of a qubit.

        Args:
            qubit (int): the qubit to measure

        Return:
            tuple: pair (outcome, probability) where outcome is '0' or '1' and
            probability is the probability of the returned outcome.


def _add_sample_measure(self, measure_params, num_samples):

<EOL>measured_qubits = list({qubit for qubit, cmembit in measure_params})<EOL>num_measured = len(measured_qubits)<EOL>axis = list(range(self._number_of_qubits))<EOL>for qubit in reversed(measured_qubits):<EOL><INDENT>axis.remove(self._number_of_qubits - <NUM_LIT:1> - qubit)<EOL><DEDENT>probabilities = np.reshape(np.sum(np.abs(self._statevector) ** <NUM_LIT:2>,<EOL>axis=tuple(axis)),<EOL><NUM_LIT:2> ** num_measured)<EOL>samples = self._local_random.choice(range(<NUM_LIT:2> ** num_measured),<EOL>num_samples, p=probabilities)<EOL>memory = []<EOL>for sample in samples:<EOL><INDENT>classical_memory = self._classical_memory<EOL>for count, (qubit, cmembit) in enumerate(sorted(measure_params)):<EOL><INDENT>qubit_outcome = int((sample & (<NUM_LIT:1> << count)) >> count)<EOL>membit = <NUM_LIT:1> << cmembit<EOL>classical_memory = (classical_memory & (~membit)) | (qubit_outcome << cmembit)<EOL><DEDENT>value = bin(classical_memory)[<NUM_LIT:2>:]<EOL>memory.append(hex(int(value, <NUM_LIT:2>)))<EOL><DEDENT>return memory<EOL>

Generate memory samples from current statevector.

        Args:
            measure_params (list): List of (qubit, cmembit) values for
                                   measure instructions to sample.
            num_samples (int): The number of memory samples to generate.

        Returns:
            list: A list of memory values in hex format.


def _add_qasm_measure(self, qubit, cmembit, cregbit=None):

<EOL>outcome, probability = self._get_measure_outcome(qubit)<EOL>membit = <NUM_LIT:1> << cmembit<EOL>self._classical_memory = (self._classical_memory & (~membit)) | (int(outcome) << cmembit)<EOL>if cregbit is not None:<EOL><INDENT>regbit = <NUM_LIT:1> << cregbit<EOL>self._classical_register =(self._classical_register & (~regbit)) | (int(outcome) << cregbit)<EOL><DEDENT>if outcome == '<STR_LIT:0>':<EOL><INDENT>update_diag = [[<NUM_LIT:1> / np.sqrt(probability), <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:0>]]<EOL><DEDENT>else:<EOL><INDENT>update_diag = [[<NUM_LIT:0>, <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:1> / np.sqrt(probability)]]<EOL><DEDENT>self._add_unitary_single(update_diag, qubit)<EOL>

Apply a measure instruction to a qubit.

        Args:
            qubit (int): qubit is the qubit measured.
            cmembit (int): is the classical memory bit to store outcome in.
            cregbit (int, optional): is the classical register bit to store outcome in.


<EOL>outcome, probability = self._get_measure_outcome(qubit)<EOL>if outcome == '<STR_LIT:0>':<EOL><INDENT>update = [[<NUM_LIT:1> / np.sqrt(probability), <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:0>]]<EOL>self._add_unitary_single(update, qubit)<EOL><DEDENT>else:<EOL><INDENT>update = [[<NUM_LIT:0>, <NUM_LIT:1> / np.sqrt(probability)], [<NUM_LIT:0>, <NUM_LIT:0>]]<EOL>self._add_unitary_single(update, qubit)<EOL><DEDENT>

Apply a reset instruction to a qubit.

        Args:
            qubit (int): the qubit being rest

        This is done by doing a simulating a measurement
        outcome and projecting onto the outcome state while
        renormalizing.


<EOL>if self._initial_statevector is None:<EOL><INDENT>return<EOL><DEDENT>length = len(self._initial_statevector)<EOL>required_dim = <NUM_LIT:2> ** self._number_of_qubits<EOL>if length != required_dim:<EOL><INDENT>raise BasicAerError('<STR_LIT>' +<EOL>'<STR_LIT>'.format(length, required_dim))<EOL><DEDENT>


<EOL>self._initial_statevector = self.DEFAULT_OPTIONS["<STR_LIT>"]<EOL>self._chop_threshold = self.DEFAULT_OPTIONS["<STR_LIT>"]<EOL>if backend_options is None:<EOL><INDENT>backend_options = {}<EOL><DEDENT>if '<STR_LIT>' in backend_options:<EOL><INDENT>self._initial_statevector = np.array(backend_options['<STR_LIT>'],<EOL>dtype=complex)<EOL><DEDENT>elif hasattr(qobj_config, '<STR_LIT>'):<EOL><INDENT>self._initial_statevector = np.array(qobj_config.initial_statevector,<EOL>dtype=complex)<EOL><DEDENT>if self._initial_statevector is not None:<EOL><INDENT>norm = np.linalg.norm(self._initial_statevector)<EOL>if round(norm, <NUM_LIT:12>) != <NUM_LIT:1>:<EOL><INDENT>raise BasicAerError('<STR_LIT>' +<EOL>'<STR_LIT>'.format(norm))<EOL><DEDENT><DEDENT>if '<STR_LIT>' in backend_options:<EOL><INDENT>self._chop_threshold = backend_options['<STR_LIT>']<EOL><DEDENT>elif hasattr(qobj_config, '<STR_LIT>'):<EOL><INDENT>self._chop_threshold = qobj_config.chop_threshold<EOL><DEDENT>


if self._initial_statevector is None:<EOL><INDENT>self._statevector = np.zeros(<NUM_LIT:2> ** self._number_of_qubits,<EOL>dtype=complex)<EOL>self._statevector[<NUM_LIT:0>] = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>self._statevector = self._initial_statevector.copy()<EOL><DEDENT>self._statevector = np.reshape(self._statevector,<EOL>self._number_of_qubits * [<NUM_LIT:2>])<EOL>

Set the initial statevector for simulation


vec = np.reshape(self._statevector, <NUM_LIT:2> ** self._number_of_qubits)<EOL>vec = np.stack([vec.real, vec.imag], axis=<NUM_LIT:1>)<EOL>vec[abs(vec) < self._chop_threshold] = <NUM_LIT:0.0><EOL>return vec<EOL>

Return the current statevector in JSON Result spec format


<EOL>if self._shots <= <NUM_LIT:1>:<EOL><INDENT>self._sample_measure = False<EOL>return<EOL><DEDENT>if hasattr(experiment.config, '<STR_LIT>'):<EOL><INDENT>self._sample_measure = experiment.config.allows_measure_sampling<EOL><DEDENT>else:<EOL><INDENT>measure_flag = False<EOL>for instruction in experiment.instructions:<EOL><INDENT>if instruction.name == "<STR_LIT>":<EOL><INDENT>self._sample_measure = False<EOL>return<EOL><DEDENT>if measure_flag:<EOL><INDENT>if instruction.name not in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT:id>", "<STR_LIT>"]:<EOL><INDENT>self._sample_measure = False<EOL>return<EOL><DEDENT><DEDENT>elif instruction.name == "<STR_LIT>":<EOL><INDENT>measure_flag = True<EOL><DEDENT><DEDENT>self._sample_measure = True<EOL><DEDENT>

Determine if measure sampling is allowed for an experiment

        Args:
            experiment (QobjExperiment): a qobj experiment.


Run qobj asynchronously.

        Args:
            qobj (Qobj): payload of the experiment
            backend_options (dict): backend options

        Returns:
            BasicAerJob: derived from BaseJob

        Additional Information:
            backend_options: Is a dict of options for the backend. It may contain
                * "initial_statevector": vector_like

            The "initial_statevector" option specifies a custom initial
            initial statevector for the simulator to be used instead of the all
            zero state. This size of this vector must be correct for the number
            of qubits in all experiments in the qobj.

            Example::

                backend_options = {
                    "initial_statevector": np.array([1, 0, 0, 1j]) / np.sqrt(2),
                }


self._validate(qobj)<EOL>result_list = []<EOL>self._shots = qobj.config.shots<EOL>self._memory = getattr(qobj.config, '<STR_LIT>', False)<EOL>self._qobj_config = qobj.config<EOL>start = time.time()<EOL>for experiment in qobj.experiments:<EOL><INDENT>result_list.append(self.run_experiment(experiment))<EOL><DEDENT>end = time.time()<EOL>result = {'<STR_LIT>': self.name(),<EOL>'<STR_LIT>': self._configuration.backend_version,<EOL>'<STR_LIT>': qobj.qobj_id,<EOL>'<STR_LIT>': job_id,<EOL>'<STR_LIT>': result_list,<EOL>'<STR_LIT:status>': '<STR_LIT>',<EOL>'<STR_LIT:success>': True,<EOL>'<STR_LIT>': (end - start),<EOL>'<STR_LIT>': qobj.header.as_dict()}<EOL>return Result.from_dict(result)<EOL>

Run experiments in qobj

        Args:
            job_id (str): unique id for the job.
            qobj (Qobj): job description

        Returns:
            Result: Result object


start = time.time()<EOL>self._number_of_qubits = experiment.config.n_qubits<EOL>self._number_of_cmembits = experiment.config.memory_slots<EOL>self._statevector = <NUM_LIT:0><EOL>self._classical_memory = <NUM_LIT:0><EOL>self._classical_register = <NUM_LIT:0><EOL>self._sample_measure = False<EOL>self._validate_initial_statevector()<EOL>if hasattr(experiment.config, '<STR_LIT>'):<EOL><INDENT>seed = experiment.config.seed<EOL><DEDENT>elif hasattr(self._qobj_config, '<STR_LIT>'):<EOL><INDENT>seed = self._qobj_config.seed<EOL><DEDENT>else:<EOL><INDENT>seed = np.random.randint(<NUM_LIT>, dtype='<STR_LIT>')<EOL><DEDENT>self._local_random.seed(seed=seed)<EOL>self._validate_measure_sampling(experiment)<EOL>memory = []<EOL>if self._sample_measure:<EOL><INDENT>shots = <NUM_LIT:1><EOL>measure_sample_ops = []<EOL><DEDENT>else:<EOL><INDENT>shots = self._shots<EOL><DEDENT>for _ in range(shots):<EOL><INDENT>self._initialize_statevector()<EOL>self._classical_memory = <NUM_LIT:0><EOL>self._classical_register = <NUM_LIT:0><EOL>for operation in experiment.instructions:<EOL><INDENT>conditional = getattr(operation, '<STR_LIT>', None)<EOL>if isinstance(conditional, int):<EOL><INDENT>conditional_bit_set = (self._classical_register >> conditional) & <NUM_LIT:1><EOL>if not conditional_bit_set:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>elif conditional is not None:<EOL><INDENT>mask = int(operation.conditional.mask, <NUM_LIT:16>)<EOL>if mask > <NUM_LIT:0>:<EOL><INDENT>value = self._classical_memory & mask<EOL>while (mask & <NUM_LIT>) == <NUM_LIT:0>:<EOL><INDENT>mask >>= <NUM_LIT:1><EOL>value >>= <NUM_LIT:1><EOL><DEDENT>if value != int(operation.conditional.val, <NUM_LIT:16>):<EOL><INDENT>continue<EOL><DEDENT><DEDENT><DEDENT>if operation.name in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>params = getattr(operation, '<STR_LIT>', None)<EOL>qubit = operation.qubits[<NUM_LIT:0>]<EOL>gate = single_gate_matrix(operation.name, params)<EOL>self._add_unitary_single(gate, qubit)<EOL><DEDENT>elif operation.name in ('<STR_LIT:id>', '<STR_LIT>'):<EOL><INDENT>pass<EOL><DEDENT>elif operation.name in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>qubit0 = operation.qubits[<NUM_LIT:0>]<EOL>qubit1 = operation.qubits[<NUM_LIT:1>]<EOL>gate = cx_gate_matrix()<EOL>self._add_unitary_two(gate, qubit0, qubit1)<EOL><DEDENT>elif operation.name == '<STR_LIT>':<EOL><INDENT>qubit = operation.qubits[<NUM_LIT:0>]<EOL>self._add_qasm_reset(qubit)<EOL><DEDENT>elif operation.name == '<STR_LIT>':<EOL><INDENT>pass<EOL><DEDENT>elif operation.name == '<STR_LIT>':<EOL><INDENT>qubit = operation.qubits[<NUM_LIT:0>]<EOL>cmembit = operation.memory[<NUM_LIT:0>]<EOL>cregbit = operation.register[<NUM_LIT:0>] if hasattr(operation, '<STR_LIT>') else None<EOL>if self._sample_measure:<EOL><INDENT>measure_sample_ops.append((qubit, cmembit))<EOL><DEDENT>else:<EOL><INDENT>self._add_qasm_measure(qubit, cmembit, cregbit)<EOL><DEDENT><DEDENT>elif operation.name == '<STR_LIT>':<EOL><INDENT>mask = int(operation.mask, <NUM_LIT:16>)<EOL>relation = operation.relation<EOL>val = int(operation.val, <NUM_LIT:16>)<EOL>cregbit = operation.register<EOL>cmembit = operation.memory if hasattr(operation, '<STR_LIT>') else None<EOL>compared = (self._classical_register & mask) - val<EOL>if relation == '<STR_LIT>':<EOL><INDENT>outcome = (compared == <NUM_LIT:0>)<EOL><DEDENT>elif relation == '<STR_LIT>':<EOL><INDENT>outcome = (compared != <NUM_LIT:0>)<EOL><DEDENT>elif relation == '<STR_LIT:<>':<EOL><INDENT>outcome = (compared < <NUM_LIT:0>)<EOL><DEDENT>elif relation == '<STR_LIT>':<EOL><INDENT>outcome = (compared <= <NUM_LIT:0>)<EOL><DEDENT>elif relation == '<STR_LIT:>>':<EOL><INDENT>outcome = (compared > <NUM_LIT:0>)<EOL><DEDENT>elif relation == '<STR_LIT>':<EOL><INDENT>outcome = (compared >= <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>raise BasicAerError('<STR_LIT>')<EOL><DEDENT>regbit = <NUM_LIT:1> << cregbit<EOL>self._classical_register =(self._classical_register & (~regbit)) | (int(outcome) << cregbit)<EOL>if cmembit is not None:<EOL><INDENT>membit = <NUM_LIT:1> << cmembit<EOL>self._classical_memory =(self._classical_memory & (~membit)) | (int(outcome) << cmembit)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>backend = self.name()<EOL>err_msg = '<STR_LIT>'<EOL>raise BasicAerError(err_msg.format(backend, operation.name))<EOL><DEDENT><DEDENT>if self._number_of_cmembits > <NUM_LIT:0>:<EOL><INDENT>if self._sample_measure:<EOL><INDENT>memory = self._add_sample_measure(measure_sample_ops, self._shots)<EOL><DEDENT>else:<EOL><INDENT>outcome = bin(self._classical_memory)[<NUM_LIT:2>:]<EOL>memory.append(hex(int(outcome, <NUM_LIT:2>)))<EOL><DEDENT><DEDENT><DEDENT>data = {'<STR_LIT>': dict(Counter(memory))}<EOL>if self._memory:<EOL><INDENT>data['<STR_LIT>'] = memory<EOL><DEDENT>if self.SHOW_FINAL_STATE:<EOL><INDENT>data['<STR_LIT>'] = self._get_statevector()<EOL>if not data['<STR_LIT>']:<EOL><INDENT>data.pop('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT>' in data and not data['<STR_LIT>']:<EOL><INDENT>data.pop('<STR_LIT>')<EOL><DEDENT><DEDENT>end = time.time()<EOL>return {'<STR_LIT:name>': experiment.header.name,<EOL>'<STR_LIT>': seed,<EOL>'<STR_LIT>': self._shots,<EOL>'<STR_LIT:data>': data,<EOL>'<STR_LIT:status>': '<STR_LIT>',<EOL>'<STR_LIT:success>': True,<EOL>'<STR_LIT>': (end - start),<EOL>'<STR_LIT>': experiment.header.as_dict()}<EOL>

Run an experiment (circuit) and return a single experiment result.

        Args:
            experiment (QobjExperiment): experiment from qobj experiments list

        Returns:
             dict: A result dictionary which looks something like::

                {
                "name": name of this experiment (obtained from qobj.experiment header)
                "seed": random seed used for simulation
                "shots": number of shots used in the simulation
                "data":
                    {
                    "counts": {'0x9: 5, ...},
                    "memory": ['0x9', '0xF', '0x1D', ..., '0x9']
                    },
                "status": status string for the simulation
                "success": boolean
                "time_taken": simulation time of this single experiment
                }
        Raises:
            BasicAerError: if an error occurred.


n_qubits = qobj.config.n_qubits<EOL>max_qubits = self.configuration().n_qubits<EOL>if n_qubits > max_qubits:<EOL><INDENT>raise BasicAerError('<STR_LIT>'.format(n_qubits) +<EOL>'<STR_LIT>'.format(max_qubits) +<EOL>'<STR_LIT>'.format(self.name()))<EOL><DEDENT>for experiment in qobj.experiments:<EOL><INDENT>name = experiment.header.name<EOL>if experiment.config.memory_slots == <NUM_LIT:0>:<EOL><INDENT>logger.warning('<STR_LIT>'<EOL>'<STR_LIT>', name)<EOL><DEDENT>elif '<STR_LIT>' not in [op.name for op in experiment.instructions]:<EOL><INDENT>logger.warning('<STR_LIT>'<EOL>'<STR_LIT>', name)<EOL><DEDENT><DEDENT>

Semantic validations of the qobj which cannot be done via schemas.


return super().run(qobj, backend_options=backend_options)<EOL>

Run qobj asynchronously.

        Args:
            qobj (Qobj): payload of the experiment
            backend_options (dict): backend options

        Returns:
            BasicAerJob: derived from BaseJob

        Additional Information::

            backend_options: Is a dict of options for the backend. It may contain
                * "initial_statevector": vector_like
                * "chop_threshold": double

            The "initial_statevector" option specifies a custom initial
            initial statevector for the simulator to be used instead of the all
            zero state. This size of this vector must be correct for the number
            of qubits in all experiments in the qobj.

            The "chop_threshold" option specifies a trunctation value for
            setting small values to zero in the output statevector. The default
            value is 1e-15.

            Example::

                backend_options = {
                    "initial_statevector": np.array([1, 0, 0, 1j]) / np.sqrt(2),
                    "chop_threshold": 1e-15
                }


n_qubits = qobj.config.n_qubits<EOL>max_qubits = self.configuration().n_qubits<EOL>if n_qubits > max_qubits:<EOL><INDENT>raise BasicAerError('<STR_LIT>'.format(n_qubits) +<EOL>'<STR_LIT>'.format(max_qubits) +<EOL>'<STR_LIT>'.format(self.name()))<EOL><DEDENT>if qobj.config.shots != <NUM_LIT:1>:<EOL><INDENT>logger.info('<STR_LIT>',<EOL>self.name())<EOL>qobj.config.shots = <NUM_LIT:1><EOL><DEDENT>for experiment in qobj.experiments:<EOL><INDENT>name = experiment.header.name<EOL>if getattr(experiment.config, '<STR_LIT>', <NUM_LIT:1>) != <NUM_LIT:1>:<EOL><INDENT>logger.info('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>self.name(), name)<EOL>experiment.config.shots = <NUM_LIT:1><EOL><DEDENT><DEDENT>

Semantic validations of the qobj which cannot be done via schemas.
        Some of these may later move to backend schemas.

        1. No shots
        2. No measurements in the middle


if gate in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return params[<NUM_LIT:0>], params[<NUM_LIT:1>], params[<NUM_LIT:2>]<EOL><DEDENT>elif gate == '<STR_LIT>':<EOL><INDENT>return np.pi / <NUM_LIT:2>, params[<NUM_LIT:0>], params[<NUM_LIT:1>]<EOL><DEDENT>elif gate == '<STR_LIT>':<EOL><INDENT>return <NUM_LIT:0>, <NUM_LIT:0>, params[<NUM_LIT:0>]<EOL><DEDENT>elif gate == '<STR_LIT:id>':<EOL><INDENT>return <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0><EOL><DEDENT>raise QiskitError('<STR_LIT>' % gate)<EOL>

Apply a single qubit gate to the qubit.

    Args:
        gate(str): the single qubit gate name
        params(list): the operation parameters op['params']
    Returns:
        tuple: a tuple of U gate parameters (theta, phi, lam)
    Raises:
        QiskitError: if the gate name is not valid


<EOL>(theta, phi, lam) = map(float, single_gate_params(gate, params))<EOL>return np.array([[np.cos(theta / <NUM_LIT:2>),<EOL>-np.exp(<NUM_LIT> * lam) * np.sin(theta / <NUM_LIT:2>)],<EOL>[np.exp(<NUM_LIT> * phi) * np.sin(theta / <NUM_LIT:2>),<EOL>np.exp(<NUM_LIT> * phi + <NUM_LIT> * lam) * np.cos(theta / <NUM_LIT:2>)]])<EOL>

Get the matrix for a single qubit.

    Args:
        gate(str): the single qubit gate name
        params(list): the operation parameters op['params']
    Returns:
        array: A numpy array representing the matrix


return 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>

Get the matrix for a controlled-NOT gate.


mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices,<EOL>number_of_qubits)<EOL>tens_r = ascii_uppercase[:number_of_qubits]<EOL>return "<STR_LIT>".format(mat_l=mat_l, mat_r=mat_r) +"<STR_LIT>".format(tens_lin=tens_lin,<EOL>tens_lout=tens_lout,<EOL>tens_r=tens_r)<EOL>

Return the index string for Numpy.eignsum matrix-matrix multiplication.

    The returned indices are to perform a matrix multiplication A.B where
    the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and
    M <= N, and identity matrices are implied on the subsystems where A has no
    support on B.

    Args:
        gate_indices (list[int]): the indices of the right matrix subsystems
                                   to contract with the left matrix.
        number_of_qubits (int): the total number of qubits for the right matrix.

    Returns:
        str: An indices string for the Numpy.einsum function.


mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices,<EOL>number_of_qubits)<EOL>return "<STR_LIT>".format(mat_l=mat_l, mat_r=mat_r) +"<STR_LIT>".format(tens_lin=tens_lin,<EOL>tens_lout=tens_lout)<EOL>

Return the index string for Numpy.eignsum matrix-vector multiplication.

    The returned indices are to perform a matrix multiplication A.v where
    the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and
    M <= N, and identity matrices are implied on the subsystems where A has no
    support on v.

    Args:
        gate_indices (list[int]): the indices of the right matrix subsystems
                                  to contract with the left matrix.
        number_of_qubits (int): the total number of qubits for the right matrix.

    Returns:
        str: An indices string for the Numpy.einsum function.


<EOL>if len(gate_indices) + number_of_qubits > <NUM_LIT>:<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>tens_in = ascii_lowercase[:number_of_qubits]<EOL>tens_out = list(tens_in)<EOL>mat_left = "<STR_LIT>"<EOL>mat_right = "<STR_LIT>"<EOL>for pos, idx in enumerate(reversed(gate_indices)):<EOL><INDENT>mat_left += ascii_lowercase[-<NUM_LIT:1> - pos]<EOL>mat_right += tens_in[-<NUM_LIT:1> - idx]<EOL>tens_out[-<NUM_LIT:1> - idx] = ascii_lowercase[-<NUM_LIT:1> - pos]<EOL><DEDENT>tens_out = "<STR_LIT>".join(tens_out)<EOL>return mat_left, mat_right, tens_in, tens_out<EOL>

Return the index string for Numpy.eignsum matrix multiplication.

    The returned indices are to perform a matrix multiplication A.v where
    the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and
    M <= N, and identity matrices are implied on the subsystems where A has no
    support on v.

    Args:
        gate_indices (list[int]): the indices of the right matrix subsystems
                                   to contract with the left matrix.
        number_of_qubits (int): the total number of qubits for the right matrix.

    Returns:
        tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for
        that may be combined into a Numpy.einsum function string.

    Raises:
        QiskitError: if the total number of qubits plus the number of
        contracted indices is greater than 26.


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


return repr(self.message)<EOL>


@functools.wraps(func)<EOL>def _wrapper(self, *args, **kwargs):<EOL><INDENT>if self._future is None:<EOL><INDENT>raise JobError("<STR_LIT>")<EOL><DEDENT>return func(self, *args, **kwargs)<EOL><DEDENT>return _wrapper<EOL>

Decorator to ensure that a submit has been performed before
calling the method.

Args:
    func (callable): test function to be decorated.

Returns:
    callable: the decorated function.


if self._future is not None:<EOL><INDENT>raise JobError("<STR_LIT>")<EOL><DEDENT>validate_qobj_against_schema(self._qobj)<EOL>self._future = self._executor.submit(self._fn, self._job_id, self._qobj)<EOL>

Submit the job to the backend for execution.

        Raises:
            QobjValidationError: if the JSON serialization of the Qobj passed
            during construction does not validate against the Qobj schema.

            JobError: if trying to re-submit the job.


return self._future.result(timeout=timeout)<EOL>

Get job result. The behavior is the same as the underlying
        concurrent Future objects,

        https://docs.python.org/3/library/concurrent.futures.html#future-objects

        Args:
            timeout (float): number of seconds to wait for results.

        Returns:
            qiskit.Result: Result object

        Raises:
            concurrent.futures.TimeoutError: if timeout occurred.
            concurrent.futures.CancelledError: if job cancelled before completed.


<EOL>if self._future.running():<EOL><INDENT>_status = JobStatus.RUNNING<EOL><DEDENT>elif self._future.cancelled():<EOL><INDENT>_status = JobStatus.CANCELLED<EOL><DEDENT>elif self._future.done():<EOL><INDENT>_status = JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR<EOL><DEDENT>else:<EOL><INDENT>_status = JobStatus.INITIALIZING<EOL><DEDENT>return _status<EOL>

Gets the status of the job by querying the Python's future

        Returns:
            qiskit.providers.JobStatus: The current JobStatus

        Raises:
            JobError: If the future is in unexpected state
            concurrent.futures.TimeoutError: if timeout occurred.


return self._backend<EOL>

Return the instance of the backend used for this job.


return self._qobj<EOL>

Return the Qobj submitted for this job.

        Returns:
            Qobj: the Qobj submitted for this job.


return {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>}<EOL>


ret = OrderedDict()<EOL>for backend_cls in SIMULATORS:<EOL><INDENT>try:<EOL><INDENT>backend_instance = self._get_backend_instance(backend_cls)<EOL>backend_name = backend_instance.name()<EOL>ret[backend_name] = backend_instance<EOL><DEDENT>except QiskitError as err:<EOL><INDENT>logger.info('<STR_LIT>',<EOL>backend_cls, str(err))<EOL><DEDENT><DEDENT>return ret<EOL>

Return the Basic Aer backends in `BACKENDS` that are
effectively available (as some of them might depend on the presence
of an optional dependency or on the existence of a binary).

Returns:
    dict[str:BaseBackend]: a dict of Basic Aer backend instances for
        the backends that could be instantiated, keyed by backend name.


<EOL>try:<EOL><INDENT>backend_instance = backend_cls(provider=self)<EOL><DEDENT>except Exception as err:<EOL><INDENT>raise QiskitError('<STR_LIT>' %<EOL>(backend_cls, err))<EOL><DEDENT>return backend_instance<EOL>

Return an instance of a backend from its class.

Args:
    backend_cls (class): Backend class.
Returns:
    BaseBackend: a backend instance.
Raises:
    QiskitError: if the backend could not be instantiated.


def get_backend(self, name=None, **kwargs):

backends = self.backends(name, **kwargs)<EOL>if len(backends) > <NUM_LIT:1>:<EOL><INDENT>raise QiskitBackendNotFoundError('<STR_LIT>')<EOL><DEDENT>elif not backends:<EOL><INDENT>raise QiskitBackendNotFoundError('<STR_LIT>')<EOL><DEDENT>return backends[<NUM_LIT:0>]<EOL>

Return a single backend matching the specified filtering.

        Args:
            name (str): name of the backend.
            **kwargs (dict): dict used for filtering.

        Returns:
            BaseBackend: a backend matching the filtering.

        Raises:
            QiskitBackendNotFoundError: if no backend could be found or
                more than one backend matches.


@abstractmethod<EOL><INDENT>def backends(self, name=None, **kwargs):<DEDENT>

pass<EOL>

Return a list of backends matching the specified filtering.

        Args:
            name (str): name of the backend.
            **kwargs (dict): dict used for filtering.

        Returns:
            list[BaseBackend]: a list of backends matching the filtering
                criteria.


return type(self).__name__ == type(other).__name__<EOL>

Equality comparison.

        By default, it is assumed that two `Providers` from the same class are
        equal. Subclassed providers can override this behavior.


self._job_id = job_id<EOL>self._backend = backend<EOL>

Initializes the asynchronous job.

        Args:
            backend (BaseBackend): the backend used to run the job.
            job_id (str): a unique id in the context of the backend used to run
                the job.


return self._job_id<EOL>


return self._backend<EOL>


pass<EOL>


pass<EOL>

Return one of the values of ``JobStatus``


@abstractmethod<EOL><INDENT>def __init__(self, configuration, provider=None):<DEDENT>

self._configuration = configuration<EOL>self._provider = provider<EOL>

Base class for backends.

        This method should initialize the module and its configuration, and
        raise an exception if a component of the module is
        not available.

        Args:
            configuration (BackendConfiguration): backend configuration
            provider (BaseProvider): provider responsible for this backend

        Raises:
            FileNotFoundError if backend executable is not available.
            QiskitError: if there is no name in the configuration


return self._configuration<EOL>

Return the backend configuration.

        Returns:
            BackendConfiguration: the configuration for the backend.


return None<EOL>

Return backend properties.

        Returns:
            BackendProperties: the configuration for the backend. If the backend
            does not support properties, it returns ``None``.


return self._provider<EOL>

Return the backend Provider.

        Returns:
            BaseProvider: the Provider responsible for the backend.


return BackendStatus(backend_name=self.name(),<EOL>backend_version=__version__,<EOL>operational=True,<EOL>pending_jobs=<NUM_LIT:0>,<EOL>status_msg='<STR_LIT>')<EOL>

Return backend status.

        Returns:
            BackendStatus: the status of the backend.


return self._configuration.backend_name<EOL>

Return backend name.

        Returns:
            str: the name of the backend.


return "<STR_LIT>".format(self.__class__.__name__,<EOL>self.name(),<EOL>self._provider)<EOL>

Official string representation of a Backend.

        Note that, by Qiskit convention, it is consciously *not* a fully valid
        Python expression. Subclasses should provide 'a string of the form
        <...some useful description...>'. [0]

        [0] https://docs.python.org/3/reference/datamodel.html#object.__repr__


def filter_backends(backends, filters=None, **kwargs):

def _match_all(obj, criteria):<EOL><INDENT>"""<STR_LIT>"""<EOL>return all(getattr(obj, key_, None) == value_ for<EOL>key_, value_ in criteria.items())<EOL><DEDENT>configuration_filters = {}<EOL>status_filters = {}<EOL>for key, value in kwargs.items():<EOL><INDENT>if all(key in backend.configuration() for backend in backends):<EOL><INDENT>configuration_filters[key] = value<EOL><DEDENT>else:<EOL><INDENT>status_filters[key] = value<EOL><DEDENT><DEDENT>if configuration_filters:<EOL><INDENT>backends = [b for b in backends if<EOL>_match_all(b.configuration(), configuration_filters)]<EOL><DEDENT>if status_filters:<EOL><INDENT>backends = [b for b in backends if<EOL>_match_all(b.status(), status_filters)]<EOL><DEDENT>backends = list(filter(filters, backends))<EOL>return backends<EOL>

Return the backends matching the specified filtering.

    Filter the `backends` list by their `configuration` or `status`
    attributes, or from a boolean callable. The criteria for filtering can
    be specified via `**kwargs` or as a callable via `filters`, and the
    backends must fulfill all specified conditions.

    Args:
        backends (list[BaseBackend]): list of backends.
        filters (callable): filtering conditions as a callable.
        **kwargs (dict): dict of criteria.

    Returns:
        list[BaseBackend]: a list of backend instances matching the
            conditions.


def resolve_backend_name(name, backends, deprecated, aliased):

available = [backend.name() for backend in backends]<EOL>resolved_name = deprecated.get(name, aliased.get(name, name))<EOL>if isinstance(resolved_name, list):<EOL><INDENT>resolved_name = next((b for b in resolved_name if b in available), "<STR_LIT>")<EOL><DEDENT>if resolved_name not in available:<EOL><INDENT>raise LookupError("<STR_LIT>".format(name))<EOL><DEDENT>if name in deprecated:<EOL><INDENT>logger.warning("<STR_LIT>", name, resolved_name)<EOL><DEDENT>return resolved_name<EOL>

Resolve backend name from a deprecated name or an alias.

    A group will be resolved in order of member priorities, depending on
    availability.

    Args:
        name (str): name of backend to resolve
        backends (list[BaseBackend]): list of available backends.
        deprecated (dict[str: str]): dict of deprecated names.
        aliased (dict[str: list[str]]): dict of aliased names.

    Returns:
        str: resolved name (name of an available backend)

    Raises:
        LookupError: if name cannot be resolved through regular available
            names, nor deprecated, nor alias names.


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


return repr(self.message)<EOL>


def to_dict_selector(self, choices, *args, **kwargs):

raise NotImplementedError<EOL>

Return an schema in ``choices`` for serialization.


def from_dict_selector(self, choices, *args, **kwargs):

raise NotImplementedError<EOL>

Return an schema in ``choices`` for deserialization.


def _deserialize(self, value, attr, data):

try:<EOL><INDENT>return super()._deserialize(value, attr, data)<EOL><DEDENT>except ValidationError as ex:<EOL><INDENT>if '<STR_LIT>' in ex.messages[<NUM_LIT:0>]:<EOL><INDENT>ex.messages[<NUM_LIT:0>] = '<STR_LIT>'<EOL><DEDENT>raise<EOL><DEDENT>

Override ``_deserialize`` for customizing the exception raised.


try:<EOL><INDENT>return super()._serialize(value, key, obj)<EOL><DEDENT>except TypeError as ex:<EOL><INDENT>if '<STR_LIT>' in str(ex):<EOL><INDENT>raise ValidationError('<STR_LIT>')<EOL><DEDENT>raise<EOL><DEDENT>

Override ``_serialize`` for customizing the exception raised.


def check_type(self, value, attr, data):

if self.many and not is_collection(value):<EOL><INDENT>raise self._not_expected_type(<EOL>value, Iterable, fields=[self], field_names=attr, data=data)<EOL><DEDENT>_check_type = super().check_type<EOL>errors = []<EOL>values = value if self.many else [value]<EOL>for idx, v in enumerate(values):<EOL><INDENT>try:<EOL><INDENT>_check_type(v, idx, values)<EOL><DEDENT>except ValidationError as err:<EOL><INDENT>errors.append(err.messages)<EOL><DEDENT><DEDENT>if errors:<EOL><INDENT>errors = errors if self.many else errors[<NUM_LIT:0>]<EOL>raise ValidationError(errors)<EOL><DEDENT>return value<EOL>

Check if the type of the value is one of the possible choices.

        Possible choices are the model classes bound to the possible schemas.