• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Qiskit / qiskit / 13415421333

19 Feb 2025 02:50PM UTC coverage: 88.855% (-0.03%) from 88.882%
13415421333

push

github

web-flow
Deprecate `qiskit.circuit.classicalfunction` (#13786)

* Deprecate `ClassicalFunction`

* Changes according to PR review

* Update releasenotes/notes/deprecate-classical-function-3bf44ef26d984366.yaml

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update qiskit/circuit/classicalfunction/__init__.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update releasenotes/notes/deprecate-classical-function-3bf44ef26d984366.yaml

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Test fix

* Deprecate `BooleanExpression` as well

* Linting

* Test fix due to deprecation

* Update the release note

* Test message fix

* Update deprecation message and ignore deprecation warning in the non-deprecated PhaseOracle

* Added an explanation on how to create a bit flip oracle from a phase flip oracle

* Fixes according to PR review

* Typo

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>

0 of 26 new or added lines in 4 files covered. (0.0%)

25 existing lines in 6 files now uncovered.

79122 of 89046 relevant lines covered (88.86%)

352060.74 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/qiskit/circuit/classicalfunction/boolean_expression.py
1
# This code is part of Qiskit.
2
#
3
# (C) Copyright IBM 2021.
4
#
5
# This code is licensed under the Apache License, Version 2.0. You may
6
# obtain a copy of this license in the LICENSE.txt file in the root directory
7
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
#
9
# Any modifications or derivative works of this code must retain this
10
# copyright notice, and modified files need to carry a notice indicating
11
# that they have been altered from the originals.
12

13
"""A quantum oracle constructed from a logical expression or a string in the DIMACS format."""
14

15
from os.path import basename, isfile
×
16
from typing import Callable, Optional
×
17

NEW
18
from qiskit.utils.deprecation import deprecate_func
×
19
from qiskit.circuit import QuantumCircuit
×
20
from qiskit.utils.optionals import HAS_TWEEDLEDUM
×
21
from .classical_element import ClassicalElement
×
22

23

24
class BooleanExpression(ClassicalElement):
×
25
    """The Boolean Expression gate."""
26

NEW
27
    @HAS_TWEEDLEDUM.require_in_instance
×
NEW
28
    @deprecate_func(
×
29
        since="1.4",
30
        removal_timeline="in Qiskit 2.0",
31
        additional_msg="Use `PhaseOracle` instead, which can be turned into a "
32
        "bit-flip oracle by applying Hadamard gates on the target "
33
        "qubit before and after the instruction, and conditioning."
34
        "the instruction on the target qubit.",
35
    )
UNCOV
36
    def __init__(self, expression: str, name: str = None, var_order: list = None) -> None:
×
37
        """
38
        Args:
39
            expression (str): The logical expression string.
40
            name (str): Optional. Instruction gate name. Otherwise part of the expression is
41
               going to be used.
42
            var_order(list): A list with the order in which variables will be created.
43
               (default: by appearance)
44
        """
45

46
        from tweedledum import BoolFunction  # pylint: disable=import-error
×
47

48
        self._tweedledum_bool_expression = BoolFunction.from_expression(
×
49
            expression, var_order=var_order
50
        )
51

52
        short_expr_for_name = (expression[:10] + "...") if len(expression) > 13 else expression
×
53
        num_qubits = (
×
54
            self._tweedledum_bool_expression.num_outputs()
55
            + self._tweedledum_bool_expression.num_inputs()
56
        )
57
        super().__init__(name or short_expr_for_name, num_qubits=num_qubits, params=[])
×
58

59
    def simulate(self, bitstring: str) -> bool:
×
60
        """Evaluate the expression on a bitstring.
61

62
        This evaluation is done classically.
63

64
        Args:
65
            bitstring: The bitstring for which to evaluate.
66

67
        Returns:
68
            bool: result of the evaluation.
69
        """
70
        from tweedledum import BitVec  # pylint: disable=import-error
×
71

72
        bits = []
×
73
        for bit in bitstring:
×
74
            bits.append(BitVec(1, bit))
×
75
        return bool(self._tweedledum_bool_expression.simulate(*bits))
×
76

77
    def synth(
×
78
        self,
79
        registerless: bool = True,
80
        synthesizer: Optional[Callable[["BooleanExpression"], QuantumCircuit]] = None,
81
    ):
82
        """Synthesis the logic network into a :class:`~qiskit.circuit.QuantumCircuit`.
83

84
        Args:
85
            registerless: Default ``True``. If ``False`` uses the parameter names
86
                to create registers with those names. Otherwise, creates a circuit with a flat
87
                quantum register.
88
            synthesizer: A callable that takes self and returns a Tweedledum
89
                circuit.
90
        Returns:
91
            QuantumCircuit: A circuit implementing the logic network.
92
        """
93
        if registerless:
×
94
            qregs = None
×
95
        else:
96
            qregs = None  # TODO: Probably from self._tweedledum_bool_expression._signature
×
97

98
        if synthesizer is None:
×
99
            from .utils import tweedledum2qiskit  # Avoid an import cycle
×
100
            from tweedledum.synthesis import pkrm_synth  # pylint: disable=import-error
×
101

102
            truth_table = self._tweedledum_bool_expression.truth_table(output_bit=0)
×
103
            return tweedledum2qiskit(pkrm_synth(truth_table), name=self.name, qregs=qregs)
×
104
        return synthesizer(self)
×
105

106
    def _define(self):
×
107
        """The definition of the boolean expression is its synthesis"""
108
        self.definition = self.synth()
×
109

110
    @classmethod
×
111
    def from_dimacs_file(cls, filename: str):
×
112
        """Create a BooleanExpression from the string in the DIMACS format.
113
        Args:
114
            filename: A file in DIMACS format.
115

116
        Returns:
117
            BooleanExpression: A gate for the input string
118

119
        Raises:
120
            FileNotFoundError: If filename is not found.
121
        """
122
        HAS_TWEEDLEDUM.require_now("BooleanExpression")
×
123

124
        from tweedledum import BoolFunction  # pylint: disable=import-error
×
125

126
        expr_obj = cls.__new__(cls)
×
127
        if not isfile(filename):
×
128
            raise FileNotFoundError(f"The file {filename} does not exists.")
×
129
        expr_obj._tweedledum_bool_expression = BoolFunction.from_dimacs_file(filename)
×
130

131
        num_qubits = (
×
132
            expr_obj._tweedledum_bool_expression.num_inputs()
133
            + expr_obj._tweedledum_bool_expression.num_outputs()
134
        )
135
        super(BooleanExpression, expr_obj).__init__(
×
136
            name=basename(filename), num_qubits=num_qubits, params=[]
137
        )
138
        return expr_obj
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc