Skip to main content

flow_gate_core/
traits.rs

1use std::fmt::{Debug, Display, Formatter};
2use std::sync::Arc;
3
4use bitvec::{order::Lsb0, vec::BitVec as InnerBitVec};
5
6use crate::error::FlowGateError;
7use crate::event::EventMatrix;
8use crate::gate::GateRegistry;
9
10#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
11pub struct ParameterName(pub Arc<str>);
12
13impl ParameterName {
14    pub fn new(name: impl AsRef<str>) -> Self {
15        Self(Arc::<str>::from(name.as_ref()))
16    }
17
18    pub fn as_str(&self) -> &str {
19        &self.0
20    }
21}
22
23impl Display for ParameterName {
24    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
25        f.write_str(self.as_str())
26    }
27}
28
29impl From<&str> for ParameterName {
30    fn from(value: &str) -> Self {
31        Self::new(value)
32    }
33}
34
35impl From<String> for ParameterName {
36    fn from(value: String) -> Self {
37        Self(Arc::<str>::from(value))
38    }
39}
40
41#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
42pub struct GateId(pub Arc<str>);
43
44impl GateId {
45    pub fn new(id: impl AsRef<str>) -> Self {
46        Self(Arc::<str>::from(id.as_ref()))
47    }
48
49    pub fn as_str(&self) -> &str {
50        &self.0
51    }
52}
53
54impl Display for GateId {
55    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
56        f.write_str(self.as_str())
57    }
58}
59
60impl From<&str> for GateId {
61    fn from(value: &str) -> Self {
62        Self::new(value)
63    }
64}
65
66impl From<String> for GateId {
67    fn from(value: String) -> Self {
68        Self(Arc::<str>::from(value))
69    }
70}
71
72pub type BitVec = InnerBitVec<u64, Lsb0>;
73
74pub trait Transform: Send + Sync + Clone + Debug {
75    fn apply(&self, value: f64) -> f64;
76    fn invert(&self, scaled: f64) -> f64;
77
78    fn apply_batch(&self, values: &[f64], out: &mut [f64]) {
79        debug_assert_eq!(values.len(), out.len());
80        values
81            .iter()
82            .zip(out.iter_mut())
83            .for_each(|(&v, o)| *o = self.apply(v));
84    }
85
86    fn transform_id(&self) -> &str;
87}
88
89pub trait Gate: Send + Sync + Debug {
90    fn dimensions(&self) -> &[ParameterName];
91    fn contains(&self, coords: &[f64]) -> bool;
92    fn gate_id(&self) -> &GateId;
93    fn parent_id(&self) -> Option<&GateId>;
94}
95
96pub trait ApplyGate: Gate {
97    /// Classify events in the matrix against this gate.
98    /// Returns a `BitVec` where each bit indicates whether the corresponding
99    /// event is inside the gate.
100    fn classify(
101        &self,
102        matrix: &EventMatrix,
103        gate_map: &GateRegistry,
104    ) -> Result<BitVec, FlowGateError>;
105}