feat(python): add interface file and other small changes

This commit is contained in:
Anand Balakrishnan 2023-04-30 22:14:33 -07:00
parent 168e881884
commit c42f892099
No known key found for this signature in database
8 changed files with 373 additions and 31 deletions

View file

@ -11,4 +11,5 @@ crate-type = ["cdylib"]
argus-core = { version = "0.1.0", path = "../argus-core" }
argus-semantics = { version = "0.1.0", path = "../argus-semantics" }
derive_more = "0.99.17"
paste = "1.0.12"
pyo3 = "0.18.1"

View file

@ -1,6 +1,8 @@
from argus import _argus
from argus._argus import *
__all__ = []
__doc__ = _argus.__doc__
if hasattr(_argus, "__all__"):
__all__ = _argus.__all__
__all__ += _argus.__all__

View file

@ -0,0 +1,30 @@
from argus._argus import *
# Names in __all__ with no definition:
# Add
# Always
# And
# BoolExpr
# BoolSignal
# Cmp
# ConstBool
# ConstFloat
# ConstInt
# ConstUInt
# Div
# Eventually
# FloatSignal
# IntSignal
# Mul
# Negate
# Next
# Not
# NumExpr
# Or
# Signal
# UnsignedIntSignal
# Until
# VarBool
# VarFloat
# VarInt
# VarUInt

160
pyargus/argus/_argus.pyi Normal file
View file

@ -0,0 +1,160 @@
from abc import ABC
from typing import List, Tuple, final
class NumExpr(ABC):
def __ge__(self, other) -> NumExpr: ...
def __gt__(self, other) -> NumExpr: ...
def __le__(self, other) -> NumExpr: ...
def __lt__(self, other) -> NumExpr: ...
def __mul__(self, other) -> NumExpr: ...
def __eq__(self, other) -> NumExpr: ... # type: ignore[override]
def __ne__(self, other) -> NumExpr: ... # type: ignore[override]
def __neg__(self) -> NumExpr: ...
def __add__(self, other) -> NumExpr: ...
def __radd__(self, other) -> NumExpr: ...
def __rmul__(self, other) -> NumExpr: ...
def __sub__(self, other) -> NumExpr: ...
def __rsub__(self, other) -> NumExpr: ...
def __truediv__(self, other) -> NumExpr: ...
def __rtruediv__(self, other) -> NumExpr: ...
def __abs__(self) -> NumExpr: ...
@final
class ConstInt(NumExpr):
def __init__(self, value: int): ...
@final
class ConstUInt(NumExpr):
def __init__(self, value: int): ...
@final
class ConstFloat(NumExpr):
def __init__(self, value: float): ...
@final
class VarInt(NumExpr):
def __init__(self, name: str): ...
@final
class VarUInt(NumExpr):
def __init__(self, name: str): ...
@final
class VarFloat(NumExpr):
def __init__(self, name: str): ...
@final
class Negate(NumExpr):
def __init__(self, arg: NumExpr): ...
@final
class Add(NumExpr):
def __init__(self, args: List[NumExpr]): ...
@final
class Mul(NumExpr):
def __init__(self, args: List[NumExpr]): ...
@final
class Div(NumExpr):
def __init__(self, dividend: NumExpr, divisor: NumExpr): ...
@final
class Abs(NumExpr):
def __init__(self, arg: NumExpr): ...
class BoolExpr(ABC):
def __and__(self, other) -> BoolExpr: ...
def __invert__(self) -> BoolExpr: ...
def __or__(self, other) -> BoolExpr: ...
def __rand__(self, other) -> BoolExpr: ...
def __ror__(self, other) -> BoolExpr: ...
@final
class ConstBool(BoolExpr):
def __init__(self, value: bool): ...
@final
class VarBool(BoolExpr):
def __init__(self, name: str): ...
@final
class Cmp(BoolExpr):
@staticmethod
def equal(lhs: NumExpr, rhs: NumExpr) -> Cmp: ...
@staticmethod
def greater_than(lhs: NumExpr, rhs: NumExpr) -> Cmp: ...
@staticmethod
def greater_than_eq(lhs: NumExpr, rhs: NumExpr) -> Cmp: ...
@staticmethod
def less_than(lhs: NumExpr, rhs: NumExpr) -> Cmp: ...
@staticmethod
def less_than_eq(lhs: NumExpr, rhs: NumExpr) -> Cmp: ...
@staticmethod
def not_equal(lhs: NumExpr, rhs: NumExpr) -> Cmp: ...
@final
class Not(BoolExpr):
def __init__(self, arg: BoolExpr): ...
@final
class And(BoolExpr):
def __init__(self, args: List[BoolExpr]): ...
@final
class Or(BoolExpr):
def __init__(self, args: List[BoolExpr]): ...
@final
class Next(BoolExpr):
def __init__(self, arg: BoolExpr): ...
@final
class Always(BoolExpr):
def __init__(self, arg: BoolExpr): ...
@final
class Eventually(BoolExpr):
def __init__(self, arg: BoolExpr): ...
@final
class Until(BoolExpr):
def __init__(self, lhs: BoolExpr, rhs: BoolExpr): ...
class Signal(ABC): ...
@final
class BoolSignal(Signal):
def __init__(self): ...
@staticmethod
def constant(value: bool) -> BoolSignal: ...
@staticmethod
def from_samples(samples: List[Tuple[float, bool]]) -> BoolSignal: ...
def push(self, time, value): ...
@final
class IntSignal(Signal):
def __init__(self): ...
@staticmethod
def constant(value: int) -> IntSignal: ...
@staticmethod
def from_samples(samples: List[Tuple[float, int]]) -> IntSignal: ...
def push(self, time, value): ...
@final
class UnsignedIntSignal(Signal):
def __init__(self): ...
@staticmethod
def constant(value: int) -> UnsignedIntSignal: ...
@staticmethod
def from_samples(samples: List[Tuple[float, int]]) -> UnsignedIntSignal: ...
def push(self, time, value): ...
@final
class FloatSignal(Signal):
def __init__(self): ...
@staticmethod
def constant(value: float) -> UnsignedIntSignal: ...
@staticmethod
def from_samples(samples: List[Tuple[float, float]]) -> FloatSignal: ...
def push(self, time, value): ...

0
pyargus/argus/py.typed Normal file
View file

View file

@ -3,8 +3,12 @@ use argus_core::prelude::*;
use pyo3::prelude::*;
use pyo3::pyclass::CompareOp;
#[pyclass(name = "NumExpr", subclass)]
#[derive(Clone, derive_more::From)]
/// A base numeric expression
///
/// This is an abstract base class that provides an interface for all numeric
/// expressions supported in Argus (literals, arithmetic, and so on).
#[pyclass(name = "NumExpr", subclass, module = "argus")]
#[derive(Debug, Clone, derive_more::From)]
struct PyNumExpr(Box<NumExpr>);
#[pymethods]
@ -49,7 +53,8 @@ impl PyNumExpr {
}
}
#[pyclass(extends=PyNumExpr)]
/// Create a constant integer expression
#[pyclass(extends=PyNumExpr, module = "argus")]
struct ConstInt;
#[pymethods]
@ -60,7 +65,13 @@ impl ConstInt {
}
}
#[pyclass(extends=PyNumExpr)]
/// Create a constant _unsigned_ integer expression
///
/// # Warning
///
/// Negating an unsigned integer during evaluation _may_ lead to the evaluation method
/// panicking.
#[pyclass(extends=PyNumExpr, module = "argus")]
struct ConstUInt;
#[pymethods]
@ -71,7 +82,8 @@ impl ConstUInt {
}
}
#[pyclass(extends=PyNumExpr)]
/// Create a constant floating point number expression.
#[pyclass(extends=PyNumExpr, module = "argus")]
struct ConstFloat;
#[pymethods]
@ -82,7 +94,8 @@ impl ConstFloat {
}
}
#[pyclass(extends=PyNumExpr)]
/// Create a integer variable
#[pyclass(extends=PyNumExpr, module = "argus")]
struct VarInt;
#[pymethods]
@ -93,7 +106,8 @@ impl VarInt {
}
}
#[pyclass(extends=PyNumExpr)]
/// Create an _unsigned_ integer variable
#[pyclass(extends=PyNumExpr, module = "argus")]
struct VarUInt;
#[pymethods]
@ -104,7 +118,8 @@ impl VarUInt {
}
}
#[pyclass(extends=PyNumExpr)]
/// Create a float variable
#[pyclass(extends=PyNumExpr, module = "argus")]
struct VarFloat;
#[pymethods]
@ -115,7 +130,8 @@ impl VarFloat {
}
}
#[pyclass(extends=PyNumExpr)]
/// Create a numeric negation expression
#[pyclass(extends=PyNumExpr, module = "argus")]
struct Negate;
#[pymethods]
@ -127,7 +143,10 @@ impl Negate {
}
}
#[pyclass(extends=PyNumExpr)]
/// Create a numeric addition expression
///
/// This expression is an `n`-ary expression that takes
#[pyclass(extends=PyNumExpr, module = "argus")]
struct Add;
#[pymethods]
@ -139,7 +158,7 @@ impl Add {
}
}
#[pyclass(extends=PyNumExpr)]
#[pyclass(extends=PyNumExpr, module = "argus")]
struct Sub;
#[pymethods]
@ -152,7 +171,7 @@ impl Sub {
}
}
#[pyclass(extends=PyNumExpr)]
#[pyclass(extends=PyNumExpr, module = "argus")]
struct Mul;
#[pymethods]
@ -164,7 +183,7 @@ impl Mul {
}
}
#[pyclass(extends=PyNumExpr)]
#[pyclass(extends=PyNumExpr, module = "argus")]
struct Div;
#[pymethods]
@ -177,7 +196,7 @@ impl Div {
}
}
#[pyclass(extends=PyNumExpr)]
#[pyclass(extends=PyNumExpr, module = "argus")]
struct Abs;
#[pymethods]
@ -189,8 +208,8 @@ impl Abs {
}
}
#[pyclass(name = "BoolExpr", subclass)]
#[derive(Clone, derive_more::From)]
#[pyclass(name = "BoolExpr", subclass, module = "argus")]
#[derive(Debug, Clone, derive_more::From)]
struct PyBoolExpr(Box<BoolExpr>);
#[pymethods]
@ -212,7 +231,7 @@ impl PyBoolExpr {
}
}
#[pyclass(extends=PyBoolExpr)]
#[pyclass(extends=PyBoolExpr, module = "argus")]
struct ConstBool;
#[pymethods]
@ -223,7 +242,7 @@ impl ConstBool {
}
}
#[pyclass(extends=PyBoolExpr)]
#[pyclass(extends=PyBoolExpr, module = "argus")]
struct VarBool;
#[pymethods]
@ -234,23 +253,24 @@ impl VarBool {
}
}
#[pyclass(extends=PyBoolExpr)]
#[pyclass(extends=PyBoolExpr, module = "argus")]
struct Cmp;
#[pyclass]
#[derive(Copy, Clone, derive_more::From)]
#[pyclass(module = "argus")]
#[derive(Debug, Copy, Clone, derive_more::From)]
struct PyOrdering(Ordering);
#[pymethods]
impl Cmp {
#[new]
fn new(op: PyOrdering, lhs: PyNumExpr, rhs: PyNumExpr) -> (Self, PyBoolExpr) {
let op = op.0;
let lhs = lhs.0;
let rhs = rhs.0;
(Self, Box::new(BoolExpr::Cmp { op, lhs, rhs }).into())
}
}
#[pymethods]
impl Cmp {
#[staticmethod]
fn less_than(lhs: PyNumExpr, rhs: PyNumExpr) -> PyResult<Py<Self>> {
Python::with_gil(|py| Py::new(py, Cmp::new(PyOrdering(Ordering::less_than()), lhs, rhs)))
@ -282,7 +302,7 @@ impl Cmp {
}
}
#[pyclass(extends=PyBoolExpr)]
#[pyclass(extends=PyBoolExpr, module = "argus")]
struct Not;
#[pymethods]
@ -294,7 +314,7 @@ impl Not {
}
}
#[pyclass(extends=PyBoolExpr)]
#[pyclass(extends=PyBoolExpr, module = "argus")]
struct And;
#[pymethods]
@ -306,7 +326,7 @@ impl And {
}
}
#[pyclass(extends=PyBoolExpr)]
#[pyclass(extends=PyBoolExpr, module = "argus")]
struct Or;
#[pymethods]
@ -318,7 +338,7 @@ impl Or {
}
}
#[pyclass(extends=PyBoolExpr)]
#[pyclass(extends=PyBoolExpr, module = "argus")]
struct Next;
#[pymethods]
@ -330,7 +350,7 @@ impl Next {
}
}
#[pyclass(extends=PyBoolExpr)]
#[pyclass(extends=PyBoolExpr, module = "argus")]
struct Always;
#[pymethods]
@ -342,7 +362,7 @@ impl Always {
}
}
#[pyclass(extends=PyBoolExpr)]
#[pyclass(extends=PyBoolExpr, module = "argus")]
struct Eventually;
#[pymethods]
@ -354,7 +374,7 @@ impl Eventually {
}
}
#[pyclass(extends=PyBoolExpr)]
#[pyclass(extends=PyBoolExpr, module = "argus")]
struct Until;
#[pymethods]
@ -379,6 +399,7 @@ pub fn init(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<Add>()?;
m.add_class::<Mul>()?;
m.add_class::<Div>()?;
m.add_class::<Abs>()?;
m.add_class::<PyBoolExpr>()?;
m.add_class::<ConstBool>()?;

View file

@ -2,8 +2,31 @@ mod expr;
mod semantics;
mod signals;
use argus_core::ArgusError;
use pyo3::exceptions::{PyKeyError, PyRuntimeError, PyTypeError, PyValueError};
use pyo3::prelude::*;
#[derive(derive_more::From)]
struct PyArgusError(ArgusError);
impl From<PyArgusError> for PyErr {
fn from(value: PyArgusError) -> Self {
use argus_core::Error::*;
match value.0 {
err @ (IncompleteArgs | InvalidOperation | IdentifierRedeclaration) => {
PyValueError::new_err(err.to_string())
}
err @ (InvalidPushToSignal
| NonMonotonicSignal {
end_time: _,
current_sample: _,
}) => PyRuntimeError::new_err(err.to_string()),
err @ SignalNotPresent => PyKeyError::new_err(err.to_string()),
err @ (InvalidSignalType | InvalidCast { from: _, to: _ }) => PyTypeError::new_err(err.to_string()),
}
}
}
#[pymodule]
#[pyo3(name = "_argus")]
fn pyargus(py: Python, m: &PyModule) -> PyResult<()> {

View file

@ -1,5 +1,110 @@
use std::time::Duration;
use argus_core::signals::{InterpolationMethod, Signal};
use pyo3::prelude::*;
pub fn init(_py: Python, m: &PyModule) -> PyResult<()> {
use crate::PyArgusError;
#[derive(Copy, Clone, Debug)]
pub enum SignalKind {
Bool,
Int,
UnsignedInt,
Float,
}
#[pyclass(name = "Signal", subclass)]
#[derive(Debug, Clone)]
pub struct PySignal {
pub kind: SignalKind,
pub interpolation: InterpolationMethod,
}
macro_rules! impl_signals {
($ty_name:ident, $ty:ty) => {
paste::paste! {
#[pyclass(extends=PySignal)]
pub struct [<$ty_name Signal>](Signal<$ty>);
impl [<$ty_name Signal>] {
#[inline]
fn super_type() -> PySignal {
PySignal {
interpolation: InterpolationMethod::Linear,
kind: SignalKind::$ty_name,
}
}
}
#[pymethods]
impl [<$ty_name Signal>] {
fn __repr__(&self) -> String {
format!("Signal::<{}>::{:?}", stringify!($ty), self.0)
}
/// Create a new empty signal
#[new]
#[pyo3(signature = ())]
fn new() -> (Self, PySignal) {
(Self(Signal::new()), Self::super_type())
}
fn __init__(self_: PyRef<'_, Self>) -> PyRef<'_, Self> {
self_
}
/// Create a new signal with constant value
#[staticmethod]
fn constant(py: Python<'_>, value: $ty) -> PyResult<Py<Self>> {
Py::new(
py,
(Self(Signal::constant(value)), Self::super_type())
)
}
/// Create a new signal from some finite number of samples
#[staticmethod]
fn from_samples(samples: Vec<(f64, $ty)>) -> PyResult<Py<Self>> {
let ret: Signal<$ty> = samples
.into_iter()
.map(|(t, v)| (Duration::from_secs_f64(t), v))
.collect();
Python::with_gil(|py| {
Py::new(
py,
(
Self(ret),
PySignal {
interpolation: InterpolationMethod::Linear,
kind: SignalKind::$ty_name,
},
),
)
})
}
/// Push a new sample into the given signal.
#[pyo3(signature = (time, value))]
fn push(&mut self, time: f64, value: $ty) -> Result<(), PyArgusError> {
self.0.push(Duration::from_secs_f64(time), value)?;
Ok(())
}
}
}
};
}
impl_signals!(Bool, bool);
impl_signals!(Int, i64);
impl_signals!(UnsignedInt, u64);
impl_signals!(Float, f64);
pub fn init(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<PySignal>()?;
m.add_class::<BoolSignal>()?;
m.add_class::<IntSignal>()?;
m.add_class::<UnsignedIntSignal>()?;
m.add_class::<FloatSignal>()?;
Ok(())
}