def test_9q_circuit_16q_coupling_sd(self): """ 9 qubits in Rueschlikon, considering the direction q0[1] → q0[0] → q1[3] → q0[3] ← q1[0] ← q1[1] → q1[2] ← 8 ↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑ q0[2] ← q1[4] → 14 ← 13 ← 12 → 11 → 10 ← 9 """ cmap16 = FakeRueschlikon().configuration().coupling_map qr0 = QuantumRegister(4, 'q0') qr1 = QuantumRegister(5, 'q1') circuit = QuantumCircuit(qr0, qr1) circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2] circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3] circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2] dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap16), strict_direction=True, seed=self.seed) pass_.run(dag) layout = pass_.property_set['layout'] self.assertEqual(layout[qr0[0]], 2) self.assertEqual(layout[qr0[1]], 1) self.assertEqual(layout[qr0[2]], 0) self.assertEqual(layout[qr0[3]], 4) self.assertEqual(layout[qr1[0]], 5) self.assertEqual(layout[qr1[1]], 6) self.assertEqual(layout[qr1[2]], 7) self.assertEqual(layout[qr1[3]], 3) self.assertEqual(layout[qr1[4]], 15) self.assertEqual(pass_.property_set['CSPLayout_stop_reason'], 'solution found')
def test_3q_circuit_5q_coupling(self): """3 qubits in Tenerife, without considering the direction qr1 / | qr0 - qr2 - 3 | / 4 """ cmap5 = FakeTenerife().configuration().coupling_map qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 circuit.cx(qr[1], qr[2]) # qr1 -> qr2 dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap5), strict_direction=False, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 3) self.assertEqual(layout[qr[1]], 2) self.assertEqual(layout[qr[2]], 4) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_3q_circuit_5q_coupling_sd(self): """ 3 qubits in Tenerife, considering the direction qr0 ↙ ↑ qr2 ← qr1 ← 3 ↑ ↙ 4 """ cmap5 = FakeTenerife().configuration().coupling_map qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 circuit.cx(qr[1], qr[2]) # qr1 -> qr2 dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap5), strict_direction=True, seed=self.seed) pass_.run(dag) layout = pass_.property_set['layout'] self.assertEqual(layout[qr[0]], 1) self.assertEqual(layout[qr[1]], 2) self.assertEqual(layout[qr[2]], 0) self.assertEqual(pass_.property_set['CSPLayout_stop_reason'], 'solution found')
def test_9q_circuit_16q_coupling(self): """9 qubits in Rueschlikon, without considering the direction q0[1] - q0[0] - q1[3] - q0[3] - q1[0] - q1[1] - q1[2] - 8 | | | | | | | | q0[2] - q1[4] -- 14 ---- 13 ---- 12 ---- 11 ---- 10 --- 9 """ cmap16 = FakeRueschlikon().configuration().coupling_map qr0 = QuantumRegister(4, "q0") qr1 = QuantumRegister(5, "q1") circuit = QuantumCircuit(qr0, qr1) circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2] circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3] circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2] dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap16), strict_direction=False, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr0[0]], 9) self.assertEqual(layout[qr0[1]], 6) self.assertEqual(layout[qr0[2]], 7) self.assertEqual(layout[qr0[3]], 5) self.assertEqual(layout[qr1[0]], 14) self.assertEqual(layout[qr1[1]], 12) self.assertEqual(layout[qr1[2]], 1) self.assertEqual(layout[qr1[3]], 8) self.assertEqual(layout[qr1[4]], 10) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_call_limit(self): """Hard to solve situations hit the call limit""" dag = TestCSPLayout.create_hard_dag() coupling_map = CouplingMap(FakeTokyo().configuration().coupling_map) pass_ = CSPLayout(coupling_map, call_limit=1, time_limit=None) start = process_time() pass_.run(dag) runtime = process_time() - start self.assertLess(runtime, 1) self.assertEqual(pass_.property_set['CSPLayout_stop_reason'], 'call limit reached')
def test_2q_circuit_2q_coupling(self): """ A simple example, without considering the direction 0 - 1 qr0 - qr1 """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap([[0, 1]]), strict_direction=False, seed=self.seed) pass_.run(dag) layout = pass_.property_set['layout'] self.assertEqual(layout[qr[0]], 0) self.assertEqual(layout[qr[1]], 1) self.assertEqual(pass_.property_set['CSPLayout_stop_reason'], 'solution found')
def test_2q_circuit_2q_coupling_sd(self): """ A simple example, considering the direction 0 -> 1 qr1 -> qr0 """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap([[0, 1]]), strict_direction=True, seed=self.seed) pass_.run(dag) layout = pass_.property_set['layout'] self.assertEqual(layout[qr[0]], 1) self.assertEqual(layout[qr[1]], 0)
def test_5q_circuit_16q_coupling_no_solution(self): """ 5 qubits in Rueschlikon, no solution q0[1] ↖ ↗ q0[2] q0[0] q0[3] ↙ ↘ q0[4] """ cmap16 = FakeRueschlikon().configuration().coupling_map qr = QuantumRegister(5, 'q') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[2]) circuit.cx(qr[0], qr[3]) circuit.cx(qr[0], qr[4]) dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap16), seed=self.seed) pass_.run(dag) layout = pass_.property_set['layout'] self.assertIsNone(layout)
def test_seed(self): """Different seeds yield different results""" seed_1 = 42 seed_2 = 43 cmap5 = FakeTenerife().configuration().coupling_map qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 circuit.cx(qr[1], qr[2]) # qr1 -> qr2 dag = circuit_to_dag(circuit) pass_1 = CSPLayout(CouplingMap(cmap5), seed=seed_1) pass_1.run(dag) layout_1 = pass_1.property_set["layout"] pass_2 = CSPLayout(CouplingMap(cmap5), seed=seed_2) pass_2.run(dag) layout_2 = pass_2.property_set["layout"] self.assertNotEqual(layout_1, layout_2)
def level_2_pass_manager( pass_manager_config: PassManagerConfig) -> PassManager: """Level 2 pass manager: medium optimization by initial layout selection and gate cancellation using commutativity rules. This pass manager applies the user-given initial layout. If none is given, a search for a perfect layout (i.e. one that satisfies all 2-qubit interactions) is conducted. If no such layout is found, qubits are laid out on the most densely connected subset which also exhibits the best gate fidelitites. The pass manager then transforms the circuit to match the coupling constraints. It is then unrolled to the basis, and any flipped cx directions are fixed. Finally, optimizations in the form of commutative gate cancellation and redundant reset removal are performed. Note: In simulators where ``coupling_map=None``, only the unrolling and optimization stages are done. Args: pass_manager_config: configuration of the pass manager. Returns: a level 2 pass manager. """ basis_gates = pass_manager_config.basis_gates coupling_map = pass_manager_config.coupling_map initial_layout = pass_manager_config.initial_layout seed_transpiler = pass_manager_config.seed_transpiler backend_properties = pass_manager_config.backend_properties # 1. Search for a perfect layout, or choose a dense layout, if no layout given _given_layout = SetLayout(initial_layout) def _choose_layout_condition(property_set): return not property_set['layout'] _choose_layout_1 = CSPLayout(coupling_map, call_limit=1000, time_limit=10) _choose_layout_2 = DenseLayout(coupling_map, backend_properties) # 2. Extend dag/layout with ancillas using the full coupling map _embed = [ FullAncillaAllocation(coupling_map), EnlargeWithAncilla(), ApplyLayout() ] # 3. Unroll to 1q or 2q gates _unroll3q = Unroll3qOrMore() # 4. Swap to fit the coupling map _swap_check = CheckMap(coupling_map) def _swap_condition(property_set): return not property_set['is_swap_mapped'] _swap = [ BarrierBeforeFinalMeasurements(), StochasticSwap(coupling_map, trials=20, seed=seed_transpiler) ] # 5. Unroll to the basis _unroll = Unroller(basis_gates) # 6. Fix any bad CX directions _direction_check = [CheckCXDirection(coupling_map)] def _direction_condition(property_set): return not property_set['is_direction_mapped'] _direction = [CXDirection(coupling_map)] # 7. Remove zero-state reset _reset = RemoveResetInZeroState() # 8. 1q rotation merge and commutative cancellation iteratively until no more change in depth _depth_check = [Depth(), FixedPoint('depth')] def _opt_control(property_set): return not property_set['depth_fixed_point'] _opt = [Optimize1qGates(), CommutativeCancellation()] # Build pass manager pm2 = PassManager() if coupling_map: pm2.append(_given_layout) pm2.append(_choose_layout_1, condition=_choose_layout_condition) pm2.append(_choose_layout_2, condition=_choose_layout_condition) pm2.append(_embed) pm2.append(_unroll3q) pm2.append(_swap_check) pm2.append(_swap, condition=_swap_condition) pm2.append(_unroll) if coupling_map and not coupling_map.is_symmetric: pm2.append(_direction_check) pm2.append(_direction, condition=_direction_condition) pm2.append(_reset) pm2.append(_depth_check + _opt, do_while=_opt_control) return pm2
def level_2_pass_manager(pass_manager_config: PassManagerConfig) -> PassManager: """Level 2 pass manager: medium optimization by initial layout selection and gate cancellation using commutativity rules. This pass manager applies the user-given initial layout. If none is given, a search for a perfect layout (i.e. one that satisfies all 2-qubit interactions) is conducted. If no such layout is found, qubits are laid out on the most densely connected subset which also exhibits the best gate fidelitites. The pass manager then transforms the circuit to match the coupling constraints. It is then unrolled to the basis, and any flipped cx directions are fixed. Finally, optimizations in the form of commutative gate cancellation and redundant reset removal are performed. Note: In simulators where ``coupling_map=None``, only the unrolling and optimization stages are done. Args: pass_manager_config: configuration of the pass manager. Returns: a level 2 pass manager. Raises: TranspilerError: if the passmanager config is invalid. """ basis_gates = pass_manager_config.basis_gates coupling_map = pass_manager_config.coupling_map initial_layout = pass_manager_config.initial_layout layout_method = pass_manager_config.layout_method or 'dense' routing_method = pass_manager_config.routing_method or 'stochastic' translation_method = pass_manager_config.translation_method or 'translator' scheduling_method = pass_manager_config.scheduling_method instruction_durations = pass_manager_config.instruction_durations seed_transpiler = pass_manager_config.seed_transpiler backend_properties = pass_manager_config.backend_properties # 1. Search for a perfect layout, or choose a dense layout, if no layout given _given_layout = SetLayout(initial_layout) def _choose_layout_condition(property_set): return not property_set['layout'] _choose_layout_1 = CSPLayout(coupling_map, call_limit=1000, time_limit=10) if layout_method == 'trivial': _choose_layout_2 = TrivialLayout(coupling_map) elif layout_method == 'dense': _choose_layout_2 = DenseLayout(coupling_map, backend_properties) elif layout_method == 'noise_adaptive': _choose_layout_2 = NoiseAdaptiveLayout(backend_properties) elif layout_method == 'sabre': _choose_layout_2 = SabreLayout(coupling_map, max_iterations=2, seed=seed_transpiler) else: raise TranspilerError("Invalid layout method %s." % layout_method) # 2. Extend dag/layout with ancillas using the full coupling map _embed = [FullAncillaAllocation(coupling_map), EnlargeWithAncilla(), ApplyLayout()] # 3. Unroll to 1q or 2q gates _unroll3q = Unroll3qOrMore() # 4. Swap to fit the coupling map _swap_check = CheckMap(coupling_map) def _swap_condition(property_set): return not property_set['is_swap_mapped'] _swap = [BarrierBeforeFinalMeasurements()] if routing_method == 'basic': _swap += [BasicSwap(coupling_map)] elif routing_method == 'stochastic': _swap += [StochasticSwap(coupling_map, trials=20, seed=seed_transpiler)] elif routing_method == 'lookahead': _swap += [LookaheadSwap(coupling_map, search_depth=5, search_width=5)] elif routing_method == 'sabre': _swap += [SabreSwap(coupling_map, heuristic='decay', seed=seed_transpiler)] else: raise TranspilerError("Invalid routing method %s." % routing_method) # 5. Unroll to the basis if translation_method == 'unroller': _unroll = [Unroller(basis_gates)] elif translation_method == 'translator': from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel _unroll = [UnrollCustomDefinitions(sel, basis_gates), BasisTranslator(sel, basis_gates)] elif translation_method == 'synthesis': _unroll = [ Unroll3qOrMore(), Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis(basis_gates), ] else: raise TranspilerError("Invalid translation method %s." % translation_method) # 6. Fix any bad CX directions _direction_check = [CheckCXDirection(coupling_map)] def _direction_condition(property_set): return not property_set['is_direction_mapped'] _direction = [CXDirection(coupling_map)] # 7. Remove zero-state reset _reset = RemoveResetInZeroState() # 8. 1q rotation merge and commutative cancellation iteratively until no more change in depth _depth_check = [Depth(), FixedPoint('depth')] def _opt_control(property_set): return not property_set['depth_fixed_point'] _opt = [Optimize1qGates(basis_gates), CommutativeCancellation()] # 9. Schedule the circuit only when scheduling_method is supplied if scheduling_method: _scheduling = [TimeUnitAnalysis(instruction_durations)] if scheduling_method in {'alap', 'as_late_as_possible'}: _scheduling += [ALAPSchedule(instruction_durations)] elif scheduling_method in {'asap', 'as_soon_as_possible'}: _scheduling += [ASAPSchedule(instruction_durations)] else: raise TranspilerError("Invalid scheduling method %s." % scheduling_method) # Build pass manager pm2 = PassManager() if coupling_map: pm2.append(_given_layout) pm2.append(_choose_layout_1, condition=_choose_layout_condition) pm2.append(_choose_layout_2, condition=_choose_layout_condition) pm2.append(_embed) pm2.append(_unroll3q) pm2.append(_swap_check) pm2.append(_swap, condition=_swap_condition) pm2.append(_unroll) if coupling_map and not coupling_map.is_symmetric: pm2.append(_direction_check) pm2.append(_direction, condition=_direction_condition) pm2.append(_reset) pm2.append(_depth_check + _opt, do_while=_opt_control) if scheduling_method: pm2.append(_scheduling) return pm2
def level_2_pass_manager(pass_manager_config: PassManagerConfig) -> PassManager: """Level 2 pass manager: medium optimization by initial layout selection and gate cancellation using commutativity rules. This pass manager applies the user-given initial layout. If none is given, a search for a perfect layout (i.e. one that satisfies all 2-qubit interactions) is conducted. If no such layout is found, qubits are laid out on the most densely connected subset which also exhibits the best gate fidelities. The pass manager then transforms the circuit to match the coupling constraints. It is then unrolled to the basis, and any flipped cx directions are fixed. Finally, optimizations in the form of commutative gate cancellation and redundant reset removal are performed. Note: In simulators where ``coupling_map=None``, only the unrolling and optimization stages are done. Args: pass_manager_config: configuration of the pass manager. Returns: a level 2 pass manager. Raises: TranspilerError: if the passmanager config is invalid. """ basis_gates = pass_manager_config.basis_gates coupling_map = pass_manager_config.coupling_map initial_layout = pass_manager_config.initial_layout layout_method = pass_manager_config.layout_method or "dense" routing_method = pass_manager_config.routing_method or "stochastic" translation_method = pass_manager_config.translation_method or "translator" scheduling_method = pass_manager_config.scheduling_method instruction_durations = pass_manager_config.instruction_durations seed_transpiler = pass_manager_config.seed_transpiler backend_properties = pass_manager_config.backend_properties approximation_degree = pass_manager_config.approximation_degree timing_constraints = pass_manager_config.timing_constraints or TimingConstraints() # 1. Search for a perfect layout, or choose a dense layout, if no layout given _given_layout = SetLayout(initial_layout) def _choose_layout_condition(property_set): # layout hasn't been set yet return not property_set["layout"] # 1a. If layout_method is not set, first try a trivial layout _choose_layout_0 = ( [] if pass_manager_config.layout_method else [ TrivialLayout(coupling_map), Layout2qDistance(coupling_map, property_name="trivial_layout_score"), ] ) # 1b. If a trivial layout wasn't perfect (ie no swaps are needed) then try using # CSP layout to find a perfect layout _choose_layout_1 = ( [] if pass_manager_config.layout_method else CSPLayout(coupling_map, call_limit=1000, time_limit=10, seed=seed_transpiler) ) def _trivial_not_perfect(property_set): # Verify that a trivial layout is perfect. If trivial_layout_score > 0 # the layout is not perfect. The layout is unconditionally set by trivial # layout so we need to clear it before contuing. if property_set["trivial_layout_score"] is not None: if property_set["trivial_layout_score"] != 0: property_set["layout"]._wrapped = None return True return False def _csp_not_found_match(property_set): # If a layout hasn't been set by the time we run csp we need to run layout if property_set["layout"] is None: return True # if CSP layout stopped for any reason other than solution found we need # to run layout since CSP didn't converge. if ( property_set["CSPLayout_stop_reason"] is not None and property_set["CSPLayout_stop_reason"] != "solution found" ): return True return False # 1c. if CSP layout doesn't converge on a solution use layout_method (dense) to get a layout if layout_method == "trivial": _choose_layout_2 = TrivialLayout(coupling_map) elif layout_method == "dense": _choose_layout_2 = DenseLayout(coupling_map, backend_properties) elif layout_method == "noise_adaptive": _choose_layout_2 = NoiseAdaptiveLayout(backend_properties) elif layout_method == "sabre": _choose_layout_2 = SabreLayout(coupling_map, max_iterations=2, seed=seed_transpiler) else: raise TranspilerError("Invalid layout method %s." % layout_method) # 2. Extend dag/layout with ancillas using the full coupling map _embed = [FullAncillaAllocation(coupling_map), EnlargeWithAncilla(), ApplyLayout()] # 3. Unroll to 1q or 2q gates _unroll3q = Unroll3qOrMore() # 4. Swap to fit the coupling map _swap_check = CheckMap(coupling_map) def _swap_condition(property_set): return not property_set["is_swap_mapped"] _swap = [BarrierBeforeFinalMeasurements()] if routing_method == "basic": _swap += [BasicSwap(coupling_map)] elif routing_method == "stochastic": _swap += [StochasticSwap(coupling_map, trials=20, seed=seed_transpiler)] elif routing_method == "lookahead": _swap += [LookaheadSwap(coupling_map, search_depth=5, search_width=5)] elif routing_method == "sabre": _swap += [SabreSwap(coupling_map, heuristic="decay", seed=seed_transpiler)] elif routing_method == "none": _swap += [ Error( msg="No routing method selected, but circuit is not routed to device. " "CheckMap Error: {check_map_msg}", action="raise", ) ] else: raise TranspilerError("Invalid routing method %s." % routing_method) # 5. Unroll to the basis if translation_method == "unroller": _unroll = [Unroller(basis_gates)] elif translation_method == "translator": from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel _unroll = [UnrollCustomDefinitions(sel, basis_gates), BasisTranslator(sel, basis_gates)] elif translation_method == "synthesis": _unroll = [ Unroll3qOrMore(), Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis(basis_gates, approximation_degree=approximation_degree), ] else: raise TranspilerError("Invalid translation method %s." % translation_method) # 6. Fix any bad CX directions _direction_check = [CheckGateDirection(coupling_map)] def _direction_condition(property_set): return not property_set["is_direction_mapped"] _direction = [GateDirection(coupling_map)] # 7. Remove zero-state reset _reset = RemoveResetInZeroState() # 8. 1q rotation merge and commutative cancellation iteratively until no more change in depth _depth_check = [Depth(), FixedPoint("depth")] def _opt_control(property_set): return not property_set["depth_fixed_point"] _opt = [ Optimize1qGatesDecomposition(basis_gates), CommutativeCancellation(basis_gates=basis_gates), ] # 9. Unify all durations (either SI, or convert to dt if known) # Schedule the circuit only when scheduling_method is supplied _scheduling = [TimeUnitConversion(instruction_durations)] if scheduling_method: if scheduling_method in {"alap", "as_late_as_possible"}: _scheduling += [ALAPSchedule(instruction_durations)] elif scheduling_method in {"asap", "as_soon_as_possible"}: _scheduling += [ASAPSchedule(instruction_durations)] else: raise TranspilerError("Invalid scheduling method %s." % scheduling_method) # 10. Call measure alignment. Should come after scheduling. _alignments = [ ValidatePulseGates( granularity=timing_constraints.granularity, min_length=timing_constraints.min_length ), AlignMeasures(alignment=timing_constraints.acquire_alignment), ] # Build pass manager pm2 = PassManager() if coupling_map or initial_layout: pm2.append(_given_layout) pm2.append(_choose_layout_0, condition=_choose_layout_condition) pm2.append(_choose_layout_1, condition=_trivial_not_perfect) pm2.append(_choose_layout_2, condition=_csp_not_found_match) pm2.append(_embed) pm2.append(_unroll3q) pm2.append(_swap_check) pm2.append(_swap, condition=_swap_condition) pm2.append(_unroll) if coupling_map and not coupling_map.is_symmetric: pm2.append(_direction_check) pm2.append(_direction, condition=_direction_condition) pm2.append(_reset) pm2.append(_depth_check + _opt + _unroll, do_while=_opt_control) pm2.append(_scheduling) pm2.append(_alignments) return pm2
def level_2_pass_manager(pass_manager_config: PassManagerConfig) -> PassManager: """Level 2 pass manager: medium optimization by noise adaptive qubit mapping and gate cancellation using commutativity rules. This pass manager applies the user-given initial layout. If none is given, and device calibration information is available, the circuit is mapped to the qubits with best readouts and to CX gates with highest fidelity. Otherwise, a layout on the most densely connected qubits is used. The pass manager then transforms the circuit to match the coupling constraints. It is then unrolled to the basis, and any flipped cx directions are fixed. Finally, optimizations in the form of commutative gate cancellation and redundant reset removal are performed. Note: In simulators where ``coupling_map=None``, only the unrolling and optimization stages are done. Args: pass_manager_config: configuration of the pass manager. Returns: a level 2 pass manager. """ basis_gates = pass_manager_config.basis_gates coupling_map = pass_manager_config.coupling_map initial_layout = pass_manager_config.initial_layout seed_transpiler = pass_manager_config.seed_transpiler backend_properties = pass_manager_config.backend_properties # 1. Unroll to the basis first, to prepare for noise-adaptive layout _unroll = Unroller(basis_gates) # 2. Layout on good qubits if calibration info available, otherwise on dense links _given_layout = SetLayout(initial_layout) def _choose_layout_condition(property_set): return not property_set['layout'] _choose_layout = DenseLayout(coupling_map, backend_properties) # 3. Extend dag/layout with ancillas using the full coupling map _embed = [FullAncillaAllocation(coupling_map), EnlargeWithAncilla(), ApplyLayout()] # 4. Unroll to 1q or 2q gates, swap to fit the coupling map _swap_check = CheckMap(coupling_map) def _swap_condition(property_set): return not property_set['is_swap_mapped'] _swap = [BarrierBeforeFinalMeasurements(), Unroll3qOrMore(), StochasticSwap(coupling_map, trials=20, seed=seed_transpiler), Decompose(SwapGate)] # 5. Fix any bad CX directions _direction_check = [CheckCXDirection(coupling_map)] def _direction_condition(property_set): return not property_set['is_direction_mapped'] _direction = [CXDirection(coupling_map)] # 6. Remove zero-state reset _reset = RemoveResetInZeroState() # 7. 1q rotation merge and commutative cancellation iteratively until no more change in depth _depth_check = [Depth(), FixedPoint('depth')] def _opt_control(property_set): return not property_set['depth_fixed_point'] _opt = [Optimize1qGates(), CommutativeCancellation()] pm2 = PassManager() pm2.append(_unroll) if coupling_map: pm2.append(_given_layout) pm2.append(CSPLayout(coupling_map, call_limit=1000, time_limit=10), condition=_choose_layout_condition) pm2.append(_choose_layout, condition=_choose_layout_condition) pm2.append(_embed) pm2.append(_swap_check) pm2.append(_swap, condition=_swap_condition) if not coupling_map.is_symmetric: pm2.append(_direction_check) pm2.append(_direction, condition=_direction_condition) pm2.append(_reset) pm2.append(_depth_check + _opt, do_while=_opt_control) return pm2
def level_3_with_contant_pure(pass_manager_config: PassManagerConfig) -> PassManager: """ Args: pass_manager_config: configuration of the pass manager. Returns: a level 3 pass manager. """ basis_gates = pass_manager_config.basis_gates coupling_map = pass_manager_config.coupling_map initial_layout = pass_manager_config.initial_layout layout_method = pass_manager_config.layout_method or 'dense' routing_method = pass_manager_config.routing_method or 'stochastic' seed_transpiler = pass_manager_config.seed_transpiler backend_properties = pass_manager_config.backend_properties # 1. Unroll to the basis first, to prepare for noise-adaptive layout _unroll = Unroller(basis_gates + ['annotation']) # 2. Layout on good qubits if calibration info available, otherwise on dense links _given_layout = SetLayout(initial_layout) def _choose_layout_condition(property_set): return not property_set['layout'] _choose_layout_1 = CSPLayout(coupling_map, call_limit=10000, time_limit=60) if layout_method == 'trivial': _choose_layout_2 = TrivialLayout(coupling_map) elif layout_method == 'dense': _choose_layout_2 = DenseLayout(coupling_map, backend_properties) elif layout_method == 'noise_adaptive': _choose_layout_2 = NoiseAdaptiveLayout(backend_properties) else: raise TranspilerError("Invalid layout method %s." % layout_method) # 3. Extend dag/layout with ancillas using the full coupling map _embed = [FullAncillaAllocation(coupling_map), EnlargeWithAncilla(), ApplyLayout()] # 4. Unroll to 1q or 2q gates, swap to fit the coupling map _swap_check = CheckMap(coupling_map) def _swap_condition(property_set): return not property_set['is_swap_mapped'] _swap = [BarrierBeforeFinalMeasurements(), Unroll3qOrMore()] if routing_method == 'basic': _swap += [BasicSwap(coupling_map)] elif routing_method == 'stochastic': _swap += [StochasticSwap(coupling_map, trials=200, seed=seed_transpiler)] elif routing_method == 'lookahead': _swap += [LookaheadSwap(coupling_map, search_depth=5, search_width=6)] else: raise TranspilerError("Invalid routing method %s." % routing_method) # 5. 1q rotation merge and commutative cancellation iteratively until no more change in depth _depth_check = [Depth(), FixedPoint('depth')] def _opt_control(property_set): return not property_set['depth_fixed_point'] _opt = [RemoveResetInZeroState(), Collect2qBlocks(), ConsolidateBlocks(), Unroller(basis_gates), # unroll unitaries Optimize1qGates(basis_gates), CommutativeCancellation(), OptimizeSwapBeforeMeasure(), RemoveDiagonalGatesBeforeMeasure()] # 6. Fix any CX direction mismatch _direction_check = [CheckCXDirection(coupling_map)] def _direction_condition(property_set): return not property_set['is_direction_mapped'] _direction = [CXDirection(coupling_map)] # Build pass manager pm = PassManager() pm.append(ConstantsStateOptimization()) pm.append(_unroll) if coupling_map: pm.append(_given_layout) pm.append(_choose_layout_1, condition=_choose_layout_condition) pm.append(_choose_layout_2, condition=_choose_layout_condition) pm.append(_embed) pm.append(_swap_check) pm.append(_swap, condition=_swap_condition) pm.append(ConstantsStateOptimization()) pm.append([Unroller(basis_gates+['swap', 'aswap', 'annotation']), Optimize1qGates(), PureStateOnU()]) pm.append(_depth_check + _opt, do_while=_opt_control) if coupling_map and not coupling_map.is_symmetric: pm.append(_direction_check) pm.append(_direction, condition=_direction_condition) return pm
def noise_pass_manager(basis_gates=None, initial_layout=None, coupling_map=None, layout_method=None, translation_method=None, seed_transpiler=None, backend=None, routing_method=None, backend_properties=None, transform=False, readout=True, alpha=0.5, next_gates=5, front=True) -> PassManager: """Level 3 pass manager: heavy optimization by noise adaptive qubit mapping and gate cancellation using commutativity rules and unitary synthesis. This pass manager applies the user-given initial layout. If none is given, a search for a perfect layout (i.e. one that satisfies all 2-qubit interactions) is conducted. If no such layout is found, and device calibration information is available, the circuit is mapped to the qubits with best readouts and to CX gates with highest fidelity. The pass manager then transforms the circuit to match the coupling constraints. It is then unrolled to the basis, and any flipped cx directions are fixed. Finally, optimizations in the form of commutative gate cancellation, resynthesis of two-qubit unitary blocks, and redundant reset removal are performed. Note: In simulators where ``coupling_map=None``, only the unrolling and optimization stages are done. Args: backend (BaseBackend) Returns: a level 3 pass manager. Raises: TranspilerError: if the passmanager config is invalid. """ if basis_gates is None: if getattr(backend, 'configuration', None): basis_gates = getattr(backend.configuration(), 'basis_gates', None) # basis_gates could be None, or a list of basis, e.g. ['u3', 'cx'] if isinstance(basis_gates, list) and all( isinstance(i, str) for i in basis_gates): basis_gates = basis_gates if basis_gates is None: basis_gates = ['u3', 'cx', 'id'] # basis_gates = ['u3', 'cx', 'id'] backend = backend if backend is None or backend.configuration().simulator: if backend_properties is None or coupling_map is None: raise QiskitError( "Backend is simulator or not specified, provide backend properties and coupling map." ) coupling_map = coupling_map backend_properties = backend_properties else: if backend_properties is not None or coupling_map is not None: warnings.warn( "A backend was provide, ignoring backend properties and coupling map", UserWarning) coupling_map = backend.configuration().coupling_map backend_properties = backend.properties() if isinstance(coupling_map, list): coupling_map = CouplingMap(couplinglist=coupling_map) initial_layout = initial_layout layout_method = layout_method or 'dense' routing_method = routing_method or 'stochastic' translation_method = translation_method or 'translator' seed_transpiler = seed_transpiler # 1. Unroll to 1q or 2q gates _unroll3q = Unroll3qOrMore() # 2. Layout on good qubits if calibration info available, otherwise on dense links _given_layout = SetLayout(initial_layout) def _choose_layout_condition(property_set): return not property_set['layout'] _choose_layout_1 = CSPLayout(coupling_map, call_limit=10000, time_limit=60) if layout_method == 'trivial': _choose_layout_2 = TrivialLayout(coupling_map) elif layout_method == 'dense': _choose_layout_2 = DenseLayout(coupling_map, backend_properties) elif layout_method == 'noise_adaptive': _choose_layout_2 = NoiseAdaptiveLayout(backend_properties) elif layout_method == 'sabre': _choose_layout_2 = SabreLayout(coupling_map, max_iterations=4, seed=seed_transpiler) elif layout_method == 'chain': _choose_layout_2 = ChainLayout(coupling_map, backend_properties, readout=readout) else: raise TranspilerError("Invalid layout method %s." % layout_method) # 3. Extend dag/layout with ancillas using the full coupling map _embed = [ FullAncillaAllocation(coupling_map), EnlargeWithAncilla(), ApplyLayout() ] # 4. Swap to fit the coupling map _swap_check = CheckMap(coupling_map) def _swap_condition(property_set): return not property_set['is_swap_mapped'] _swap = [BarrierBeforeFinalMeasurements()] if routing_method == 'basic': _swap += [BasicSwap(coupling_map)] elif routing_method == 'stochastic': _swap += [ StochasticSwap(coupling_map, trials=200, seed=seed_transpiler) ] elif routing_method == 'lookahead': _swap += [LookaheadSwap(coupling_map, search_depth=5, search_width=6)] elif routing_method == 'sabre': _swap += [ SabreSwap(coupling_map, heuristic='decay', seed=seed_transpiler) ] elif routing_method == 'noise_adaptive': _swap += [ NoiseAdaptiveSwap(coupling_map, backend_properties, invert_score=invert_score, swap_score=swap_score, readout=readout, alpha=alpha, next_gates=next_gates, front=front) ] else: raise TranspilerError("Invalid routing method %s." % routing_method) # 5. Unroll to the basis if translation_method == 'unroller': _unroll = [Unroller(basis_gates)] elif translation_method == 'translator': from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel _unroll = [ UnrollCustomDefinitions(sel, basis_gates), BasisTranslator(sel, basis_gates) ] elif translation_method == 'synthesis': _unroll = [ Unroll3qOrMore(), Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis(basis_gates), ] else: raise TranspilerError("Invalid translation method %s." % translation_method) # 6. Fix any CX direction mismatch _direction_check = [CheckCXDirection(coupling_map)] def _direction_condition(property_set): return not property_set['is_direction_mapped'] _direction = [CXDirection(coupling_map)] # 8. Optimize iteratively until no more change in depth. Removes useless gates # after reset and before measure, commutes gates and optimizes continguous blocks. _depth_check = [Depth(), FixedPoint('depth')] def _opt_control(property_set): return not property_set['depth_fixed_point'] _reset = [RemoveResetInZeroState()] _meas = [OptimizeSwapBeforeMeasure(), RemoveDiagonalGatesBeforeMeasure()] _opt = [ Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis(basis_gates), Optimize1qGates(basis_gates), CommutativeCancellation(), ] # Build pass manager pm3 = PassManager() pm3.append(_unroll3q) if transform: _transform = TransformCxCascade() pm3.append(_transform) pm3.append(_reset + _meas) if coupling_map: pm3.append(_given_layout) pm3.append(_choose_layout_1, condition=_choose_layout_condition) pm3.append(_choose_layout_2, condition=_choose_layout_condition) pm3.append(_embed) pm3.append(_swap_check) pm3.append(_swap, condition=_swap_condition) pm3.append(_unroll) pm3.append(_depth_check + _opt + _unroll, do_while=_opt_control) if coupling_map and not coupling_map.is_symmetric: pm3.append(_direction_check) pm3.append(_direction, condition=_direction_condition) pm3.append(_reset) return pm3
def level_3_pass_manager( pass_manager_config: PassManagerConfig) -> PassManager: """Level 3 pass manager: heavy optimization by noise adaptive qubit mapping and gate cancellation using commutativity rules and unitary synthesis. This pass manager applies the user-given initial layout. If none is given, a search for a perfect layout (i.e. one that satisfies all 2-qubit interactions) is conducted. If no such layout is found, and device calibration information is available, the circuit is mapped to the qubits with best readouts and to CX gates with highest fidelity. The pass manager then transforms the circuit to match the coupling constraints. It is then unrolled to the basis, and any flipped cx directions are fixed. Finally, optimizations in the form of commutative gate cancellation, resynthesis of two-qubit unitary blocks, and redundant reset removal are performed. Note: In simulators where ``coupling_map=None``, only the unrolling and optimization stages are done. Args: pass_manager_config: configuration of the pass manager. Returns: a level 3 pass manager. Raises: TranspilerError: if the passmanager config is invalid. """ basis_gates = pass_manager_config.basis_gates coupling_map = pass_manager_config.coupling_map initial_layout = pass_manager_config.initial_layout layout_method = pass_manager_config.layout_method or 'dense' routing_method = pass_manager_config.routing_method or 'stochastic' translation_method = pass_manager_config.translation_method or 'translator' scheduling_method = pass_manager_config.scheduling_method instruction_durations = pass_manager_config.instruction_durations seed_transpiler = pass_manager_config.seed_transpiler backend_properties = pass_manager_config.backend_properties # 1. Unroll to 1q or 2q gates _unroll3q = Unroll3qOrMore() # 2. Layout on good qubits if calibration info available, otherwise on dense links _given_layout = SetLayout(initial_layout) def _choose_layout_condition(property_set): return not property_set['layout'] _choose_layout_1 = [] if pass_manager_config.layout_method \ else CSPLayout(coupling_map, call_limit=10000, time_limit=60, seed=seed_transpiler) if layout_method == 'trivial': _choose_layout_2 = TrivialLayout(coupling_map) elif layout_method == 'dense': _choose_layout_2 = DenseLayout(coupling_map, backend_properties) elif layout_method == 'noise_adaptive': _choose_layout_2 = NoiseAdaptiveLayout(backend_properties) elif layout_method == 'sabre': _choose_layout_2 = SabreLayout(coupling_map, max_iterations=4, seed=seed_transpiler) else: raise TranspilerError("Invalid layout method %s." % layout_method) # 3. Extend dag/layout with ancillas using the full coupling map _embed = [ FullAncillaAllocation(coupling_map), EnlargeWithAncilla(), ApplyLayout() ] # 4. Swap to fit the coupling map _swap_check = CheckMap(coupling_map) def _swap_condition(property_set): return not property_set['is_swap_mapped'] _swap = [BarrierBeforeFinalMeasurements()] if routing_method == 'basic': _swap += [BasicSwap(coupling_map)] elif routing_method == 'stochastic': _swap += [ StochasticSwap(coupling_map, trials=200, seed=seed_transpiler) ] elif routing_method == 'lookahead': _swap += [LookaheadSwap(coupling_map, search_depth=5, search_width=6)] elif routing_method == 'sabre': _swap += [ SabreSwap(coupling_map, heuristic='decay', seed=seed_transpiler) ] elif routing_method == 'none': _swap += [ Error( msg= 'No routing method selected, but circuit is not routed to device. ' 'CheckMap Error: {check_map_msg}', action='raise') ] else: raise TranspilerError("Invalid routing method %s." % routing_method) # 5. Unroll to the basis if translation_method == 'unroller': _unroll = [Unroller(basis_gates)] elif translation_method == 'translator': from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel _unroll = [ UnrollCustomDefinitions(sel, basis_gates), BasisTranslator(sel, basis_gates) ] elif translation_method == 'synthesis': _unroll = [ Unroll3qOrMore(), Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis(basis_gates), ] else: raise TranspilerError("Invalid translation method %s." % translation_method) # 6. Fix any CX direction mismatch _direction_check = [CheckCXDirection(coupling_map)] def _direction_condition(property_set): return not property_set['is_direction_mapped'] _direction = [CXDirection(coupling_map)] # 8. Optimize iteratively until no more change in depth. Removes useless gates # after reset and before measure, commutes gates and optimizes contiguous blocks. _depth_check = [Depth(), FixedPoint('depth')] def _opt_control(property_set): return not property_set['depth_fixed_point'] _reset = [RemoveResetInZeroState()] _meas = [OptimizeSwapBeforeMeasure(), RemoveDiagonalGatesBeforeMeasure()] _opt = [ Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis(basis_gates), Optimize1qGatesDecomposition(basis_gates), CommutativeCancellation(), ] # Schedule the circuit only when scheduling_method is supplied if scheduling_method: _scheduling = [TimeUnitAnalysis(instruction_durations)] if scheduling_method in {'alap', 'as_late_as_possible'}: _scheduling += [ALAPSchedule(instruction_durations)] elif scheduling_method in {'asap', 'as_soon_as_possible'}: _scheduling += [ASAPSchedule(instruction_durations)] else: raise TranspilerError("Invalid scheduling method %s." % scheduling_method) # Build pass manager pm3 = PassManager() pm3.append(_unroll3q) pm3.append(_reset + _meas) if coupling_map or initial_layout: pm3.append(_given_layout) pm3.append(_choose_layout_1, condition=_choose_layout_condition) pm3.append(_choose_layout_2, condition=_choose_layout_condition) pm3.append(_embed) pm3.append(_swap_check) pm3.append(_swap, condition=_swap_condition) pm3.append(_unroll) pm3.append(_depth_check + _opt + _unroll, do_while=_opt_control) if coupling_map and not coupling_map.is_symmetric: pm3.append(_direction_check) pm3.append(_direction, condition=_direction_condition) pm3.append(_reset) if scheduling_method: pm3.append(_scheduling) return pm3
def level_3_pass_manager(pass_manager_config: PassManagerConfig) -> PassManager: """Level 3 pass manager: heavy optimization by noise adaptive qubit mapping and gate cancellation using commutativity rules and unitary synthesis. This pass manager applies the user-given initial layout. If none is given, a search for a perfect layout (i.e. one that satisfies all 2-qubit interactions) is conducted. If no such layout is found, and device calibration information is available, the circuit is mapped to the qubits with best readouts and to CX gates with highest fidelity. The pass manager then transforms the circuit to match the coupling constraints. It is then unrolled to the basis, and any flipped cx directions are fixed. Finally, optimizations in the form of commutative gate cancellation, resynthesis of two-qubit unitary blocks, and redundant reset removal are performed. Note: In simulators where ``coupling_map=None``, only the unrolling and optimization stages are done. Args: pass_manager_config: configuration of the pass manager. Returns: a level 3 pass manager. """ basis_gates = pass_manager_config.basis_gates coupling_map = pass_manager_config.coupling_map initial_layout = pass_manager_config.initial_layout seed_transpiler = pass_manager_config.seed_transpiler backend_properties = pass_manager_config.backend_properties # 1. Unroll to the basis first, to prepare for noise-adaptive layout _unroll = Unroller(basis_gates) # 2. Layout on good qubits if calibration info available, otherwise on dense links _given_layout = SetLayout(initial_layout) def _choose_layout_condition(property_set): return not property_set['layout'] _choose_layout_1 = CSPLayout(coupling_map, call_limit=10000, time_limit=60) # TODO: benchmark DenseLayout vs. NoiseAdaptiveLayout in terms of noise aware mapping _choose_layout_2 = DenseLayout(coupling_map, backend_properties) # 3. Extend dag/layout with ancillas using the full coupling map _embed = [FullAncillaAllocation(coupling_map), EnlargeWithAncilla(), ApplyLayout()] # 4. Unroll to 1q or 2q gates, swap to fit the coupling map _swap_check = CheckMap(coupling_map) def _swap_condition(property_set): return not property_set['is_swap_mapped'] _swap = [BarrierBeforeFinalMeasurements(), Unroll3qOrMore(), StochasticSwap(coupling_map, trials=20, seed=seed_transpiler)] # 5. 1q rotation merge and commutative cancellation iteratively until no more change in depth _depth_check = [Depth(), FixedPoint('depth')] def _opt_control(property_set): return not property_set['depth_fixed_point'] _opt = [RemoveResetInZeroState(), Collect2qBlocks(), ConsolidateBlocks(), Unroller(basis_gates), # unroll unitaries Optimize1qGates(), CommutativeCancellation(), OptimizeSwapBeforeMeasure(), RemoveDiagonalGatesBeforeMeasure()] # 6. Fix any CX direction mismatch _direction_check = [CheckCXDirection(coupling_map)] def _direction_condition(property_set): return not property_set['is_direction_mapped'] _direction = [CXDirection(coupling_map)] # Build pass manager pm3 = PassManager() pm3.append(_unroll) if coupling_map: pm3.append(_given_layout) pm3.append(_choose_layout_1, condition=_choose_layout_condition) pm3.append(_choose_layout_2, condition=_choose_layout_condition) pm3.append(_embed) pm3.append(_swap_check) pm3.append(_swap, condition=_swap_condition) pm3.append(_depth_check + _opt, do_while=_opt_control) if coupling_map and not coupling_map.is_symmetric: pm3.append(_direction_check) pm3.append(_direction, condition=_direction_condition) return pm3
def level_3_pass_manager(pass_manager_config: PassManagerConfig) -> PassManager: """Level 3 pass manager: heavy optimization by noise adaptive qubit mapping and gate cancellation using commutativity rules and unitary synthesis. This pass manager applies the user-given initial layout. If none is given, a search for a perfect layout (i.e. one that satisfies all 2-qubit interactions) is conducted. If no such layout is found, and device calibration information is available, the circuit is mapped to the qubits with best readouts and to CX gates with highest fidelity. The pass manager then transforms the circuit to match the coupling constraints. It is then unrolled to the basis, and any flipped cx directions are fixed. Finally, optimizations in the form of commutative gate cancellation, resynthesis of two-qubit unitary blocks, and redundant reset removal are performed. Note: In simulators where ``coupling_map=None``, only the unrolling and optimization stages are done. Args: pass_manager_config: configuration of the pass manager. Returns: a level 3 pass manager. Raises: TranspilerError: if the passmanager config is invalid. """ basis_gates = pass_manager_config.basis_gates inst_map = pass_manager_config.inst_map coupling_map = pass_manager_config.coupling_map initial_layout = pass_manager_config.initial_layout layout_method = pass_manager_config.layout_method or "sabre" routing_method = pass_manager_config.routing_method or "sabre" translation_method = pass_manager_config.translation_method or "translator" scheduling_method = pass_manager_config.scheduling_method instruction_durations = pass_manager_config.instruction_durations seed_transpiler = pass_manager_config.seed_transpiler backend_properties = pass_manager_config.backend_properties approximation_degree = pass_manager_config.approximation_degree unitary_synthesis_method = pass_manager_config.unitary_synthesis_method timing_constraints = pass_manager_config.timing_constraints or TimingConstraints() unitary_synthesis_plugin_config = pass_manager_config.unitary_synthesis_plugin_config target = pass_manager_config.target # 1. Unroll to 1q or 2q gates _unroll3q = [ # Use unitary synthesis for basis aware decomposition of UnitaryGates UnitarySynthesis( basis_gates, approximation_degree=approximation_degree, method=unitary_synthesis_method, plugin_config=unitary_synthesis_plugin_config, min_qubits=3, ), Unroll3qOrMore(), ] # 2. Layout on good qubits if calibration info available, otherwise on dense links _given_layout = SetLayout(initial_layout) def _choose_layout_condition(property_set): # layout hasn't been set yet return not property_set["layout"] def _csp_not_found_match(property_set): # If a layout hasn't been set by the time we run csp we need to run layout if property_set["layout"] is None: return True # if CSP layout stopped for any reason other than solution found we need # to run layout since CSP didn't converge. if ( property_set["CSPLayout_stop_reason"] is not None and property_set["CSPLayout_stop_reason"] != "solution found" ): return True return False # 2a. If layout method is not set, first try a trivial layout _choose_layout_0 = ( [] if pass_manager_config.layout_method else [ TrivialLayout(coupling_map), Layout2qDistance(coupling_map, property_name="trivial_layout_score"), ] ) # 2b. If trivial layout wasn't perfect (ie no swaps are needed) then try # using CSP layout to find a perfect layout _choose_layout_1 = ( [] if pass_manager_config.layout_method else CSPLayout(coupling_map, call_limit=10000, time_limit=60, seed=seed_transpiler) ) def _trivial_not_perfect(property_set): # Verify that a trivial layout is perfect. If trivial_layout_score > 0 # the layout is not perfect. The layout property set is unconditionally # set by trivial layout so we clear that before running CSP if property_set["trivial_layout_score"] is not None: if property_set["trivial_layout_score"] != 0: return True return False # 2c. if CSP didn't converge on a solution use layout_method (dense). if layout_method == "trivial": _choose_layout_2 = TrivialLayout(coupling_map) elif layout_method == "dense": _choose_layout_2 = DenseLayout(coupling_map, backend_properties) elif layout_method == "noise_adaptive": _choose_layout_2 = NoiseAdaptiveLayout(backend_properties) elif layout_method == "sabre": _choose_layout_2 = SabreLayout(coupling_map, max_iterations=4, seed=seed_transpiler) else: raise TranspilerError("Invalid layout method %s." % layout_method) # 3. Extend dag/layout with ancillas using the full coupling map _embed = [FullAncillaAllocation(coupling_map), EnlargeWithAncilla(), ApplyLayout()] # 4. Swap to fit the coupling map _swap_check = CheckMap(coupling_map) def _swap_condition(property_set): return not property_set["is_swap_mapped"] _swap = [BarrierBeforeFinalMeasurements()] if routing_method == "basic": _swap += [BasicSwap(coupling_map)] elif routing_method == "stochastic": _swap += [StochasticSwap(coupling_map, trials=200, seed=seed_transpiler)] elif routing_method == "lookahead": _swap += [LookaheadSwap(coupling_map, search_depth=5, search_width=6)] elif routing_method == "sabre": _swap += [SabreSwap(coupling_map, heuristic="decay", seed=seed_transpiler)] elif routing_method == "none": _swap += [ Error( msg=( "No routing method selected, but circuit is not routed to device. " "CheckMap Error: {check_map_msg}" ), action="raise", ) ] else: raise TranspilerError("Invalid routing method %s." % routing_method) # 5. Unroll to the basis if translation_method == "unroller": _unroll = [Unroller(basis_gates)] elif translation_method == "translator": from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel _unroll = [ UnitarySynthesis( basis_gates, approximation_degree=approximation_degree, coupling_map=coupling_map, backend_props=backend_properties, plugin_config=unitary_synthesis_plugin_config, method=unitary_synthesis_method, ), UnrollCustomDefinitions(sel, basis_gates), BasisTranslator(sel, basis_gates, target), ] elif translation_method == "synthesis": _unroll = [ UnitarySynthesis( basis_gates, approximation_degree=approximation_degree, coupling_map=coupling_map, backend_props=backend_properties, method=unitary_synthesis_method, plugin_config=unitary_synthesis_plugin_config, min_qubits=3, ), Unroll3qOrMore(), Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis( basis_gates, approximation_degree=approximation_degree, coupling_map=coupling_map, backend_props=backend_properties, method=unitary_synthesis_method, plugin_config=unitary_synthesis_plugin_config, ), ] else: raise TranspilerError("Invalid translation method %s." % translation_method) # 6. Fix any CX direction mismatch _direction_check = [CheckGateDirection(coupling_map, target)] def _direction_condition(property_set): return not property_set["is_direction_mapped"] _direction = [GateDirection(coupling_map, target)] # 8. Optimize iteratively until no more change in depth. Removes useless gates # after reset and before measure, commutes gates and optimizes contiguous blocks. _depth_check = [Depth(), FixedPoint("depth")] def _opt_control(property_set): return not property_set["depth_fixed_point"] _reset = [RemoveResetInZeroState()] _meas = [OptimizeSwapBeforeMeasure(), RemoveDiagonalGatesBeforeMeasure()] _opt = [ Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis( basis_gates, approximation_degree=approximation_degree, coupling_map=coupling_map, backend_props=backend_properties, method=unitary_synthesis_method, plugin_config=unitary_synthesis_plugin_config, ), Optimize1qGatesDecomposition(basis_gates), CommutativeCancellation(), ] # 9. Unify all durations (either SI, or convert to dt if known) # Schedule the circuit only when scheduling_method is supplied _time_unit_setup = [ContainsInstruction("delay")] _time_unit_conversion = [TimeUnitConversion(instruction_durations)] def _contains_delay(property_set): return property_set["contains_delay"] _scheduling = [] if scheduling_method: _scheduling += _time_unit_conversion if scheduling_method in {"alap", "as_late_as_possible"}: _scheduling += [ALAPSchedule(instruction_durations)] elif scheduling_method in {"asap", "as_soon_as_possible"}: _scheduling += [ASAPSchedule(instruction_durations)] else: raise TranspilerError("Invalid scheduling method %s." % scheduling_method) # 10. Call measure alignment. Should come after scheduling. if ( timing_constraints.granularity != 1 or timing_constraints.min_length != 1 or timing_constraints.acquire_alignment != 1 ): _alignments = [ ValidatePulseGates( granularity=timing_constraints.granularity, min_length=timing_constraints.min_length ), AlignMeasures(alignment=timing_constraints.acquire_alignment), ] else: _alignments = [] # Build pass manager pm3 = PassManager() pm3.append(_unroll3q) pm3.append(_reset + _meas) if coupling_map or initial_layout: pm3.append(_given_layout) pm3.append(_choose_layout_0, condition=_choose_layout_condition) pm3.append(_choose_layout_1, condition=_trivial_not_perfect) pm3.append(_choose_layout_2, condition=_csp_not_found_match) pm3.append(_embed) pm3.append(_swap_check) pm3.append(_swap, condition=_swap_condition) pm3.append(_unroll) if (coupling_map and not coupling_map.is_symmetric) or ( target is not None and target.get_non_global_operation_names(strict_direction=True) ): pm3.append(_direction_check) pm3.append(_direction, condition=_direction_condition) pm3.append(_reset) # For transpiling to a target we need to run GateDirection in the # optimization loop to correct for incorrect directions that might be # inserted by UnitarySynthesis which is direction aware but only via # the coupling map which with a target doesn't give a full picture if target is not None: pm3.append(_depth_check + _opt + _unroll + _direction, do_while=_opt_control) else: pm3.append(_depth_check + _opt + _unroll, do_while=_opt_control) else: pm3.append(_reset) pm3.append(_depth_check + _opt + _unroll, do_while=_opt_control) if inst_map and inst_map.has_custom_gate(): pm3.append(PulseGates(inst_map=inst_map)) if scheduling_method: pm3.append(_scheduling) elif instruction_durations: pm3.append(_time_unit_setup) pm3.append(_time_unit_conversion, condition=_contains_delay) pm3.append(_alignments) return pm3
def multi_pass_manager(pass_manager_config: PassManagerConfig, crosstalk_prop=None) -> PassManager: basis_gates = pass_manager_config.basis_gates coupling_map = pass_manager_config.coupling_map initial_layout = pass_manager_config.initial_layout layout_method = pass_manager_config.layout_method or 'dense' routing_method = pass_manager_config.routing_method or 'stochastic' translation_method = pass_manager_config.translation_method or 'translator' scheduling_method = pass_manager_config.scheduling_method instruction_durations = pass_manager_config.instruction_durations seed_transpiler = pass_manager_config.seed_transpiler backend_properties = pass_manager_config.backend_properties # 1. Unroll to 1q or 2q gates _unroll3q = Unroll3qOrMore() # 2. Layout on good qubits if calibration info available, otherwise on dense links _given_layout = SetLayout(initial_layout) def _choose_layout_condition(property_set): return not property_set['layout'] _choose_layout_1 = CSPLayout(coupling_map, call_limit=10000, time_limit=60) if layout_method == 'trivial': _choose_layout_2 = TrivialLayout(coupling_map) elif layout_method == 'dense': _choose_layout_2 = DenseLayout(coupling_map, backend_properties) elif layout_method == 'noise_adaptive': _choose_layout_2 = NoiseAdaptiveLayout(backend_properties) elif layout_method == 'sabre': _choose_layout_2 = SabreLayout(coupling_map, max_iterations=4, seed=seed_transpiler) elif layout_method == 'xtalk_adaptive': _choose_layout_2 = CrosstalkAdaptiveMultiLayout( backend_properties, crosstalk_prop=crosstalk_prop) # elif layout_method == 'xtalk_sabre': # _choose_layout_2 = CrosstalkSabreLayout(coupling_map, max_iterations=4, seed=seed_transpiler, crosstalk_prop=crosstalk_prop) else: raise TranspilerError("Invalid layout method %s." % layout_method) # 3. Extend dag/layout with ancillas using the full coupling map _embed = [ FullAncillaAllocation(coupling_map), EnlargeWithAncilla(), ApplyLayout() ] # 4. Swap to fit the coupling map _swap_check = CheckMap(coupling_map) def _swap_condition(property_set): return not property_set['is_swap_mapped'] _swap = [BarrierBeforeFinalMeasurements()] if routing_method == 'basic': _swap += [BasicSwap(coupling_map)] elif routing_method == 'stochastic': _swap += [ StochasticSwap(coupling_map, trials=200, seed=seed_transpiler) ] elif routing_method == 'lookahead': _swap += [LookaheadSwap(coupling_map, search_depth=5, search_width=6)] elif routing_method == 'sabre': _swap += [ SabreSwap(coupling_map, heuristic='decay', seed=seed_transpiler) ] else: raise TranspilerError("Invalid routing method %s." % routing_method) # 5. Unroll to the basis if translation_method == 'unroller': _unroll = [Unroller(basis_gates)] elif translation_method == 'translator': from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel _unroll = [ UnrollCustomDefinitions(sel, basis_gates), BasisTranslator(sel, basis_gates) ] elif translation_method == 'synthesis': _unroll = [ Unroll3qOrMore(), Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis(basis_gates), ] else: raise TranspilerError("Invalid translation method %s." % translation_method) # 6. Fix any CX direction mismatch _direction_check = [CheckCXDirection(coupling_map)] def _direction_condition(property_set): return not property_set['is_direction_mapped'] _direction = [CXDirection(coupling_map)] # 8. Optimize iteratively until no more change in depth. Removes useless gates # after reset and before measure, commutes gates and optimizes continguous blocks. _depth_check = [Depth(), FixedPoint('depth')] def _opt_control(property_set): return not property_set['depth_fixed_point'] _reset = [RemoveResetInZeroState()] _meas = [OptimizeSwapBeforeMeasure(), RemoveDiagonalGatesBeforeMeasure()] if basis_gates and ('u1' in basis_gates or 'u2' in basis_gates or 'u3' in basis_gates): _opt = [ Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis(basis_gates), Optimize1qGates(basis_gates), CommutativeCancellation(), ] else: _opt = [ Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis(basis_gates), Optimize1qGatesDecomposition(basis_gates), CommutativeCancellation(), ] # Schedule the circuit only when scheduling_method is supplied if scheduling_method: _scheduling = [TimeUnitAnalysis(instruction_durations)] if scheduling_method in {'alap', 'as_late_as_possible'}: _scheduling += [MultiALAPSchedule(instruction_durations)] elif scheduling_method in {'asap', 'as_soon_as_possible'}: # _scheduling += [ASAPSchedule(instruction_durations)] """FIXME""" raise TranspilerError( "Sorry now this method is not available: %s." % scheduling_method) else: raise TranspilerError("Invalid scheduling method %s." % scheduling_method) # Build pass manager multi_pm = PassManager() multi_pm.append(_unroll3q) multi_pm.append(_reset + _meas) if coupling_map or initial_layout: multi_pm.append(_given_layout) multi_pm.append(_choose_layout_1, condition=_choose_layout_condition) multi_pm.append(_choose_layout_2, condition=_choose_layout_condition) multi_pm.append(_embed) multi_pm.append(_swap_check) multi_pm.append(_swap, condition=_swap_condition) multi_pm.append(_unroll) multi_pm.append(_depth_check + _opt + _unroll, do_while=_opt_control) if coupling_map and not coupling_map.is_symmetric: multi_pm.append(_direction_check) multi_pm.append(_direction, condition=_direction_condition) multi_pm.append(_reset) if scheduling_method: multi_pm.append(_scheduling) return multi_pm