示例#1
0
def _combine_args(shared_transpiler_args, unique_config):
    # Pop optimization_level to exclude it from the kwargs when building a
    # PassManagerConfig
    level = shared_transpiler_args.pop("optimization_level")
    pass_manager_config = shared_transpiler_args
    pass_manager_config.update(unique_config.pop("pass_manager_config"))
    pass_manager_config = PassManagerConfig(**pass_manager_config)
    # restore optimization_level in the input shared dict in case it's used again
    # in the same process
    shared_transpiler_args["optimization_level"] = level

    transpile_config = unique_config
    transpile_config["pass_manager_config"] = pass_manager_config

    if transpile_config["faulty_qubits_map"]:
        pass_manager_config.initial_layout = _remap_layout_faulty_backend(
            pass_manager_config.initial_layout,
            transpile_config["faulty_qubits_map"])

    # we choose an appropriate one based on desired optimization level
    if level == 0:
        pass_manager = level_0_pass_manager(pass_manager_config)
    elif level == 1:
        pass_manager = level_1_pass_manager(pass_manager_config)
    elif level == 2:
        pass_manager = level_2_pass_manager(pass_manager_config)
    elif level == 3:
        pass_manager = level_3_pass_manager(pass_manager_config)
    else:
        raise TranspilerError("optimization_level can range from 0 to 3.")
    return transpile_config, pass_manager
示例#2
0
    def test_custom_multiple_circuits(self):
        """Test transpiling with custom pass manager and multiple circuits.
        This tests created a deadlock, so it needs to be monitored for timeout.
        See: https://github.com/Qiskit/qiskit-terra/issues/3925
        """
        qc = QuantumCircuit(2)
        qc.h(0)
        qc.cx(0, 1)

        pm_conf = PassManagerConfig(initial_layout=None,
                                    basis_gates=['u1', 'u2', 'u3', 'cx'],
                                    coupling_map=CouplingMap([[0, 1]]),
                                    backend_properties=None,
                                    seed_transpiler=1)
        passmanager = level_0_pass_manager(pm_conf)

        transpiled = passmanager.run([qc, qc])

        expected = QuantumCircuit(QuantumRegister(2, 'q'))
        expected.append(U2Gate(0, 3.141592653589793), [0])
        expected.cx(0, 1)

        self.assertEqual(len(transpiled), 2)
        self.assertEqual(transpiled[0], expected)
        self.assertEqual(transpiled[1], expected)
示例#3
0
def _parse_transpile_args(circuits, backend, basis_gates, coupling_map,
                          backend_properties, initial_layout, layout_method,
                          routing_method, seed_transpiler, optimization_level,
                          callback, output_name) -> List[Dict]:
    """Resolve the various types of args allowed to the transpile() function through
    duck typing, overriding args, etc. Refer to the transpile() docstring for details on
    what types of inputs are allowed.

    Here the args are resolved by converting them to standard instances, and prioritizing
    them in case a transpile option is passed through multiple args (explicitly setting an
    arg has more priority than the arg set by backend).

    Returns:
        list[dicts]: a list of transpile parameters.
    """
    if initial_layout is not None and layout_method is not None:
        warnings.warn("initial_layout provided; layout_method is ignored.",
                      UserWarning)
    # Each arg could be single or a list. If list, it must be the same size as
    # number of circuits. If single, duplicate to create a list of that size.
    num_circuits = len(circuits)

    basis_gates = _parse_basis_gates(basis_gates, backend, circuits)
    coupling_map = _parse_coupling_map(coupling_map, backend, num_circuits)
    backend_properties = _parse_backend_properties(backend_properties, backend,
                                                   num_circuits)
    initial_layout = _parse_initial_layout(initial_layout, circuits)
    layout_method = _parse_layout_method(layout_method, num_circuits)
    routing_method = _parse_routing_method(routing_method, num_circuits)
    seed_transpiler = _parse_seed_transpiler(seed_transpiler, num_circuits)
    optimization_level = _parse_optimization_level(optimization_level,
                                                   num_circuits)
    output_name = _parse_output_name(output_name, circuits)
    callback = _parse_callback(callback, num_circuits)

    list_transpile_args = []
    for args in zip(basis_gates, coupling_map, backend_properties,
                    initial_layout, layout_method, routing_method,
                    seed_transpiler, optimization_level, output_name,
                    callback):
        transpile_args = {
            'pass_manager_config':
            PassManagerConfig(basis_gates=args[0],
                              coupling_map=args[1],
                              backend_properties=args[2],
                              initial_layout=args[3],
                              layout_method=args[4],
                              routing_method=args[5],
                              seed_transpiler=args[6]),
            'optimization_level':
            args[7],
            'output_name':
            args[8],
            'callback':
            args[9]
        }
        list_transpile_args.append(transpile_args)

    return list_transpile_args
 def test_config_from_backend_v2(self):
     """Test from_backend() with a BackendV2 instance."""
     backend = FakeAlmadenV2()
     config = PassManagerConfig.from_backend(backend)
     self.assertEqual(config.basis_gates, backend.operation_names)
     self.assertEqual(config.inst_map, backend.instruction_schedule_map)
     self.assertEqual(config.coupling_map.get_edges(),
                      backend.coupling_map.get_edges())
    def test_default_pass_manager_two(self):
        """Test default_pass_manager.run(circuitS).

        circuit1 and circuit2:
        qr0:-[H]--.------------  -> 1
                  |
        qr1:-----(+)--.--------  -> 2
                      |
        qr2:---------(+)--.----  -> 3
                          |
        qr3:-------------(+)---  -> 5

        device:
        0  -  1  -  2  -  3  -  4  -  5  -  6

              |     |     |     |     |     |

              13 -  12  - 11 -  10 -  9  -  8  -   7
        """
        qr = QuantumRegister(4, "qr")
        circuit1 = QuantumCircuit(qr)
        circuit1.h(qr[0])
        circuit1.cx(qr[0], qr[1])
        circuit1.cx(qr[1], qr[2])
        circuit1.cx(qr[2], qr[3])

        circuit2 = QuantumCircuit(qr)
        circuit2.cx(qr[1], qr[2])
        circuit2.cx(qr[0], qr[1])
        circuit2.cx(qr[2], qr[3])

        coupling_map = FakeMelbourne().configuration().coupling_map
        basis_gates = FakeMelbourne().configuration().basis_gates
        initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]]

        pass_manager = level_1_pass_manager(
            PassManagerConfig(
                basis_gates=basis_gates,
                coupling_map=CouplingMap(coupling_map),
                initial_layout=Layout.from_qubit_list(initial_layout),
                seed_transpiler=42,
            ))
        new_circuits = pass_manager.run([circuit1, circuit2])

        for new_circuit in new_circuits:
            bit_indices = {
                bit: idx
                for idx, bit in enumerate(new_circuit.qregs[0])
            }

            for gate, qargs, _ in new_circuit.data:
                if isinstance(gate, CXGate):
                    self.assertIn([bit_indices[x] for x in qargs],
                                  coupling_map)
    def test_config_from_backend(self):
        """Test from_backend() with a valid backend.

        `FakeAlmaden` is used in this testcase. This backend has `defaults` attribute
        that contains an instruction schedule map.
        """
        backend = FakeAlmaden()
        config = PassManagerConfig.from_backend(backend)
        self.assertEqual(config.basis_gates,
                         backend.configuration().basis_gates)
        self.assertEqual(config.inst_map,
                         backend.defaults().instruction_schedule_map)
        self.assertEqual(
            str(config.coupling_map),
            str(CouplingMap(backend.configuration().coupling_map)))
    def test_default_pass_manager_single(self):
        """Test default_pass_manager.run(circuit).

        circuit:
        qr0:-[H]--.------------  -> 1
                  |
        qr1:-----(+)--.--------  -> 2
                      |
        qr2:---------(+)--.----  -> 3
                          |
        qr3:-------------(+)---  -> 5

        device:
        0  -  1  -  2  -  3  -  4  -  5  -  6

              |     |     |     |     |     |

              13 -  12  - 11 -  10 -  9  -  8  -   7
        """
        qr = QuantumRegister(4, 'qr')
        circuit = QuantumCircuit(qr)
        circuit.h(qr[0])
        circuit.cx(qr[0], qr[1])
        circuit.cx(qr[1], qr[2])
        circuit.cx(qr[2], qr[3])

        coupling_map = FakeMelbourne().configuration().coupling_map
        basis_gates = FakeMelbourne().configuration().basis_gates
        initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]]

        pass_manager = level_1_pass_manager(
            PassManagerConfig(
                basis_gates=basis_gates,
                coupling_map=CouplingMap(coupling_map),
                initial_layout=Layout.from_qubit_list(initial_layout),
                seed_transpiler=42))
        new_circuit = pass_manager.run(circuit)

        for gate, qargs, _ in new_circuit.data:
            if isinstance(gate, CXGate):
                self.assertIn([x.index for x in qargs], coupling_map)
    def test_from_backend_and_user(self):
        """Test from_backend() with a backend and user options.

        `FakeMelbourne` is used in this testcase. This backend does not have
        `defaults` attribute and thus not provide an instruction schedule map.
        """
        qr = QuantumRegister(4, "qr")
        initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]]

        backend = FakeMelbourne()
        config = PassManagerConfig.from_backend(backend,
                                                basis_gates=["user_gate"],
                                                initial_layout=initial_layout)
        self.assertEqual(config.basis_gates, ["user_gate"])
        self.assertNotEqual(config.basis_gates,
                            backend.configuration().basis_gates)
        self.assertIsNone(config.inst_map)
        self.assertEqual(
            str(config.coupling_map),
            str(CouplingMap(backend.configuration().coupling_map)))
        self.assertEqual(config.initial_layout, initial_layout)
示例#9
0
def _parse_transpile_args(circuits, backend,
                          basis_gates, coupling_map, backend_properties,
                          initial_layout, layout_method, routing_method, translation_method,
                          scheduling_method, instruction_durations, dt,
                          approximation_degree, seed_transpiler, optimization_level,
                          callback, output_name) -> List[Dict]:
    """Resolve the various types of args allowed to the transpile() function through
    duck typing, overriding args, etc. Refer to the transpile() docstring for details on
    what types of inputs are allowed.

    Here the args are resolved by converting them to standard instances, and prioritizing
    them in case a transpile option is passed through multiple args (explicitly setting an
    arg has more priority than the arg set by backend).

    Returns:
        list[dicts]: a list of transpile parameters.

    Raises:
        TranspilerError: If instruction_durations are required but not supplied or found.
    """
    if initial_layout is not None and layout_method is not None:
        warnings.warn("initial_layout provided; layout_method is ignored.",
                      UserWarning)
    # Each arg could be single or a list. If list, it must be the same size as
    # number of circuits. If single, duplicate to create a list of that size.
    num_circuits = len(circuits)

    basis_gates = _parse_basis_gates(basis_gates, backend, circuits)
    faulty_qubits_map = _parse_faulty_qubits_map(backend, num_circuits)
    coupling_map = _parse_coupling_map(coupling_map, backend, num_circuits)
    backend_properties = _parse_backend_properties(backend_properties, backend, num_circuits)
    backend_num_qubits = _parse_backend_num_qubits(backend, num_circuits)
    initial_layout = _parse_initial_layout(initial_layout, circuits)
    layout_method = _parse_layout_method(layout_method, num_circuits)
    routing_method = _parse_routing_method(routing_method, num_circuits)
    translation_method = _parse_translation_method(translation_method, num_circuits)
    approximation_degree = _parse_approximation_degree(approximation_degree, num_circuits)
    seed_transpiler = _parse_seed_transpiler(seed_transpiler, num_circuits)
    optimization_level = _parse_optimization_level(optimization_level, num_circuits)
    output_name = _parse_output_name(output_name, circuits)
    callback = _parse_callback(callback, num_circuits)
    durations = _parse_instruction_durations(backend, instruction_durations, dt, circuits)
    scheduling_method = _parse_scheduling_method(scheduling_method, circuits)
    if scheduling_method and not durations:
        raise TranspilerError("Transpiling a circuit with a scheduling method or with delay "
                              "instructions requires a backend or instruction_durations.")

    list_transpile_args = []
    for args in zip(basis_gates, coupling_map, backend_properties, initial_layout,
                    layout_method, routing_method, translation_method, scheduling_method,
                    durations, approximation_degree, seed_transpiler, optimization_level,
                    output_name, callback, backend_num_qubits, faulty_qubits_map):
        transpile_args = {'pass_manager_config': PassManagerConfig(basis_gates=args[0],
                                                                   coupling_map=args[1],
                                                                   backend_properties=args[2],
                                                                   initial_layout=args[3],
                                                                   layout_method=args[4],
                                                                   routing_method=args[5],
                                                                   translation_method=args[6],
                                                                   scheduling_method=args[7],
                                                                   instruction_durations=args[8],
                                                                   approximation_degree=args[9],
                                                                   seed_transpiler=args[10]),
                          'optimization_level': args[11],
                          'output_name': args[12],
                          'callback': args[13],
                          'backend_num_qubits': args[14],
                          'faulty_qubits_map': args[15]}
        list_transpile_args.append(transpile_args)

    return list_transpile_args
示例#10
0
def _parse_transpile_args(
    circuits,
    backend,
    basis_gates,
    inst_map,
    coupling_map,
    backend_properties,
    initial_layout,
    layout_method,
    routing_method,
    translation_method,
    scheduling_method,
    instruction_durations,
    dt,
    approximation_degree,
    seed_transpiler,
    optimization_level,
    callback,
    output_name,
    timing_constraints,
    unitary_synthesis_method,
    unitary_synthesis_plugin_config,
    target,
) -> List[Dict]:
    """Resolve the various types of args allowed to the transpile() function through
    duck typing, overriding args, etc. Refer to the transpile() docstring for details on
    what types of inputs are allowed.

    Here the args are resolved by converting them to standard instances, and prioritizing
    them in case a transpile option is passed through multiple args (explicitly setting an
    arg has more priority than the arg set by backend).

    Returns:
        list[dicts]: a list of transpile parameters.

    Raises:
        TranspilerError: If instruction_durations are required but not supplied or found.
    """
    if initial_layout is not None and layout_method is not None:
        warnings.warn("initial_layout provided; layout_method is ignored.",
                      UserWarning)
    # Each arg could be single or a list. If list, it must be the same size as
    # number of circuits. If single, duplicate to create a list of that size.
    num_circuits = len(circuits)

    # If a target is specified have it override any implicit selections from a backend
    # but if an argument is explicitly passed use that instead of the target version
    if target is not None:
        if coupling_map is None:
            coupling_map = target.build_coupling_map()
        if basis_gates is None:
            basis_gates = target.operation_names
        if instruction_durations is None:
            instruction_durations = target.durations()
        if inst_map is None:
            inst_map = target.instruction_schedule_map()
        if dt is None:
            dt = target.dt
        if timing_constraints is None:
            timing_constraints = target.timing_constraints()
        if backend_properties is None:
            backend_properties = _target_to_backend_properties(target)

    basis_gates = _parse_basis_gates(basis_gates, backend, circuits)
    inst_map = _parse_inst_map(inst_map, backend, num_circuits)
    faulty_qubits_map = _parse_faulty_qubits_map(backend, num_circuits)
    coupling_map = _parse_coupling_map(coupling_map, backend, num_circuits)
    backend_properties = _parse_backend_properties(backend_properties, backend,
                                                   num_circuits)
    backend_num_qubits = _parse_backend_num_qubits(backend, num_circuits)
    initial_layout = _parse_initial_layout(initial_layout, circuits)
    layout_method = _parse_layout_method(layout_method, num_circuits)
    routing_method = _parse_routing_method(routing_method, num_circuits)
    translation_method = _parse_translation_method(translation_method,
                                                   num_circuits)
    approximation_degree = _parse_approximation_degree(approximation_degree,
                                                       num_circuits)
    unitary_synthesis_method = _parse_unitary_synthesis_method(
        unitary_synthesis_method, num_circuits)
    unitary_synthesis_plugin_config = _parse_unitary_plugin_config(
        unitary_synthesis_plugin_config, num_circuits)
    seed_transpiler = _parse_seed_transpiler(seed_transpiler, num_circuits)
    optimization_level = _parse_optimization_level(optimization_level,
                                                   num_circuits)
    output_name = _parse_output_name(output_name, circuits)
    callback = _parse_callback(callback, num_circuits)
    durations = _parse_instruction_durations(backend, instruction_durations,
                                             dt, circuits)
    scheduling_method = _parse_scheduling_method(scheduling_method,
                                                 num_circuits)
    timing_constraints = _parse_timing_constraints(backend, timing_constraints,
                                                   num_circuits)
    target = _parse_target(backend, target, num_circuits)
    if scheduling_method and any(d is None for d in durations):
        raise TranspilerError("Transpiling a circuit with a scheduling method"
                              "requires a backend or instruction_durations.")

    list_transpile_args = []
    for kwargs in _zip_dict({
            "basis_gates": basis_gates,
            "inst_map": inst_map,
            "coupling_map": coupling_map,
            "backend_properties": backend_properties,
            "initial_layout": initial_layout,
            "layout_method": layout_method,
            "routing_method": routing_method,
            "translation_method": translation_method,
            "scheduling_method": scheduling_method,
            "durations": durations,
            "approximation_degree": approximation_degree,
            "timing_constraints": timing_constraints,
            "seed_transpiler": seed_transpiler,
            "optimization_level": optimization_level,
            "output_name": output_name,
            "callback": callback,
            "backend_num_qubits": backend_num_qubits,
            "faulty_qubits_map": faulty_qubits_map,
            "unitary_synthesis_method": unitary_synthesis_method,
            "unitary_synthesis_plugin_config": unitary_synthesis_plugin_config,
            "target": target,
    }):
        transpile_args = {
            "pass_manager_config":
            PassManagerConfig(
                basis_gates=kwargs["basis_gates"],
                inst_map=kwargs["inst_map"],
                coupling_map=kwargs["coupling_map"],
                backend_properties=kwargs["backend_properties"],
                initial_layout=kwargs["initial_layout"],
                layout_method=kwargs["layout_method"],
                routing_method=kwargs["routing_method"],
                translation_method=kwargs["translation_method"],
                scheduling_method=kwargs["scheduling_method"],
                instruction_durations=kwargs["durations"],
                approximation_degree=kwargs["approximation_degree"],
                timing_constraints=kwargs["timing_constraints"],
                seed_transpiler=kwargs["seed_transpiler"],
                unitary_synthesis_method=kwargs["unitary_synthesis_method"],
                unitary_synthesis_plugin_config=kwargs[
                    "unitary_synthesis_plugin_config"],
                target=kwargs["target"],
            ),
            "optimization_level":
            kwargs["optimization_level"],
            "output_name":
            kwargs["output_name"],
            "callback":
            kwargs["callback"],
            "backend_num_qubits":
            kwargs["backend_num_qubits"],
            "faulty_qubits_map":
            kwargs["faulty_qubits_map"],
        }
        list_transpile_args.append(transpile_args)

    return list_transpile_args
    def test_str(self):
        """Test string output."""
        pm_config = PassManagerConfig.from_backend(FakeArmonk())
        # For testing remove instruction schedule map it's str output is non-deterministic
        # based on hash seed
        pm_config.inst_map = None
        str_out = str(pm_config)
        expected = """Pass Manager Config:
	initial_layout: None
	basis_gates: ['id', 'rz', 'sx', 'x']
	inst_map: None
	coupling_map: 
	layout_method: None
	routing_method: None
	translation_method: None
	scheduling_method: None
	instruction_durations: id(0,): 7.111111111111111e-08 s
	rz(0,): 0.0 s
	sx(0,): 7.111111111111111e-08 s
	x(0,): 7.111111111111111e-08 s
	measure(0,): 4.977777777777777e-06 s
	
	backend_properties: {'backend_name': 'ibmq_armonk',
	 'backend_version': '2.4.3',
	 'gates': [{'gate': 'id',
	            'name': 'id0',
	            'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)),
	                            'name': 'gate_error',
	                            'unit': '',
	                            'value': 0.00019769550670970334},
	                           {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
	                            'name': 'gate_length',
	                            'unit': 'ns',
	                            'value': 71.11111111111111}],
	            'qubits': [0]},
	           {'gate': 'rz',
	            'name': 'rz0',
	            'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
	                            'name': 'gate_error',
	                            'unit': '',
	                            'value': 0},
	                           {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
	                            'name': 'gate_length',
	                            'unit': 'ns',
	                            'value': 0}],
	            'qubits': [0]},
	           {'gate': 'sx',
	            'name': 'sx0',
	            'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)),
	                            'name': 'gate_error',
	                            'unit': '',
	                            'value': 0.00019769550670970334},
	                           {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
	                            'name': 'gate_length',
	                            'unit': 'ns',
	                            'value': 71.11111111111111}],
	            'qubits': [0]},
	           {'gate': 'x',
	            'name': 'x0',
	            'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)),
	                            'name': 'gate_error',
	                            'unit': '',
	                            'value': 0.00019769550670970334},
	                           {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
	                            'name': 'gate_length',
	                            'unit': 'ns',
	                            'value': 71.11111111111111}],
	            'qubits': [0]}],
	 'general': [],
	 'last_update_date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
	 'qubits': [[{'date': datetime.datetime(2021, 3, 15, 0, 36, 17, tzinfo=tzoffset(None, -14400)),
	              'name': 'T1',
	              'unit': 'us',
	              'value': 182.6611165336624},
	             {'date': datetime.datetime(2021, 3, 14, 0, 33, 45, tzinfo=tzoffset(None, -18000)),
	              'name': 'T2',
	              'unit': 'us',
	              'value': 237.8589220110257},
	             {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
	              'name': 'frequency',
	              'unit': 'GHz',
	              'value': 4.971852852405576},
	             {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
	              'name': 'anharmonicity',
	              'unit': 'GHz',
	              'value': -0.34719293148282626},
	             {'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)),
	              'name': 'readout_error',
	              'unit': '',
	              'value': 0.02400000000000002},
	             {'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)),
	              'name': 'prob_meas0_prep1',
	              'unit': '',
	              'value': 0.0234},
	             {'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)),
	              'name': 'prob_meas1_prep0',
	              'unit': '',
	              'value': 0.024599999999999955},
	             {'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)),
	              'name': 'readout_length',
	              'unit': 'ns',
	              'value': 4977.777777777777}]]}
	approximation_degree: None
	seed_transpiler: None
	timing_constraints: None
	unitary_synthesis_method: default
	unitary_synthesis_plugin_config: None
	target: None
"""
        self.assertEqual(str_out, expected)
 def test_invalid_user_option(self):
     """Test from_backend() with an invalid user option."""
     with self.assertRaises(TypeError):
         PassManagerConfig.from_backend(FakeMelbourne(),
                                        invalid_option=None)
 def test_invalid_backend(self):
     """Test from_backend() with an invalid backend."""
     with self.assertRaises(AttributeError):
         PassManagerConfig.from_backend(Backend())
示例#14
0
def generate_preset_pass_manager(
    optimization_level,
    backend=None,
    target=None,
    basis_gates=None,
    inst_map=None,
    coupling_map=None,
    instruction_durations=None,
    backend_properties=None,
    timing_constraints=None,
    initial_layout=None,
    layout_method=None,
    routing_method=None,
    translation_method=None,
    scheduling_method=None,
    approximation_degree=None,
    seed_transpiler=None,
    unitary_synthesis_method="default",
    unitary_synthesis_plugin_config=None,
):
    """Generate a preset :class:`~.PassManager`

    This function is used to quickly generate a preset pass manager. A preset pass
    manager are the default pass managers used by the :func:`~.transpile`
    function. This function provides a convenient and simple method to construct
    a standalone :class:`~.PassManager` object that mirrors what the transpile


    Args:
        optimization_level (int): The optimization level to generate a
            :class:`~.PassManager` for. This can be 0, 1, 2, or 3. Higher
            levels generate more optimized circuits, at the expense of
            longer transpilation time:

                * 0: no optimization
                * 1: light optimization
                * 2: heavy optimization
                * 3: even heavier optimization

        backend (Backend): An optional backend object which can be used as the
            source of the default values for the ``basis_gates``, ``inst_map``,
            ``couplig_map``, ``backend_properties``, ``instruction_durations``,
            ``timing_constraints``, and ``target``. If any of those other arguments
            are specified in addition to ``backend`` they will take precedence
            over the value contained in the backend.
        target (Target): The :class:`~.Target` representing a backend compilation
            target. The following attributes will be inferred from this
            argument if they are not set: ``coupling_map``, ``basis_gates``,
            ``instruction_durations``, ``inst_map``, ``timing_constraints``
            and ``backend_properties``.
        basis_gates (list): List of basis gate names to unroll to
            (e.g: ``['u1', 'u2', 'u3', 'cx']``).
        inst_map (InstructionScheduleMap): Mapping object that maps gate to schedules.
            If any user defined calibration is found in the map and this is used in a
            circuit, transpiler attaches the custom gate definition to the circuit.
            This enables one to flexibly override the low-level instruction
            implementation.
        coupling_map (CouplingMap): Directed graph represented a coupling
            map.
        instruction_durations (InstructionDurations): Dictionary of duration
            (in dt) for each instruction.
        timing_constraints (TimingConstraints): Hardware time alignment restrictions.
        initial_layout (Layout): Initial position of virtual qubits on
            physical qubits.
        layout_method (str): The :class:`~.Pass` to use for choosing initial qubit
            placement. Valid choices are ``'trivial'``, ``'dense'``, ``'noise_adaptive'``,
            and, ``'sabre'`` repsenting :class:`~.TrivialLayout`, :class:`~DenseLayout`,
            :class:`~.NoiseAdaptiveLayout`, :class:`~.SabreLayout` respectively.
        routing_method (str): The pass to use for routing qubits on the
            architecture. Valid choices are ``'basic'``, ``'lookahead'``, ``'stochastic'``,
            ``'sabre'``, and ``'none'`` representing :class:`~.BasicSwap`,
            :class:`~.LookaheadSwap`, :class:`~.StochasticSwap`, :class:`~.SabreSwap`, and
            erroring if routing is required respectively.
        translation_method (str): The method to use for translating gates to
            basis gates. Valid choices ``'unroller'``, ``'translator'``, ``'synthesis'``
            representing :class:`~.Unroller`, :class:`~.BasisTranslator`, and
            :class:`~.UnitarySynthesis` respectively.
        scheduling_method (str): The pass to use for scheduling instructions. Valid choices
            are ``'alap'`` and ``'asap'``.
        backend_properties (BackendProperties): Properties returned by a
            backend, including information on gate errors, readout errors,
            qubit coherence times, etc.
        approximation_degree (float): Heuristic dial used for circuit approximation
            (1.0=no approximation, 0.0=maximal approximation).
        seed_transpiler (int): Sets random seed for the stochastic parts of
            the transpiler.
        unitary_synthesis_method (str): The name of the unitary synthesis
            method to use. By default 'default' is used, which is the only
            method included with qiskit. If you have installed any unitary
            synthesis plugins you can use the name exported by the plugin.
        unitary_synthesis_plugin_config (dict): An optional configuration dictionary
            that will be passed directly to the unitary synthesis plugin. By
            default this setting will have no effect as the default unitary
            synthesis method does not take custom configuration. This should
            only be necessary when a unitary synthesis plugin is specified with
            the ``unitary_synthesis`` argument. As this is custom for each
            unitary synthesis plugin refer to the plugin documentation for how
            to use this option.

    Returns:
        StagedPassManager: The preset pass manager for the given options

    Raises:
        ValueError: if an invalid value for ``optimization_level`` is passed in.
    """
    if target is not None:
        if coupling_map is None:
            coupling_map = target.build_coupling_map()
        if basis_gates is None:
            basis_gates = target.operation_names
        if instruction_durations is None:
            instruction_durations = target.durations()
        if inst_map is None:
            inst_map = target.instruction_schedule_map()
        if timing_constraints is None:
            timing_constraints = target.timing_constraints()
        if backend_properties is None:
            backend_properties = target_to_backend_properties(target)

    pm_options = dict(
        target=target,
        basis_gates=basis_gates,
        inst_map=inst_map,
        coupling_map=coupling_map,
        instruction_durations=instruction_durations,
        backend_properties=backend_properties,
        timing_constraints=timing_constraints,
        layout_method=layout_method,
        routing_method=routing_method,
        translation_method=translation_method,
        scheduling_method=scheduling_method,
        approximation_degree=approximation_degree,
        seed_transpiler=seed_transpiler,
        unitary_synthesis_method=unitary_synthesis_method,
        unitary_synthesis_plugin_config=unitary_synthesis_plugin_config,
        initial_layout=initial_layout,
    )

    if backend is not None:
        pm_config = PassManagerConfig.from_backend(backend, **pm_options)
    else:
        pm_config = PassManagerConfig(**pm_options)

    if optimization_level == 0:
        pm = level_0_pass_manager(pm_config)
    elif optimization_level == 1:
        pm = level_1_pass_manager(pm_config)
    elif optimization_level == 2:
        pm = level_2_pass_manager(pm_config)
    elif optimization_level == 3:
        pm = level_3_pass_manager(pm_config)
    else:
        raise ValueError(f"Invalid optimization level {optimization_level}")
    return pm
示例#15
0
def _parse_transpile_args(
    circuits,
    backend,
    basis_gates,
    coupling_map,
    backend_properties,
    initial_layout,
    layout_method,
    routing_method,
    translation_method,
    seed_transpiler,
    optimization_level,
    callback,
    output_name,
    multi_opt,
    crosstalk_prop,
) -> List[Dict]:
    """Resolve the various types of args allowed to the transpile() function through
    duck typing, overriding args, etc. Refer to the transpile() docstring for details on
    what types of inputs are allowed.

    Here the args are resolved by converting them to standard instances, and prioritizing
    them in case a transpile option is passed through multiple args (explicitly setting an
    arg has more priority than the arg set by backend).

    Returns:
        list[dicts]: a list of transpile parameters.
    """
    if initial_layout is not None and layout_method is not None:
        warnings.warn("initial_layout provided; layout_method is ignored.",
                      UserWarning)
    # Each arg could be single or a list. If list, it must be the same size as
    # number of circuits. If single, duplicate to create a list of that size.
    num_circuits = len(circuits)

    basis_gates = _parse_basis_gates(basis_gates, backend, num_circuits)
    """FIXME
    _parse_faulty_qubits_mapの周りの実装
    """
    faulty_qubits_map = [None] * num_circuits

    coupling_map = _parse_coupling_map(coupling_map, backend, num_circuits)
    backend_properties = _parse_backend_properties(backend_properties, backend,
                                                   num_circuits)
    backend_num_qubits = _parse_backend_num_qubits(backend, num_circuits)
    """FIXME
    _parse_initial_layoutの引数に、combine後のcircuitを入れたい
    現状、num_circuitsにしているため、initial_layoutは実際には指定しても、作用しない
    """
    initial_layout = _parse_initial_layout(initial_layout, num_circuits)

    layout_method = _parse_layout_method(layout_method, num_circuits)
    routing_method = _parse_routing_method(routing_method, num_circuits)
    translation_method = _parse_translation_method(translation_method,
                                                   num_circuits)
    seed_transpiler = _parse_seed_transpiler(seed_transpiler, num_circuits)
    optimization_level = _parse_optimization_level(optimization_level,
                                                   num_circuits)
    output_name = _parse_output_name(output_name, num_circuits)
    callback = _parse_callback(callback, num_circuits)
    multi_opt = _parse_multi_opt(multi_opt, num_circuits)
    crosstalk_prop = _parse_crosstalk_prop(crosstalk_prop, num_circuits)

    list_transpile_args = []
    for args in zip(
            basis_gates,
            coupling_map,
            backend_properties,
            initial_layout,
            layout_method,
            routing_method,
            translation_method,
            seed_transpiler,
            optimization_level,
            output_name,
            callback,
            backend_num_qubits,
            faulty_qubits_map,
            multi_opt,
            crosstalk_prop,
    ):
        transpile_args = {
            "pass_manager_config":
            PassManagerConfig(
                basis_gates=args[0],
                coupling_map=args[1],
                backend_properties=args[2],
                initial_layout=args[3],
                layout_method=args[4],
                routing_method=args[5],
                translation_method=args[6],
                seed_transpiler=args[7],
            ),
            "optimization_level":
            args[8],
            "output_name":
            args[9],
            "callback":
            args[10],
            "backend_num_qubits":
            args[11],
            "faulty_qubits_map":
            args[12],
            "multi_opt":
            args[13],
            "crosstalk_prop":
            args[14],
        }
        list_transpile_args.append(transpile_args)

    return list_transpile_args
示例#16
0
def multi_transpile(circuits: Union[List[QuantumCircuit], List[List[QuantumCircuit]]],
                    backend: Optional[Union[Backend, BaseBackend]] = None,
                    basis_gates: Optional[List[str]] = None,
                    coupling_map: Optional[Union[CouplingMap, List[List[int]]]] = None,
                    backend_properties: Optional[BackendProperties] = None,
                    initial_layout: Optional[Union[Layout, Dict, List]] = None,
                    layout_method: Optional[str] = None,
                    routing_method: Optional[str] = None,
                    translation_method: Optional[str] = None,
                    scheduling_method: Optional[str] = None,
                    instruction_durations: Optional[InstructionDurationsType] = None,
                    dt: Optional[float] = None,
                    seed_transpiler: Optional[int] = None,
                    optimization_level: Optional[int] = None,
                    pass_manager: Optional[PassManager] = None,
                    callback: Optional[Callable[[BasePass, DAGCircuit, float,
                                                PropertySet, int], Any]] = None,
                    output_name: Optional[Union[str, List[str]]] = None, 
                    xtalk_prop: Optional[Dict[Tuple[int], Dict[Tuple[int], int]]] = None):
    """Mapping several circuits to single circuit based on calibration for the backend

    Args:
        circuits: Small circuits to compose one big circuit(s)
        backend:
        backend_properties:
        output_name: the name of output circuit. str or List[str]

    Returns:
        composed multitasking circuit(s)..
    """
    circuits = circuits if isinstance(circuits[0], list) else [circuits]
    output_name_list = output_name if isinstance(output_name, list) else [output_name] * len(circuits)


    # combine circuits in parallel
    multi_circuits = list(map(_compose_multicircuits, circuits, output_name_list))


    backend_properties = _backend_properties(backend_properties, backend)
    coupling_map = _coupling_map(coupling_map, backend)

    pass_manager_config = PassManagerConfig(basis_gates=basis_gates,
                                            coupling_map=coupling_map,
                                            backend_properties=backend_properties,
                                            initial_layout= Layout(),
                                            layout_method=layout_method,
                                            routing_method=routing_method,
                                            translation_method=translation_method,
                                            scheduling_method=scheduling_method,
                                            instruction_durations=instruction_durations,
                                            seed_transpiler=seed_transpiler)
    # define pass manager
    if pass_manager:
        pass

    elif optimization_level and not pass_manager:
        logger.info("############## qiskit transpile optimization level "+str(optimization_level)+" ##############")
    elif layout_method == 'xtalk_adaptive':
        pass_manager = multi_pass_manager(pass_manager_config, xtalk_prop)
        # layout_method=None
        logger.info("############## xtalk-adaptive multi transpile ##############")
        transpiled_multi_circuits = list(map(pass_manager.run, multi_circuits))
        if len(transpiled_multi_circuits) == 1: 
            return transpiled_multi_circuits[0]
        return transpiled_multi_circuits
    else:
        pass_manager = multi_pass_manager(pass_manager_config)
        logger.info("############## multi transpile ##############")
        
        transpiled_multi_circuits = list(map(pass_manager.run, multi_circuits))
        if len(transpiled_multi_circuits) == 1: 
            return transpiled_multi_circuits[0]
        return transpiled_multi_circuits

    # transpile multi_circuit(s)
    transpied_circuit = transpile(
                            circuits=multi_circuits, backend=backend, basis_gates=basis_gates, coupling_map=coupling_map, 
                            backend_properties=backend_properties, initial_layout=initial_layout, 
                            layout_method=layout_method, routing_method=routing_method, translation_method=translation_method, 
                            scheduling_method=scheduling_method, instruction_durations=instruction_durations, dt=dt, 
                            seed_transpiler=seed_transpiler, optimization_level=optimization_level, 
                            pass_manager=pass_manager, callback=callback, output_name=output_name)
    if isinstance(transpied_circuit, list) and len(transpied_circuit)==1: 
        return transpied_circuit[0]
    return transpied_circuit