differential_dataflow/operators/
iterate.rs

1//! Iterative application of a differential dataflow fragment.
2//!
3//! The `iterate` operator takes as an argument a closure from a differential dataflow collection
4//! to a collection of the same type. The output collection is the result of applying this closure
5//! an unbounded number of times.
6//!
7//! The implementation of `iterate` does not directly apply the closure, but rather establishes an
8//! iterative timely dataflow subcomputation, in which differences circulate until they dissipate
9//! (indicating that the computation has reached fixed point), or until some number of iterations
10//! have passed.
11//!
12//! **Note**: The dataflow assembled by `iterate` does not automatically insert `consolidate` for
13//! you. This means that either (i) you should insert one yourself, (ii) you should be certain that
14//! all paths from the input to the output of the loop involve consolidation, or (iii) you should
15//! be worried that logically cancelable differences may circulate indefinitely.
16//!
17//! # Details
18//!
19//! The `iterate` method is written using a `Variable`, which lets you define your own iterative
20//! computations when `iterate` itself is not sufficient. This can happen when you have two
21//! collections that should evolve simultaneously, or when you would like to rotate your loop and
22//! return an intermediate result.
23//!
24//! Using `Variable` requires more explicit arrangement of your computation, but isn't much more
25//! complicated. You must define a new variable from an existing stream (its initial value), and
26//! then set it to be a function of this variable (and perhaps other collections and variables).
27//!
28//! A `Variable` dereferences to a `Collection`, the one corresponding to its value in each iteration,
29//! and it can be used in most situations where a collection can be used. The act of setting a
30//! `Variable` consumes it and returns the corresponding `Collection`, preventing you from setting
31//! it multiple times.
32
33use std::fmt::Debug;
34use std::ops::Deref;
35
36use timely::Container;
37use timely::progress::Timestamp;
38use timely::order::Product;
39
40use timely::dataflow::*;
41use timely::dataflow::scopes::child::Iterative;
42use timely::dataflow::operators::{Feedback, ConnectLoop};
43use timely::dataflow::operators::feedback::Handle;
44
45use crate::{Data, VecCollection, Collection};
46use crate::difference::{Semigroup, Abelian};
47use crate::lattice::Lattice;
48
49/// An extension trait for the `iterate` method.
50pub trait Iterate<G: Scope<Timestamp: Lattice>, D: Data, R: Semigroup> {
51    /// Iteratively apply `logic` to the source collection until convergence.
52    ///
53    /// Importantly, this method does not automatically consolidate results.
54    /// It may be important to conclude with `consolidate()` to ensure that
55    /// logically empty collections that contain cancelling records do not
56    /// result in non-termination. Operators like `reduce`, `distinct`, and
57    /// `count` also perform consolidation, and are safe to conclude with.
58    ///
59    /// # Examples
60    ///
61    /// ```
62    /// use differential_dataflow::input::Input;
63    /// use differential_dataflow::operators::Iterate;
64    ///
65    /// ::timely::example(|scope| {
66    ///
67    ///     scope.new_collection_from(1 .. 10u32).1
68    ///          .iterate(|values| {
69    ///              values.map(|x| if x % 2 == 0 { x/2 } else { x })
70    ///                    .consolidate()
71    ///          });
72    /// });
73    /// ```
74    fn iterate<F>(&self, logic: F) -> VecCollection<G, D, R>
75    where
76        for<'a> F: FnOnce(&VecCollection<Iterative<'a, G, u64>, D, R>)->VecCollection<Iterative<'a, G, u64>, D, R>;
77}
78
79impl<G: Scope<Timestamp: Lattice>, D: Ord+Data+Debug, R: Abelian+'static> Iterate<G, D, R> for VecCollection<G, D, R> {
80    fn iterate<F>(&self, logic: F) -> VecCollection<G, D, R>
81    where
82        for<'a> F: FnOnce(&VecCollection<Iterative<'a, G, u64>, D, R>)->VecCollection<Iterative<'a, G, u64>, D, R>,
83    {
84        self.inner.scope().scoped("Iterate", |subgraph| {
85            // create a new variable, apply logic, bind variable, return.
86            //
87            // this could be much more succinct if we returned the collection
88            // wrapped by `variable`, but it also results in substantially more
89            // diffs produced; `result` is post-consolidation, and means fewer
90            // records are yielded out of the loop.
91            let variable = Variable::new_from(self.enter(subgraph), Product::new(Default::default(), 1));
92            let result = logic(&variable);
93            variable.set(&result);
94            result.leave()
95        })
96    }
97}
98
99impl<G: Scope<Timestamp: Lattice>, D: Ord+Data+Debug, R: Semigroup+'static> Iterate<G, D, R> for G {
100    fn iterate<F>(&self, logic: F) -> VecCollection<G, D, R>
101    where
102        for<'a> F: FnOnce(&VecCollection<Iterative<'a, G, u64>, D, R>)->VecCollection<Iterative<'a, G, u64>, D, R>,
103    {
104        // TODO: This makes me think we have the wrong ownership pattern here.
105        let mut clone = self.clone();
106        clone
107            .scoped("Iterate", |subgraph| {
108                // create a new variable, apply logic, bind variable, return.
109                //
110                // this could be much more succinct if we returned the collection
111                // wrapped by `variable`, but it also results in substantially more
112                // diffs produced; `result` is post-consolidation, and means fewer
113                // records are yielded out of the loop.
114                let variable = SemigroupVariable::new(subgraph, Product::new(Default::default(), 1));
115                let result = logic(&variable);
116                variable.set(&result);
117                result.leave()
118            }
119        )
120    }
121}
122
123/// A recursively defined collection.
124///
125/// The `Variable` struct allows differential dataflow programs requiring more sophisticated
126/// iterative patterns than singly recursive iteration. For example: in mutual recursion two
127/// collections evolve simultaneously.
128///
129/// # Examples
130///
131/// The following example is equivalent to the example for the `Iterate` trait.
132///
133/// ```
134/// use timely::order::Product;
135/// use timely::dataflow::Scope;
136///
137/// use differential_dataflow::input::Input;
138/// use differential_dataflow::operators::iterate::Variable;
139///
140/// ::timely::example(|scope| {
141///
142///     let numbers = scope.new_collection_from(1 .. 10u32).1;
143///
144///     scope.iterative::<u64,_,_>(|nested| {
145///         let summary = Product::new(Default::default(), 1);
146///         let variable = Variable::new_from(numbers.enter(nested), summary);
147///         let result = variable.map(|x| if x % 2 == 0 { x/2 } else { x })
148///                              .consolidate();
149///         variable.set(&result)
150///                 .leave()
151///     });
152/// })
153/// ```
154pub struct Variable<G, C>
155where
156    G: Scope<Timestamp: Lattice>,
157    C: Container,
158{
159    collection: Collection<G, C>,
160    feedback: Handle<G, C>,
161    source: Option<Collection<G, C>>,
162    step: <G::Timestamp as Timestamp>::Summary,
163}
164
165/// A `Variable` specialized to a vector container of update triples (data, time, diff).
166pub type VecVariable<G, D, R> = Variable<G, Vec<(D, <G as ScopeParent>::Timestamp, R)>>;
167
168impl<G, C: Container> Variable<G, C>
169where
170    G: Scope<Timestamp: Lattice>,
171    C: crate::collection::containers::Negate + crate::collection::containers::ResultsIn<<G::Timestamp as Timestamp>::Summary>,
172{
173    /// Creates a new initially empty `Variable`.
174    ///
175    /// This method produces a simpler dataflow graph than `new_from`, and should
176    /// be used whenever the variable has an empty input.
177    pub fn new(scope: &mut G, step: <G::Timestamp as Timestamp>::Summary) -> Self {
178        let (feedback, updates) = scope.feedback(step.clone());
179        let collection = Collection::<G, C>::new(updates);
180        Self { collection, feedback, source: None, step }
181    }
182
183    /// Creates a new `Variable` from a supplied `source` stream.
184    pub fn new_from(source: Collection<G, C>, step: <G::Timestamp as Timestamp>::Summary) -> Self {
185        let (feedback, updates) = source.inner.scope().feedback(step.clone());
186        let collection = Collection::<G, C>::new(updates).concat(&source);
187        Variable { collection, feedback, source: Some(source), step }
188    }
189
190    /// Set the definition of the `Variable` to a collection.
191    ///
192    /// This method binds the `Variable` to be equal to the supplied collection,
193    /// which may be recursively defined in terms of the variable itself.
194    pub fn set(self, result: &Collection<G, C>) -> Collection<G, C> {
195        let mut in_result = result.clone();
196        if let Some(source) = &self.source {
197            in_result = in_result.concat(&source.negate());
198        }
199        self.set_concat(&in_result)
200    }
201
202    /// Set the definition of the `Variable` to a collection concatenated to `self`.
203    ///
204    /// This method is a specialization of `set` which has the effect of concatenating
205    /// `result` and `self` before calling `set`. This method avoids some dataflow
206    /// complexity related to retracting the initial input, and will do less work in
207    /// that case.
208    ///
209    /// This behavior can also be achieved by using `new` to create an empty initial
210    /// collection, and then using `self.set(self.concat(result))`.
211    pub fn set_concat(self, result: &Collection<G, C>) -> Collection<G, C> {
212        let step = self.step;
213        result
214            .results_in(step)
215            .inner
216            .connect_loop(self.feedback);
217
218        self.collection
219    }
220}
221
222impl<G: Scope<Timestamp: Lattice>, C: Container> Deref for Variable<G, C> {
223    type Target = Collection<G, C>;
224    fn deref(&self) -> &Self::Target {
225        &self.collection
226    }
227}
228
229/// A recursively defined collection that only "grows".
230///
231/// `SemigroupVariable` is a weakening of `Variable` to allow difference types
232/// that do not implement `Abelian` and only implement `Semigroup`. This means
233/// that it can be used in settings where the difference type does not support
234/// negation.
235pub struct SemigroupVariable<G, C>
236where
237    G: Scope<Timestamp: Lattice>,
238    C: Container,
239{
240    collection: Collection<G, C>,
241    feedback: Handle<G, C>,
242    step: <G::Timestamp as Timestamp>::Summary,
243}
244
245impl<G, C: Container> SemigroupVariable<G, C>
246where
247    G: Scope<Timestamp: Lattice>,
248    C: crate::collection::containers::ResultsIn<<G::Timestamp as Timestamp>::Summary>,
249{
250    /// Creates a new initially empty `SemigroupVariable`.
251    pub fn new(scope: &mut G, step: <G::Timestamp as Timestamp>::Summary) -> Self {
252        let (feedback, updates) = scope.feedback(step.clone());
253        let collection = Collection::<G,C>::new(updates);
254        SemigroupVariable { collection, feedback, step }
255    }
256
257    /// Adds a new source of data to `self`.
258    pub fn set(self, result: &Collection<G, C>) -> Collection<G, C> {
259        let step = self.step;
260        result
261            .results_in(step)
262            .inner
263            .connect_loop(self.feedback);
264
265        self.collection
266    }
267}
268
269impl<G: Scope, C: Container> Deref for SemigroupVariable<G, C> where G::Timestamp: Lattice {
270    type Target = Collection<G, C>;
271    fn deref(&self) -> &Self::Target {
272        &self.collection
273    }
274}