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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
//! Create subcircuits that iterate until a specified condition
//! defined over the contents of a stream is satisfied.
use crate::{
Timestamp,
circuit::{
ChildCircuit, Circuit, Stream,
circuit_builder::IterativeCircuit,
schedule::{Error as SchedulerError, Scheduler},
},
};
use std::{cell::Cell, marker::PhantomData, rc::Rc};
impl<C, D> Stream<C, D>
where
C: Circuit,
D: 'static + Clone,
{
/// Attach a condition to a stream.
///
/// A [`Condition`] is a condition on the value in the stream
/// checked on each clock cycle, that can be used to terminate
/// the execution of the subcircuit (see
/// [`ChildCircuit::iterate_with_condition`] and
/// [`ChildCircuit::iterate_with_conditions`]).
pub fn condition<F>(&self, condition_func: F) -> Condition<C>
where
F: 'static + Fn(&D) -> bool,
{
let cond = Rc::new(Cell::new(false));
let cond_clone = cond.clone();
self.inspect(move |v| cond_clone.set(condition_func(v)));
Condition::new(cond)
}
}
impl<P, T> ChildCircuit<P, T>
where
P: 'static,
T: Timestamp,
Self: Circuit,
{
/// Create a subcircuit that iterates until a condition is satisfied.
///
/// This method is similar to [`Circuit::iterate`], which creates
/// a subcircuit that iterates until a specified condition is
/// satisfied, but here the condition is a predicate over the
/// contents of a stream captured by a [`Condition`].
///
/// The `constructor` closure populates the child circuit and returns
/// a condition that will be evaluated to check the termination
/// condition on each iteration and an arbitrary user-defined return
/// value that typically contains output streams of the child.
/// The subcircuit will iterate until the condition returns true.
pub fn iterate_with_condition<F, V>(&self, constructor: F) -> Result<V, SchedulerError>
where
F: FnOnce(
&mut IterativeCircuit<Self>,
) -> Result<(Condition<IterativeCircuit<Self>>, V), SchedulerError>,
{
self.iterate(|child| {
let (condition, res) = constructor(child)?;
Ok((async move || Ok(condition.check()), res))
})
}
/// Similar to `Self::iterate_with_condition`, but with a user-specified
/// [`Scheduler`].
pub fn iterate_with_condition_and_scheduler<F, V, S>(
&self,
constructor: F,
) -> Result<V, SchedulerError>
where
F: FnOnce(
&mut IterativeCircuit<Self>,
) -> Result<(Condition<IterativeCircuit<Self>>, V), SchedulerError>,
S: Scheduler + 'static,
{
self.iterate_with_scheduler::<_, _, _, S>(|child| {
let (condition, res) = constructor(child)?;
Ok((async move || Ok(condition.check()), res))
})
}
/// Create a subcircuit that iterates until multiple conditions are
/// satisfied.
///
/// Similar to `Self::iterate_with_condition`, but allows the subcircuit to
/// have multiple conditions. The subcircuit will iterate until _all_
/// conditions are satisfied _simultaneously_ in the same clock cycle.
pub fn iterate_with_conditions<F, V>(&self, constructor: F) -> Result<V, SchedulerError>
where
F: FnOnce(
&mut IterativeCircuit<Self>,
) -> Result<(Vec<Condition<IterativeCircuit<Self>>>, V), SchedulerError>,
{
self.iterate(|child| {
let (conditions, res) = constructor(child)?;
Ok((
async move || Ok(conditions.iter().all(Condition::check)),
res,
))
})
}
/// Similar to `Self::iterate_with_conditions`, but with a user-specified
/// [`Scheduler`].
pub fn iterate_with_conditions_and_scheduler<F, V, S>(
&self,
constructor: F,
) -> Result<V, SchedulerError>
where
F: FnOnce(
&mut IterativeCircuit<Self>,
) -> Result<(Vec<Condition<IterativeCircuit<Self>>>, V), SchedulerError>,
S: 'static + Scheduler,
{
self.iterate_with_scheduler::<_, _, _, S>(|child| {
let (conditions, res) = constructor(child)?;
Ok((
async move || Ok(conditions.iter().all(Condition::check)),
res,
))
})
}
}
/// A condition attached to a stream that can be used
/// to terminate the execution of a subcircuit
/// (see [`ChildCircuit::iterate_with_condition`] and
/// [`ChildCircuit::iterate_with_conditions`]).
///
/// A condition is created by the [`Stream::condition`] method.
pub struct Condition<C> {
cond: Rc<Cell<bool>>,
_phantom: PhantomData<C>,
}
impl<C> Condition<C> {
fn new(cond: Rc<Cell<bool>>) -> Self {
Self {
cond,
_phantom: PhantomData,
}
}
fn check(&self) -> bool {
self.cond.get()
}
}
#[cfg(test)]
mod test {
use crate::{
Circuit, RootCircuit, Stream,
circuit::{
circuit_builder::IterativeCircuit,
schedule::{DynamicScheduler, Scheduler},
},
monitor::TraceMonitor,
operator::{DelayedFeedback, Generator},
typed_batch::{OrdIndexedZSet, OrdZSet},
utils::Tup2,
zset,
};
#[test]
fn iterate_with_conditions_dynamic() {
iterate_with_conditions::<DynamicScheduler>();
}
fn iterate_with_conditions<S>()
where
S: Scheduler + 'static,
{
let circuit = RootCircuit::build_with_scheduler::<_, _, S>(|circuit| {
TraceMonitor::new_panic_on_error().attach(circuit, "monitor");
// Graph edges
let edges = circuit.add_source(Generator::new(move || {
zset! {
Tup2(0, 3) => 1,
Tup2(1, 2) => 1,
Tup2(2, 1) => 1,
Tup2(3, 1) => 1,
Tup2(3, 4) => 1,
Tup2(4, 5) => 1,
Tup2(4, 6) => 1,
Tup2(5, 6) => 1,
Tup2(5, 1) => 1,
}
}));
// Two sets of initial states. The inner circuit computes sets of nodes
// reachable from each of these initial sets.
let init1 = circuit.add_source(Generator::new(|| zset! { 1 => 1, 2 => 1, 3 => 1 }));
let init2 = circuit.add_source(Generator::new(|| zset! { 4 => 1 }));
let (reachable1, reachable2) = circuit
.iterate_with_conditions_and_scheduler::<_, _, S>(|child| {
let edges = edges.delta0(child).integrate();
let init1 = init1.delta0(child).integrate();
let init2 = init2.delta0(child).integrate();
let edges_indexed: Stream<_, OrdIndexedZSet<u64, u64>> =
edges.map_index(|Tup2(k, v)| (*k, *v));
// Builds a subcircuit that computes nodes reachable from `init`:
//
// ```
// init
// ────────────► + ─────┐
// ▲ │
// │ │
// ┌─────┘ distinct
// │ │
// suc ◄─── z ◄──┘
// │
// └───────────►
// ```
//
// where suc computes the set of successor nodes.
let reachable_circuit =
|init: Stream<IterativeCircuit<RootCircuit>, OrdZSet<u64>>| {
let feedback = <DelayedFeedback<_, OrdZSet<u64>>>::new(child);
let feedback_pairs: Stream<_, OrdZSet<(u64, ())>> =
feedback.stream().map(|&node| (node, ()));
let feedback_indexed: Stream<_, OrdIndexedZSet<u64, ()>> =
feedback_pairs.map_index(|(k, v)| (*k, *v));
let suc =
feedback_indexed.stream_join(&edges_indexed, |_node, &(), &to| to);
let reachable = init.plus(&suc).stream_distinct();
feedback.connect(&reachable);
let condition = reachable.differentiate().condition(|z| z.is_empty());
(condition, reachable.export())
};
let (condition1, export1) = reachable_circuit(init1);
let (condition2, export2) = reachable_circuit(init2);
Ok((vec![condition1, condition2], (export1, export2)))
})
.unwrap();
reachable1.inspect(|r| {
assert_eq!(r, &zset! { 1 => 1, 2 => 1, 3 => 1, 4 => 1, 5 => 1, 6 => 1})
});
reachable2.inspect(|r| assert_eq!(r, &zset! { 1 => 1, 2 => 1, 4 => 1, 5 => 1, 6 => 1}));
Ok(())
})
.unwrap()
.0;
for _ in 0..3 {
circuit.transaction().unwrap();
}
}
}