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