示例#1
0
    def test_optimize_1q_gates_collapse_identity(self):
        """test optimize_1q_gates removes u1(2*pi) rotations.

        See: https://github.com/Qiskit/qiskit-terra/issues/159
        """
        qr = QuantumRegister(2, 'qr')
        cr = ClassicalRegister(2, 'cr')
        qc = QuantumCircuit(qr, cr)
        qc.h(qr[0])
        qc.cx(qr[1], qr[0])
        qc.u1(2 * sympy.pi,
              qr[0])  # TODO: this identity should be removed (but is not)
        qc.cx(qr[1], qr[0])
        qc.u1(sympy.pi / 2, qr[0])  # these three should combine
        qc.u1(sympy.pi, qr[0])  # to identity then
        qc.u1(sympy.pi / 2, qr[0])  # optimized away.
        qc.cx(qr[1], qr[0])
        qc.u1(np.pi, qr[1])  # this doesn't become precisely 0, so should
        qc.u1(np.pi,
              qr[1])  # combine but stay, until an approximate optimizer.
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])

        dag = DAGCircuit.fromQuantumCircuit(qc)
        simplified_dag = mapper.optimize_1q_gates(dag)
        num_u1_gates_remaining = len(simplified_dag.get_named_nodes('u1'))
        self.assertEqual(num_u1_gates_remaining, 2)
def _qiskit_compiler(dag_circuit, coupling_map=None, gate_costs=None):
    import copy
    from qiskit.mapper import swap_mapper, direction_mapper, cx_cancellation, optimize_1q_gates, Coupling
    from qiskit import qasm, unroll
    initial_layout = None
    coupling = Coupling(coupling_map)

    # # paler 31.08.2018
    # # use heuristic to generate it
    # from startconfiguration import cuthill_order
    # y = cuthill_order(dag_circuit)
    # for i in range(len(y)):
    #     initial_layout[i] = y[i]  # qubit i@i
    # # end paler 31.08.2018

    # compiled_dag, final_layout = swap_mapper(copy.deepcopy(dag_circuit), coupling, initial_layout, trials=40, seed=19)
    compiled_dag, final_layout = swap_mapper(copy.deepcopy(dag_circuit), coupling, initial_layout,
                                             trials=40, seed=gate_costs['seed'])

    # Expand swaps
    basis_gates = "u1,u2,u3,cx,id"  # QE target basis
    program_node_circuit = qasm.Qasm(data=compiled_dag.qasm()).parse()
    unroller_circuit = unroll.Unroller(program_node_circuit,
                                       unroll.DAGBackend(
                                           basis_gates.split(",")))
    compiled_dag = unroller_circuit.execute()
    # Change cx directions
    compiled_dag = direction_mapper(compiled_dag, coupling)
    # Simplify cx gates
    cx_cancellation(compiled_dag)
    # Simplify single qubit gates
    compiled_dag = optimize_1q_gates(compiled_dag)
    # Return the compiled dag circuit
    return compiled_dag
示例#3
0
def _qiskit_compiler(dag_circuit, coupling_map=None, gate_costs=None):
    import copy
    from qiskit.mapper import swap_mapper, direction_mapper, cx_cancellation, optimize_1q_gates, Coupling
    from qiskit import qasm, unroll
    initial_layout = None
    coupling = Coupling(coupling_map)
    compiled_dag, final_layout = swap_mapper(copy.deepcopy(dag_circuit),
                                             coupling,
                                             initial_layout,
                                             trials=40,
                                             seed=19)
    # Expand swaps
    basis_gates = "u1,u2,u3,cx,id"  # QE target basis
    program_node_circuit = qasm.Qasm(data=compiled_dag.qasm()).parse()
    unroller_circuit = unroll.Unroller(
        program_node_circuit, unroll.DAGBackend(basis_gates.split(",")))
    compiled_dag = unroller_circuit.execute()
    # Change cx directions
    compiled_dag = direction_mapper(compiled_dag, coupling)
    # Simplify cx gates
    cx_cancellation(compiled_dag)
    # Simplify single qubit gates
    compiled_dag = optimize_1q_gates(compiled_dag)
    # Return the compiled dag circuit
    return compiled_dag
def compiler_function(dag_circuit, coupling_map=None, gate_costs=None):
    """
    Modify a DAGCircuit based on a gate cost function.

    Instructions:
        Your submission involves filling in the implementation
        of this function. The function takes as input a DAGCircuit
        object, which can be generated from a QASM file by using the
        function 'qasm_to_dag_circuit' from the included 
        'submission_evaluation.py' module. For more information
        on the DAGCircuit object see the or QISKit documentation
        (eg. 'help(DAGCircuit)').

    Args:
        dag_circuit (DAGCircuit): DAGCircuit object to be compiled.
        coupling_circuit (list): Coupling map for device topology.
                                 A coupling map of None corresponds an
                                 all-to-all connected topology.
        gate_costs (dict) : dictionary of gate names and costs.

    Returns:
        A modified DAGCircuit object that satisfies an input coupling_map
        and has as low a gate_cost as possible.
    """

    #####################
    # Put your code here
    #####################
    # Example using mapper passes in Qiskit
    import copy
    from qiskit.mapper import swap_mapper, direction_mapper, cx_cancellation, optimize_1q_gates, Coupling
    from qiskit import qasm, unroll
    initial_layout = None
    coupling = Coupling(coupling_map)
    compiled_dag, final_layout = swap_mapper(copy.deepcopy(dag_circuit),
                                             coupling,
                                             initial_layout,
                                             trials=40,
                                             seed=19)
    # Expand swaps
    basis_gates = "u1,u2,u3,cx,id"  # QE target basis
    program_node_circuit = qasm.Qasm(data=compiled_dag.qasm()).parse()
    unroller_circuit = unroll.Unroller(
        program_node_circuit, unroll.DAGBackend(basis_gates.split(",")))
    compiled_dag = unroller_circuit.execute()
    # Change cx directions
    compiled_dag = direction_mapper(compiled_dag, coupling)
    # Simplify cx gates
    cx_cancellation(compiled_dag)
    # Simplify single qubit gates
    compiled_dag = optimize_1q_gates(compiled_dag)
    #####################
    # Put your code here
    #####################
    # Return the compiled dag circuit
    return compiled_dag
示例#5
0
    def test_symbolic_power(self):
        """Test symbolic math in DAGBackend and optimizer with a power (^).

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(data=QASM_SYMBOLIC_POWER).parse()
        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_POWER)
示例#6
0
    def test_symbolic_power(self):
        """Test symbolic math in DAGBackend and optimizer with a power (^).

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(data=QASM_SYMBOLIC_POWER).parse()
        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_POWER)
示例#7
0
    def test_symbolic_extern(self):
        """Test symbolic math in DAGBackend and optimizer with an external function.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_extern.qasm')).parse()
        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_EXTERN)
示例#8
0
    def test_symbolic_extern(self):
        """Test symbolic math in DAGBackend and optimizer with an external function.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_extern.qasm')).parse()
        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_EXTERN)
示例#9
0
    def test_symbolic_unary(self):
        """SymPy with a prefix.

        See: https://github.com/QISKit/qiskit-terra/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_unary.qasm')).parse()
        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_UNARY)
示例#10
0
    def test_optimize_1q_gates_symbolic(self):
        """optimizes single qubit gate sequences with symbolic params.

        See: https://github.com/Qiskit/qiskit-terra/issues/172
        """
        qr = QuantumRegister(4)
        cr = ClassicalRegister(4)
        circ = QuantumCircuit(qr, cr)
        # unary
        circ.u1(-sympy.pi, qr[0])
        circ.u1(-sympy.pi / 2, qr[0])
        # binary
        circ.u1(0.2 * sympy.pi + 0.3 * sympy.pi, qr[1])
        circ.u1(1.3 - 0.3, qr[1])
        circ.u1(0.1 * sympy.pi / 2, qr[1])
        # extern
        circ.u1(sympy.sin(0.2 + 0.3 - sympy.pi), qr[2])
        # power
        circ.u1(sympy.pi, qr[3])
        circ.u1(0.3 + (-sympy.pi)**2, qr[3])

        dag = DAGCircuit.fromQuantumCircuit(circ)
        simplified_dag = mapper.optimize_1q_gates(dag)

        params = set()
        for n in simplified_dag.multi_graph.nodes:
            node = simplified_dag.multi_graph.node[n]
            if node['name'] == 'u1':
                params.add(node['op'].param[0])

        expected_params = {
            -3 * sympy.pi / 2, 1.0 + 0.55 * sympy.pi,
            sympy.N(-0.479425538604203), 0.3 + sympy.pi + sympy.pi**2
        }

        self.assertEqual(params, expected_params)
示例#11
0
def transpile(dag,
              basis_gates='u1,u2,u3,cx,id',
              coupling_map=None,
              initial_layout=None,
              get_layout=False,
              format='dag',
              seed=None,
              pass_manager=None):
    """Transform a dag circuit into another dag circuit (transpile), through
    consecutive passes on the dag.

    Args:
        dag (DAGCircuit): dag circuit to transform via transpilation
        basis_gates (str): a comma separated string for the target basis gates
        coupling_map (list): A graph of coupling::

            [
             [control0(int), target0(int)],
             [control1(int), target1(int)],
            ]

            eg. [[0, 2], [1, 2], [1, 3], [3, 4]}

        initial_layout (dict): A mapping of qubit to qubit::

                              {
                                ("q", start(int)): ("q", final(int)),
                                ...
                              }
                              eg.
                              {
                                ("q", 0): ("q", 0),
                                ("q", 1): ("q", 1),
                                ("q", 2): ("q", 2),
                                ("q", 3): ("q", 3)
                              }
        get_layout (bool): flag for returning the final layout after mapping
        format (str): The target format of the compilation:
            {'dag', 'json', 'qasm'}
        seed (int): random seed for the swap mapper
        pass_manager (PassManager): pass manager instance for the transpilation process
            If None, a default set of passes are run.
            Otherwise, the passes defined in it will run.
            If contains no passes in it, no dag transformations occur.

    Returns:
        DAGCircuit: transformed dag
        DAGCircuit, dict: transformed dag along with the final layout on backend qubits

    Raises:
        TranspilerError: if the format is not valid.
    """
    # TODO: `basis_gates` will be removed after we have the unroller pass.
    # TODO: `coupling_map`, `initial_layout`, `get_layout`, `seed` removed after mapper pass.

    # TODO: move this to the mapper pass
    num_qubits = sum(dag.qregs.values())
    if num_qubits == 1 or coupling_map == "all-to-all":
        coupling_map = None

    final_layout = None

    if pass_manager:
        # run the passes specified by the pass manager
        # TODO return the property set too. See #1086
        dag = pass_manager.run_passes(dag)
    else:
        # default set of passes
        # TODO: move each step here to a pass, and use a default passmanager below
        basis = basis_gates.split(',') if basis_gates else []
        dag_unroller = DagUnroller(dag, DAGBackend(basis))
        dag = dag_unroller.expand_gates()
        # if a coupling map is given compile to the map
        if coupling_map:
            logger.info("pre-mapping properties: %s", dag.property_summary())
            # Insert swap gates
            coupling = Coupling(coupling_list2dict(coupling_map))
            removed_meas = remove_last_measurements(dag)
            logger.info("measurements moved: %s", removed_meas)
            logger.info("initial layout: %s", initial_layout)
            dag, final_layout, last_layout = swap_mapper(dag,
                                                         coupling,
                                                         initial_layout,
                                                         trials=20,
                                                         seed=seed)
            logger.info("final layout: %s", final_layout)
            # Expand swaps
            dag_unroller = DagUnroller(dag, DAGBackend(basis))
            dag = dag_unroller.expand_gates()
            # Change cx directions
            dag = direction_mapper(dag, coupling)
            # Simplify cx gates
            cx_cancellation(dag)
            # Simplify single qubit gates
            dag = optimize_1q_gates(dag)
            return_last_measurements(dag, removed_meas, last_layout)
            logger.info("post-mapping properties: %s", dag.property_summary())

    # choose output format
    # TODO: do we need all of these formats, or just the dag?
    if format == 'dag':
        compiled_circuit = dag
    elif format == 'json':
        # FIXME: JsonBackend is wrongly taking an ordered dict as basis, not list
        dag_unroller = DagUnroller(dag, JsonBackend(dag.basis))
        compiled_circuit = dag_unroller.execute()
    elif format == 'qasm':
        compiled_circuit = dag.qasm()
    else:
        raise TranspilerError('unrecognized circuit format')

    if get_layout:
        return compiled_circuit, final_layout
    return compiled_circuit
示例#12
0
def transpile_dag(dag,
                  basis_gates='u1,u2,u3,cx,id',
                  coupling_map=None,
                  initial_layout=None,
                  get_layout=False,
                  format='dag',
                  seed_mapper=None,
                  pass_manager=None):
    """Transform a dag circuit into another dag circuit (transpile), through
    consecutive passes on the dag.

    Args:
        dag (DAGCircuit): dag circuit to transform via transpilation
        basis_gates (str): a comma separated string for the target basis gates
        coupling_map (list): A graph of coupling::

            [
             [control0(int), target0(int)],
             [control1(int), target1(int)],
            ]

            eg. [[0, 2], [1, 2], [1, 3], [3, 4]}

        initial_layout (dict): A mapping of qubit to qubit::

                              {
                                ("q", start(int)): ("q", final(int)),
                                ...
                              }
                              eg.
                              {
                                ("q", 0): ("q", 0),
                                ("q", 1): ("q", 1),
                                ("q", 2): ("q", 2),
                                ("q", 3): ("q", 3)
                              }
        get_layout (bool): flag for returning the final layout after mapping
        format (str): DEPRECATED The target format of the compilation: {'dag', 'json', 'qasm'}
        seed_mapper (int): random seed_mapper for the swap mapper
        pass_manager (PassManager): pass manager instance for the transpilation process
            If None, a default set of passes are run.
            Otherwise, the passes defined in it will run.
            If contains no passes in it, no dag transformations occur.

    Returns:
        DAGCircuit: transformed dag
        DAGCircuit, dict: transformed dag along with the final layout on backend qubits
    """
    # TODO: `basis_gates` will be removed after we have the unroller pass.
    # TODO: `coupling_map`, `initial_layout`, `get_layout`, `seed_mapper` removed after mapper pass.

    # TODO: move this to the mapper pass
    num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
    if num_qubits == 1 or coupling_map == "all-to-all":
        coupling_map = None

    final_layout = None

    if pass_manager:
        # run the passes specified by the pass manager
        # TODO return the property set too. See #1086
        dag = pass_manager.run_passes(dag)
    else:
        # default set of passes
        # TODO: move each step here to a pass, and use a default passmanager below
        basis = basis_gates.split(',') if basis_gates else []
        dag = Unroller(basis).run(dag)
        # if a coupling map is given compile to the map
        if coupling_map:
            logger.info("pre-mapping properties: %s", dag.properties())
            # Insert swap gates
            coupling = Coupling(couplinglist=coupling_map)
            removed_meas = remove_last_measurements(dag)
            logger.info("measurements moved: %s", removed_meas)
            logger.info("initial layout: %s", initial_layout)
            dag, final_layout, last_layout = swap_mapper(dag,
                                                         coupling,
                                                         initial_layout,
                                                         trials=20,
                                                         seed=seed_mapper)
            logger.info("final layout: %s", final_layout)
            # Expand swaps
            dag = Unroller(basis).run(dag)
            # Change cx directions
            dag = direction_mapper(dag, coupling)
            # Simplify cx gates
            cx_cancellation(dag)
            # Simplify single qubit gates
            dag = optimize_1q_gates(dag)
            return_last_measurements(dag, removed_meas, last_layout)
            logger.info("post-mapping properties: %s", dag.properties())

    if format != 'dag':
        warnings.warn(
            "transpiler no longer supports different formats. "
            "only dag to dag transformations are supported.",
            DeprecationWarning)

    if get_layout:
        return dag, final_layout
    return dag
示例#13
0
def transpile(dag_circuit,
              basis_gates='u1,u2,u3,cx,id',
              coupling_map=None,
              initial_layout=None,
              get_layout=False,
              format='dag',
              seed=None,
              pass_manager=None):
    """Transform a dag circuit into another dag circuit (transpile), through
    consecutive passes on the dag.

    Args:
        dag_circuit (DAGCircuit): dag circuit to transform via transpilation
        basis_gates (str): a comma seperated string for the target basis gates
        coupling_map (list): A graph of coupling::

            [
             [control0(int), target0(int)],
             [control1(int), target1(int)],
            ]

            eg. [[0, 2], [1, 2], [1, 3], [3, 4]}

        initial_layout (dict): A mapping of qubit to qubit::

                              {
                                ("q", start(int)): ("q", final(int)),
                                ...
                              }
                              eg.
                              {
                                ("q", 0): ("q", 0),
                                ("q", 1): ("q", 1),
                                ("q", 2): ("q", 2),
                                ("q", 3): ("q", 3)
                              }
        get_layout (bool): flag for returning the layout
        format (str): The target format of the compilation:
            {'dag', 'json', 'qasm'}
        seed (int): random seed for simulators
        pass_manager (PassManager): pass manager instance for the tranpilation process
            If None, a default set of passes are run.
            Otherwise, the passes defined in it will run.
            If contains no passes in it, no dag transformations occur.

    Returns:
        object: If get_layout == False, the compiled circuit in the specified
            format. If get_layout == True, a tuple is returned, with the
            second element being the layout.

    Raises:
        TranspilerError: if the format is not valid.
    """
    final_layout = None

    if pass_manager:
        # run the passes specified by the pass manager
        for pass_ in pass_manager.passes():
            pass_.run(dag_circuit)
    else:
        # default set of passes
        # TODO: move each step here to a pass, and use a default passmanager below
        basis = basis_gates.split(',') if basis_gates else []
        dag_unroller = DagUnroller(dag_circuit, DAGBackend(basis))
        dag_circuit = dag_unroller.expand_gates()
        # if a coupling map is given compile to the map
        if coupling_map:
            logger.info("pre-mapping properties: %s",
                        dag_circuit.property_summary())
            # Insert swap gates
            coupling = Coupling(coupling_list2dict(coupling_map))
            logger.info("initial layout: %s", initial_layout)
            dag_circuit, final_layout = swap_mapper(dag_circuit,
                                                    coupling,
                                                    initial_layout,
                                                    trials=20,
                                                    seed=seed)
            logger.info("final layout: %s", final_layout)
            # Expand swaps
            dag_unroller = DagUnroller(dag_circuit, DAGBackend(basis))
            dag_circuit = dag_unroller.expand_gates()
            # Change cx directions
            dag_circuit = direction_mapper(dag_circuit, coupling)
            # Simplify cx gates
            cx_cancellation(dag_circuit)
            # Simplify single qubit gates
            dag_circuit = optimize_1q_gates(dag_circuit)
            logger.info("post-mapping properties: %s",
                        dag_circuit.property_summary())

    # choose output format
    # TODO: do we need all of these formats, or just the dag?
    if format == 'dag':
        compiled_circuit = dag_circuit
    elif format == 'json':
        # FIXME: JsonBackend is wrongly taking an ordered dict as basis, not list
        dag_unroller = DagUnroller(dag_circuit, JsonBackend(dag_circuit.basis))
        compiled_circuit = dag_unroller.execute()
    elif format == 'qasm':
        compiled_circuit = dag_circuit.qasm()
    else:
        raise TranspilerError('unrecognized circuit format')

    if get_layout:
        return compiled_circuit, final_layout
    return compiled_circuit
def compile(qasm_circuit, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
            initial_layout=None, silent=True, get_layout=False):
    """Compile the circuit.

    This builds the internal "to execute" list which is list of quantum
    circuits to run on different backends.

    Args:
        qasm_circuit (str): qasm text to compile
        silent (bool): is an option to print out the compiling information
            or not
        basis_gates (str): a comma seperated string and are the base gates,
                           which by default are: u1,u2,u3,cx,id
        coupling_map (dict): A directed graph of coupling::

            {
             control(int):
                 [
                     target1(int),
                     target2(int),
                     , ...
                 ],
                 ...
            }

            eg. {0: [2], 1: [2], 3: [2]}

        initial_layout (dict): A mapping of qubit to qubit::

                              {
                                ("q", strart(int)): ("q", final(int)),
                                ...
                              }
                              eg.
                              {
                                ("q", 0): ("q", 0),
                                ("q", 1): ("q", 1),
                                ("q", 2): ("q", 2),
                                ("q", 3): ("q", 3)
                              }

    Returns:
        Compiled DAGCircuit.
    """
    compiled_dag_circuit = _unroller_code(qasm_circuit,
                                          basis_gates=basis_gates)
    final_layout = None
    # if a coupling map is given compile to the map
    if coupling_map:
        if not silent:
            print("pre-mapping properties: %s"
                  % compiled_dag_circuit.property_summary())
        # Insert swap gates
        coupling = mapper.Coupling(coupling_map)
        if not silent:
            print("initial layout: %s" % initial_layout)
        compiled_dag_circuit, final_layout = mapper.swap_mapper(
            compiled_dag_circuit, coupling, initial_layout, trials=20, verbose=False)
        if not silent:
            print("final layout: %s" % final_layout)
        # Expand swaps
        compiled_dag_circuit = _unroller_code(compiled_dag_circuit.qasm())
        # Change cx directions
        compiled_dag_circuit = mapper.direction_mapper(compiled_dag_circuit, coupling)
        # Simplify cx gates
        mapper.cx_cancellation(compiled_dag_circuit)
        # Simplify single qubit gates
        compiled_dag_circuit = mapper.optimize_1q_gates(compiled_dag_circuit)
        if not silent:
            print("post-mapping properties: %s"
                  % compiled_dag_circuit.property_summary())
    if get_layout:
        return compiled_dag_circuit, final_layout
    else:
        return compiled_dag_circuit
def compile(qasm_circuit,
            basis_gates='u1,u2,u3,cx,id',
            coupling_map=None,
            initial_layout=None,
            get_layout=False,
            format='dag'):
    """Compile the circuit.

    This builds the internal "to execute" list which is list of quantum
    circuits to run on different backends.

    Args:
        qasm_circuit (str): qasm text to compile
        basis_gates (str): a comma seperated string and are the base gates,
                           which by default are: u1,u2,u3,cx,id
        coupling_map (dict): A directed graph of coupling::

            {
             control(int):
                 [
                     target1(int),
                     target2(int),
                     , ...
                 ],
                 ...
            }

            eg. {0: [2], 1: [2], 3: [2]}

        initial_layout (dict): A mapping of qubit to qubit::

                              {
                                ("q", start(int)): ("q", final(int)),
                                ...
                              }
                              eg.
                              {
                                ("q", 0): ("q", 0),
                                ("q", 1): ("q", 1),
                                ("q", 2): ("q", 2),
                                ("q", 3): ("q", 3)
                              }
        get_layout (bool): flag for returning the layout.
        format (str): The target format of the compilation:
            {'dag', 'json', 'qasm'}

    Returns:
        object: If get_layout == False, the compiled circuit in the specified
            format. If get_layout == True, a tuple is returned, with the
            second element being the layout.

    Raises:
        QISKitCompilerError: if the format is not valid.
    """
    compiled_dag_circuit = _unroller_code(qasm_circuit,
                                          basis_gates=basis_gates)
    final_layout = None
    # if a coupling map is given compile to the map
    if coupling_map:
        logger.info("pre-mapping properties: %s",
                    compiled_dag_circuit.property_summary())
        # Insert swap gates
        coupling = mapper.Coupling(coupling_map)
        logger.info("initial layout: %s", initial_layout)
        compiled_dag_circuit, final_layout = mapper.swap_mapper(
            compiled_dag_circuit, coupling, initial_layout, trials=20, seed=13)
        logger.info("final layout: %s", final_layout)
        # Expand swaps
        compiled_dag_circuit = _unroller_code(compiled_dag_circuit.qasm())
        # Change cx directions
        compiled_dag_circuit = mapper.direction_mapper(compiled_dag_circuit,
                                                       coupling)
        # Simplify cx gates
        mapper.cx_cancellation(compiled_dag_circuit)
        # Simplify single qubit gates
        compiled_dag_circuit = mapper.optimize_1q_gates(compiled_dag_circuit)
        logger.info("post-mapping properties: %s",
                    compiled_dag_circuit.property_summary())
    # choose output format
    if format == 'dag':
        compiled_circuit = compiled_dag_circuit
    elif format == 'json':
        compiled_circuit = dag2json(compiled_dag_circuit)
    elif format == 'qasm':
        compiled_circuit = compiled_dag_circuit.qasm()
    else:
        raise QISKitCompilerError('unrecognized circuit format')

    if get_layout:
        return compiled_circuit, final_layout
    return compiled_circuit
def compile(qasm_circuit,
            basis_gates='u1,u2,u3,cx,id',
            coupling_map=None,
            initial_layout=None,
            silent=True,
            get_layout=False,
            format='dag'):
    """Compile the circuit.

    This builds the internal "to execute" list which is list of quantum
    circuits to run on different backends.

    Args:
        qasm_circuit (str): qasm text to compile
        silent (bool): is an option to print out the compiling information
            or not
        basis_gates (str): a comma seperated string and are the base gates,
                           which by default are: u1,u2,u3,cx,id
        coupling_map (dict): A directed graph of coupling::

            {
             control(int):
                 [
                     target1(int),
                     target2(int),
                     , ...
                 ],
                 ...
            }

            eg. {0: [2], 1: [2], 3: [2]}

        initial_layout (dict): A mapping of qubit to qubit::

                              {
                                ("q", strart(int)): ("q", final(int)),
                                ...
                              }
                              eg.
                              {
                                ("q", 0): ("q", 0),
                                ("q", 1): ("q", 1),
                                ("q", 2): ("q", 2),
                                ("q", 3): ("q", 3)
                              }
        format (str): The target format of the compilation:
            {'dag', 'json', 'qasm'}

    Returns:
        Compiled circuit
    """
    compiled_dag_circuit = _unroller_code(qasm_circuit,
                                          basis_gates=basis_gates)
    final_layout = None
    # if a coupling map is given compile to the map
    if coupling_map:
        if not silent:
            print("pre-mapping properties: %s" %
                  compiled_dag_circuit.property_summary())
        # Insert swap gates
        coupling = mapper.Coupling(coupling_map)
        if not silent:
            print("initial layout: %s" % initial_layout)
        compiled_dag_circuit, final_layout = mapper.swap_mapper(
            compiled_dag_circuit,
            coupling,
            initial_layout,
            trials=20,
            verbose=False)
        if not silent:
            print("final layout: %s" % final_layout)
        # Expand swaps
        compiled_dag_circuit = _unroller_code(compiled_dag_circuit.qasm())
        # Change cx directions
        compiled_dag_circuit = mapper.direction_mapper(compiled_dag_circuit,
                                                       coupling)
        # Simplify cx gates
        mapper.cx_cancellation(compiled_dag_circuit)
        # Simplify single qubit gates
        compiled_dag_circuit = mapper.optimize_1q_gates(compiled_dag_circuit)
        if not silent:
            print("post-mapping properties: %s" %
                  compiled_dag_circuit.property_summary())
    # choose output format
    if format == 'dag':
        compiled_circuit = compiled_dag_circuit
    elif format == 'json':
        compiled_circuit = dag2json(compiled_dag_circuit)
    elif format == 'qasm':
        compiled_circuit = compiled_dag_circuit.qasm()
    else:
        raise QiskitCompilerError('unrecognized circuit format')

    if get_layout:
        return compiled_circuit, final_layout
    else:
        return compiled_circuit
def compile(qasm_circuit, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
            initial_layout=None, get_layout=False, format='dag'):
    """Compile the circuit.

    This builds the internal "to execute" list which is list of quantum
    circuits to run on different backends.

    Args:
        qasm_circuit (str): qasm text to compile
        basis_gates (str): a comma seperated string and are the base gates,
                           which by default are: u1,u2,u3,cx,id
        coupling_map (dict): A directed graph of coupling::

            {
             control(int):
                 [
                     target1(int),
                     target2(int),
                     , ...
                 ],
                 ...
            }

            eg. {0: [2], 1: [2], 3: [2]}

        initial_layout (dict): A mapping of qubit to qubit::

                              {
                                ("q", start(int)): ("q", final(int)),
                                ...
                              }
                              eg.
                              {
                                ("q", 0): ("q", 0),
                                ("q", 1): ("q", 1),
                                ("q", 2): ("q", 2),
                                ("q", 3): ("q", 3)
                              }
        format (str): The target format of the compilation:
            {'dag', 'json', 'qasm'}

    Returns:
        Compiled circuit
    """
    compiled_dag_circuit = _unroller_code(qasm_circuit,
                                          basis_gates=basis_gates)
    final_layout = None
    # if a coupling map is given compile to the map
    if coupling_map:
        logger.info("pre-mapping properties: %s",
                    compiled_dag_circuit.property_summary())
        # Insert swap gates
        coupling = mapper.Coupling(coupling_map)
        logger.info("initial layout: %s", initial_layout)
        compiled_dag_circuit, final_layout = mapper.swap_mapper(
            compiled_dag_circuit, coupling, initial_layout, trials=20)
        logger.info("final layout: %s", final_layout)
        # Expand swaps
        compiled_dag_circuit = _unroller_code(compiled_dag_circuit.qasm())
        # Change cx directions
        compiled_dag_circuit = mapper.direction_mapper(compiled_dag_circuit, coupling)
        # Simplify cx gates
        mapper.cx_cancellation(compiled_dag_circuit)
        # Simplify single qubit gates
        compiled_dag_circuit = mapper.optimize_1q_gates(compiled_dag_circuit)
        logger.info("post-mapping properties: %s",
                    compiled_dag_circuit.property_summary())
    # choose output format
    if format == 'dag':
        compiled_circuit = compiled_dag_circuit
    elif format == 'json':
        compiled_circuit = dag2json(compiled_dag_circuit)
    elif format == 'qasm':
        compiled_circuit = compiled_dag_circuit.qasm()
    else:
        raise QiskitCompilerError('unrecognized circuit format')

    if get_layout:
        return compiled_circuit, final_layout
    return compiled_circuit