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

Qiskit / qiskit / 13181147036

06 Feb 2025 02:35PM UTC coverage: 88.588% (-0.08%) from 88.667%
13181147036

Pull #13786

github

web-flow
Merge 7b4bee509 into 9ba33cceb
Pull Request #13786: Deprecate `qiskit.circuit.classicalfunction`

0 of 8 new or added lines in 3 files covered. (0.0%)

975 existing lines in 24 files now uncovered.

79332 of 89552 relevant lines covered (88.59%)

351826.4 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` or `BitFlipOracle` instead",
32
    )
UNCOV
33
    def __init__(self, expression: str, name: str = None, var_order: list = None) -> None:
×
34
        """
35
        Args:
36
            expression (str): The logical expression string.
37
            name (str): Optional. Instruction gate name. Otherwise part of the expression is
38
               going to be used.
39
            var_order(list): A list with the order in which variables will be created.
40
               (default: by appearance)
41
        """
42

43
        from tweedledum import BoolFunction  # pylint: disable=import-error
×
44

45
        self._tweedledum_bool_expression = BoolFunction.from_expression(
×
46
            expression, var_order=var_order
47
        )
48

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

56
    def simulate(self, bitstring: str) -> bool:
×
57
        """Evaluate the expression on a bitstring.
58

59
        This evaluation is done classically.
60

61
        Args:
62
            bitstring: The bitstring for which to evaluate.
63

64
        Returns:
65
            bool: result of the evaluation.
66
        """
67
        from tweedledum import BitVec  # pylint: disable=import-error
×
68

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

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

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

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

99
            truth_table = self._tweedledum_bool_expression.truth_table(output_bit=0)
×
100
            return tweedledum2qiskit(pkrm_synth(truth_table), name=self.name, qregs=qregs)
×
101
        return synthesizer(self)
×
102

103
    def _define(self):
×
104
        """The definition of the boolean expression is its synthesis"""
105
        self.definition = self.synth()
×
106

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

113
        Returns:
114
            BooleanExpression: A gate for the input string
115

116
        Raises:
117
            FileNotFoundError: If filename is not found.
118
        """
119
        HAS_TWEEDLEDUM.require_now("BooleanExpression")
×
120

121
        from tweedledum import BoolFunction  # pylint: disable=import-error
×
122

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

128
        num_qubits = (
×
129
            expr_obj._tweedledum_bool_expression.num_inputs()
130
            + expr_obj._tweedledum_bool_expression.num_outputs()
131
        )
132
        super(BooleanExpression, expr_obj).__init__(
×
133
            name=basename(filename), num_qubits=num_qubits, params=[]
134
        )
135
        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