Skip to content
Merged
Show file tree
Hide file tree
Changes from 113 commits
Commits
Show all changes
121 commits
Select commit Hold shift + click to select a range
af4ba52
WIP
kevinhartman Feb 7, 2025
e423bf9
Add try_const to lift.
kevinhartman Feb 7, 2025
0a5917b
Try multiple singletons, new one for const.
kevinhartman Feb 7, 2025
a97434d
Revert "Try multiple singletons, new one for const."
kevinhartman Feb 7, 2025
1afc965
Remove Bool singleton test.
kevinhartman Feb 7, 2025
86655f1
Add const handling for stores, fix test bugs.
kevinhartman Feb 7, 2025
aaeae9b
Fix formatting.
kevinhartman Feb 7, 2025
a2a444b
Remove Duration and Stretch for now.
kevinhartman Feb 7, 2025
8ac2dc3
Cleanup, fix const bug in index.
kevinhartman Feb 7, 2025
9f8313c
Fix ordering issue for types with differing const-ness.
kevinhartman Feb 9, 2025
db9d9cb
Fix QPY serialization.
kevinhartman Feb 10, 2025
71b7e7a
Make expr.Lift default to non-const.
kevinhartman Feb 11, 2025
2091557
Revert to old test_expr_constructors.py.
kevinhartman Feb 11, 2025
7307be9
Make binary_logical lift independent again.
kevinhartman Feb 11, 2025
9b30284
Update tests, handle a few edge cases.
kevinhartman Feb 12, 2025
ce1faf1
Fix docstring.
kevinhartman Feb 12, 2025
4fee48f
Remove now redundant arg from tests.
kevinhartman Feb 12, 2025
88ab046
Add const testing for ordering.
kevinhartman Feb 12, 2025
c5a230f
Add const tests for shifts.
kevinhartman Feb 12, 2025
7c88d88
Add release note.
kevinhartman Feb 12, 2025
c58a7b8
Add const store tests.
kevinhartman Feb 12, 2025
d9e9a8c
Address lint, minor cleanup.
kevinhartman Feb 13, 2025
4a56150
Add Float type to classical expressions.
kevinhartman Feb 12, 2025
23b5961
Allow DANGEROUS conversion from Float to Bool.
kevinhartman Feb 12, 2025
8bf2e4f
Test Float ordering.
kevinhartman Feb 12, 2025
111eb32
Improve error messages for using Float with logical operators.
kevinhartman Feb 12, 2025
a839d51
Float tests for constructors.
kevinhartman Feb 12, 2025
a19b39a
Add release note.
kevinhartman Feb 12, 2025
7f02e56
Add Duration and Stretch classical types.
kevinhartman Feb 13, 2025
55af327
Add Duration type to qiskit.circuit.
kevinhartman Feb 13, 2025
86b7af9
Block Stretch from use in binary relations.
kevinhartman Feb 13, 2025
9b3c821
Add type ordering tests for Duration and Stretch.
kevinhartman Feb 13, 2025
69eab91
Test expr constructors for Duration and Stretch.
kevinhartman Feb 13, 2025
971cc26
Fix lint.
kevinhartman Feb 13, 2025
657b666
Implement operators +, -, *, /.
kevinhartman Feb 14, 2025
fc53d47
Add expression tests for arithmetic ops.
kevinhartman Feb 15, 2025
25508bf
Reject const vars in add_var and add_input.
kevinhartman Feb 17, 2025
2c8ce43
Merge branch 'main' of github.com:Qiskit/qiskit into const-expr
kevinhartman Feb 17, 2025
ccf9441
Implement QPY support for const-typed expressions.
kevinhartman Feb 18, 2025
c6eab02
Remove invalid test.
kevinhartman Feb 18, 2025
edd7806
Update QPY version 14 desc.
kevinhartman Feb 18, 2025
8afa92e
Fix lint.
kevinhartman Feb 18, 2025
4e0f2df
Add serialization testing.
kevinhartman Feb 18, 2025
15ba943
Merge branch 'main' of github.com:Qiskit/qiskit into const-expr
kevinhartman Feb 18, 2025
81c5833
Merge branch 'const-expr' into expr-float
kevinhartman Feb 18, 2025
50c31d3
Test pre-v14 QPY rejects const-typed exprs.
kevinhartman Feb 18, 2025
7e43322
Merge branch 'main' of github.com:Qiskit/qiskit into const-expr
kevinhartman Feb 18, 2025
2449ee6
Merge branch 'const-expr' into expr-float
kevinhartman Feb 18, 2025
e55e189
QASM export for floats.
kevinhartman Feb 18, 2025
1d51022
QPY support for floats.
kevinhartman Feb 18, 2025
eb8f150
Fix lint.
kevinhartman Feb 18, 2025
415f62e
Merge branch 'expr-float' into expr-timing
kevinhartman Feb 18, 2025
d38f3e9
Settle on Duration circuit core type.
kevinhartman Feb 19, 2025
fd66c1d
QPY serialization for durations and stretches.
kevinhartman Feb 19, 2025
e9b6d97
Add QPY testing.
kevinhartman Feb 19, 2025
52da3cc
QASM support for stretch and duration.
kevinhartman Feb 19, 2025
a3be688
Fix lint.
kevinhartman Feb 19, 2025
2ff7e7a
Merge branch 'expr-timing' into math-expr
kevinhartman Feb 19, 2025
6e8080c
Add arithmetic operators to QASM.
kevinhartman Feb 19, 2025
9266166
QPY testing for arithmetic operations.
kevinhartman Feb 19, 2025
e92dcc5
QASM testing for arithmetic operations.
kevinhartman Feb 19, 2025
07771f1
Merge branch 'main' of github.com:Qiskit/qiskit into const-expr
kevinhartman Feb 20, 2025
9332ed3
Merge branch 'const-expr' into expr-float
kevinhartman Feb 20, 2025
17241c6
Merge branch 'expr-float' into expr-timing
kevinhartman Feb 20, 2025
ca91bfd
Don't use match since we still support Python 3.9.
kevinhartman Feb 20, 2025
368b0ac
Merge branch 'expr-timing' into math-expr
kevinhartman Feb 20, 2025
ad87e78
Fix enum match.
kevinhartman Feb 20, 2025
9afd68c
Merge branch 'expr-timing' into math-expr
kevinhartman Feb 20, 2025
d3bca5f
Merge branch 'main' of github.com:Qiskit/qiskit into const-expr
kevinhartman Feb 24, 2025
50deb93
Revert visitors.py.
kevinhartman Feb 24, 2025
f1dc1a1
Address review comments.
kevinhartman Feb 24, 2025
1f439a0
Merge branch 'main' of github.com:Qiskit/qiskit into const-expr
kevinhartman Feb 25, 2025
166d7b2
Improve type docs.
kevinhartman Feb 26, 2025
10b2c8d
Merge branch 'main' of github.com:Qiskit/qiskit into const-expr
kevinhartman Feb 26, 2025
9d6cf39
Revert QPY, since the old format can support constexprs.
kevinhartman Feb 26, 2025
8021e00
Move const-ness from Type to Expr.
kevinhartman Feb 26, 2025
a15141b
Revert QPY testing, no longer needed.
kevinhartman Feb 26, 2025
ca2785d
Add explicit validation of const expr.
kevinhartman Feb 26, 2025
e902009
Revert stuff I didn't need to touch.
kevinhartman Feb 26, 2025
16475c3
Update release note.
kevinhartman Feb 26, 2025
6b5930d
A few finishing touches.
kevinhartman Feb 27, 2025
be73180
Merge branch 'const-expr-expr' into expr-float-expr
kevinhartman Feb 27, 2025
25f1693
Fix-up after merge.
kevinhartman Feb 27, 2025
ecc343b
Merge branch 'expr-float-expr' into expr-timing-expr
kevinhartman Feb 27, 2025
b32e6f0
Fix-ups after merge.
kevinhartman Feb 27, 2025
864506d
Fix lint.
kevinhartman Feb 27, 2025
6bc728a
Fix comment and release note.
kevinhartman Feb 27, 2025
2d38178
Merge branch 'expr-float' into expr-timing
kevinhartman Feb 27, 2025
84f5a66
Merge branch 'expr-timing' into math-expr
kevinhartman Feb 27, 2025
91b4c75
Fixes after merge.
kevinhartman Feb 27, 2025
e1dbd1d
Fix test.
kevinhartman Feb 28, 2025
1ad4388
Fix lint.
kevinhartman Feb 28, 2025
42258b8
Merge branch 'main' of github.com:Qiskit/qiskit into expr-float
kevinhartman Feb 28, 2025
481700a
Merge branch 'expr-float' into expr-timing
kevinhartman Feb 28, 2025
e09762f
Special-case Var const-ness for Stretch type.
kevinhartman Feb 28, 2025
cbd55db
Address review comments.
kevinhartman Feb 28, 2025
f12afb4
Update release note.
kevinhartman Feb 28, 2025
8d059cd
Merge branch 'expr-float' into expr-timing
kevinhartman Feb 28, 2025
e05d9ff
Update docs.
kevinhartman Feb 28, 2025
bd6bf35
Merge branch 'expr-timing' into math-expr
kevinhartman Feb 28, 2025
ef04db2
Add release notes and doc link.
kevinhartman Feb 28, 2025
0f14cca
Address review comments.
kevinhartman Mar 1, 2025
7db8222
Merge branch 'expr-float' into expr-timing
kevinhartman Mar 1, 2025
65f2198
Merge branch 'expr-timing' into math-expr
kevinhartman Mar 1, 2025
34e615b
Merge branch 'main' of github.com:Qiskit/qiskit into expr-timing
kevinhartman Mar 1, 2025
bbe67a6
Remove Stretch type.
kevinhartman Mar 2, 2025
0acc450
Remove a few more mentions of the binned stretch type.
kevinhartman Mar 2, 2025
7fea216
Add docstring for Duration.
kevinhartman Mar 2, 2025
4a317e8
Merge branch 'expr-timing' into math-expr
kevinhartman Mar 2, 2025
f5709ae
Remove Stretch type stuff.
kevinhartman Mar 2, 2025
78b2951
Address review comments.
kevinhartman Mar 3, 2025
97bbeba
Remove unused import.
kevinhartman Mar 3, 2025
3a34220
Merge branch 'expr-timing' into math-expr
kevinhartman Mar 3, 2025
49f2af8
Remove visitor short circuit.
kevinhartman Mar 3, 2025
69b985b
Merge branch 'expr-timing' into math-expr
kevinhartman Mar 3, 2025
f780d9a
Address review comments.
kevinhartman Mar 3, 2025
e7ca9c4
Address review comments.
kevinhartman Mar 3, 2025
d4cef21
Merge branch 'main' of github.com:Qiskit/qiskit into math-expr
kevinhartman Mar 3, 2025
60bcfdb
Support division by Uint.
kevinhartman Mar 3, 2025
d40cb32
Fix lint.
kevinhartman Mar 3, 2025
ad54644
Merge branch 'main' of github.com:Qiskit/qiskit into math-expr
kevinhartman Mar 4, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions crates/circuit/src/duration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// This code is part of Qiskit.
//
// (C) Copyright IBM 2025
//
// This code is licensed under the Apache License, Version 2.0. You may
// obtain a copy of this license in the LICENSE.txt file in the root directory
// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
//
// Any modifications or derivative works of this code must retain this
// copyright notice, and modified files need to carry a notice indicating
// that they have been altered from the originals.

use pyo3::prelude::*;
use pyo3::IntoPyObjectExt;

/// A length of time used to express circuit timing.
///
/// It defines a group of classes which are all subclasses of itself (functionally, an
/// enumeration carrying data).
///
/// In Python 3.10+, you can use it in a match statement::
///
/// match duration:
/// case Duration.dt(dt):
/// return dt
/// case Duration.s(seconds):
/// return seconds / 5e-7
/// case _:
/// raise ValueError("expected dt or seconds")
///
/// And in Python 3.9, you can use :meth:`Duration.unit` to determine which variant
/// is populated::
///
/// if duration.unit() == "dt":
/// return duration.value()
/// elif duration.unit() == "s":
/// return duration.value() / 5e-7
/// else:
/// raise ValueError("expected dt or seconds")
#[pyclass(eq, module = "qiskit._accelerate.circuit")]
#[derive(PartialEq, Clone, Copy, Debug)]
#[allow(non_camel_case_types)]
pub enum Duration {
dt(i64),
ns(f64),
us(f64),
ms(f64),
s(f64),
}

#[pymethods]
impl Duration {
/// The corresponding ``unit`` of the duration.
fn unit(&self) -> &'static str {
match self {
Duration::dt(_) => "dt",
Duration::us(_) => "us",
Duration::ns(_) => "ns",
Duration::ms(_) => "ms",
Duration::s(_) => "s",
}
}

/// The ``value`` of the duration.
///
/// This will be a Python ``int`` if the :meth:`~Duration.unit` is ``"dt"``,
/// else a ``float``.
#[pyo3(name = "value")]
fn py_value(&self, py: Python) -> PyResult<PyObject> {
match self {
Duration::dt(v) => v.into_py_any(py),
Duration::us(v) | Duration::ns(v) | Duration::ms(v) | Duration::s(v) => {
v.into_py_any(py)
}
}
}
}

impl Duration {
fn __repr__(&self) -> String {
match self {
Duration::ns(t) => format!("Duration.ns({})", t),
Duration::us(t) => format!("Duration.us({})", t),
Duration::ms(t) => format!("Duration.ms({})", t),
Duration::s(t) => format!("Duration.s({})", t),
Duration::dt(t) => format!("Duration.dt({})", t),
}
}
}
2 changes: 2 additions & 0 deletions crates/circuit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub mod converters;
pub mod dag_circuit;
pub mod dag_node;
mod dot_utils;
pub mod duration;
pub mod error;
pub mod gate_matrix;
pub mod imports;
Expand Down Expand Up @@ -157,6 +158,7 @@ macro_rules! impl_intopyobject_for_copy_pyclass {
}

pub fn circuit(m: &Bound<PyModule>) -> PyResult<()> {
m.add_class::<duration::Duration>()?;
m.add_class::<circuit_data::CircuitData>()?;
m.add_class::<circuit_instruction::CircuitInstruction>()?;
m.add_class::<dag_circuit::DAGCircuit>()?;
Expand Down
2 changes: 2 additions & 0 deletions qiskit/circuit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1282,6 +1282,8 @@ def __array__(self, dtype=None, copy=None):
\end{pmatrix}
"""

from qiskit._accelerate.circuit import Duration # pylint: disable=unused-import

from .exceptions import CircuitError
from . import _utils
from .quantumcircuit import QuantumCircuit
Expand Down
12 changes: 12 additions & 0 deletions qiskit/circuit/classical/expr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,10 @@
.. autofunction:: greater_equal
.. autofunction:: shift_left
.. autofunction:: shift_right
.. autofunction:: add
.. autofunction:: sub
.. autofunction:: mul
.. autofunction:: div

You can index into unsigned integers and bit-likes using another unsigned integer of any width.
This includes in storing operations, if the target of the index is writeable.
Expand Down Expand Up @@ -214,6 +218,10 @@
"greater",
"greater_equal",
"index",
"add",
"sub",
"mul",
"div",
"lift_legacy_condition",
]

Expand All @@ -238,5 +246,9 @@
shift_left,
shift_right,
index,
add,
sub,
mul,
div,
lift_legacy_condition,
)
216 changes: 215 additions & 1 deletion qiskit/circuit/classical/expr/constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@
"shift_left",
"shift_right",
"index",
"add",
"sub",
"mul",
"div",
"lift_legacy_condition",
]

Expand Down Expand Up @@ -109,7 +113,7 @@ def lift(value: typing.Any, /, type: types.Type | None = None) -> Expr:
if type is not None:
raise ValueError("use 'cast' to cast existing expressions, not 'lift'")
return value
from qiskit.circuit import Clbit, ClassicalRegister # pylint: disable=cyclic-import
from qiskit.circuit import Clbit, ClassicalRegister, Duration # pylint: disable=cyclic-import

inferred: types.Type
if value is True or value is False or isinstance(value, Clbit):
Expand All @@ -126,6 +130,9 @@ def lift(value: typing.Any, /, type: types.Type | None = None) -> Expr:
elif isinstance(value, float):
inferred = types.Float()
constructor = Value
elif isinstance(value, Duration):
inferred = types.Duration()
constructor = Value
else:
raise TypeError(f"failed to infer a type for '{value}'")
if type is None:
Expand Down Expand Up @@ -561,3 +568,210 @@ def index(target: typing.Any, index: typing.Any, /) -> Expr:
if target.type.kind is not types.Uint or index.type.kind is not types.Uint:
raise TypeError(f"invalid types for indexing: '{target.type}' and '{index.type}'")
return Index(target, index, types.Bool())


def _binary_sum(op: Binary.Op, left: typing.Any, right: typing.Any) -> Expr:
left, right = _lift_binary_operands(left, right)
if (
left.type.kind is types.Bool
or right.type.kind is types.Bool
or left.type.kind is not right.type.kind
and types.order(left.type, right.type) is types.Ordering.NONE
):
raise TypeError(f"invalid types for '{op}': '{left.type}' and '{right.type}'")
Comment thread
kevinhartman marked this conversation as resolved.
Outdated
type = types.greater(left.type, right.type)
return Binary(
op,
_coerce_lossless(left, type),
_coerce_lossless(right, type),
type,
)


def add(left: typing.Any, right: typing.Any, /) -> Expr:
"""Create an addition expression node from the given values, resolving any implicit casts and
lifting the values into :class:`Value` nodes if required.

Examples:
Addition of two floating point numbers::

>>> from qiskit.circuit.classical import expr
>>> expr.add(5.0, 2.0)
Binary(\
Binary.Op.ADD, \
Value(5.0, Float()), \
Value(2.0, Float()), \
Float())

Addition of two durations::

>>> from qiskit.circuit import Duration
>>> from qiskit.circuit.classical import expr
>>> expr.add(Duration.dt(1000), Duration.dt(1000))
Binary(\
Binary.Op.ADD, \
Value(Duration.dt(1000), Duration()), \
Value(Duration.dt(1000), Duration()), \
Duration())
"""
return _binary_sum(Binary.Op.ADD, left, right)


def sub(left: typing.Any, right: typing.Any, /) -> Expr:
"""Create a subtraction expression node from the given values, resolving any implicit casts and
lifting the values into :class:`Value` nodes if required.

Examples:
Subtration of two floating point numbers::
Comment thread
kevinhartman marked this conversation as resolved.
Outdated

>>> from qiskit.circuit.classical import expr
>>> expr.sub(5.0, 2.0)
Binary(\
Binary.Op.SUB, \
Value(5.0, Float()), \
Value(2.0, Float()), \
Float())

Subtraction of two durations::
Comment thread
kevinhartman marked this conversation as resolved.
Outdated

>>> from qiskit.circuit import Duration
>>> from qiskit.circuit.classical import expr
>>> expr.add(Duration.dt(1000), Duration.dt(1000))
Binary(\
Binary.Op.SUB, \
Value(Duration.dt(1000), Duration()), \
Value(Duration.dt(1000), Duration()), \
Duration())
"""
return _binary_sum(Binary.Op.SUB, left, right)


def mul(left: typing.Any, right: typing.Any) -> Expr:
"""Create a multiplication expression node from the given values, resolving any implicit casts and
lifting the values into :class:`Value` nodes if required.

This can be used to multiply numeric operands of the same type kind, or to multiply a duration
operand by a :class:`~.types.Float`.
Comment thread
kevinhartman marked this conversation as resolved.
Outdated

Examples:
Multiplication of two floating point numbers::

>>> from qiskit.circuit.classical import expr
>>> expr.mul(5.0, 2.0)
Binary(\
Binary.Op.MUL, \
Value(5.0, Float()), \
Value(2.0, Float()), \
Float())

Multiplication of a duration by a float::

>>> from qiskit.circuit import Duration
>>> from qiskit.circuit.classical import expr
>>> expr.mul(Duration.dt(1000), 0.5)
Binary(\
Binary.Op.MUL, \
Value(Duration.dt(1000), Duration()), \
Value(0.5, Float()), \
Duration())
"""
left, right = _lift_binary_operands(left, right)
type: types.Type
if left.type.kind is types.Duration and right.type.kind is types.Duration:
raise TypeError("cannot multiply two durations")
if left.type.kind is types.Duration and right.type.kind is types.Float:
if not right.const:
raise ValueError(
f"multiplying operands '{left}' and '{right}' would result in a non-const '{left.type}'"
)
type = left.type
elif right.type.kind is types.Duration and left.type.kind is types.Float:
if not left.const:
raise ValueError(
f"multiplying operands '{left}' and '{right}' would result in a non-const '{right.type}'"
)
type = right.type
elif (
left.type.kind is right.type.kind
and left.type.kind is not types.Bool
and types.order(left.type, right.type) is not types.Ordering.NONE
):
type = types.greater(left.type, right.type)
left = _coerce_lossless(left, type)
right = _coerce_lossless(right, type)
else:
raise TypeError(f"invalid types for '{Binary.Op.MUL}': '{left.type}' and '{right.type}'")
return Binary(
Binary.Op.MUL,
left,
right,
type,
)


def div(left: typing.Any, right: typing.Any) -> Expr:
"""Create a division expression node from the given values, resolving any implicit casts and
lifting the values into :class:`Value` nodes if required.

This can be used to divide numeric operands of the same type kind, to divide a
:class`~.types.Duration` operand by a :class:`~.types.Float`, or to divide two
:class`~.types.Duration` operands which yields an expression of type
:class:`~.types.Float`.
Comment thread
kevinhartman marked this conversation as resolved.

Examples:
Division of two floating point numbers::

>>> from qiskit.circuit.classical import expr
>>> expr.div(5.0, 2.0)
Binary(\
Binary.Op.DIV, \
Value(5.0, Float()), \
Value(2.0, Float()), \
Float())

Division of two durations::

>>> from qiskit.circuit import Duration
>>> from qiskit.circuit.classical import expr
>>> expr.div(Duration.dt(10000), Duration.dt(1000))
Binary(\
Binary.Op.DIV, \
Value(Duration.dt(10000), Duration()), \
Value(Duration.dt(1000), Duration()), \
Float())


Division of a duration by a float::

>>> from qiskit.circuit import Duration
>>> from qiskit.circuit.classical import expr
>>> expr.div(Duration.dt(10000), 12.0)
Binary(\
Binary.Op.DIV, \
Value(Duration.dt(10000), Duration()), \
Value(12.0, types.Float()), \
Duration())
"""
left, right = _lift_binary_operands(left, right)
type: types.Type
if left.type.kind is right.type.kind is not types.Bool:
if left.type.kind is types.Duration:
type = types.Float()
elif types.order(left.type, right.type) is not types.Ordering.NONE:
type = types.greater(left.type, right.type)
left = _coerce_lossless(left, type)
right = _coerce_lossless(right, type)
elif left.type.kind is types.Duration and right.type.kind is types.Float:
if not right.const:
raise ValueError(
f"division of '{left}' and '{right}' would result in a non-const '{left.type}'"
)
type = left.type
else:
raise TypeError(f"invalid types for '{Binary.Op.DIV}': '{left.type}' and '{right.type}'")
return Binary(
Binary.Op.DIV,
left,
right,
type,
)
Loading