Skip to content

Commit

Permalink
Have QuantumCircuit.store do integer-literal type promotion (#12201)
Browse files Browse the repository at this point in the history
* Have `QuantumCircuit.store` do integer-literal type promotion

`QuantumCircuit.store` does convenience lifting of arbitary values to
`expr.Expr` nodes.  Similar to the binary-operation creators, it's
convenient to have `QuantumCircuit.store` correctly infer the required
widths of integer literals in the rvalue.

This isn't full type inference, just a small amount of convenience.

* Add integer-literal widening to `add_var`

* Add no-widen test of `QuantumCircuit.add_var`
  • Loading branch information
jakelishman committed Apr 30, 2024
1 parent b442b1c commit aacd493
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 3 deletions.
21 changes: 19 additions & 2 deletions qiskit/circuit/quantumcircuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -1765,7 +1765,18 @@ def add_var(self, name_or_var: str | expr.Var, /, initial: typing.Any) -> expr.V
# Validate the initialiser first to catch cases where the variable to be declared is being
# used in the initialiser.
circuit_scope = self._current_scope()
initial = _validate_expr(circuit_scope, expr.lift(initial))
# Convenience method to widen Python integer literals to the right width during the initial
# lift, if the type is already known via the variable.
if (
isinstance(name_or_var, expr.Var)
and name_or_var.type.kind is types.Uint
and isinstance(initial, int)
and not isinstance(initial, bool)
):
coerce_type = name_or_var.type
else:
coerce_type = None
initial = _validate_expr(circuit_scope, expr.lift(initial, coerce_type))
if isinstance(name_or_var, str):
var = expr.Var.new(name_or_var, initial.type)
elif not name_or_var.standalone:
Expand Down Expand Up @@ -2669,7 +2680,13 @@ def store(self, lvalue: typing.Any, rvalue: typing.Any, /) -> InstructionSet:
:meth:`add_var`
Create a new variable in the circuit that can be written to with this method.
"""
return self.append(Store(expr.lift(lvalue), expr.lift(rvalue)), (), (), copy=False)
# As a convenience, lift integer-literal rvalues to the matching width.
lvalue = expr.lift(lvalue)
rvalue_type = (
lvalue.type if isinstance(rvalue, int) and not isinstance(rvalue, bool) else None
)
rvalue = expr.lift(rvalue, rvalue_type)
return self.append(Store(lvalue, rvalue), (), (), copy=False)

def measure(self, qubit: QubitSpecifier, cbit: ClbitSpecifier) -> InstructionSet:
r"""Measure a quantum bit (``qubit``) in the Z basis into a classical bit (``cbit``).
Expand Down
26 changes: 25 additions & 1 deletion test/python/circuit/test_circuit_vars.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from test import QiskitTestCase

from qiskit.circuit import QuantumCircuit, CircuitError, Clbit, ClassicalRegister
from qiskit.circuit import QuantumCircuit, CircuitError, Clbit, ClassicalRegister, Store
from qiskit.circuit.classical import expr, types


Expand Down Expand Up @@ -241,6 +241,30 @@ def test_initialise_declarations_equal_to_add_var(self):
self.assertEqual(list(qc_init.iter_vars()), list(qc_manual.iter_vars()))
self.assertEqual(qc_init.data, qc_manual.data)

def test_declarations_widen_integer_literals(self):
a = expr.Var.new("a", types.Uint(8))
b = expr.Var.new("b", types.Uint(16))
qc = QuantumCircuit(declarations=[(a, 3)])
qc.add_var(b, 5)
actual_initializers = [
(op.lvalue, op.rvalue)
for instruction in qc
if isinstance((op := instruction.operation), Store)
]
expected_initializers = [
(a, expr.Value(3, types.Uint(8))),
(b, expr.Value(5, types.Uint(16))),
]
self.assertEqual(actual_initializers, expected_initializers)

def test_declaration_does_not_widen_bool_literal(self):
# `bool` is a subclass of `int` in Python (except some arithmetic operations have different
# semantics...). It's not in Qiskit's value type system, though.
a = expr.Var.new("a", types.Uint(8))
qc = QuantumCircuit()
with self.assertRaisesRegex(CircuitError, "explicit cast is required"):
qc.add_var(a, True)

def test_cannot_shadow_vars(self):
"""Test that exact duplicate ``Var`` nodes within different combinations of the inputs are
detected and rejected."""
Expand Down
16 changes: 16 additions & 0 deletions test/python/circuit/test_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,22 @@ def test_lifts_values(self):
qc.store(b, 0xFFFF)
self.assertEqual(qc.data[-1].operation, Store(b, expr.lift(0xFFFF)))

def test_lifts_integer_literals_to_full_width(self):
a = expr.Var.new("a", types.Uint(8))
qc = QuantumCircuit(inputs=[a])
qc.store(a, 1)
self.assertEqual(qc.data[-1].operation, Store(a, expr.Value(1, a.type)))
qc.store(a, 255)
self.assertEqual(qc.data[-1].operation, Store(a, expr.Value(255, a.type)))

def test_does_not_widen_bool_literal(self):
# `bool` is a subclass of `int` in Python (except some arithmetic operations have different
# semantics...). It's not in Qiskit's value type system, though.
a = expr.Var.new("a", types.Uint(8))
qc = QuantumCircuit(captures=[a])
with self.assertRaisesRegex(CircuitError, "explicit cast is required"):
qc.store(a, True)

def test_rejects_vars_not_in_circuit(self):
a = expr.Var.new("a", types.Bool())
b = expr.Var.new("b", types.Bool())
Expand Down

0 comments on commit aacd493

Please sign in to comment.