differential_dataflow/algorithms/
prefix_sum.rs

1//! Implementation of Parallel Prefix Sum
2
3use timely::dataflow::Scope;
4
5use crate::{Collection, ExchangeData};
6use crate::lattice::Lattice;
7use crate::operators::*;
8
9/// Extension trait for the prefix_sum method.
10pub trait PrefixSum<G: Scope, K, D> {
11    /// Computes the prefix sum for each element in the collection.
12    ///
13    /// The prefix sum is data-parallel, in the sense that the sums are computed independently for
14    /// each key of type `K`. For a single prefix sum this type can be `()`, but this permits the
15    /// more general accumulation of multiple independent sequences.
16    fn prefix_sum<F>(&self, zero: D, combine: F) -> Self where F: Fn(&K,&D,&D)->D + 'static;
17
18    /// Determine the prefix sum at each element of `location`.
19    fn prefix_sum_at<F>(&self, locations: Collection<G, (usize, K)>, zero: D, combine: F) -> Self where F: Fn(&K,&D,&D)->D + 'static;
20}
21
22impl<G, K, D> PrefixSum<G, K, D> for Collection<G, ((usize, K), D)>
23where
24    G: Scope,
25    G::Timestamp: Lattice,
26    K: ExchangeData+::std::hash::Hash,
27    D: ExchangeData+::std::hash::Hash,
28{
29    fn prefix_sum<F>(&self, zero: D, combine: F) -> Self where F: Fn(&K,&D,&D)->D + 'static {
30        self.prefix_sum_at(self.map(|(x,_)| x), zero, combine)
31    }
32
33    fn prefix_sum_at<F>(&self, locations: Collection<G, (usize, K)>, zero: D, combine: F) -> Self where F: Fn(&K,&D,&D)->D + 'static {
34
35        let combine1 = ::std::rc::Rc::new(combine);
36        let combine2 = combine1.clone();
37
38        let ranges = aggregate(self.clone(), move |k,x,y| (*combine1)(k,x,y));        
39        broadcast(ranges, locations, zero, move |k,x,y| (*combine2)(k,x,y))
40    }
41}
42
43/// Accumulate data in `collection` into all powers-of-two intervals containing them.
44pub fn aggregate<G, K, D, F>(collection: Collection<G, ((usize, K), D)>, combine: F) -> Collection<G, ((usize, usize, K), D)>
45where
46    G: Scope,
47    G::Timestamp: Lattice,
48    K: ExchangeData+::std::hash::Hash,
49    D: ExchangeData+::std::hash::Hash,
50    F: Fn(&K,&D,&D)->D + 'static,
51{
52    // initial ranges are at each index, and with width 2^0.
53    let unit_ranges = collection.map(|((index, key), data)| ((index, 0, key), data));
54
55    unit_ranges
56        .iterate(|ranges|
57
58            // Each available range, of size less than usize::max_value(), advertises itself as the range
59            // twice as large, aligned to integer multiples of its size. Each range, which may contain at
60            // most two elements, then summarizes itself using the `combine` function. Finally, we re-add
61            // the initial `unit_ranges` intervals, so that the set of ranges grows monotonically.
62
63            ranges
64                .filter(|&((_pos, log, _), _)| log < 64)
65                .map(|((pos, log, key), data)| ((pos >> 1, log + 1, key), (pos, data)))
66                .reduce(move |&(_pos, _log, ref key), input, output| {
67                    let mut result = (input[0].0).1.clone();
68                    if input.len() > 1 { result = combine(key, &result, &(input[1].0).1); }
69                    output.push((result, 1));
70                })
71                .concat(&unit_ranges.enter(&ranges.scope()))
72        )
73}
74
75/// Produces the accumulated values at each of the `usize` locations in `queries`.
76pub fn broadcast<G, K, D, F>(
77    ranges: Collection<G, ((usize, usize, K), D)>,
78    queries: Collection<G, (usize, K)>,
79    zero: D,
80    combine: F) -> Collection<G, ((usize, K), D)>
81where
82    G: Scope,
83    G::Timestamp: Lattice+Ord+::std::fmt::Debug,
84    K: ExchangeData+::std::hash::Hash,
85    D: ExchangeData+::std::hash::Hash,
86    F: Fn(&K,&D,&D)->D + 'static,
87{
88
89    let zero0 = zero.clone();
90    let zero1 = zero.clone();
91    let zero2 = zero.clone();
92
93    // The `queries` collection may not line up with an existing element of `ranges`, and so we must
94    // track down the first range that matches. If it doesn't exist, we will need to produce a zero
95    // value. We could produce the full path from (0, key) to (idx, key), and aggregate any and all
96    // matches. This has the defect of being n log n rather than linear, as the root ranges will be
97    // replicated for each query.
98    //
99    // I think it works to have each (idx, key) propose each of the intervals it knows should be used
100    // to assemble its input. We then `distinct` these and intersect them with the offered `ranges`,
101    // essentially performing a semijoin. We then perform the unfolding, where we might need to use
102    // empty ranges if none exist in `ranges`.
103
104    // We extract desired ranges for each `idx` from its binary representation: each set bit requires
105    // the contribution of a range, and we call out each of these. This could produce a super-linear
106    // amount of data (multiple requests for the roots), but it will be compacted down in `distinct`.
107    // We could reduce the amount of data by producing the requests iteratively, with a distinct in
108    // the loop to pre-suppress duplicate requests. This comes at a complexity cost, though.
109    let requests =
110        queries
111            .flat_map(|(idx, key)|
112                (0 .. 64)
113                    .filter(move |i| (idx & (1usize << i)) != 0)    // set bits require help.
114                    .map(move |i| ((idx >> i) - 1, i, key.clone())) // width 2^i interval.
115            )
116            .distinct();
117
118    // Acquire each requested range.
119    let full_ranges =
120        ranges
121            .semijoin(&requests);
122
123    // Each requested range should exist, even if as a zero range, for correct reconstruction.
124    let zero_ranges =
125        full_ranges
126            .map(move |((idx, log, key), _)| ((idx, log, key), zero0.clone()))
127            .negate()
128            .concat(&requests.map(move |(idx, log, key)| ((idx, log, key), zero1.clone())));
129
130    // Merge occupied and empty ranges.
131    let used_ranges = full_ranges.concat(&zero_ranges);
132
133    // Each key should initiate a value of `zero` at position `0`.
134    let init_states =
135        queries
136            .map(move |(_, key)| ((0, key), zero2.clone()))
137            .distinct();
138
139    // Iteratively expand assigned values by joining existing ranges with current assignments.
140    init_states
141        .iterate(|states| {
142            used_ranges
143                .enter(&states.scope())
144                .map(|((pos, log, key), data)| ((pos << log, key), (log, data)))
145                .join_map(states, move |&(pos, ref key), &(log, ref data), state|
146                    ((pos + (1 << log), key.clone()), combine(key, state, data)))
147                .concat(&init_states.enter(&states.scope()))
148                .distinct()
149        })
150        .semijoin(&queries)
151}