Update.
[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
24 using namespace std;
25
26 class Edge {
27 public:
28   int id, occupied;
29   scalar_t length, positivized_length;
30   Vertex *origin_vertex, *terminal_vertex;
31
32   // These are the links in the origin_vertex leaving edge list
33   Edge *next_leaving_edge, *pred_leaving_edge;
34
35   inline void revert();
36 };
37
38 class Vertex {
39 public:
40   int id;
41   Edge *leaving_edges;
42   scalar_t distance_from_source;
43   Edge *best_pred_edge_to_source;
44
45   int iteration; // Used in find_shortest_path to know if we already
46                  // added this vertex to the front
47   Vertex();
48   inline void add_edge(Edge *e);
49   inline void del_edge(Edge *e);
50 };
51
52 //////////////////////////////////////////////////////////////////////
53
54 void Edge::revert() {
55   length = - length;
56   positivized_length = 0;
57   origin_vertex->del_edge(this);
58   terminal_vertex->add_edge(this);
59   Vertex *t = terminal_vertex;
60   terminal_vertex = origin_vertex;
61   origin_vertex = t;
62 }
63
64 //////////////////////////////////////////////////////////////////////
65
66 Vertex::Vertex() {
67   leaving_edges = 0;
68 }
69
70 void Vertex::add_edge(Edge *e) {
71   e->next_leaving_edge = leaving_edges;
72   e->pred_leaving_edge = 0;
73   if(leaving_edges) { leaving_edges->pred_leaving_edge = e; }
74   leaving_edges = e;
75 }
76
77 void Vertex::del_edge(Edge *e) {
78   if(e == leaving_edges) { leaving_edges = e->next_leaving_edge; }
79   if(e->pred_leaving_edge) { e->pred_leaving_edge->next_leaving_edge = e->next_leaving_edge; }
80   if(e->next_leaving_edge) { e->next_leaving_edge->pred_leaving_edge = e->pred_leaving_edge; }
81 }
82
83 //////////////////////////////////////////////////////////////////////
84
85 MTPGraph::MTPGraph(int nb_vertices, int nb_edges,
86                    int *from, int *to,
87                    int source, int sink) {
88   _nb_vertices = nb_vertices;
89   _nb_edges = nb_edges;
90
91   _edges = new Edge[_nb_edges];
92   _vertices = new Vertex[_nb_vertices];
93   _front = new Vertex *[_nb_vertices];
94   _new_front = new Vertex *[_nb_vertices];
95
96   _source = &_vertices[source];
97   _sink = &_vertices[sink];
98
99   for(int v = 0; v < _nb_vertices; v++) {
100     _vertices[v].id = v;
101   }
102
103   for(int e = 0; e < nb_edges; e++) {
104     _vertices[from[e]].add_edge(_edges + e);
105     _edges[e].occupied = 0;
106     _edges[e].id = e;
107     _edges[e].origin_vertex = _vertices + from[e];
108     _edges[e].terminal_vertex = _vertices + to[e];
109   }
110
111   paths = 0;
112   nb_paths = 0;
113 }
114
115 MTPGraph::~MTPGraph() {
116   delete[] _vertices;
117   delete[] _edges;
118   delete[] _front;
119   delete[] _new_front;
120   for(int p = 0; p < nb_paths; p++) delete paths[p];
121   delete[] paths;
122 }
123
124 //////////////////////////////////////////////////////////////////////
125
126 void MTPGraph::print() {
127   for(int k = 0; k < _nb_edges; k++) {
128     Edge *e = _edges + k;
129     cout << e->origin_vertex->id
130          << " -> "
131          << e->terminal_vertex->id
132          << " "
133          << e->length;
134     if(e->occupied) {
135       cout << " *";
136     }
137     cout << endl;
138   }
139 }
140
141 void MTPGraph::print_dot() {
142   cout << "digraph {" << endl;
143   cout << "  node[shape=circle];" << endl;
144   for(int k = 0; k < _nb_edges; k++) {
145     Edge *e = _edges + k;
146     if(e->occupied) {
147       cout << "  " << e->origin_vertex->id << " -> " << e->terminal_vertex->id
148            << " [style=bold,color=black,label=\"" << -e->length << "\"];" << endl;
149     } else {
150       cout << "  " << e->origin_vertex->id << " -> " << e->terminal_vertex->id
151            << " [color=gray,label=\"" << e->length << "\"];" << endl;
152     }
153   }
154   cout << "}" << endl;
155 }
156
157 //////////////////////////////////////////////////////////////////////
158
159 void MTPGraph::initialize_positivized_lengths_with_min() {
160   scalar_t length_min = 0;
161   for(int n = 0; n < _nb_vertices; n++) {
162     for(Edge *e = _vertices[n].leaving_edges; e; e = e->next_leaving_edge) {
163       length_min = min(e->length, length_min);
164     }
165   }
166   for(int n = 0; n < _nb_vertices; n++) {
167     for(Edge *e = _vertices[n].leaving_edges; e; e = e->next_leaving_edge) {
168       e->positivized_length = e->length - length_min;
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 += e->terminal_vertex->distance_from_source - e->terminal_vertex->distance_from_source;
177   }
178 }
179
180 void MTPGraph::force_positivized_lengths() {
181 #ifdef VERBOSE
182   scalar_t residual_error = 0.0;
183 #endif
184   for(int n = 0; n < _nb_vertices; n++) {
185     for(Edge *e = _vertices[n].leaving_edges; e; e = e->next_leaving_edge) {
186       if(e->positivized_length < 0) {
187 #ifdef VERBOSE
188         residual_error -= e->positivized_length;
189 #endif
190         e->positivized_length = 0.0;
191       }
192     }
193   }
194 #ifdef VERBOSE
195   cerr << "residual_error " << residual_error << endl;
196 #endif
197 }
198
199 // This method does not change the edge occupation. It update
200 // distance_from_source and best_pred_edge_to_source.
201 void MTPGraph::find_shortest_path(Vertex **_front, Vertex **_new_front) {
202   Vertex **tmp_front;
203   int tmp_front_size;
204   Vertex *v, *tv;
205   Edge *e;
206   scalar_t d;
207
208   for(int v = 0; v < _nb_vertices; v++) {
209     _vertices[v].distance_from_source = FLT_MAX;
210     _vertices[v].best_pred_edge_to_source = 0;
211     _vertices[v].iteration = 0;
212   }
213
214   int iteration = 0;
215
216   int _front_size = 0, _new_front_size;
217   _front[_front_size++] = _source;
218   _source->distance_from_source = 0;
219
220   do {
221     _new_front_size = 0;
222     iteration++;
223     for(int f = 0; f < _front_size; f++) {
224       v = _front[f];
225       for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
226         d = v->distance_from_source + e->positivized_length;
227         tv = e->terminal_vertex;
228         if(d < tv->distance_from_source) {
229           tv->distance_from_source = d;
230           tv->best_pred_edge_to_source = e;
231           if(tv->iteration < iteration) {
232             _new_front[_new_front_size++] = tv;
233             tv->iteration = iteration;
234           }
235         }
236       }
237     }
238
239     tmp_front = _new_front;
240     _new_front = _front;
241     _front = tmp_front;
242
243     tmp_front_size = _new_front_size;
244     _new_front_size = _front_size;
245     _front_size = tmp_front_size;
246   } while(_front_size > 0);
247 }
248
249 void MTPGraph::find_best_paths(scalar_t *lengths, int *result_edge_occupation) {
250   scalar_t total_length;
251   Vertex *v;
252   Edge *e;
253
254   for(int e = 0; e < _nb_edges; e++) {
255     _edges[e].length = lengths[e];
256     _edges[e].positivized_length = _edges[e].length;
257   }
258
259   // We use one iteration of find_shortest_path simply to propagate
260   // the distance to make all the edge lengths positive.
261   find_shortest_path(_front, _new_front);
262   update_positivized_lengths();
263
264   // #warning
265   // initialize_positivized_lengths_with_min();
266
267   do {
268     force_positivized_lengths();
269     find_shortest_path(_front, _new_front);
270     update_positivized_lengths();
271
272     total_length = 0.0;
273
274     // Do we reach the _sink?
275     if(_sink->best_pred_edge_to_source) {
276       // If yes, compute the length of the best path
277       v = _sink;
278       while(v->best_pred_edge_to_source) {
279         total_length += v->best_pred_edge_to_source->length;
280         v = v->best_pred_edge_to_source->origin_vertex;
281       }
282       // If that length is negative
283       if(total_length < 0.0) {
284 #ifdef VERBOSE
285         cout << "Found a path of length " << total_length << endl;
286 #endif
287         // Invert all the edges along the best path
288         v = _sink;
289         while(v->best_pred_edge_to_source) {
290           e = v->best_pred_edge_to_source;
291           v = e->origin_vertex;
292           e->revert();
293           // This is the only place where we change the occupations of
294           // edges
295           e->occupied = 1 - e->occupied;
296         }
297       }
298     }
299
300   } while(total_length < 0.0);
301
302   for(int k = 0; k < _nb_edges; k++) {
303     Edge *e = _edges + k;
304     if(e->occupied) { e->revert(); }
305     result_edge_occupation[k] = e->occupied;
306   }
307 }
308
309 void MTPGraph::retrieve_paths() {
310   Edge *e;
311
312   for(int p = 0; p < nb_paths; p++) delete paths[p];
313   delete[] paths;
314
315   nb_paths = 0;
316   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
317     if(e->occupied) { nb_paths++; }
318   }
319
320   paths = new Path *[nb_paths];
321
322   int p = 0;
323   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
324     if(e->occupied) {
325       paths[p] = new Path();
326       p++;
327     }
328   }
329
330   cout << "NB_PATHS " << nb_paths << endl;
331 }