Skip to content

Commit

Permalink
Revert memory-owning expr.Var nodes
Browse files Browse the repository at this point in the history
This commit is a roll-up reversion of the following commits (PR):

* This reverts commit a79e879 (Qiskit#10977)
* This reverts commit ba161e9 (Qiskit#10974)
* This reverts commit 50e8137 (Qiskit#10944)

This is being done to clear the 1.0 branch of memory-owning `expr.Var`
variables and `Store` instructions.  It should be re-applied once 1.0 is
released.

The individual reverts had conflicts, since various other large-scale
changes include wrap-ups of the changes to be reverted.  This reversion
should have handled all that, and other places where standalone `Var`
nodes were referenced (such as in "See also" sections), even if not
used.
  • Loading branch information
jakelishman committed Jan 29, 2024
1 parent 8f0646a commit 33ba003
Show file tree
Hide file tree
Showing 28 changed files with 234 additions and 2,481 deletions.
2 changes: 0 additions & 2 deletions qiskit/circuit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,6 @@
InstructionSet
Operation
EquivalenceLibrary
Store
Control Flow Operations
-----------------------
Expand Down Expand Up @@ -377,7 +376,6 @@
from .delay import Delay
from .measure import Measure
from .reset import Reset
from .store import Store
from .parameter import Parameter
from .parametervector import ParameterVector
from .parameterexpression import ParameterExpression
Expand Down
23 changes: 4 additions & 19 deletions qiskit/circuit/classical/expr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,10 @@
These objects are mutable and should not be reused in a different location without a copy.
The base for dynamic variables is the :class:`Var`, which can be either an arbitrarily typed runtime
variable, or a wrapper around a :class:`.Clbit` or :class:`.ClassicalRegister`.
The entry point from general circuit objects to the expression system is by wrapping the object
in a :class:`Var` node and associating a :class:`~.types.Type` with it.
.. autoclass:: Var
:members: var, name
Similarly, literals used in comparison (such as integers) should be lifted to :class:`Value` nodes
with associated types.
Expand Down Expand Up @@ -87,18 +86,10 @@
The functions and methods described in this section are a more user-friendly way to build the
expression tree, while staying close to the internal representation. All these functions will
automatically lift valid Python scalar values into corresponding :class:`Var` or :class:`Value`
objects, and will resolve any required implicit casts on your behalf. If you want to directly use
some scalar value as an :class:`Expr` node, you can manually :func:`lift` it yourself.
objects, and will resolve any required implicit casts on your behalf.
.. autofunction:: lift
Typically you should create memory-owning :class:`Var` instances by using the
:meth:`.QuantumCircuit.add_var` method to declare them in some circuit context, since a
:class:`.QuantumCircuit` will not accept an :class:`Expr` that contains variables that are not
already declared in it, since it needs to know how to allocate the storage and how the variable will
be initialized. However, should you want to do this manually, you should use the low-level
:meth:`Var.new` call to safely generate a named variable for usage.
You can manually specify casts in cases where the cast is allowed in explicit form, but may be
lossy (such as the cast of a higher precision :class:`~.types.Uint` to a lower precision one).
Expand Down Expand Up @@ -160,11 +151,6 @@
suitable "key" functions to do the comparison.
.. autofunction:: structurally_equivalent
Some expressions have associated memory locations, and others may be purely temporary.
You can use :func:`is_lvalue` to determine whether an expression has an associated memory location.
.. autofunction:: is_lvalue
"""

__all__ = [
Expand All @@ -177,7 +163,6 @@
"ExprVisitor",
"iter_vars",
"structurally_equivalent",
"is_lvalue",
"lift",
"cast",
"bit_not",
Expand All @@ -197,7 +182,7 @@
]

from .expr import Expr, Var, Value, Cast, Unary, Binary
from .visitors import ExprVisitor, iter_vars, structurally_equivalent, is_lvalue
from .visitors import ExprVisitor, iter_vars, structurally_equivalent
from .constructors import (
lift,
cast,
Expand Down
52 changes: 45 additions & 7 deletions qiskit/circuit/classical/expr/constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,27 +35,65 @@
"lift_legacy_condition",
]

import enum
import typing

from .expr import Expr, Var, Value, Unary, Binary, Cast
from ..types import CastKind, cast_kind
from .. import types

if typing.TYPE_CHECKING:
import qiskit


class _CastKind(enum.Enum):
EQUAL = enum.auto()
"""The two types are equal; no cast node is required at all."""
IMPLICIT = enum.auto()
"""The 'from' type can be cast to the 'to' type implicitly. A ``Cast(implicit=True)`` node is
the minimum required to specify this."""
LOSSLESS = enum.auto()
"""The 'from' type can be cast to the 'to' type explicitly, and the cast will be lossless. This
requires a ``Cast(implicit=False)`` node, but there's no danger from inserting one."""
DANGEROUS = enum.auto()
"""The 'from' type has a defined cast to the 'to' type, but depending on the value, it may lose
data. A user would need to manually specify casts."""
NONE = enum.auto()
"""There is no casting permitted from the 'from' type to the 'to' type."""


def _uint_cast(from_: types.Uint, to_: types.Uint, /) -> _CastKind:
if from_.width == to_.width:
return _CastKind.EQUAL
if from_.width < to_.width:
return _CastKind.LOSSLESS
return _CastKind.DANGEROUS


_ALLOWED_CASTS = {
(types.Bool, types.Bool): lambda _a, _b, /: _CastKind.EQUAL,
(types.Bool, types.Uint): lambda _a, _b, /: _CastKind.LOSSLESS,
(types.Uint, types.Bool): lambda _a, _b, /: _CastKind.IMPLICIT,
(types.Uint, types.Uint): _uint_cast,
}


def _cast_kind(from_: types.Type, to_: types.Type, /) -> _CastKind:
if (coercer := _ALLOWED_CASTS.get((from_.kind, to_.kind))) is None:
return _CastKind.NONE
return coercer(from_, to_)


def _coerce_lossless(expr: Expr, type: types.Type) -> Expr:
"""Coerce ``expr`` to ``type`` by inserting a suitable :class:`Cast` node, if the cast is
lossless. Otherwise, raise a ``TypeError``."""
kind = cast_kind(expr.type, type)
if kind is CastKind.EQUAL:
kind = _cast_kind(expr.type, type)
if kind is _CastKind.EQUAL:
return expr
if kind is CastKind.IMPLICIT:
if kind is _CastKind.IMPLICIT:
return Cast(expr, type, implicit=True)
if kind is CastKind.LOSSLESS:
if kind is _CastKind.LOSSLESS:
return Cast(expr, type, implicit=False)
if kind is CastKind.DANGEROUS:
if kind is _CastKind.DANGEROUS:
raise TypeError(f"cannot cast '{expr}' to '{type}' without loss of precision")
raise TypeError(f"no cast is defined to take '{expr}' to '{type}'")

Expand Down Expand Up @@ -160,7 +198,7 @@ def cast(operand: typing.Any, type: types.Type, /) -> Expr:
Cast(Value(5, types.Uint(32)), types.Uint(8), implicit=False)
"""
operand = lift(operand)
if cast_kind(operand.type, type) is CastKind.NONE:
if _cast_kind(operand.type, type) is _CastKind.NONE:
raise TypeError(f"cannot cast '{operand}' to '{type}'")
return Cast(operand, type)

Expand Down
85 changes: 8 additions & 77 deletions qiskit/circuit/classical/expr/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import abc
import enum
import typing
import uuid

from .. import types

Expand Down Expand Up @@ -109,92 +108,24 @@ def __repr__(self):

@typing.final
class Var(Expr):
"""A classical variable.
These variables take two forms: a new-style variable that owns its storage location and has an
associated name; and an old-style variable that wraps a :class:`.Clbit` or
:class:`.ClassicalRegister` instance that is owned by some containing circuit. In general,
construction of variables for use in programs should use :meth:`Var.new` or
:meth:`.QuantumCircuit.add_var`.
Variables are immutable after construction, so they can be used as dictionary keys."""

__slots__ = ("var", "name")

var: qiskit.circuit.Clbit | qiskit.circuit.ClassicalRegister | uuid.UUID
"""A reference to the backing data storage of the :class:`Var` instance. When lifting
old-style :class:`.Clbit` or :class:`.ClassicalRegister` instances into a :class:`Var`,
this is exactly the :class:`.Clbit` or :class:`.ClassicalRegister`. If the variable is a
new-style classical variable (one that owns its own storage separate to the old
:class:`.Clbit`/:class:`.ClassicalRegister` model), this field will be a :class:`~uuid.UUID`
to uniquely identify it."""
name: str | None
"""The name of the variable. This is required to exist if the backing :attr:`var` attribute
is a :class:`~uuid.UUID`, i.e. if it is a new-style variable, and must be ``None`` if it is
an old-style variable."""
"""A classical variable."""

__slots__ = ("var",)

def __init__(
self,
var: qiskit.circuit.Clbit | qiskit.circuit.ClassicalRegister | uuid.UUID,
type: types.Type,
*,
name: str | None = None,
self, var: qiskit.circuit.Clbit | qiskit.circuit.ClassicalRegister, type: types.Type
):
super().__setattr__("type", type)
super().__setattr__("var", var)
super().__setattr__("name", name)

@classmethod
def new(cls, name: str, type: types.Type) -> typing.Self:
"""Generate a new named variable that owns its own backing storage."""
return cls(uuid.uuid4(), type, name=name)

@property
def standalone(self) -> bool:
"""Whether this :class:`Var` is a standalone variable that owns its storage location. If
false, this is a wrapper :class:`Var` around a pre-existing circuit object."""
return isinstance(self.var, uuid.UUID)
self.type = type
self.var = var

def accept(self, visitor, /):
return visitor.visit_var(self)

def __setattr__(self, key, value):
if hasattr(self, key):
raise AttributeError(f"'Var' object attribute '{key}' is read-only")
raise AttributeError(f"'Var' object has no attribute '{key}'")

def __hash__(self):
return hash((self.type, self.var, self.name))

def __eq__(self, other):
return (
isinstance(other, Var)
and self.type == other.type
and self.var == other.var
and self.name == other.name
)
return isinstance(other, Var) and self.type == other.type and self.var == other.var

def __repr__(self):
if self.name is None:
return f"Var({self.var}, {self.type})"
return f"Var({self.var}, {self.type}, name='{self.name}')"

def __getstate__(self):
return (self.var, self.type, self.name)

def __setstate__(self, state):
var, type, name = state
super().__setattr__("type", type)
super().__setattr__("var", var)
super().__setattr__("name", name)

def __copy__(self):
# I am immutable...
return self

def __deepcopy__(self, memo):
# ... as are all my consituent parts.
return self
return f"Var({self.var}, {self.type})"


@typing.final
Expand Down
63 changes: 0 additions & 63 deletions qiskit/circuit/classical/expr/visitors.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,66 +215,3 @@ def structurally_equivalent(
True
"""
return left.accept(_StructuralEquivalenceImpl(right, left_var_key, right_var_key))


class _IsLValueImpl(ExprVisitor[bool]):
__slots__ = ()

def visit_var(self, node, /):
return True

def visit_value(self, node, /):
return False

def visit_unary(self, node, /):
return False

def visit_binary(self, node, /):
return False

def visit_cast(self, node, /):
return False


_IS_LVALUE = _IsLValueImpl()


def is_lvalue(node: expr.Expr, /) -> bool:
"""Return whether this expression can be used in l-value positions, that is, whether it has a
well-defined location in memory, such as one that might be writeable.
Being an l-value is a necessary but not sufficient for this location to be writeable; it is
permissible that a larger object containing this memory location may not allow writing from
the scope that attempts to write to it. This would be an access property of the containing
program, however, and not an inherent property of the expression system.
Examples:
Literal values are never l-values; there's no memory location associated with (for example)
the constant ``1``::
>>> from qiskit.circuit.classical import expr
>>> expr.is_lvalue(expr.lift(2))
False
:class:`~.expr.Var` nodes are always l-values, because they always have some associated
memory location::
>>> from qiskit.circuit.classical import types
>>> from qiskit.circuit import Clbit
>>> expr.is_lvalue(expr.Var.new("a", types.Bool()))
True
>>> expr.is_lvalue(expr.lift(Clbit()))
True
Currently there are no unary or binary operations on variables that can produce an l-value
expression, but it is likely in the future that some sort of "indexing" operation will be
added, which could produce l-values::
>>> a = expr.Var.new("a", types.Uint(8))
>>> b = expr.Var.new("b", types.Uint(8))
>>> expr.is_lvalue(a) and expr.is_lvalue(b)
True
>>> expr.is_lvalue(expr.bit_and(a, b))
False
"""
return node.accept(_IS_LVALUE)
27 changes: 1 addition & 26 deletions qiskit/circuit/classical/types/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
Typing (:mod:`qiskit.circuit.classical.types`)
==============================================
Representation
==============
The type system of the expression tree is exposed through this module. This is inherently linked to
the expression system in the :mod:`~.classical.expr` module, as most expressions can only be
Expand All @@ -43,18 +41,11 @@
Note that :class:`Uint` defines a family of types parametrised by their width; it is not one single
type, which may be slightly different to the 'classical' programming languages you are used to.
Working with types
==================
There are some functions on these types exposed here as well. These are mostly expected to be used
only in manipulations of the expression tree; users who are building expressions using the
:ref:`user-facing construction interface <circuit-classical-expressions-expr-construction>` should
not need to use these.
Partial ordering of types
-------------------------
The type system is equipped with a partial ordering, where :math:`a < b` is interpreted as
":math:`a` is a strict subtype of :math:`b`". Note that the partial ordering is a subset of the
directed graph that describes the allowed explicit casting operations between types. The partial
Expand All @@ -75,20 +66,6 @@
.. autofunction:: is_subtype
.. autofunction:: is_supertype
.. autofunction:: greater
Casting between types
---------------------
It is common to need to cast values of one type to another type. The casting rules for this are
embedded into the :mod:`types` module. You can query the casting kinds using :func:`cast_kind`:
.. autofunction:: cast_kind
The return values from this function are an enumeration explaining the types of cast that are
allowed from the left type to the right type.
.. autoclass:: CastKind
"""

__all__ = [
Expand All @@ -100,9 +77,7 @@
"is_subtype",
"is_supertype",
"greater",
"CastKind",
"cast_kind",
]

from .types import Type, Bool, Uint
from .ordering import Ordering, order, is_subtype, is_supertype, greater, CastKind, cast_kind
from .ordering import Ordering, order, is_subtype, is_supertype, greater
Loading

0 comments on commit 33ba003

Please sign in to comment.