915b5b640a3a9ba0ee768dc3db92b623c24cec0c
[mtp.git] / mtp_graph.cc
1
2 ///////////////////////////////////////////////////////////////////////////
3 // This program is free software: you can redistribute it and/or modify  //
4 // it under the terms of the version 3 of the GNU General Public License //
5 // as published by the Free Software Foundation.                         //
6 //                                                                       //
7 // This program is distributed in the hope that it will be useful, but   //
8 // WITHOUT ANY WARRANTY; without even the implied warranty of            //
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      //
10 // General Public License for more details.                              //
11 //                                                                       //
12 // You should have received a copy of the GNU General Public License     //
13 // along with this program. If not, see <http://www.gnu.org/licenses/>.  //
14 //                                                                       //
15 // Written by and Copyright (C) Francois Fleuret                         //
16 // Contact <francois.fleuret@idiap.ch> for comments & bug reports        //
17 ///////////////////////////////////////////////////////////////////////////
18
19 #include "mtp_graph.h"
20
21 #include <iostream>
22 #include <float.h>
23 #include <stdlib.h>
24
25 using namespace std;
26
27 class Edge {
28 public:
29   int id, occupied;
30   scalar_t length, positivized_length;
31   Vertex *origin_vertex, *terminal_vertex;
32
33   // These are the links in the origin_vertex leaving edge list
34   Edge *next_leaving_edge, *pred_leaving_edge;
35
36   inline void invert();
37 };
38
39 class Vertex {
40 public:
41   int id;
42   Edge *leaving_edges;
43   scalar_t distance_from_source;
44   Edge *pred_edge_toward_source;
45
46   int iteration; // Used in find_shortest_path to know if we already
47                  // added this vertex to the front
48   Vertex();
49   inline void add_leaving_edge(Edge *e);
50   inline void del_leaving_edge(Edge *e);
51 };
52
53 //////////////////////////////////////////////////////////////////////
54
55 void Edge::invert() {
56   length = - length;
57   positivized_length = 0;
58   origin_vertex->del_leaving_edge(this);
59   terminal_vertex->add_leaving_edge(this);
60   Vertex *t = terminal_vertex;
61   terminal_vertex = origin_vertex;
62   origin_vertex = t;
63 }
64
65 //////////////////////////////////////////////////////////////////////
66
67 Vertex::Vertex() {
68   leaving_edges = 0;
69 }
70
71 void Vertex::add_leaving_edge(Edge *e) {
72   e->next_leaving_edge = leaving_edges;
73   e->pred_leaving_edge = 0;
74   if(leaving_edges) { leaving_edges->pred_leaving_edge = e; }
75   leaving_edges = e;
76 }
77
78 void Vertex::del_leaving_edge(Edge *e) {
79   if(e == leaving_edges) {
80     leaving_edges = e->next_leaving_edge;
81   }
82   if(e->pred_leaving_edge) {
83     e->pred_leaving_edge->next_leaving_edge = e->next_leaving_edge;
84   }
85   if(e->next_leaving_edge) {
86     e->next_leaving_edge->pred_leaving_edge = e->pred_leaving_edge;
87   }
88 }
89
90 //////////////////////////////////////////////////////////////////////
91
92 MTPGraph::MTPGraph(int nb_vertices, int nb_edges,
93                    int *from, int *to,
94                    int source, int sink) {
95   _nb_vertices = nb_vertices;
96   _nb_edges = nb_edges;
97
98   _edges = new Edge[_nb_edges];
99   _vertices = new Vertex[_nb_vertices];
100   _front = new Vertex *[_nb_vertices];
101   _new_front = new Vertex *[_nb_vertices];
102
103   _source = &_vertices[source];
104   _sink = &_vertices[sink];
105
106   for(int v = 0; v < _nb_vertices; v++) {
107     _vertices[v].id = v;
108   }
109
110   for(int e = 0; e < nb_edges; e++) {
111     _vertices[from[e]].add_leaving_edge(_edges + e);
112     _edges[e].occupied = 0;
113     _edges[e].id = e;
114     _edges[e].origin_vertex = _vertices + from[e];
115     _edges[e].terminal_vertex = _vertices + to[e];
116   }
117
118   paths = 0;
119   nb_paths = 0;
120 }
121
122 MTPGraph::~MTPGraph() {
123   delete[] _vertices;
124   delete[] _edges;
125   delete[] _front;
126   delete[] _new_front;
127   for(int p = 0; p < nb_paths; p++) delete paths[p];
128   delete[] paths;
129 }
130
131 //////////////////////////////////////////////////////////////////////
132
133 void MTPGraph::print(ostream *os) {
134   for(int k = 0; k < _nb_edges; k++) {
135     Edge *e = _edges + k;
136     (*os) << e->origin_vertex->id
137          << " -> "
138          << e->terminal_vertex->id
139          << " "
140          << e->length;
141     if(e->occupied) {
142       (*os) << " *";
143     }
144     (*os) << endl;
145   }
146 }
147
148 void MTPGraph::print_dot(ostream *os) {
149   (*os) << "digraph {" << endl;
150   (*os) << "        node [shape=circle,width=0.75,fixedsize=true];" << endl;
151   (*os) << "        edge [color=gray,arrowhead=open]" << endl;
152   (*os) << "        " << _source->id << " [peripheries=2];" << endl;
153   (*os) << "        " << _sink->id << " [peripheries=2];" << endl;
154   // (*os) << "        " << _source->id << " [style=bold,color=red];" << endl;
155   // (*os) << "        " << _sink->id << " [style=bold,color=green];" << endl;
156   for(int k = 0; k < _nb_edges; k++) {
157     Edge *e = _edges + k;
158     // (*os) << "  " << e->origin_vertex->id << " -> " << e->terminal_vertex->id
159     // << ";"
160     // << endl;
161     (*os) << "        " << e->origin_vertex->id << " -> " << e->terminal_vertex->id
162           << " [";
163     if(e->occupied) {
164       (*os) << "style=bold,color=black,";
165     }
166     (*os) << "label=\"" << e->length << "\"];" << endl;
167   }
168   (*os) << "}" << endl;
169 }
170
171 //////////////////////////////////////////////////////////////////////
172
173 void MTPGraph::update_positivized_lengths() {
174   for(int k = 0; k < _nb_edges; k++) {
175     Edge *e = _edges + k;
176     e->positivized_length +=
177       e->origin_vertex->distance_from_source - e->terminal_vertex->distance_from_source;
178   }
179 }
180
181 void MTPGraph::force_positivized_lengths() {
182 #ifdef VERBOSE
183   scalar_t residual_error = 0.0;
184   scalar_t max_error = 0.0;
185 #endif
186   for(int n = 0; n < _nb_vertices; n++) {
187     for(Edge *e = _vertices[n].leaving_edges; e; e = e->next_leaving_edge) {
188       if(e->positivized_length < 0) {
189 #ifdef VERBOSE
190         residual_error -= e->positivized_length;
191         max_error = max(max_error, - e->positivized_length);
192 #endif
193         e->positivized_length = 0.0;
194       }
195     }
196   }
197 #ifdef VERBOSE
198   cerr << "residual_error " << residual_error << " max_error " << residual_error << endl;
199 #endif
200 }
201
202 // This method does not change the edge occupation. It update
203 // distance_from_source and pred_edge_toward_source.
204 void MTPGraph::find_shortest_path() {
205   Vertex **tmp_front;
206   int tmp_front_size;
207   Vertex *v, *tv;
208   Edge *e;
209   scalar_t d;
210
211   for(int v = 0; v < _nb_vertices; v++) {
212     _vertices[v].distance_from_source = FLT_MAX;
213     _vertices[v].pred_edge_toward_source = 0;
214     _vertices[v].iteration = 0;
215   }
216
217   int iteration = 0;
218
219   int _front_size = 0, _new_front_size;
220   _front[_front_size++] = _source;
221   _source->distance_from_source = 0;
222
223   do {
224     _new_front_size = 0;
225     iteration++;
226
227     for(int f = 0; f < _front_size; f++) {
228       v = _front[f];
229       for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
230         d = v->distance_from_source + e->positivized_length;
231         tv = e->terminal_vertex;
232         if(d < tv->distance_from_source) {
233           tv->distance_from_source = d;
234           tv->pred_edge_toward_source = e;
235           if(tv->iteration < iteration) {
236             _new_front[_new_front_size++] = tv;
237             tv->iteration = iteration;
238           }
239         }
240       }
241     }
242
243     tmp_front = _new_front;
244     _new_front = _front;
245     _front = tmp_front;
246
247     tmp_front_size = _new_front_size;
248     _new_front_size = _front_size;
249     _front_size = tmp_front_size;
250   } while(_front_size > 0);
251 }
252
253 void MTPGraph::find_best_paths(scalar_t *lengths) {
254   scalar_t total_length;
255   Vertex *v;
256   Edge *e;
257
258   for(int e = 0; e < _nb_edges; e++) {
259     _edges[e].length = lengths[e];
260     _edges[e].occupied = 0;
261     _edges[e].positivized_length = _edges[e].length;
262   }
263
264   // We use one iteration of find_shortest_path simply to propagate
265   // the distance to make all the edge lengths positive.
266   find_shortest_path();
267
268   do {
269     update_positivized_lengths();
270     force_positivized_lengths();
271     find_shortest_path();
272
273     total_length = 0.0;
274
275     // Do we reach the _sink?
276     if(_sink->pred_edge_toward_source) {
277       // If yes, compute the length of the best path
278       v = _sink;
279       while(v->pred_edge_toward_source) {
280         total_length += v->pred_edge_toward_source->length;
281         v = v->pred_edge_toward_source->origin_vertex;
282       }
283       // If that length is negative
284       if(total_length < 0.0) {
285 #ifdef VERBOSE
286         cerr << "Found a path of length " << total_length << endl;
287 #endif
288         // Invert all the edges along the best path
289         v = _sink;
290         while(v->pred_edge_toward_source) {
291           e = v->pred_edge_toward_source;
292           v = e->origin_vertex;
293           e->invert();
294           // This is the only place where we change the occupations of
295           // edges
296           e->occupied = 1 - e->occupied;
297         }
298       }
299     }
300
301   } while(total_length < 0.0);
302
303   // Put back the graph in its original state (i.e. invert edges which
304   // have been inverted in the process)
305   for(int k = 0; k < _nb_edges; k++) {
306     Edge *e = _edges + k;
307     if(e->occupied) { e->invert(); }
308   }
309 }
310
311 int MTPGraph::retrieve_one_path(Edge *e, Path *path) {
312   Edge *f, *next = 0;
313   int l = 0;
314
315   if(path) {
316     path->nodes[l++] = e->origin_vertex->id;
317     path->length = e->length;
318   } else l++;
319
320   while(e->terminal_vertex != _sink) {
321     if(path) {
322       path->nodes[l++] = e->terminal_vertex->id;
323       path->length += e->length;
324     } else l++;
325     int nb_choices = 0;
326     for(f = e->terminal_vertex->leaving_edges; f; f = f->next_leaving_edge) {
327       if(f->occupied) { nb_choices++; next = f; }
328       if(nb_choices == 0) {
329         cerr << "retrieve_one_path: Non-sink end point." << endl;
330         abort();
331       }
332       if(nb_choices > 1) {
333         cerr << "retrieve_one_path: Non node-disjoint paths." << endl;
334         abort();
335       }
336     }
337     e = next;
338   }
339
340   if(path) {
341     path->nodes[l++] = e->terminal_vertex->id;
342     path->length += e->length;
343   } else l++;
344
345   return l;
346 }
347
348 void MTPGraph::retrieve_disjoint_paths() {
349   Edge *e;
350
351   for(int p = 0; p < nb_paths; p++) delete paths[p];
352   delete[] paths;
353
354   nb_paths = 0;
355   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
356     if(e->occupied) { nb_paths++; }
357   }
358
359   paths = new Path *[nb_paths];
360
361   int p = 0;
362   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
363     if(e->occupied) {
364       int l = retrieve_one_path(e, 0);
365       paths[p] = new Path(l);
366       retrieve_one_path(e, paths[p]);
367       p++;
368     }
369   }
370 }