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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
/// A directed graph implementation with interleave op node and data node
/// and all the edges are data node.

use std::collections::{BTreeMap, BTreeSet};

/// Graph
pub struct Graph<TData, TOp> {
    data: BTreeSet<TData>,
    op: BTreeSet<TOp>,
    forward_dt_op: BTreeMap<TData, BTreeSet<TOp>>,
    forward_op_dt: BTreeMap<TOp, BTreeSet<TData>>,
    backward_dt_op: BTreeMap<TData, BTreeSet<TOp>>,
    backward_op_dt: BTreeMap<TOp, BTreeSet<TData>>,
}

impl<TData: Clone + Copy + Ord, TOp: Clone + Copy + Ord> Default for Graph<TData, TOp> {
    fn default() -> Graph<TData, TOp> {
        Graph{
            data: BTreeSet::new(),
            op: BTreeSet::new(),
            forward_dt_op: BTreeMap::new(),
            forward_op_dt: BTreeMap::new(),
            backward_dt_op: BTreeMap::new(),
            backward_op_dt: BTreeMap::new(),
        }
    }
}

impl<TData: Clone + Copy + Ord, TOp: Clone + Copy + Ord> Graph<TData, TOp> {
    /// Create a graph with defaults
    pub fn new() -> Graph<TData, TOp> {
        Graph{
            data: BTreeSet::new(),
            op: BTreeSet::new(),
            forward_dt_op: BTreeMap::new(),
            forward_op_dt: BTreeMap::new(),
            backward_dt_op: BTreeMap::new(),
            backward_op_dt: BTreeMap::new(),
        }
    }

    /// iterator over data node.
    pub fn iter_data(&self) -> NodeIterator<TData> {
        NodeIterator {
            iter: self.data.iter()
        }
    }
    /// iterator over op node.
    pub fn iter_op(&self) -> NodeIterator<TOp> {
        NodeIterator {
            iter: self.op.iter()
        }
    }

    ///
    /// Return the list of ops that the given variable is the input of the func.
    ///
    pub fn iter_op_given_input(&self, var: &TData) -> Result<NodeIterator<TOp>, &str> {
        if !self.data.contains(var) {
            Err("Not a valid variable/data")
        } else {
            Ok(NodeIterator {
                iter: self.forward_dt_op.get(var).expect("").iter()
            })
        }
    }

    ///
    /// Return the list of ops that the given variable is the output.
    ///
    pub fn iter_op_given_output(&self, var: &TData) -> Result<NodeIterator<TOp>, &str> {
        if !self.data.contains(var) {
            Err("Not a valid variable/data")
        } else {
            Ok(NodeIterator {
                iter: self.backward_dt_op.get(var).expect("").iter()
            })
        }
    }

    ///
    /// Return the list of input given the func.
    ///
    pub fn iter_input_given_op(&self, func: &TOp) -> Result<NodeIterator<TData>, &str> {
        if !self.op.contains(func) {
            Err("Bad func id.")
        } else {
            Ok(NodeIterator {
                iter: self.backward_op_dt.get(func).expect("").iter()
            })
        }
    }

    ///
    /// Return a list of data as the output of the op.
    ///
    pub fn iter_output_given_op(&self, func: &TOp) -> Result<NodeIterator<TData>, &str> {
        if !self.op.contains(func) {
            Err("Bad func id.")
        } else {
            Ok(NodeIterator {
                iter: self.forward_op_dt.get(func).expect("").iter()
            })
        }
    }

    /// Add a data node.
    /// ```
    /// # use auto_diff::collection::graph::*;
    /// # use auto_diff::collection::generational_index::*;
    /// let mut g = Graph::<NetIndex, NetIndex>::new();
    /// let data1 = NetIndex::new(0,0);
    /// let data2 = NetIndex::new(1,0);
    /// g.add_data(&data1);
    /// g.add_data(&data2);
    /// ```
    pub fn add_data(&mut self, id: &TData) -> Result<TData, &str> {
        if !self.data.contains(id) {
            self.data.insert(*id);
            self.forward_dt_op.insert(*id, BTreeSet::new());
            self.backward_dt_op.insert(*id, BTreeSet::new());
            Ok(*id)
        } else {
            Err("data is exits!")
        }
    }

    /// Remove a data node, op node and downstream data/op node are removed.
    pub fn drop_data(&mut self, id: &TData) -> Result<TData, &str> {
        if self.data.contains(id) {
            self.data.remove(id);
            for i in self.forward_dt_op.get_mut(id).expect("").iter() {
                self.backward_op_dt.get_mut(i).expect("").remove(id);
            }
            self.forward_dt_op.remove(id);
            for i in self.backward_dt_op.get_mut(id).expect("").iter() {
                self.forward_op_dt.get_mut(i).expect("").remove(id);
            }
            self.backward_dt_op.remove(id);

            Ok(*id)
        } else {
            Err("data id is not found!")
        }
    }

    /// Add a danglging op node.
    pub fn add_op(&mut self, id: &TOp) -> Result<TOp, &str> {
        if !self.op.contains(id) {
            self.op.insert(*id);
            self.forward_op_dt.insert(id.clone(), BTreeSet::new());
            self.backward_op_dt.insert(id.clone(), BTreeSet::new());
            Ok(*id)
        } else {
            Err("op id exists.")
        }
    }

    /// Remvoe an op node, input data node and downstream data/op node are removed.
    pub fn drop_op(&mut self, id: &TOp) -> Result<TOp, &str> {
        if self.op.contains(id) {
            self.op.remove(id);
            for i in self.forward_op_dt.get_mut(id).expect("").iter() {
                self.backward_dt_op.get_mut(i).expect("").remove(id);
            }
            self.forward_op_dt.remove(id);
            for i in self.backward_op_dt.get_mut(id).expect("").iter() {
                self.forward_dt_op.get_mut(i).expect("").remove(id);
            }
            self.backward_op_dt.remove(id);
            Ok(*id)
        } else {
            Err("op id is not found!")
        }

    }

    ///
    /// Decouple input variable and op
    ///
    pub fn decouple_data_func(&mut self, var: &TData, func: &TOp) -> Result<(), ()> {
        if self.data.contains(var) && self.op.contains(func) {
            self.forward_dt_op.get_mut(var).expect("").remove(func);
            self.backward_op_dt.get_mut(func).expect("").remove(var);
            Ok(())
        } else {
            Err(())
        }
    }

    ///
    /// Decouple op and output variable
    ///
    pub fn decouple_func_data(&mut self, func: &TOp, var: &TData) -> Result<(), ()> {
        if self.data.contains(var) && self.op.contains(func) {
            self.forward_op_dt.get_mut(func).expect("").remove(var);
            self.backward_dt_op.get_mut(var).expect("").remove(func);
            Ok(())
        } else {
            Err(())
        }
    }

    /// list data node without upstream op node in a set.
    pub fn get_input_edge_data(&self) -> BTreeSet<TData> {
        let mut jobs = BTreeSet::new();
        for i in &self.data {
            if self.backward_dt_op.get(i).expect("").is_empty() {
                jobs.insert(*i);
            }
        }
        jobs
    }

    /// list data node without downstream op node in a set.
    pub fn get_output_edge_data(&self) -> BTreeSet<TData> {
        let mut jobs = BTreeSet::new();
        for i in &self.data {
            if self.forward_dt_op.get(i).expect("").is_empty() {
                jobs.insert(*i);
            }
        }
        jobs
    }

    /// Connect input data, output data and operation
    pub fn connect(&mut self, dti: &[TData],
                   dto: &[TData],
                   op: &TOp) -> Result<TOp, &str> {
        let mut valid_ids = true;

        // make sure pre-exist
        if !self.op.contains(op) {
            valid_ids = false;
        }
        // make sure input data pre-exist
        for i in dti {
            if !self.data.contains(i) {
                valid_ids = false;
            }
        }
        // make sure output data pre-exist
        for i in dto {
            if !self.data.contains(i) {
                valid_ids = false;
            }
        }
        
        if valid_ids {
            for i in dti {
                self.forward_dt_op.get_mut(i).expect("").insert(*op);
                self.backward_op_dt.get_mut(op).expect("").insert(*i);
            }
            for i in dto {
                self.forward_op_dt.get_mut(op).expect("").insert(*i);
                self.backward_dt_op.get_mut(i).expect("").insert(*op);
            }
            Ok(*op)
        } else {
            Err("Invalid id!")
        }
    }

    /// Auxilary connect, This allows the graph to support loop.
    pub fn connect_aux(&mut self, input_data: &[TData],
                       output_data: &[TData],
                       op: &TOp) -> Result<TOp, &str> {
        if !self.op.contains(op) ||
            input_data.iter().any(|x| !self.data.contains(x)) ||
            output_data.iter().any(|x| !self.data.contains(x)) {
                return Err("Invalid id!");
            }
        unimplemented!();
        //return Ok(*op);
    }

    ///
    /// Walk through the graph with a starting set of data nodes.
    /// Go through backwards if forward is false.
    /// The closure call provides the side-effect.
    ///
    pub fn walk<F>(&self, start_set: &[TData],
                   forward: bool,
                   closure: F) -> Result<(), BTreeSet<TData>>
    where F: Fn(&[TData], &[TData], &TOp)  {
        let mut fdo = &self.forward_dt_op;
        let mut fod = &self.forward_op_dt;
        //let mut bdo = &self.backward_dt_op;
        let mut bod = &self.backward_op_dt;
        if !forward {
            fdo = &self.backward_dt_op;
            fod = &self.backward_op_dt;
            //bdo = &self.forward_dt_op;
            bod = &self.forward_op_dt;
        }

        // data id has a value
        let mut jobs = BTreeSet::<TData>::new();
        // op is done.
        let mut done = BTreeSet::<TOp>::new(); // ops done.

        for index in start_set {
            jobs.insert(*index);
        }
        
        loop {
            let mut made_progress = false;

            // collect ops needs to do given the data in jobs.
            let mut edge_op = BTreeSet::<TOp>::new();
            for dt in &jobs {
                for op_candidate in &fdo[dt] {
                    edge_op.insert(*op_candidate);
                }
            }

            // process op if possible
            for op_candidate in edge_op {
                if bod[&op_candidate]
                    .iter()
                    .all(|dt| jobs.contains(dt)) {

                        // collect input ids.
                        let mut inputs = Vec::<TData>::new();
                        for input in bod[&op_candidate].iter() {
                            inputs.push(*input);
                        }
                        // collect output ids.
                        let mut outputs = Vec::<TData>::new();
                        for output in fod[&op_candidate].iter() {
                            outputs.push(*output);
                        }

                        // all the closure
                        closure(&inputs, &outputs, &op_candidate);

                        // maintain the list
                        // the following line should go before the rest.
                        done.insert(op_candidate);
                        // remove the data from jobs if all its downstream op is done.
                        for input in bod[&op_candidate].iter() {
                            if fdo[input]
                                .iter()
                                .all(|op| done.contains(op)) {
                                    jobs.remove(input);
                                }
                        }
                        // add the output back to the jobs.
                        for output in fod[&op_candidate].iter() {
                            // don't add to jobs if it's the final data node.
                            if !fdo[output].is_empty() {
                                jobs.insert(*output);                                
                            }
                        }

                        // flag there is sth done.
                        made_progress = true;
                    }
            }

            if ! made_progress {
                break;
            }
        }

        if !jobs.is_empty() {
            Err(jobs)
        } else {
            Ok(())
        }
    }

    /////
    ///// Walk through the graph with a starting set of data nodes.
    ///// Go through backwards if forward is false.
    /////
    //pub fn walk_dyn(&self, start_set: &[TData],
    //               forward: bool,
    //                closure: dyn Calling) -> Result<(), BTreeSet<TData>> {
    //    Ok(())
    //}

    /// Move all the graph/network structure to this graph,
    /// with the boundary for both the this and other graph are specified.
    pub fn append(&self, other: &mut Self,
                  boundary: &[TData], other_boundary: &[TData],
    ) -> Result<(), &str> {
        if boundary.len() != other_boundary.len() {
            return Err("The boundary size should be equal for append two network.");
        }
        if other.iter_op().any(|x| self.op.contains(x)) {
            return Err("The op id cannot be overlap.");
        }
        if other.iter_data().any(|x| self.data.contains(x)
                                 && self.get_output_edge_data().contains(x) ) {
            return Err("The data id cannot be overlap.");
        }
        
        Ok(())
    }
}

// iterator
pub struct NodeIterator<'a, TNode> {
    iter: std::collections::btree_set::Iter<'a, TNode>,
}
impl<'a, TNode> Iterator for NodeIterator<'a, TNode> {
    type Item = &'a TNode;
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }
}

/////
//pub trait Calling {
//    fn calling<TData, TOp>(self, input: &[TData], output: &[TData], op: &TOp);
//}



#[cfg(test)]
mod tests {
    use super::*;
    use crate::collection::generational_index::{NetIndex};
    
    #[test]
    fn new() {
        let _g = Graph::<NetIndex, NetIndex>::new();
    }

    // A   B
    //  \ /
    //   Op
    //   |
    //   C
    fn setup_y(g: &mut Graph<NetIndex, NetIndex>) {
        let data_a = NetIndex::new(0,0);
        let data_b = NetIndex::new(1,0);
        let data_c = NetIndex::new(2,0);
        g.add_data(&data_a).expect("");
        g.add_data(&data_b).expect("");
        g.add_data(&data_c).expect("");
        
        let op_a = NetIndex::new(0,0);
        g.add_op(&op_a).expect("");

        g.connect(&[data_a, data_b], &[data_c,], &op_a).expect("");
    }

    // A   B
    //  \ /
    //   Op1
    //   |
    //   C   D
    //    \ /
    //     Op2
    //     |
    //     E
    fn setup_yy(g: &mut Graph<NetIndex, NetIndex>) {
        let data_a = NetIndex::new(0,0);
        let data_b = NetIndex::new(1,0);
        let data_c = NetIndex::new(2,0);
        let data_d = NetIndex::new(3,0);
        let data_e = NetIndex::new(4,0);
        g.add_data(&data_a).expect("");
        g.add_data(&data_b).expect("");
        g.add_data(&data_c).expect("");
        g.add_data(&data_d).expect("");
        g.add_data(&data_e).expect("");
        
        let op1 = NetIndex::new(0,0);
        g.add_op(&op1).expect("");
        let op2 = NetIndex::new(1,0);
        g.add_op(&op2).expect("");

        g.connect(&[data_a, data_b], &[data_c,], &op1).expect("");
        g.connect(&[data_c, data_d], &[data_e,], &op2).expect("");
    }

    #[test]
    fn iter() {
        let mut g = Graph::new();
        setup_yy(&mut g);
        
        for i in g.iter_data() {
            println!("{:?}", i);
        }

        for i in g.iter_op() {
            println!("{:?}", i);
        }
    }

    #[test]
    fn test_get_input_cache() {
        let mut g = Graph::new();
        setup_y(&mut g);
        assert_eq!(g.get_input_edge_data().len(), 2);

        let mut g = Graph::<NetIndex, NetIndex>::new();
        setup_yy(&mut g);
        assert_eq!(g.get_input_edge_data().len(), 3);
    }

    #[test]
    fn test_get_output_cache() {
        let mut g = Graph::new();
        setup_y(&mut g);
        assert_eq!(g.get_output_edge_data().len(), 1);

        let mut g = Graph::<NetIndex, NetIndex>::new();
        setup_yy(&mut g);
        assert_eq!(g.get_output_edge_data().len(), 1);
    }
}