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
// Copyright (c) 2018 10X Genomics, Inc. All rights reserved.

// Define generic digraph functions.
//
// Some of the functions here are unnecessarily quadratic in the vertex degree for
// petgraph as a result of calling v_from and related functions below.  The
// quadratic behavior might be avoided but might make the code a bit less readable.
//
// These functions seem unnecessarily specialized to u32.

extern crate petgraph;
extern crate vector_utils;

use petgraph::{prelude::*, EdgeType};
use std::collections::HashSet;
use vector_utils::*;

pub trait GraphSimple<T> {
    // =============================================================================
    // Return the object associated to an edge id.
    // =============================================================================

    fn edge_obj(&self, e: u32) -> &T;

    // =============================================================================
    // Return the source or target of an edge.
    // =============================================================================

    fn to_left(&self, e: u32) -> u32;
    fn to_right(&self, e: u32) -> u32;

    // =============================================================================
    // Return the number of edges exiting or entering a given vertex.
    // =============================================================================

    fn n_from(&self, v: usize) -> usize;
    fn n_to(&self, v: usize) -> usize;

    // =============================================================================
    // Return id of the nth vertex exiting or entering a given vertex id.
    // Note that this is O(n).
    // =============================================================================

    fn v_from(&self, v: usize, n: usize) -> usize;
    fn v_to(&self, v: usize, n: usize) -> usize;

    // =============================================================================
    // Return id of the nth edge exiting or entering a given vertex id.
    // Note that this is O(n).
    // =============================================================================

    fn e_from(&self, v: usize, n: usize) -> usize;
    fn e_to(&self, v: usize, n: usize) -> usize;

    // =============================================================================
    // Return the nth edge exiting or entering a given vertex id.
    // Note that this is O(n).
    // =============================================================================

    fn o_from(&self, v: usize, n: usize) -> &T;
    fn o_to(&self, v: usize, n: usize) -> &T;

    // =============================================================================
    // get_predecessors: find all vertices which have a directed path to a vertex
    // in v.  This includes the vertices in v by definition.  Return a sorted list
    // x.  get_successors: go the other way.
    // get_predecessors1 and get_successors1: start from one vertex
    // =============================================================================

    fn get_predecessors(&self, v: &Vec<i32>, x: &mut Vec<u32>);
    fn get_predecessors1(&self, v: i32, x: &mut Vec<u32>);
    fn get_successors(&self, v: &Vec<i32>, x: &mut Vec<u32>);
    fn get_successors1(&self, v: i32, x: &mut Vec<u32>);

    // =============================================================================
    // Determine if there is a path from one vertex to another, allowing for the
    // case of a zero length path, where the vertices are equal.
    // =============================================================================

    fn have_path(&self, v: i32, w: i32) -> bool;

    // =============================================================================
    // Find the connected components.  Each component is a sorted list of vertices.
    // =============================================================================

    fn components(&self, comp: &mut Vec<Vec<u32>>);

    // =============================================================================
    // Find the connected components as lists of edges.  Each component is an
    // UNSORTED list of edges.
    // =============================================================================

    fn components_e(&self, comp: &mut Vec<Vec<u32>>);

    // =============================================================================
    // Find the connected components as lists of edges, sorted within each component
    // to try to follow the order of the graph.  This is slow and suboptimal.
    // =============================================================================

    fn components_e_pos_sorted(&self, comp: &mut Vec<Vec<u32>>);
}

impl<S, T, U, V> GraphSimple<T> for Graph<S, T, U, V>
where
    U: EdgeType,
    V: petgraph::csr::IndexType,
{
    fn edge_obj(&self, e: u32) -> &T {
        &self[EdgeIndex::<V>::new(e as usize)]
    }

    fn to_left(&self, e: u32) -> u32 {
        self.edge_endpoints(EdgeIndex::<V>::new(e as usize))
            .unwrap()
            .0
            .index() as u32
    }

    fn to_right(&self, e: u32) -> u32 {
        self.edge_endpoints(EdgeIndex::<V>::new(e as usize))
            .unwrap()
            .1
            .index() as u32
    }

    fn n_from(&self, v: usize) -> usize {
        self.neighbors(NodeIndex::<V>::new(v)).count()
    }

    fn n_to(&self, v: usize) -> usize {
        self.neighbors_directed(NodeIndex::<V>::new(v), Incoming)
            .count()
    }

    fn v_from(&self, v: usize, n: usize) -> usize {
        self.edges_directed(NodeIndex::<V>::new(v), Outgoing)
            .nth(n)
            .unwrap()
            .target()
            .index()
    }

    fn v_to(&self, v: usize, n: usize) -> usize {
        self.edges_directed(NodeIndex::<V>::new(v), Incoming)
            .nth(n)
            .unwrap()
            .source()
            .index()
    }

    fn e_from(&self, v: usize, n: usize) -> usize {
        let mut e: EdgeIndex<V> = self.first_edge(NodeIndex::<V>::new(v), Outgoing).unwrap();
        for _j in 0..n {
            let f = self.next_edge(e, Outgoing).unwrap();
            e = f;
        }
        e.index()
    }

    fn e_to(&self, v: usize, n: usize) -> usize {
        let mut e: EdgeIndex<V> = self.first_edge(NodeIndex::<V>::new(v), Incoming).unwrap();
        for _j in 0..n {
            let f = self.next_edge(e, Incoming).unwrap();
            e = f;
        }
        e.index()
    }

    fn o_from(&self, v: usize, n: usize) -> &T {
        self.edge_obj(self.e_from(v, n) as u32)
    }

    fn o_to(&self, v: usize, n: usize) -> &T {
        self.edge_obj(self.e_to(v, n) as u32)
    }

    fn get_predecessors(&self, v: &Vec<i32>, x: &mut Vec<u32>) {
        let mut check: Vec<u32> = Vec::new();
        let mut tov: HashSet<u32> = HashSet::new();
        for j in 0..v.len() {
            let s: u32 = v[j] as u32;
            check.push(s);
            tov.insert(s);
        }
        while !check.is_empty() {
            let x = check.pop().unwrap();
            let n = self.n_to(x as usize);
            for i in 0..n {
                let y = self.v_to(x as usize, i);
                if tov.contains(&(y as u32)) {
                    continue;
                }
                check.push(y as u32);
                tov.insert(y as u32);
            }
        }
        x.clear();
        for v in tov {
            x.push(v);
        }
        x.sort();
    }

    fn get_predecessors1(&self, v: i32, x: &mut Vec<u32>) {
        let vs = vec![v];
        self.get_predecessors(&vs, x);
    }

    fn get_successors(&self, v: &Vec<i32>, x: &mut Vec<u32>) {
        let mut check: Vec<u32> = Vec::new();
        let mut fromv: HashSet<u32> = HashSet::new();
        for j in 0..v.len() {
            let s: u32 = v[j] as u32;
            check.push(s);
            fromv.insert(s);
        }
        while !check.is_empty() {
            let x = check.pop().unwrap();
            let n = self.n_from(x as usize);
            for i in 0..n {
                let y = self.v_from(x as usize, i);
                if fromv.contains(&(y as u32)) {
                    continue;
                }
                check.push(y as u32);
                fromv.insert(y as u32);
            }
        }
        x.clear();
        for v in fromv {
            x.push(v);
        }
        x.sort();
    }

    fn get_successors1(&self, v: i32, x: &mut Vec<u32>) {
        let vs = vec![v];
        self.get_successors(&vs, x);
    }

    fn have_path(&self, v: i32, w: i32) -> bool {
        let mut vsuc: Vec<u32> = Vec::new();
        self.get_successors1(v, &mut vsuc);
        let mut wpre: Vec<u32> = Vec::new();
        self.get_predecessors1(w, &mut wpre);
        meet(&vsuc, &wpre)
    }

    fn components(&self, comp: &mut Vec<Vec<u32>>) {
        comp.clear();
        let mut used: Vec<bool> = vec![false; self.node_count()];
        let mut c: Vec<u32> = Vec::new();
        let mut cnext: Vec<u32> = Vec::new();
        for v in 0..self.node_count() {
            if used[v] {
                continue;
            }
            c.clear();
            cnext.clear();
            cnext.push(v as u32);
            while cnext.len() > 0 {
                let w = cnext.pop().unwrap();
                if used[w as usize] {
                    continue;
                }
                used[w as usize] = true;
                c.push(w);
                let n = self.n_from(w as usize);
                for j in 0..n {
                    cnext.push(self.v_from(w as usize, j) as u32);
                }
                let n = self.n_to(w as usize);
                for j in 0..n {
                    cnext.push(self.v_to(w as usize, j) as u32);
                }
            }
            c.sort();
            comp.push(c.clone());
        }
    }

    fn components_e(&self, comp: &mut Vec<Vec<u32>>) {
        self.components(comp);
        for j in 0..comp.len() {
            let mut c = Vec::<u32>::new();
            for i in 0..comp[j].len() {
                let v = comp[j][i];
                let n = self.n_from(v as usize);
                for l in 0..n {
                    c.push(self.e_from(v as usize, l) as u32);
                }
            }
            comp[j] = c;
        }
    }

    fn components_e_pos_sorted(&self, comp: &mut Vec<Vec<u32>>) {
        self.components_e(comp);
        for u in 0..comp.len() {
            comp[u].sort_by(|a, b| {
                if a == b {
                    return std::cmp::Ordering::Equal;
                }
                let v = self.to_right(*a);
                let w = self.to_left(*b);
                if self.have_path(v as i32, w as i32) {
                    return std::cmp::Ordering::Less;
                }
                let v = self.to_right(*b);
                let w = self.to_left(*a);
                if self.have_path(v as i32, w as i32) {
                    return std::cmp::Ordering::Greater;
                }
                std::cmp::Ordering::Equal
            });
        }
    }
}