Added README.md
[mtp.git] / mtp_graph.cc
index 6c97c5d..2cbb338 100644 (file)
@@ -24,6 +24,7 @@
 
 #include "mtp_graph.h"
 
+#include <cmath>
 #include <float.h>
 
 using namespace std;
@@ -43,9 +44,10 @@ public:
 
 class Vertex {
 public:
-  Edge *leaving_edges;
   scalar_t distance_from_source;
   Edge *pred_edge_toward_source;
+
+  Edge *leaving_edge_list_root;
   Vertex **heap_slot;
 
   Vertex();
@@ -53,7 +55,7 @@ public:
   inline void add_leaving_edge(Edge *e);
   inline void del_leaving_edge(Edge *e);
   inline void decrease_distance_in_heap(Vertex **heap);
-  inline void increase_distance_in_heap(Vertex **heap, int heap_size);
+  inline void increase_distance_in_heap(Vertex **heap, Vertex **heap_bottom);
 };
 
 //////////////////////////////////////////////////////////////////////
@@ -63,27 +65,27 @@ void Edge::invert() {
   positivized_length = - positivized_length;
   origin_vertex->del_leaving_edge(this);
   terminal_vertex->add_leaving_edge(this);
-  Vertex *t = terminal_vertex;
-  terminal_vertex = origin_vertex;
-  origin_vertex = t;
+  swap(terminal_vertex, origin_vertex);
 }
 
 //////////////////////////////////////////////////////////////////////
 
 Vertex::Vertex() {
-  leaving_edges = 0;
+  leaving_edge_list_root = 0;
 }
 
 void Vertex::add_leaving_edge(Edge *e) {
-  e->next_leaving_edge = leaving_edges;
+  e->next_leaving_edge = leaving_edge_list_root;
   e->pred_leaving_edge = 0;
-  if(leaving_edges) { leaving_edges->pred_leaving_edge = e; }
-  leaving_edges = e;
+  if(leaving_edge_list_root) {
+    leaving_edge_list_root->pred_leaving_edge = e;
+  }
+  leaving_edge_list_root = e;
 }
 
 void Vertex::del_leaving_edge(Edge *e) {
-  if(e == leaving_edges) {
-    leaving_edges = e->next_leaving_edge;
+  if(e == leaving_edge_list_root) {
+    leaving_edge_list_root = e->next_leaving_edge;
   }
   if(e->pred_leaving_edge) {
     e->pred_leaving_edge->next_leaving_edge = e->next_leaving_edge;
@@ -95,51 +97,46 @@ void Vertex::del_leaving_edge(Edge *e) {
 
 void Vertex::decrease_distance_in_heap(Vertex **heap) {
   Vertex **p, **h;
-  // There is some beauty in that
   h = heap_slot;
-  while(h > heap &&
-        (p = heap + (h - heap + 1) / 2 - 1,
-         (*p)->distance_from_source > (*h)->distance_from_source)) {
+  while(1) {
+    if(h <= heap) break;
+    p = heap + ((h - heap + 1) >> 1) - 1;
+    if((*p)->distance_from_source <= distance_from_source) break;
+    swap((*p)->heap_slot, heap_slot);
     swap(*p, *h);
-    swap((*p)->heap_slot, (*h)->heap_slot);
     h = p;
   }
 }
 
-void Vertex::increase_distance_in_heap(Vertex **heap, int heap_size) {
+void Vertex::increase_distance_in_heap(Vertex **heap, Vertex **heap_bottom) {
   Vertex **c1, **c2, **h;
-  // omg, that's beautiful
   h = heap_slot;
-  while(c1 = heap + 2 * (h - heap) + 1,
-        c1 < heap + heap_size &&
-        (c2 = c1 + 1,
-         (*c1)->distance_from_source < (*h)->distance_from_source
-         ||
-         (c2 < heap + heap_size && (*c2)->distance_from_source < (*h)->distance_from_source)
-         )) {
-    if(c2 < heap + heap_size && (*c2)->distance_from_source <= (*c1)->distance_from_source) {
-      swap(*c2, *h);
-      swap((*c2)->heap_slot, (*h)->heap_slot);
-      h = c2;
+  while(1) {
+    c1 = heap + 2 * (h - heap) + 1;
+    if(c1 >= heap_bottom) break;
+    c2 = c1 + 1;
+    if((*c1)->distance_from_source < distance_from_source) {
+      if(c2 < heap_bottom && (*c2)->distance_from_source < (*c1)->distance_from_source) {
+        swap((*c2)->heap_slot, heap_slot);
+        swap(*c2, *h);
+        h = c2;
+      } else {
+        swap((*c1)->heap_slot, heap_slot);
+        swap(*c1, *h);
+        h = c1;
+      }
     } else {
-      swap(*c1, *h);
-      swap((*c1)->heap_slot, (*h)->heap_slot);
-      h = c1;
+      if(c2 < heap_bottom && (*c2)->distance_from_source < distance_from_source) {
+        swap((*c2)->heap_slot, heap_slot);
+        swap(*c2, *h);
+        h = c2;
+      } else break;
     }
   }
 }
 
 //////////////////////////////////////////////////////////////////////
 
-static int compare_vertex(const void *v1, const void *v2) {
-  scalar_t delta =
-    (*((Vertex **) v1))->distance_from_source -
-    (*((Vertex **) v2))->distance_from_source;
-  if(delta < 0) return -1;
-  else if(delta > 0) return 1;
-  else return 0;
-}
-
 MTPGraph::MTPGraph(int nb_vertices, int nb_edges,
                    int *vertex_from, int *vertex_to,
                    int source, int sink) {
@@ -155,10 +152,10 @@ MTPGraph::MTPGraph(int nb_vertices, int nb_edges,
   _sink = &_vertices[sink];
 
   for(int e = 0; e < nb_edges; e++) {
-    _vertices[vertex_from[e]].add_leaving_edge(_edges + e);
+    _vertices[vertex_from[e]].add_leaving_edge(&_edges[e]);
     _edges[e].occupied = 0;
-    _edges[e].origin_vertex = _vertices + vertex_from[e];
-    _edges[e].terminal_vertex = _vertices + vertex_to[e];
+    _edges[e].origin_vertex = &_vertices[vertex_from[e]];
+    _edges[e].terminal_vertex = &_vertices[vertex_to[e]];
   }
 
   for(int v = 0; v < _nb_vertices; v++) {
@@ -169,16 +166,7 @@ MTPGraph::MTPGraph(int nb_vertices, int nb_edges,
   paths = 0;
   nb_paths = 0;
 
-  if(compute_dp_distances()) {
-    // Here the distance_from_source field of every vertex is the
-    // number of DP iterations needed to update it. Hence we only have
-    // to process the vertex in that order.
-    for(int v = 0; v < _nb_vertices; v++) { _dp_order[v] = &_vertices[v]; }
-    qsort(_dp_order, _nb_vertices, sizeof(Vertex *), compare_vertex);
-  } else {
-    cerr << __FILE__ << ": This graph is not a DAG." << endl;
-    abort();
-  }
+  compute_dp_ordering();
 }
 
 MTPGraph::~MTPGraph() {
@@ -194,15 +182,12 @@ MTPGraph::~MTPGraph() {
 
 void MTPGraph::print(ostream *os) {
   for(int k = 0; k < _nb_edges; k++) {
-    Edge *e = _edges + k;
+    Edge *e = &_edges[k];
     (*os) << e->origin_vertex - _vertices
-         << " -> "
-         << e->terminal_vertex - _vertices
-         << " "
-         << e->length;
-    if(e->occupied) {
-      (*os) << " *";
-    }
+          << " -> "
+          << e->terminal_vertex - _vertices
+          << " (" << e->length << ")";
+    if(e->occupied) { (*os) << " *"; }
     (*os) << endl;
   }
 }
@@ -215,7 +200,7 @@ void MTPGraph::print_dot(ostream *os) {
   (*os) << "        " << _source - _vertices << " [peripheries=2];" << endl;
   (*os) << "        " << _sink - _vertices << " [peripheries=2];" << endl;
   for(int k = 0; k < _nb_edges; k++) {
-    Edge *e = _edges + k;
+    Edge *e = &_edges[k];
     (*os) << "        "
           << e->origin_vertex - _vertices
           << " -> "
@@ -233,7 +218,7 @@ void MTPGraph::print_dot(ostream *os) {
 
 void MTPGraph::update_positivized_lengths() {
   for(int k = 0; k < _nb_edges; k++) {
-    Edge *e = _edges + k;
+    Edge *e = &_edges[k];
     e->positivized_length +=
       e->origin_vertex->distance_from_source - e->terminal_vertex->distance_from_source;
   }
@@ -245,10 +230,9 @@ void MTPGraph::force_positivized_lengths() {
   scalar_t max_error = 0.0;
 #endif
   for(int k = 0; k < _nb_edges; k++) {
-    Edge *e = _edges + k;
+    Edge *e = &_edges[k];
 
     if(e->positivized_length < 0) {
-
 #ifdef VERBOSE
       residual_error -= e->positivized_length;
       max_error = max(max_error, - e->positivized_length);
@@ -257,62 +241,10 @@ void MTPGraph::force_positivized_lengths() {
     }
   }
 #ifdef VERBOSE
-  cerr << __FILE__ << ": residual_error " << residual_error << " max_error " << residual_error << endl;
+  cerr << __FILE__ << ": residual_error " << residual_error << " max_error " << max_error << endl;
 #endif
 }
 
-int MTPGraph::compute_dp_distances() {
-  Vertex *v;
-  Edge *e;
-
-  // This procedure computes for each node the longest link from the
-  // source and abort if the graph is not a DAG. It works by removing
-  // successively nodes without predecessor: At the first iteration it
-  // removes the source, then the nodes with incoming edge only from
-  // the source, etc. If it can remove all the nodes that way, the
-  // graph is a DAG. If at some point it can not remove node anymore
-  // and there are some remaining nodes, the graph is not a DAG.
-
-  Vertex **active = new Vertex *[_nb_vertices];
-
-  // All the nodes are active at first
-  for(int k = 0; k < _nb_vertices; k++) {
-    _vertices[k].distance_from_source = 0;
-    active[k] = &_vertices[k];
-  }
-
-  scalar_t nb_iterations = 1;
-  int nb_active = _nb_vertices, pred_nb_active;
-
-  do {
-    // We set the distance_from_source field of all the vertices with incoming
-    // edges to the current nb_iterations value
-    for(int f = 0; f < nb_active; f++) {
-      v = active[f];
-      for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
-        e->terminal_vertex->distance_from_source = nb_iterations;
-      }
-    }
-
-    pred_nb_active = nb_active;
-    nb_active = 0;
-
-    // We keep all the vertices with incoming nodes
-    for(int f = 0; f < pred_nb_active; f++) {
-      v = active[f];
-      if(v->distance_from_source == nb_iterations) {
-        active[nb_active++] = v;
-      }
-    }
-
-    nb_iterations++;
-  } while(nb_active < pred_nb_active);
-
-  delete[] active;
-
-  return nb_active == 0;
-}
-
 void MTPGraph::dp_compute_distances() {
   Vertex *v, *tv;
   Edge *e;
@@ -327,13 +259,12 @@ void MTPGraph::dp_compute_distances() {
 
   for(int k = 0; k < _nb_vertices; k++) {
     v = _dp_order[k];
-    for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
+    for(e = v->leaving_edge_list_root; e; e = e->next_leaving_edge) {
       d = v->distance_from_source + e->positivized_length;
       tv = e->terminal_vertex;
       if(d < tv->distance_from_source) {
         tv->distance_from_source = d;
         tv->pred_edge_toward_source = e;
-        tv->decrease_distance_in_heap(_heap);
       }
     }
   }
@@ -344,7 +275,8 @@ void MTPGraph::dp_compute_distances() {
 // pred_edge_toward_source.
 
 void MTPGraph::find_shortest_path() {
-  Vertex *v, *tv, **a, **b;
+  int heap_size;
+  Vertex *v, *tv, **last_slot;
   Edge *e;
   scalar_t d;
 
@@ -353,38 +285,38 @@ void MTPGraph::find_shortest_path() {
     _vertices[k].pred_edge_toward_source = 0;
   }
 
-  _heap_size = _nb_vertices;
+  heap_size = _nb_vertices;
   _source->distance_from_source = 0;
   _source->decrease_distance_in_heap(_heap);
 
-  do {
+  while(heap_size > 1) {
     // Get the closest to the source
     v = _heap[0];
 
-    // Remove it from the heap (swap it with the last in the heap, and
+    // Remove it from the heap (swap it with the last_slot in the heap, and
     // update the distance of that one)
-    _heap_size--;
-    a = _heap;
-    b = _heap + _heap_size;
-    swap(*a, *b); swap((*a)->heap_slot, (*b)->heap_slot);
-    _heap[0]->increase_distance_in_heap(_heap, _heap_size);
-
-    // Now update the neighbors of the currently closest to the source
-    for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
+    heap_size--;
+    last_slot = _heap + heap_size;
+    swap(*_heap, *last_slot); swap((*_heap)->heap_slot, (*last_slot)->heap_slot);
+    (*_heap)->increase_distance_in_heap(_heap, last_slot);
+
+    // Now update the neighbors of the node currently closest to the
+    // source
+    for(e = v->leaving_edge_list_root; e; e = e->next_leaving_edge) {
       d = v->distance_from_source + e->positivized_length;
       tv = e->terminal_vertex;
       if(d < tv->distance_from_source) {
-        ASSERT(tv->heap_slot - _heap < _heap_size);
+        ASSERT(tv->heap_slot < last_slot);
         tv->distance_from_source = d;
         tv->pred_edge_toward_source = e;
         tv->decrease_distance_in_heap(_heap);
       }
     }
-  } while(_heap_size > 0);
+  }
 }
 
 void MTPGraph::find_best_paths(scalar_t *lengths) {
-  scalar_t total_length;
+  scalar_t shortest_path_length;
   Vertex *v;
   Edge *e;
 
@@ -394,15 +326,21 @@ void MTPGraph::find_best_paths(scalar_t *lengths) {
     _edges[e].positivized_length = _edges[e].length;
   }
 
-  // Update the distances to the source in "good order"
+  // Compute the distance of all the nodes from the source by just
+  // visiting them in the proper DAG ordering we computed when
+  // building the graph
   dp_compute_distances();
 
   do {
+    // Use the current distance from the source to make all edge
+    // lengths positive
     update_positivized_lengths();
+    // Fix numerical errors
     force_positivized_lengths();
+
     find_shortest_path();
 
-    total_length = 0.0;
+    shortest_path_length = 0.0;
 
     // Do we reach the sink?
     if(_sink->pred_edge_toward_source) {
@@ -410,13 +348,13 @@ void MTPGraph::find_best_paths(scalar_t *lengths) {
       // original edge lengths
       v = _sink;
       while(v->pred_edge_toward_source) {
-        total_length += v->pred_edge_toward_source->length;
+        shortest_path_length += v->pred_edge_toward_source->length;
         v = v->pred_edge_toward_source->origin_vertex;
       }
       // If that length is negative
-      if(total_length < 0.0) {
+      if(shortest_path_length < 0.0) {
 #ifdef VERBOSE
-        cerr << __FILE__ << ": Found a path of length " << total_length << endl;
+        cerr << __FILE__ << ": Found a path of length " << shortest_path_length << endl;
 #endif
         // Invert all the edges along the best path
         v = _sink;
@@ -431,34 +369,36 @@ void MTPGraph::find_best_paths(scalar_t *lengths) {
       }
     }
 
-  } while(total_length < 0.0);
+  } while(shortest_path_length < 0.0);
 
   // Put back the graph in its original state (i.e. invert edges which
   // have been inverted in the process)
   for(int k = 0; k < _nb_edges; k++) {
-    e = _edges + k;
+    e = &_edges[k];
     if(e->occupied) { e->invert(); }
   }
 }
 
-int MTPGraph::retrieve_one_path(Edge *e, Path *path) {
+int MTPGraph::retrieve_one_path(Edge *e, Path *path, int *used_edges) {
   Edge *f, *next = 0;
   int l = 0, nb_occupied_next;
 
   if(path) {
-    path->nodes[l++] = e->origin_vertex - _vertices;
+    path->nodes[l++] = int(e->origin_vertex - _vertices);
     path->length = e->length;
   } else l++;
 
   while(e->terminal_vertex != _sink) {
     if(path) {
-      path->nodes[l++] = e->terminal_vertex - _vertices;
+      path->nodes[l++] = int(e->terminal_vertex - _vertices);
       path->length += e->length;
     } else l++;
 
     nb_occupied_next = 0;
-    for(f = e->terminal_vertex->leaving_edges; f; f = f->next_leaving_edge) {
-      if(f->occupied) { nb_occupied_next++; next = f; }
+    for(f = e->terminal_vertex->leaving_edge_list_root; f; f = f->next_leaving_edge) {
+      if(f->occupied && !used_edges[f - _edges]) {
+        nb_occupied_next++; next = f;
+      }
     }
 
 #ifdef DEBUG
@@ -466,45 +406,115 @@ int MTPGraph::retrieve_one_path(Edge *e, Path *path) {
       cerr << __FILE__ << ": retrieve_one_path: Non-sink end point." << endl;
       abort();
     }
-
-    else if(nb_occupied_next > 1) {
-      cerr << __FILE__ << ": retrieve_one_path: Non node-disjoint paths." << endl;
-      abort();
-    }
 #endif
 
+    if(path) { used_edges[next - _edges] = 1; }
+
     e = next;
   }
 
   if(path) {
-    path->nodes[l++] = e->terminal_vertex - _vertices;
+    path->nodes[l++] = int(e->terminal_vertex - _vertices);
     path->length += e->length;
   } else l++;
 
   return l;
 }
 
+//////////////////////////////////////////////////////////////////////
+
+void MTPGraph::compute_dp_ordering() {
+  Vertex *v;
+  Edge *e;
+  int ntv;
+
+  // This method orders the nodes by putting first the ones with no
+  // predecessors, then going on adding nodes whose predecessors have
+  // all been already added. Computing the distances from the source
+  // by visiting nodes in that order is equivalent to DP.
+
+  int *nb_predecessors = new int[_nb_vertices];
+
+  Vertex **already_processed = _dp_order, **front = _dp_order, **new_front = _dp_order;
+
+  for(int k = 0; k < _nb_vertices; k++) {
+    nb_predecessors[k] = 0;
+  }
+
+  for(int k = 0; k < _nb_vertices; k++) {
+    v = &_vertices[k];
+    for(e = v->leaving_edge_list_root; e; e = e->next_leaving_edge) {
+      ntv = int(e->terminal_vertex - _vertices);
+      nb_predecessors[ntv]++;
+    }
+  }
+
+  for(int k = 0; k < _nb_vertices; k++) {
+    if(nb_predecessors[k] == 0) {
+      *(front++) = _vertices + k;
+    }
+  }
+
+  while(already_processed < front) {
+    // Here, nodes before already_processed can be ignored, nodes
+    // before front were set to 0 predecessors during the previous
+    // iteration. During this new iteration, we have to visit the
+    // successors of these ones only, since they are the only ones
+    // which may end up with no predecessors.
+    new_front = front;
+    while(already_processed < front) {
+      v = *(already_processed++);
+      for(e = v->leaving_edge_list_root; e; e = e->next_leaving_edge) {
+        ntv = int(e->terminal_vertex - _vertices);
+        nb_predecessors[ntv]--;
+        ASSERT(nb_predecessors[ntv] >= 0);
+        if(nb_predecessors[ntv] == 0) {
+          *(new_front++) = e->terminal_vertex;
+        }
+      }
+    }
+    front = new_front;
+  }
+
+  if(already_processed < _dp_order + _nb_vertices) {
+    cerr << __FILE__ << ": The graph is not a DAG." << endl;
+    abort();
+  }
+
+  delete[] nb_predecessors;
+}
+
+//////////////////////////////////////////////////////////////////////
+
 void MTPGraph::retrieve_disjoint_paths() {
   Edge *e;
   int p, l;
+  int *used_edges;
 
   for(int p = 0; p < nb_paths; p++) delete paths[p];
   delete[] paths;
 
   nb_paths = 0;
-  for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
+  for(e = _source->leaving_edge_list_root; e; e = e->next_leaving_edge) {
     if(e->occupied) { nb_paths++; }
   }
 
   paths = new Path *[nb_paths];
+  used_edges = new int[_nb_edges];
+  for(int e = 0; e < _nb_edges; e++) {
+    used_edges[e] = 0;
+  }
 
   p = 0;
-  for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
-    if(e->occupied) {
-      l = retrieve_one_path(e, 0);
+  for(e = _source->leaving_edge_list_root; e; e = e->next_leaving_edge) {
+    if(e->occupied && !used_edges[e - _edges]) {
+      l = retrieve_one_path(e, 0, used_edges);
       paths[p] = new Path(l);
-      retrieve_one_path(e, paths[p]);
+      retrieve_one_path(e, paths[p], used_edges);
+      used_edges[e - _edges] = 1;
       p++;
     }
   }
+
+  delete[] used_edges;
 }