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

Qiskit / qiskit / 13179504157

06 Feb 2025 01:08PM UTC coverage: 88.614% (-0.05%) from 88.667%
13179504157

Pull #13786

github

web-flow
Merge e003971da into 3e947a72b
Pull Request #13786: Deprecate `qiskit.circuit.classicalfunction`

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

959 existing lines in 23 files now uncovered.

79356 of 89552 relevant lines covered (88.61%)

351632.0 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

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

NEW
26
    @HAS_TWEEDLEDUM.require_in_instance
×
NEW
27
    @deprecate_func(
×
28
        since="1.4",
29
        removal_timeline="in Qiskit 2.0",
30
        additional_msg="Use `PhaseOracle` or `BitFlipOracle` instead",
31
    )
UNCOV
32
    def __init__(self, expression: str, name: str = None, var_order: list = None) -> None:
×
33
        """
34
        Args:
35
            expression (str): The logical expression string.
36
            name (str): Optional. Instruction gate name. Otherwise part of the expression is
37
               going to be used.
38
            var_order(list): A list with the order in which variables will be created.
39
               (default: by appearance)
40
        """
41

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

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

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

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

58
        This evaluation is done classically.
59

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

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

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

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

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

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

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

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

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

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

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

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

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

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