• 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/classicalfunction.py
1
# This code is part of Qiskit.
2
#
3
# (C) Copyright IBM 2020.
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
"""ClassicalFunction class"""
14

15
import ast
×
16
from typing import Callable, Optional
×
17

NEW
18
from qiskit.utils.deprecation import deprecate_func
×
19
from qiskit.circuit import QuantumCircuit, QuantumRegister
×
20
from qiskit.exceptions import QiskitError
×
21
from qiskit.utils.optionals import HAS_TWEEDLEDUM
×
22
from .classical_element import ClassicalElement
×
23
from .classical_function_visitor import ClassicalFunctionVisitor
×
24
from .utils import tweedledum2qiskit
×
25

26

27
class ClassicalFunction(ClassicalElement):
×
28
    """Represent a classical function and its logic network."""
29

NEW
30
    @HAS_TWEEDLEDUM.require_in_instance
×
NEW
31
    @deprecate_func(
×
32
        since="1.4",
33
        removal_timeline="in Qiskit 2.0",
34
        additional_msg="Use `PhaseOracle` or `BitFlipOracle` instead",
35
    )
UNCOV
36
    def __init__(self, source, name=None):
×
37
        """Creates a ``ClassicalFunction`` from Python source code in ``source``.
38

39
        The code should be a single function with types.
40

41
        Args:
42
            source (str): Python code with type hints.
43
            name (str): Optional. Default: "*classicalfunction*". ClassicalFunction name.
44

45
        Raises:
46
            QiskitError: If source is not a string.
47
        """
48
        if not isinstance(source, str):
×
49
            raise QiskitError("ClassicalFunction needs a source code as a string.")
×
50
        self._ast = ast.parse(source)
×
51
        self._network = None
×
52
        self._scopes = None
×
53
        self._args = None
×
54
        self._truth_table = None
×
55
        super().__init__(
×
56
            name or "*classicalfunction*",
57
            num_qubits=sum(qreg.size for qreg in self.qregs),
58
            params=[],
59
        )
60

61
    def compile(self):
×
62
        """Parses and creates the logical circuit"""
63
        _classical_function_visitor = ClassicalFunctionVisitor()
×
64
        _classical_function_visitor.visit(self._ast)
×
65
        self._network = _classical_function_visitor._network
×
66
        self._scopes = _classical_function_visitor.scopes
×
67
        self._args = _classical_function_visitor.args
×
68
        self.name = _classical_function_visitor.name
×
69

70
    @property
×
71
    def network(self):
×
72
        """Returns the logical network"""
73
        if self._network is None:
×
74
            self.compile()
×
75
        return self._network
×
76

77
    @property
×
78
    def scopes(self):
×
79
        """Returns the scope dict"""
80
        if self._scopes is None:
×
81
            self.compile()
×
82
        return self._scopes
×
83

84
    @property
×
85
    def args(self):
×
86
        """Returns the classicalfunction arguments"""
87
        if self._args is None:
×
88
            self.compile()
×
89
        return self._args
×
90

91
    @property
×
92
    def types(self):
×
93
        """Dumps a list of scopes with their variables and types.
94

95
        Returns:
96
            list(dict): A list of scopes as dicts, where key is the variable name and
97
            value is its type.
98
        """
99
        ret = []
×
100
        for scope in self.scopes:
×
101
            ret.append({k: v[0] for k, v in scope.items()})
×
102
        return ret
×
103

104
    def simulate(self, bitstring: str) -> bool:
×
105
        """Evaluate the expression on a bitstring.
106

107
        This evaluation is done classically.
108

109
        Args:
110
            bitstring: The bitstring for which to evaluate.
111

112
        Returns:
113
            bool: result of the evaluation.
114
        """
115
        from tweedledum.classical import simulate  # pylint: disable=import-error
×
116

117
        return simulate(self._network, bitstring)
×
118

119
    def simulate_all(self):
×
120
        """
121
        Returns a truth table.
122

123
        Returns:
124
            str: a bitstring with a truth table
125
        """
126
        result = []
×
127
        for position in range(2 ** self._network.num_pis()):
×
128
            sim_result = "".join([str(int(tt[position])) for tt in self.truth_table])
×
129
            result.append(sim_result)
×
130

131
        return "".join(reversed(result))
×
132

133
    @property
×
134
    def truth_table(self):
×
135
        """Returns (and computes) the truth table"""
136
        from tweedledum.classical import simulate  # pylint: disable=import-error
×
137

138
        if self._truth_table is None:
×
139
            self._truth_table = simulate(self._network)
×
140
        return self._truth_table
×
141

142
    def synth(
×
143
        self,
144
        registerless: bool = True,
145
        synthesizer: Optional[Callable[[ClassicalElement], QuantumCircuit]] = None,
146
    ) -> QuantumCircuit:
147
        """Synthesis the logic network into a :class:`~qiskit.circuit.QuantumCircuit`.
148

149
        Args:
150
            registerless: Default ``True``. If ``False`` uses the parameter names to create
151
            registers with those names. Otherwise, creates a circuit with a flat quantum register.
152
            synthesizer: Optional. If None tweedledum's pkrm_synth is used.
153

154
        Returns:
155
            QuantumCircuit: A circuit implementing the logic network.
156
        """
157
        if registerless:
×
158
            qregs = None
×
159
        else:
160
            qregs = self.qregs
×
161

162
        if synthesizer:
×
163
            return synthesizer(self)
×
164

165
        from tweedledum.synthesis import pkrm_synth  # pylint: disable=import-error
×
166

167
        return tweedledum2qiskit(pkrm_synth(self.truth_table[0]), name=self.name, qregs=qregs)
×
168

169
    def _define(self):
×
170
        """The definition of the classical function is its synthesis"""
171
        self.definition = self.synth()
×
172

173
    @property
×
174
    def qregs(self):
×
175
        """The list of qregs used by the classicalfunction"""
176
        qregs = [QuantumRegister(1, name=arg) for arg in self.args if self.types[0][arg] == "Int1"]
×
177
        if self.types[0]["return"] == "Int1":
×
178
            qregs.append(QuantumRegister(1, name="return"))
×
179
        return qregs
×
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