summaryrefslogtreecommitdiff
path: root/boost/graph/detail/compressed_sparse_row_struct.hpp
blob: 6e7b60d74b505cea1b47f67a885518559d91e5ca (plain)
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
// Copyright 2005-2009 The Trustees of Indiana University.

// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  Authors: Jeremiah Willcock
//           Douglas Gregor
//           Andrew Lumsdaine

// Compressed sparse row graph type internal structure

#ifndef BOOST_GRAPH_COMPRESSED_SPARSE_ROW_STRUCT_HPP
#define BOOST_GRAPH_COMPRESSED_SPARSE_ROW_STRUCT_HPP

#ifndef BOOST_GRAPH_COMPRESSED_SPARSE_ROW_GRAPH_HPP
#error This file should only be included from boost/graph/compressed_sparse_row_graph.hpp
#endif

#include <vector>
#include <utility>
#include <algorithm>
#include <climits>
#include <boost/assert.hpp>
#include <iterator>
#if 0
#include <iostream> // For some debugging code below
#endif
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/properties.hpp>
#include <boost/graph/filtered_graph.hpp> // For keep_all
#include <boost/graph/detail/indexed_properties.hpp>
#include <boost/graph/detail/histogram_sort.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <boost/iterator/counting_iterator.hpp>
#include <boost/iterator/reverse_iterator.hpp>
#include <boost/iterator/zip_iterator.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/integer.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/mpl/if.hpp>
#include <boost/graph/graph_selectors.hpp>
#include <boost/static_assert.hpp>
#include <boost/functional/hash.hpp>

namespace boost {

namespace detail {
  // Forward declaration of CSR edge descriptor type, needed to pass to
  // indexed_edge_properties.
  template<typename Vertex, typename EdgeIndex>
  class csr_edge_descriptor;

  // Add edge_index property map
  template<typename Vertex, typename EdgeIndex>
  struct csr_edge_index_map
  {
    typedef EdgeIndex                 value_type;
    typedef EdgeIndex                 reference;
    typedef csr_edge_descriptor<Vertex, EdgeIndex> key_type;
    typedef readable_property_map_tag category;
  };

  template<typename Vertex, typename EdgeIndex>
  inline EdgeIndex
  get(const csr_edge_index_map<Vertex, EdgeIndex>&,
      const csr_edge_descriptor<Vertex, EdgeIndex>& key)
  {
    return key.idx;
  }

  /** Compressed sparse row graph internal structure.
   *
   * Vertex and EdgeIndex should be unsigned integral types and should
   * specialize numeric_limits.
   */
  template <typename EdgeProperty,
            typename Vertex = std::size_t, typename EdgeIndex = Vertex>
  class compressed_sparse_row_structure :
    public detail::indexed_edge_properties<
             compressed_sparse_row_structure<EdgeProperty, Vertex, EdgeIndex>,
             EdgeProperty,
             csr_edge_descriptor<Vertex, EdgeIndex>,
             csr_edge_index_map<Vertex, EdgeIndex> > {
    public:
    typedef detail::indexed_edge_properties<
              compressed_sparse_row_structure<EdgeProperty, Vertex, EdgeIndex>,
              EdgeProperty,
              csr_edge_descriptor<Vertex, EdgeIndex>,
              csr_edge_index_map<Vertex, EdgeIndex> >
      inherited_edge_properties;

    typedef Vertex vertices_size_type;
    typedef Vertex vertex_descriptor;
    typedef EdgeIndex edges_size_type;

    static vertex_descriptor null_vertex() { return vertex_descriptor(-1); }

    std::vector<EdgeIndex> m_rowstart;
    std::vector<Vertex> m_column;

    compressed_sparse_row_structure(Vertex numverts = 0)
      : m_rowstart(numverts + 1, EdgeIndex(0)), m_column()
      {}
    
    //  Rebuild graph from number of vertices and multi-pass unsorted list of
    //  edges (filtered using source_pred and mapped using global_to_local)
    template <typename MultiPassInputIterator, typename GlobalToLocal, typename SourcePred>
    void
    assign_unsorted_multi_pass_edges(MultiPassInputIterator edge_begin,
                                     MultiPassInputIterator edge_end,
                                     vertices_size_type numlocalverts,
                                     const GlobalToLocal& global_to_local,
                                     const SourcePred& source_pred) {
      m_rowstart.clear();
      m_rowstart.resize(numlocalverts + 1, 0);
      typedef std::pair<vertices_size_type, vertices_size_type> edge_type;
      typedef boost::transform_iterator<boost::graph::detail::project1st<edge_type>, MultiPassInputIterator> source_iterator;
      typedef boost::transform_iterator<boost::graph::detail::project2nd<edge_type>, MultiPassInputIterator> target_iterator;
      source_iterator sources_begin(edge_begin, boost::graph::detail::project1st<edge_type>());
      source_iterator sources_end(edge_end, boost::graph::detail::project1st<edge_type>());
      target_iterator targets_begin(edge_begin, boost::graph::detail::project2nd<edge_type>());
      target_iterator targets_end(edge_end, boost::graph::detail::project2nd<edge_type>());

      boost::graph::detail::count_starts
        (sources_begin, sources_end, m_rowstart.begin(), numlocalverts,
         source_pred, boost::make_property_map_function(global_to_local));

      m_column.resize(m_rowstart.back());
      inherited_edge_properties::resize(m_rowstart.back());

      boost::graph::detail::histogram_sort
        (sources_begin, sources_end, m_rowstart.begin(), numlocalverts,
         targets_begin, m_column.begin(),
         source_pred, boost::make_property_map_function(global_to_local));
    }

    //  Rebuild graph from number of vertices and multi-pass unsorted list of
    //  edges and their properties (filtered using source_pred and mapped using
    //  global_to_local)
    template <typename MultiPassInputIterator, typename EdgePropertyIterator, typename GlobalToLocal, typename SourcePred>
    void
    assign_unsorted_multi_pass_edges(MultiPassInputIterator edge_begin,
                                     MultiPassInputIterator edge_end,
                                     EdgePropertyIterator ep_iter,
                                     vertices_size_type numlocalverts,
                                     const GlobalToLocal& global_to_local,
                                     const SourcePred& source_pred) {
      m_rowstart.clear();
      m_rowstart.resize(numlocalverts + 1, 0);
      typedef std::pair<vertices_size_type, vertices_size_type> edge_type;
      typedef boost::transform_iterator<boost::graph::detail::project1st<edge_type>, MultiPassInputIterator> source_iterator;
      typedef boost::transform_iterator<boost::graph::detail::project2nd<edge_type>, MultiPassInputIterator> target_iterator;
      source_iterator sources_begin(edge_begin, boost::graph::detail::project1st<edge_type>());
      source_iterator sources_end(edge_end, boost::graph::detail::project1st<edge_type>());
      target_iterator targets_begin(edge_begin, boost::graph::detail::project2nd<edge_type>());
      target_iterator targets_end(edge_end, boost::graph::detail::project2nd<edge_type>());

      boost::graph::detail::count_starts
        (sources_begin, sources_end, m_rowstart.begin(), numlocalverts,
         source_pred, boost::make_property_map_function(global_to_local));

      m_column.resize(m_rowstart.back());
      inherited_edge_properties::resize(m_rowstart.back());

      boost::graph::detail::histogram_sort
        (sources_begin, sources_end, m_rowstart.begin(), numlocalverts,
         targets_begin, m_column.begin(),
         ep_iter, inherited_edge_properties::begin(),
         source_pred, boost::make_property_map_function(global_to_local));
    }

    //  Assign from number of vertices and sorted list of edges
    template<typename InputIterator, typename GlobalToLocal, typename SourcePred>
    void assign_from_sorted_edges(
           InputIterator edge_begin, InputIterator edge_end,
           const GlobalToLocal& global_to_local,
           const SourcePred& source_pred,
           vertices_size_type numlocalverts,
           edges_size_type numedges_or_zero) {
      m_column.clear();
      m_column.reserve(numedges_or_zero);
      m_rowstart.resize(numlocalverts + 1);
      EdgeIndex current_edge = 0;
      Vertex current_vertex_plus_one = 1;
      m_rowstart[0] = 0;
      for (InputIterator ei = edge_begin; ei != edge_end; ++ei) {
        if (!source_pred(ei->first)) continue;
        Vertex src = get(global_to_local, ei->first);
        Vertex tgt = ei->second;
        for (; current_vertex_plus_one != src + 1; ++current_vertex_plus_one)
          m_rowstart[current_vertex_plus_one] = current_edge;
        m_column.push_back(tgt);
        ++current_edge;
      }

      // The remaining vertices have no edges
      for (; current_vertex_plus_one != numlocalverts + 1; ++current_vertex_plus_one)
        m_rowstart[current_vertex_plus_one] = current_edge;

      // Default-construct properties for edges
      inherited_edge_properties::resize(m_column.size());
    }

    //  Assign from number of vertices and sorted list of edges
    template<typename InputIterator, typename EdgePropertyIterator, typename GlobalToLocal, typename SourcePred>
    void assign_from_sorted_edges(
           InputIterator edge_begin, InputIterator edge_end,
           EdgePropertyIterator ep_iter,
           const GlobalToLocal& global_to_local,
           const SourcePred& source_pred,
           vertices_size_type numlocalverts,
           edges_size_type numedges_or_zero) {
      // Reserving storage in advance can save us lots of time and
      // memory, but it can only be done if we have forward iterators or
      // the user has supplied the number of edges.
      edges_size_type numedges = numedges_or_zero;
      if (numedges == 0) {
        numedges = boost::graph::detail::reserve_count_for_single_pass(edge_begin, edge_end);
      }
      m_column.clear();
      m_column.reserve(numedges_or_zero);
      inherited_edge_properties::clear();
      inherited_edge_properties::reserve(numedges_or_zero);
      m_rowstart.resize(numlocalverts + 1);
      EdgeIndex current_edge = 0;
      Vertex current_vertex_plus_one = 1;
      m_rowstart[0] = 0;
      for (InputIterator ei = edge_begin; ei != edge_end; ++ei, ++ep_iter) {
        if (!source_pred(ei->first)) continue;
        Vertex src = get(global_to_local, ei->first);
        Vertex tgt = ei->second;
        for (; current_vertex_plus_one != src + 1; ++current_vertex_plus_one)
          m_rowstart[current_vertex_plus_one] = current_edge;
        m_column.push_back(tgt);
        inherited_edge_properties::push_back(*ep_iter);
        ++current_edge;
      }

      // The remaining vertices have no edges
      for (; current_vertex_plus_one != numlocalverts + 1; ++current_vertex_plus_one)
        m_rowstart[current_vertex_plus_one] = current_edge;
    }

    // Replace graph with sources and targets given, sorting them in-place, and
    // using the given global-to-local property map to get local indices from
    // global ones in the two arrays.
    template <typename GlobalToLocal>
    void assign_sources_and_targets_global(std::vector<vertex_descriptor>& sources,
                                           std::vector<vertex_descriptor>& targets,
                                           vertices_size_type numverts,
                                           GlobalToLocal global_to_local) {
      BOOST_ASSERT (sources.size() == targets.size());
      // Do an in-place histogram sort (at least that's what I think it is) to
      // sort sources and targets
      m_rowstart.clear();
      m_rowstart.resize(numverts + 1);
      boost::graph::detail::count_starts
        (sources.begin(), sources.end(), m_rowstart.begin(), numverts,
         keep_all(), boost::make_property_map_function(global_to_local));
      boost::graph::detail::histogram_sort_inplace
        (sources.begin(), m_rowstart.begin(), numverts,
         targets.begin(), boost::make_property_map_function(global_to_local));
      // Now targets is the correct vector (properly sorted by source) for
      // m_column
      m_column.swap(targets);
      inherited_edge_properties::resize(m_rowstart.back());
    }

    // Replace graph with sources and targets and edge properties given, sorting
    // them in-place, and using the given global-to-local property map to get
    // local indices from global ones in the two arrays.
    template <typename GlobalToLocal>
    void assign_sources_and_targets_global(std::vector<vertex_descriptor>& sources,
                                           std::vector<vertex_descriptor>& targets,
                                           std::vector<typename inherited_edge_properties::edge_bundled>& edge_props,
                                           vertices_size_type numverts,
                                           GlobalToLocal global_to_local) {
      BOOST_ASSERT (sources.size() == targets.size());
      BOOST_ASSERT (sources.size() == edge_props.size());
      // Do an in-place histogram sort (at least that's what I think it is) to
      // sort sources and targets
      m_rowstart.clear();
      m_rowstart.resize(numverts + 1);
      boost::graph::detail::count_starts
        (sources.begin(), sources.end(), m_rowstart.begin(), numverts,
         keep_all(), boost::make_property_map_function(global_to_local));
      boost::graph::detail::histogram_sort_inplace
        (sources.begin(), m_rowstart.begin(), numverts,
         targets.begin(), edge_props.begin(),
         boost::make_property_map_function(global_to_local));
      // Now targets is the correct vector (properly sorted by source) for
      // m_column, and edge_props for m_edge_properties
      m_column.swap(targets);
      this->m_edge_properties.swap(edge_props);
    }

    // From any graph (slow and uses a lot of memory)
    //   Requires IncidenceGraph and a vertex index map
    //   Internal helper function
    //   Note that numedges must be doubled for undirected source graphs
    template<typename Graph, typename VertexIndexMap>
    void
    assign(const Graph& g, const VertexIndexMap& vi,
           vertices_size_type numverts, edges_size_type numedges)
    {
      m_rowstart.resize(numverts + 1);
      m_column.resize(numedges);
      inherited_edge_properties::resize(numedges);
      EdgeIndex current_edge = 0;
      typedef typename boost::graph_traits<Graph>::vertex_descriptor g_vertex;
      typedef typename boost::graph_traits<Graph>::out_edge_iterator
        g_out_edge_iter;

      std::vector<g_vertex> ordered_verts_of_g(numverts);
      BGL_FORALL_VERTICES_T(v, g, Graph) {
        ordered_verts_of_g[get(vertex_index, g, v)] = v;
      }
      for (Vertex i = 0; i != numverts; ++i) {
        m_rowstart[i] = current_edge;
        g_vertex v = ordered_verts_of_g[i];
        g_out_edge_iter ei, ei_end;
        for (boost::tie(ei, ei_end) = out_edges(v, g); ei != ei_end; ++ei) {
          m_column[current_edge++] = get(vi, target(*ei, g));
        }
      }
      m_rowstart[numverts] = current_edge;
    }

    // Add edges from a sorted (smallest sources first) range of pairs and edge
    // properties
    template <typename BidirectionalIteratorOrig, typename EPIterOrig,
              typename GlobalToLocal>
    void
    add_edges_sorted_internal(
        BidirectionalIteratorOrig first_sorted,
        BidirectionalIteratorOrig last_sorted,
        EPIterOrig ep_iter_sorted,
        const GlobalToLocal& global_to_local) {
      typedef boost::reverse_iterator<BidirectionalIteratorOrig> BidirectionalIterator;
      typedef boost::reverse_iterator<EPIterOrig> EPIter;
      // Flip sequence
      BidirectionalIterator first(last_sorted);
      BidirectionalIterator last(first_sorted);
      typedef Vertex vertex_num;
      typedef EdgeIndex edge_num;
      edge_num new_edge_count = std::distance(first, last);

      EPIter ep_iter(ep_iter_sorted);
      std::advance(ep_iter, -(std::ptrdiff_t)new_edge_count);
      edge_num edges_added_before_i = new_edge_count; // Count increment to add to rowstarts
      m_column.resize(m_column.size() + new_edge_count);
      inherited_edge_properties::resize(inherited_edge_properties::size() + new_edge_count);
      BidirectionalIterator current_new_edge = first, prev_new_edge = first;
      EPIter current_new_edge_prop = ep_iter;
      for (vertex_num i_plus_1 = m_rowstart.size() - 1; i_plus_1 > 0; --i_plus_1) {
        vertex_num i = i_plus_1 - 1;
        prev_new_edge = current_new_edge;
        // edges_added_to_this_vertex = #mbrs of new_edges with first == i
        edge_num edges_added_to_this_vertex = 0;
        while (current_new_edge != last) {
          if (get(global_to_local, current_new_edge->first) != i) break;
          ++current_new_edge;
          ++current_new_edge_prop;
          ++edges_added_to_this_vertex;
        }
        edges_added_before_i -= edges_added_to_this_vertex;
        // Invariant: edges_added_before_i = #mbrs of new_edges with first < i
        edge_num old_rowstart = m_rowstart[i];
        edge_num new_rowstart = m_rowstart[i] + edges_added_before_i;
        edge_num old_degree = m_rowstart[i + 1] - m_rowstart[i];
        edge_num new_degree = old_degree + edges_added_to_this_vertex;
        // Move old edges forward (by #new_edges before this i) to make room
        // new_rowstart > old_rowstart, so use copy_backwards
        if (old_rowstart != new_rowstart) {
          std::copy_backward(m_column.begin() + old_rowstart,
                             m_column.begin() + old_rowstart + old_degree,
                             m_column.begin() + new_rowstart + old_degree);
          inherited_edge_properties::move_range(old_rowstart, old_rowstart + old_degree, new_rowstart);
        }
        // Add new edges (reversed because current_new_edge is a
        // const_reverse_iterator)
        BidirectionalIterator temp = current_new_edge;
        EPIter temp_prop = current_new_edge_prop;
        for (; temp != prev_new_edge; ++old_degree) {
          --temp;
          --temp_prop;
          m_column[new_rowstart + old_degree] = temp->second;
          inherited_edge_properties::write_by_index(new_rowstart + old_degree, *temp_prop);
        }
        m_rowstart[i + 1] = new_rowstart + new_degree;
        if (edges_added_before_i == 0) break; // No more edges inserted before this point
        // m_rowstart[i] will be fixed up on the next iteration (to avoid
        // changing the degree of vertex i - 1); the last iteration never changes
        // it (either because of the condition of the break or because
        // m_rowstart[0] is always 0)
      }
    }

  };

  template<typename Vertex, typename EdgeIndex>
  class csr_edge_descriptor
  {
   public:
    Vertex src;
    EdgeIndex idx;

    csr_edge_descriptor(Vertex src, EdgeIndex idx): src(src), idx(idx) {}
    csr_edge_descriptor(): src(0), idx(0) {}

    bool operator==(const csr_edge_descriptor& e) const {return idx == e.idx;}
    bool operator!=(const csr_edge_descriptor& e) const {return idx != e.idx;}
    bool operator<(const csr_edge_descriptor& e) const {return idx < e.idx;}
    bool operator>(const csr_edge_descriptor& e) const {return idx > e.idx;}
    bool operator<=(const csr_edge_descriptor& e) const {return idx <= e.idx;}
    bool operator>=(const csr_edge_descriptor& e) const {return idx >= e.idx;}

    template<typename Archiver>
    void serialize(Archiver& ar, const unsigned int /*version*/)
    {
      ar & src & idx;
    }
  };

  // Common out edge and edge iterators
  template<typename CSRGraph>
  class csr_out_edge_iterator
    : public iterator_facade<csr_out_edge_iterator<CSRGraph>,
                             typename CSRGraph::edge_descriptor,
                             std::random_access_iterator_tag,
                             const typename CSRGraph::edge_descriptor&,
                             typename int_t<CHAR_BIT * sizeof(typename CSRGraph::edges_size_type)>::fast>
  {
   public:
    typedef typename CSRGraph::edges_size_type EdgeIndex;
    typedef typename CSRGraph::edge_descriptor edge_descriptor;
    typedef typename int_t<CHAR_BIT * sizeof(EdgeIndex)>::fast difference_type;

    csr_out_edge_iterator() {}
    // Implicit copy constructor OK
    explicit csr_out_edge_iterator(edge_descriptor edge) : m_edge(edge) { }

   public: // GCC 4.2.1 doesn't like the private-and-friend thing
    // iterator_facade requirements
    const edge_descriptor& dereference() const { return m_edge; }

    bool equal(const csr_out_edge_iterator& other) const
    { return m_edge == other.m_edge; }

    void increment() { ++m_edge.idx; }
    void decrement() { --m_edge.idx; }
    void advance(difference_type n) { m_edge.idx += n; }

    difference_type distance_to(const csr_out_edge_iterator& other) const
    { return other.m_edge.idx - m_edge.idx; }

    edge_descriptor m_edge;

    friend class iterator_core_access;
  };

  template<typename CSRGraph>
  class csr_edge_iterator
    : public iterator_facade<csr_edge_iterator<CSRGraph>,
                             typename CSRGraph::edge_descriptor,
                             boost::forward_traversal_tag,
                             typename CSRGraph::edge_descriptor>
  {
   private:
    typedef typename CSRGraph::edge_descriptor edge_descriptor;
    typedef typename CSRGraph::edges_size_type EdgeIndex;

   public:
    csr_edge_iterator() : rowstart_array(0), current_edge(), end_of_this_vertex(0), total_num_edges(0) {}

    csr_edge_iterator(const CSRGraph& graph,
                      edge_descriptor current_edge,
                      EdgeIndex end_of_this_vertex)
      : rowstart_array(&graph.m_forward.m_rowstart[0]),
        current_edge(current_edge),
        end_of_this_vertex(end_of_this_vertex),
        total_num_edges(num_edges(graph)) {}

   public: // See above
    friend class boost::iterator_core_access;

    edge_descriptor dereference() const {return current_edge;}

    bool equal(const csr_edge_iterator& o) const {
      return current_edge == o.current_edge;
    }

    void increment() {
      ++current_edge.idx;
      if (current_edge.idx == total_num_edges) return;
      while (current_edge.idx == end_of_this_vertex) {
        ++current_edge.src;
        end_of_this_vertex = rowstart_array[current_edge.src + 1];
      }
    }

    const EdgeIndex* rowstart_array;
    edge_descriptor current_edge;
    EdgeIndex end_of_this_vertex;
    EdgeIndex total_num_edges;
  };

  // Only for bidirectional graphs
  template<typename CSRGraph>
  class csr_in_edge_iterator
    : public iterator_facade<csr_in_edge_iterator<CSRGraph>,
                             typename CSRGraph::edge_descriptor,
                             boost::forward_traversal_tag,
                             typename CSRGraph::edge_descriptor>
  {
   public:
    typedef typename CSRGraph::edges_size_type EdgeIndex;
    typedef typename CSRGraph::edge_descriptor edge_descriptor;

    csr_in_edge_iterator(): m_graph(0) {}
    // Implicit copy constructor OK
    csr_in_edge_iterator(const CSRGraph& graph,
                         EdgeIndex index_in_backward_graph)
      : m_index_in_backward_graph(index_in_backward_graph), m_graph(&graph) {}

   public: // See above
    // iterator_facade requirements
    edge_descriptor dereference() const {
      return edge_descriptor(
               m_graph->m_backward.m_column[m_index_in_backward_graph],
               m_graph->m_backward.m_edge_properties[m_index_in_backward_graph]);
    }

    bool equal(const csr_in_edge_iterator& other) const
    { return m_index_in_backward_graph == other.m_index_in_backward_graph; }

    void increment() { ++m_index_in_backward_graph; }
    void decrement() { --m_index_in_backward_graph; }
    void advance(std::ptrdiff_t n) { m_index_in_backward_graph += n; }

    std::ptrdiff_t distance_to(const csr_in_edge_iterator& other) const
    { return other.m_index_in_backward_graph - m_index_in_backward_graph; }

    EdgeIndex m_index_in_backward_graph;
    const CSRGraph* m_graph;

    friend class iterator_core_access;
  };

  template <typename A, typename B>
  struct transpose_pair {
    typedef std::pair<B, A> result_type;
    result_type operator()(const std::pair<A, B>& p) const {
      return result_type(p.second, p.first);
    }
  };

  template <typename Iter>
  struct transpose_iterator_gen {
    typedef typename std::iterator_traits<Iter>::value_type vt;
    typedef typename vt::first_type first_type;
    typedef typename vt::second_type second_type;
    typedef transpose_pair<first_type, second_type> transpose;
    typedef boost::transform_iterator<transpose, Iter> type;
    static type make(Iter it) {
      return type(it, transpose());
    }
  };

  template <typename Iter>
  typename transpose_iterator_gen<Iter>::type transpose_edges(Iter i) {
    return transpose_iterator_gen<Iter>::make(i);
  }

  template<typename GraphT, typename VertexIndexMap>
  class edge_to_index_pair
  {
    typedef typename boost::graph_traits<GraphT>::vertices_size_type
      vertices_size_type;
    typedef typename boost::graph_traits<GraphT>::edge_descriptor edge_descriptor;

   public:
    typedef std::pair<vertices_size_type, vertices_size_type> result_type;

    edge_to_index_pair() : g(0), index() { }
    edge_to_index_pair(const GraphT& g, const VertexIndexMap& index)
      : g(&g), index(index)
    { }

    result_type operator()(edge_descriptor e) const
    {
      return result_type(get(index, source(e, *g)), get(index, target(e, *g)));
    }

   private:
    const GraphT* g;
    VertexIndexMap index;
  };

  template<typename GraphT, typename VertexIndexMap>
  edge_to_index_pair<GraphT, VertexIndexMap>
  make_edge_to_index_pair(const GraphT& g, const VertexIndexMap& index)
  {
    return edge_to_index_pair<GraphT, VertexIndexMap>(g, index);
  }

  template<typename GraphT>
  edge_to_index_pair
    <GraphT,
     typename boost::property_map<GraphT,boost::vertex_index_t>::const_type>
  make_edge_to_index_pair(const GraphT& g)
  {
    typedef typename boost::property_map<GraphT,
                                         boost::vertex_index_t>::const_type
      VertexIndexMap;
    return edge_to_index_pair<GraphT, VertexIndexMap>(g,
                                                     get(boost::vertex_index,
                                                         g));
  }

  template<typename GraphT, typename VertexIndexMap, typename Iter>
  boost::transform_iterator<edge_to_index_pair<GraphT, VertexIndexMap>, Iter>
  make_edge_to_index_pair_iter(const GraphT& g, const VertexIndexMap& index,
                               Iter it) {
    return boost::transform_iterator<edge_to_index_pair<GraphT, VertexIndexMap>, Iter>(it, edge_to_index_pair<GraphT, VertexIndexMap>(g, index));
  }

} // namespace detail

  template<typename Vertex, typename EdgeIndex>
  struct hash<detail::csr_edge_descriptor<Vertex, EdgeIndex> >
  {
    std::size_t operator()
                  (detail::csr_edge_descriptor<Vertex, EdgeIndex> const& x) const
    {
      std::size_t hash = hash_value(x.src);
      hash_combine(hash, x.idx);
      return hash;
    }
  };

} // namespace boost

#endif // BOOST_GRAPH_COMPRESSED_SPARSE_ROW_STRUCT_HPP