예제 #1
0
    def test_pass_manager_drawer_style(self):
        """Test to see if the colours are updated when provided by the user"""
        # set colours for some passes, but leave others to take the default values
        style = {SetLayout: 'cyan',
                 CheckMap: 'green',
                 EnlargeWithAncilla: 'pink',
                 RemoveResetInZeroState: 'grey'}

        filename = self._get_resource_path('current_l1.dot')
        level_1_pass_manager(self.config).draw(filename=filename, style=style, raw=True)

        self.assertFilesAreEqual(filename,
                                 path_to_diagram_reference('pass_manager_style_l1.dot'))
        os.remove(filename)
예제 #2
0
def _transpile_circuit(circuit_config_tuple):
    """Select a PassManager and run a single circuit through it.
    Args:
        circuit_config_tuple (tuple):
            circuit (QuantumCircuit): circuit to transpile
            transpile_config (dict): configuration dictating how to transpile. The
                dictionary has the following format:
                {'optimization_level': int,
                 'pass_manager': PassManager,
                 'output_name': string,
                 'callback': callable,
                 'pass_manager_config': PassManagerConfig}
    Returns:
        QuantumCircuit: transpiled circuit
    Raises:
        TranspilerError: if transpile_config is not valid or transpilation incurs error
    """
    circuit, transpile_config = circuit_config_tuple

    pass_manager_config = transpile_config['pass_manager_config']

    # Workaround for ion trap support: If basis gates includes
    # Mølmer-Sørensen (rxx) and the circuit includes gates outside the basis,
    # first unroll to u3, cx, then run MSBasisDecomposer to target basis.
    basic_insts = ['measure', 'reset', 'barrier', 'snapshot']
    device_insts = set(pass_manager_config.basis_gates).union(basic_insts)
    ms_basis_swap = None
    if 'rxx' in pass_manager_config.basis_gates and \
            not device_insts >= circuit.count_ops().keys():
        ms_basis_swap = pass_manager_config.basis_gates
        pass_manager_config.basis_gates = list(
            set(['u3', 'cx']).union(pass_manager_config.basis_gates))

    if transpile_config['pass_manager'] is not None:
        # either the pass manager is already selected...
        pass_manager = transpile_config['pass_manager']
    else:
        # or we choose an appropriate one based on desired optimization level (default: level 1)
        if transpile_config['optimization_level'] is not None:
            level = transpile_config['optimization_level']
        else:
            level = 1

        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.")

    if ms_basis_swap is not None:
        pass_manager.append(MSBasisDecomposer(ms_basis_swap))

    return pass_manager.run(circuit,
                            callback=transpile_config['callback'],
                            output_name=transpile_config['output_name'])
예제 #3
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
예제 #4
0
def transpile_circuit(circuit, transpile_config):
    """Select a PassManager and run a single circuit through it.

    Args:
        circuit (QuantumCircuit): circuit to transpile
        transpile_config (TranspileConfig): configuration dictating how to transpile

    Returns:
        QuantumCircuit: transpiled circuit

    Raises:
        TranspilerError: if transpile_config is not valid or transpilation incurs error
    """

    # either the pass manager is already selected...
    if transpile_config.pass_manager is not None:
        pass_manager = transpile_config.pass_manager

    # or we choose an appropriate one based on desired optimization level (default: level 1)
    else:
        # Workaround for ion trap support: If basis gates includes
        # Mølmer-Sørensen (rxx) and the circuit includes gates outside the basis,
        # first unroll to u3, cx, then run MSBasisDecomposer to target basis.
        basic_insts = ['measure', 'reset', 'barrier', 'snapshot']
        device_insts = set(transpile_config.basis_gates).union(basic_insts)

        ms_basis_swap = None
        if 'rxx' in transpile_config.basis_gates and \
                not device_insts >= circuit.count_ops().keys():
            ms_basis_swap = transpile_config.basis_gates
            transpile_config.basis_gates = list(
                set(['u3', 'cx']).union(transpile_config.basis_gates))

        level = transpile_config.optimization_level
        if level is None:
            level = 1

        if level == 0:
            pass_manager = level_0_pass_manager(transpile_config)
        elif level == 1:
            pass_manager = level_1_pass_manager(transpile_config)
        elif level == 2:
            pass_manager = level_2_pass_manager(transpile_config)
        elif level == 3:
            pass_manager = level_3_pass_manager(transpile_config)
        else:
            raise TranspilerError("optimization_level can range from 0 to 3.")

        if ms_basis_swap is not None:
            pass_manager.append(MSBasisDecomposer(ms_basis_swap))

    # Set a callback on the pass manager there is one
    if getattr(transpile_config, 'callback', None):
        pass_manager.callback = transpile_config.callback

    out_circuit = pass_manager.run(circuit)
    out_circuit.name = transpile_config.output_name

    return out_circuit
예제 #5
0
def _transpile_circuit(
        circuit_config_tuple: Tuple[QuantumCircuit, Dict]) -> QuantumCircuit:
    """Select a PassManager and run a single circuit through it.
    Args:
        circuit_config_tuple (tuple):
            circuit (QuantumCircuit): circuit to transpile
            transpile_config (dict): configuration dictating how to transpile. The
                dictionary has the following format:
                {'optimization_level': int,
                 'output_name': string,
                 'callback': callable,
                 'pass_manager_config': PassManagerConfig}
    Returns:
        The transpiled circuit
    Raises:
        TranspilerError: if transpile_config is not valid or transpilation incurs error
    """
    circuit, transpile_config = circuit_config_tuple

    pass_manager_config = transpile_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
    level = transpile_config['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.")

    if pass_manager_config.scheduling_method is not None:
        if pass_manager_config.basis_gates:
            if 'delay' not in pass_manager_config.basis_gates:
                pass_manager_config.basis_gates.append('delay')
        else:
            pass_manager_config.basis_gates = ['delay']

    result = pass_manager.run(circuit,
                              callback=transpile_config['callback'],
                              output_name=transpile_config['output_name'])

    if transpile_config['faulty_qubits_map']:
        return _remap_circuit_faulty_backend(
            result, transpile_config['backend_num_qubits'],
            pass_manager_config.backend_properties,
            transpile_config['faulty_qubits_map'])

    return result
    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)
예제 #7
0
def transpile_circuit(circuit, transpile_config):
    """Select a PassManager and run a single circuit through it.

    Args:
        circuit (QuantumCircuit): circuit to transpile
        transpile_config (TranspileConfig): configuration dictating how to transpile

    Returns:
        QuantumCircuit: transpiled circuit

    Raises:
        TranspilerError: if transpile_config is not valid or transpilation incurs error
    """
    # if the pass manager is not already selected, choose an appropriate one.
    if transpile_config.pass_manager:
        pass_manager = transpile_config.pass_manager

    elif transpile_config.optimization_level is not None:
        level = transpile_config.optimization_level
        if level == 0:
            pass_manager = level_0_pass_manager(transpile_config)
        elif level == 1:
            pass_manager = level_1_pass_manager(transpile_config)
        elif level == 2:
            pass_manager = level_2_pass_manager(transpile_config)
        elif level == 3:
            pass_manager = level_3_pass_manager(transpile_config)
        else:
            raise TranspilerError("optimization_level can range from 0 to 3.")

    # legacy behavior
    elif transpile_config.coupling_map:
        pass_manager = level_1_pass_manager(transpile_config)
    else:
        pass_manager = default_pass_manager_simulator(transpile_config)

    # Set a callback on the pass manager if it's set
    if getattr(transpile_config, 'callback', None):
        pass_manager.callback = transpile_config.callback

    return pass_manager.run(circuit)
    def test_custom_pass_manager(self, backend):
        """Test quantum kernel with a custom pass manager."""

        quantum_instance = QuantumInstance(
            backend,
            shots=100,
            seed_simulator=algorithm_globals.random_seed,
            seed_transpiler=algorithm_globals.random_seed,
            pass_manager=level_1_pass_manager(
                PassManagerConfig(basis_gates=["u3", "cx"])),
            bound_pass_manager=level_1_pass_manager(
                PassManagerConfig(basis_gates=["u3", "cx"])),
        )

        kernel = QuantumKernel(feature_map=self.feature_map,
                               quantum_instance=quantum_instance)

        svc = SVC(kernel=kernel.evaluate)
        svc.fit(self.sample_train, self.label_train)
        score = svc.score(self.sample_test, self.label_test)

        self.assertEqual(score, 0.5)
예제 #9
0
    def test_2step_transpile(self):
        """Test the two-step transpiler pass."""
        # count how often the pass for parameterized circuits is called
        pre_counter = LogPass("pre_passmanager")
        pre_pass = PassManager(pre_counter)
        config = PassManagerConfig(basis_gates=["u3", "cx"])
        pre_pass += level_1_pass_manager(config)

        # ... and the pass for bound circuits
        bound_counter = LogPass("bound_pass_manager")
        bound_pass = PassManager(bound_counter)

        quantum_instance = QuantumInstance(
            backend=BasicAer.get_backend("statevector_simulator"),
            basis_gates=["u3", "cx"],
            pass_manager=pre_pass,
            bound_pass_manager=bound_pass,
        )

        optimizer = SPSA(maxiter=5, learning_rate=0.01, perturbation=0.01)

        vqe = VQE(optimizer=optimizer, quantum_instance=quantum_instance)
        _ = vqe.compute_minimum_eigenvalue(Z)

        with self.assertLogs(logger, level="INFO") as cm:
            _ = vqe.compute_minimum_eigenvalue(Z)

        expected = [
            "pre_passmanager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "pre_passmanager",
            "bound_pass_manager",
        ]
        self.assertEqual([record.message for record in cm.records], expected)
예제 #10
0
    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(
            TranspileConfig(
                basis_gates=basis_gates,
                coupling_map=CouplingMap(coupling_map),
                initial_layout=Layout.from_qubit_list(initial_layout),
                seed_transpiler=42,
                optimization_level=1))
        new_circuit = pass_manager.run(circuit)

        for gate, qargs, _ in new_circuit.data:
            if isinstance(gate, CnotGate):
                self.assertIn([x.index for x in qargs], coupling_map)
예제 #11
0
def transpile_circuit(circuit, transpile_config):
    """Select a PassManager and run a single circuit through it.

    Args:
        circuit (QuantumCircuit): circuit to transpile
        transpile_config (TranspileConfig): configuration dictating how to transpile

    Returns:
        QuantumCircuit: transpiled circuit

    Raises:
        TranspilerError: if transpile_config is not valid or transpilation incurs error
    """
    # either the pass manager is already selected...
    if transpile_config.pass_manager:
        pass_manager = transpile_config.pass_manager

    # or we choose an appropriate one based on desired optimization level (default: level 1)
    else:
        level = transpile_config.optimization_level
        if level is None:
            level = 1

        if level == 0:
            pass_manager = level_0_pass_manager(transpile_config)
        elif level == 1:
            pass_manager = level_1_pass_manager(transpile_config)
        elif level == 2:
            pass_manager = level_2_pass_manager(transpile_config)
        elif level == 3:
            pass_manager = level_3_pass_manager(transpile_config)
        else:
            raise TranspilerError("optimization_level can range from 0 to 3.")

    # Set a callback on the pass manager there is one
    if getattr(transpile_config, 'callback', None):
        pass_manager.callback = transpile_config.callback

    out_circuit = pass_manager.run(circuit)
    out_circuit.name = transpile_config.output_name

    return out_circuit
예제 #12
0
def _transpile_circuit(
        circuit_config_tuple: Tuple[QuantumCircuit, Dict]) -> QuantumCircuit:
    """Select a PassManager and run a single circuit through it.
    Args:
        circuit_config_tuple (tuple):
            circuit (QuantumCircuit): circuit to transpile
            transpile_config (dict): configuration dictating how to transpile. The
                dictionary has the following format:
                {'optimization_level': int,
                 'output_name': string,
                 'callback': callable,
                 'pass_manager_config': PassManagerConfig}
    Returns:
        The transpiled circuit
    Raises:
        TranspilerError: if transpile_config is not valid or transpilation incurs error
    """
    circuit, transpile_config = circuit_config_tuple

    pass_manager_config = transpile_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'])

    ms_basis_swap = None
    if (pass_manager_config.translation_method == 'unroller'
            and pass_manager_config.basis_gates is not None):
        # Workaround for ion trap support: If basis gates includes
        # Mølmer-Sørensen (rxx) and the circuit includes gates outside the basis,
        # first unroll to u3, cx, then run MSBasisDecomposer to target basis.
        basic_insts = ['measure', 'reset', 'barrier', 'snapshot']
        device_insts = set(pass_manager_config.basis_gates).union(basic_insts)
        if 'rxx' in pass_manager_config.basis_gates and \
                not device_insts >= circuit.count_ops().keys():
            ms_basis_swap = pass_manager_config.basis_gates
            pass_manager_config.basis_gates = list(
                set(['u3', 'cx']).union(pass_manager_config.basis_gates))

    # we choose an appropriate one based on desired optimization level
    level = transpile_config['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.")

    if ms_basis_swap is not None:
        pass_manager.append(MSBasisDecomposer(ms_basis_swap))

    result = pass_manager.run(circuit,
                              callback=transpile_config['callback'],
                              output_name=transpile_config['output_name'])

    if transpile_config['faulty_qubits_map']:
        return _remap_circuit_faulty_backend(
            result, transpile_config['backend_num_qubits'],
            pass_manager_config.backend_properties,
            transpile_config['faulty_qubits_map'])

    return result