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 _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
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
def impose_swap_coupling(circuit, coupling_list): """Impose a qubit topology on the given circuit using swap gates. Args: circuit :: qiskit.QuantumCircuit - the circuit to impose a topology upon. coupling_list :: [(int, int)] - the list of connected qubit pairs Returns: coupled_circuit :: qiskit.QuantumCircuit - the circuit equivalent to the original that abides by the qubit mapping via swap gates """ dag = circuit_to_dag(circuit) coupling_map = CouplingMap(coupling_list) coupled_dag = swap_mapper(dag, coupling_map)[0] coupled_circuit = dag_to_circuit(coupled_dag) return coupled_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) } 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 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
def transpile_dag(dag, basis_gates=None, coupling_map=None, initial_layout=None, 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 (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] 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) } 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 """ # TODO: `basis_gates` will be removed after we have the unroller pass. # TODO: `coupling_map`, `initial_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 if basis_gates is None: basis_gates = ['u1', 'u2', 'u3', 'cx', 'id'] if isinstance(basis_gates, str): warnings.warn( "The parameter basis_gates is now a list of strings. " "For example, this basis ['u1','u2','u3','cx'] should be used " "instead of 'u1,u2,u3,cx'. The string format will be " "removed after 0.9", DeprecationWarning, 2) basis_gates = basis_gates.split(',') 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 name = dag.name dag = Unroller(basis_gates).run(dag) dag = BarrierBeforeFinalMeasurements().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 = CouplingMap(coupling_map) logger.info("initial layout: %s", initial_layout) dag, final_layout = swap_mapper(dag, coupling, initial_layout, trials=20, seed=seed_mapper) logger.info("final layout: %s", final_layout) # Expand swaps dag = Decompose(SwapGate).run(dag) # Change cx directions dag = CXDirection(coupling).run(dag) # Simplify cx gates dag = CXCancellation().run(dag) # Unroll to the basis dag = Unroller(['u1', 'u2', 'u3', 'id', 'cx']).run(dag) # Simplify single qubit gates dag = Optimize1qGates().run(dag) logger.info("post-mapping properties: %s", dag.properties()) dag.name = name return dag
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
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 transpile_dag(dag, basis_gates=None, coupling_map=None, initial_layout=None, 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 (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] 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 (Layout or None): A layout object 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 """ # TODO: `basis_gates` will be removed after we have the unroller pass. # TODO: `coupling_map`, `initial_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: coupling_map = None if basis_gates is None: basis_gates = ['u1', 'u2', 'u3', 'cx', 'id'] if isinstance(basis_gates, str): warnings.warn( "The parameter basis_gates is now a list of strings. " "For example, this basis ['u1','u2','u3','cx'] should be used " "instead of 'u1,u2,u3,cx'. The string format will be " "removed after 0.9", DeprecationWarning, 2) basis_gates = basis_gates.split(',') if initial_layout is None: initial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) 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 name = dag.name dag = Unroller(basis_gates).run(dag) dag = BarrierBeforeFinalMeasurements().run(dag) # if a coupling map is given compile to the map if coupling_map: logger.info("pre-mapping properties: %s", dag.properties()) coupling = CouplingMap(coupling_map) # Extend and enlarge the the dag/layout with ancillas using the full coupling map logger.info("initial layout: %s", initial_layout) pass_ = ExtendLayout(coupling) pass_.property_set['layout'] = initial_layout pass_.run(dag) initial_layout = pass_.property_set['layout'] pass_ = EnlargeWithAncilla(initial_layout) dag = pass_.run(dag) initial_layout = pass_.property_set['layout'] logger.info("initial layout (ancilla extended): %s", initial_layout) # temporarily build old-style layout dict # (TODO: remove after transition to StochasticSwap pass) virtual_qubits = initial_layout.get_virtual_bits() initial_layout = {(v[0].name, v[1]): ('q', initial_layout[v]) for v in virtual_qubits} # Swap mapper dag, final_layout = swap_mapper(dag, coupling, initial_layout, trials=20, seed=seed_mapper) logger.info("final layout: %s", final_layout) # Expand swaps dag = Decompose(SwapGate).run(dag) # Change cx directions dag = CXDirection(coupling).run(dag) # Unroll to the basis dag = Unroller(['u1', 'u2', 'u3', 'id', 'cx']).run(dag) # Simplify single qubit gates and CXs pm_4_optimization = PassManager() pm_4_optimization.append( [Optimize1qGates(), CXCancellation(), DAGFixedPoint()], do_while=lambda property_set: not property_set[ 'dag_fixed_point']) dag = transpile_dag(dag, pass_manager=pm_4_optimization) dag.name = name return dag
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) } 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