1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
use std::any::Any;
use std::sync::Mutex;

use crate::internal::*;
use lazy_static::lazy_static;
use tract_pulse_opl::ops::Delay;

pub mod array;
pub mod cnn;
pub mod delay;
pub mod downsample;
pub mod dummy;
pub mod scan;
pub mod slice;
pub mod source;

pub(crate) fn sync_inputs(
    node: &TypedNode,
    target: &mut PulsedModel,
    mapping: &HashMap<OutletId, OutletId>,
) -> TractResult<TVec<OutletId>> {
    let mut max_delay = 0;
    for input in &node.inputs {
        let fact = target.outlet_fact(mapping[input])?;
        if let Some(stream) = &fact.stream {
            max_delay = max_delay.max(stream.delay);
        }
    }
    let mut inputs = tvec!();
    for input in &node.inputs {
        let mut input = mapping[input];
        let fact = target.outlet_fact(input)?.clone();
        if let Some(stream) = &fact.stream {
            if stream.delay < max_delay {
                let add_delay = max_delay - stream.delay;
                let delay_axis = stream.axis;
                input = target.wire_node(
                    format!("{}.Delay", &*node.name),
                    Delay::new_typed(&fact.into(), delay_axis, add_delay, 0),
                    &[input],
                )?[0];
            }
        }
        inputs.push(input);
    }
    Ok(inputs)
}

register_all_mod!(array, cnn, downsample, scan, source);

type PulsifierFn = fn(
    &TypedModel,
    &TypedNode,
    &mut PulsedModel,
    &HashMap<OutletId, OutletId>,
    &Symbol,
    &TDim,
) -> TractResult<Option<TVec<OutletId>>>;

pub struct OpPulsifier {
    pub type_id: std::any::TypeId,
    pub name: &'static str,
    pub func: PulsifierFn,
}

impl OpPulsifier {
    pub fn inventory() -> Arc<Mutex<HashMap<TypeId, OpPulsifier>>> {
        lazy_static! {
            static ref INVENTORY: Arc<Mutex<HashMap<TypeId, OpPulsifier>>> = {
                let mut it = HashMap::default();
                register_all(&mut it);
                Arc::new(Mutex::new(it))
            };
        };
        (*INVENTORY).clone()
    }

    pub fn register<T: Any>(func: PulsifierFn) -> TractResult<()> {
        let inv = Self::inventory();
        let mut inv = inv.lock().map_err(|e| anyhow!("Fail to lock inventory {e}"))?;
        inv.insert(
            std::any::TypeId::of::<T>(),
            OpPulsifier {
                type_id: std::any::TypeId::of::<T>(),
                name: std::any::type_name::<T>(),
                func,
            },
        );
        Ok(())
    }

    pub fn pulsify(
        source: &TypedModel,
        node: &TypedNode,
        target: &mut PulsedModel,
        mapping: &HashMap<OutletId, OutletId>,
        symbol: &Symbol,
        pulse: &TDim,
    ) -> TractResult<Option<TVec<OutletId>>> {
        let inv = Self::inventory();
        let inv = inv.lock().map_err(|e| anyhow!("Fail to lock inventory {e}"))?;
        if let Some(pulsifier) = inv.get(&(*node.op).type_id()) {
            if let Some(pulsified) = (pulsifier.func)(source, node, target, mapping, symbol, pulse)?
            {
                return Ok(Some(pulsified));
            }
        }
        Ok(None)
    }
}

pub trait PulsedOp:
    Op + fmt::Debug + tract_core::dyn_clone::DynClone + Send + Sync + 'static + Downcast + EvalOp
{
    /// Reinterpret the PulsedOp as an Op.
    fn as_op(&self) -> &dyn Op;

    /// Reinterpret the PulsedOp as an Op, mutably.
    fn as_op_mut(&mut self) -> &mut dyn Op;

    /// Reinterpret the PulsedOp as an TypedOp.
    fn to_typed(&self) -> Box<dyn TypedOp>;

    /// Deduce output facts from input facts.
    fn pulsed_output_facts(&self, inputs: &[&PulsedFact]) -> TractResult<TVec<PulsedFact>>;
}

tract_core::dyn_clone::clone_trait_object!(PulsedOp);

impl<O: PulsedOp> From<O> for Box<dyn PulsedOp> {
    fn from(it: O) -> Box<dyn PulsedOp> {
        Box::new(it)
    }
}

impl AsMut<dyn Op> for Box<dyn PulsedOp> {
    fn as_mut(&mut self) -> &mut dyn Op {
        self.as_op_mut()
    }
}

impl AsRef<dyn Op> for dyn PulsedOp {
    fn as_ref(&self) -> &dyn Op {
        self.as_op()
    }
}

impl AsRef<dyn Op> for Box<dyn PulsedOp> {
    fn as_ref(&self) -> &dyn Op {
        self.as_op()
    }
}

impl AsMut<dyn Op> for dyn PulsedOp {
    fn as_mut(&mut self) -> &mut dyn Op {
        self.as_op_mut()
    }
}

impl std::fmt::Display for Box<dyn PulsedOp> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}", self.name())
    }
}

impl<'a> From<&'a Box<dyn PulsedOp>> for Box<dyn TypedOp> {
    fn from(op: &'a Box<dyn PulsedOp>) -> Box<dyn TypedOp> {
        op.to_typed()
    }
}