Cosmetics.
[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 #include <stdlib.h>
30
31 using namespace std;
32
33 class Edge {
34 public:
35   int id, occupied;
36   scalar_t length, positivized_length;
37   Vertex *origin_vertex, *terminal_vertex;
38
39   // These are the links in the origin_vertex leaving edge list
40   Edge *next_leaving_edge, *pred_leaving_edge;
41
42   inline void invert();
43 };
44
45 class Vertex {
46 public:
47   int id;
48   Edge *leaving_edges;
49   scalar_t distance_from_source;
50   Edge *pred_edge_toward_source;
51
52   int iteration; // Used in find_shortest_path to know if we already
53                  // added this vertex to the front
54   Vertex();
55   inline void add_leaving_edge(Edge *e);
56   inline void del_leaving_edge(Edge *e);
57 };
58
59 //////////////////////////////////////////////////////////////////////
60
61 void Edge::invert() {
62   length = - length;
63   positivized_length = 0;
64   origin_vertex->del_leaving_edge(this);
65   terminal_vertex->add_leaving_edge(this);
66   Vertex *t = terminal_vertex;
67   terminal_vertex = origin_vertex;
68   origin_vertex = t;
69 }
70
71 //////////////////////////////////////////////////////////////////////
72
73 Vertex::Vertex() {
74   leaving_edges = 0;
75 }
76
77 void Vertex::add_leaving_edge(Edge *e) {
78   e->next_leaving_edge = leaving_edges;
79   e->pred_leaving_edge = 0;
80   if(leaving_edges) { leaving_edges->pred_leaving_edge = e; }
81   leaving_edges = e;
82 }
83
84 void Vertex::del_leaving_edge(Edge *e) {
85   if(e == leaving_edges) {
86     leaving_edges = e->next_leaving_edge;
87   }
88   if(e->pred_leaving_edge) {
89     e->pred_leaving_edge->next_leaving_edge = e->next_leaving_edge;
90   }
91   if(e->next_leaving_edge) {
92     e->next_leaving_edge->pred_leaving_edge = e->pred_leaving_edge;
93   }
94 }
95
96 //////////////////////////////////////////////////////////////////////
97
98 MTPGraph::MTPGraph(int nb_vertices, int nb_edges,
99                    int *vertex_from, int *vertex_to,
100                    int source, int sink) {
101   _nb_vertices = nb_vertices;
102   _nb_edges = nb_edges;
103
104   _edges = new Edge[_nb_edges];
105   _vertices = new Vertex[_nb_vertices];
106   _front = new Vertex *[_nb_vertices];
107   _new_front = new Vertex *[_nb_vertices];
108
109   _source = &_vertices[source];
110   _sink = &_vertices[sink];
111
112   for(int v = 0; v < _nb_vertices; v++) {
113     _vertices[v].id = v;
114   }
115
116   for(int e = 0; e < nb_edges; e++) {
117     _vertices[vertex_from[e]].add_leaving_edge(_edges + e);
118     _edges[e].occupied = 0;
119     _edges[e].id = e;
120     _edges[e].origin_vertex = _vertices + vertex_from[e];
121     _edges[e].terminal_vertex = _vertices + vertex_to[e];
122   }
123
124   paths = 0;
125   nb_paths = 0;
126 }
127
128 MTPGraph::~MTPGraph() {
129   delete[] _vertices;
130   delete[] _edges;
131   delete[] _front;
132   delete[] _new_front;
133   for(int p = 0; p < nb_paths; p++) delete paths[p];
134   delete[] paths;
135 }
136
137 //////////////////////////////////////////////////////////////////////
138
139 void MTPGraph::print(ostream *os) {
140   for(int k = 0; k < _nb_edges; k++) {
141     Edge *e = _edges + k;
142     (*os) << e->origin_vertex->id
143          << " -> "
144          << e->terminal_vertex->id
145          << " "
146          << e->length;
147     if(e->occupied) {
148       (*os) << " *";
149     }
150     (*os) << endl;
151   }
152 }
153
154 void MTPGraph::print_dot(ostream *os) {
155   (*os) << "digraph {" << endl;
156   (*os) << "        node [shape=circle,width=0.75,fixedsize=true];" << endl;
157   (*os) << "        edge [color=gray,arrowhead=open]" << endl;
158   (*os) << "        " << _source->id << " [peripheries=2];" << endl;
159   (*os) << "        " << _sink->id << " [peripheries=2];" << endl;
160   // (*os) << "        " << _source->id << " [style=bold,color=red];" << endl;
161   // (*os) << "        " << _sink->id << " [style=bold,color=green];" << 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 n = 0; n < _nb_vertices; n++) {
193     for(Edge *e = _vertices[n].leaving_edges; e; e = e->next_leaving_edge) {
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   }
203 #ifdef VERBOSE
204   cerr << "residual_error " << residual_error << " max_error " << residual_error << endl;
205 #endif
206 }
207
208 // This method does not change the edge occupation. It update
209 // distance_from_source and pred_edge_toward_source.
210 void MTPGraph::find_shortest_path() {
211   Vertex **tmp_front;
212   int tmp_front_size;
213   Vertex *v, *tv;
214   Edge *e;
215   scalar_t d;
216
217   for(int v = 0; v < _nb_vertices; v++) {
218     _vertices[v].distance_from_source = FLT_MAX;
219     _vertices[v].pred_edge_toward_source = 0;
220     _vertices[v].iteration = 0;
221   }
222
223   int iteration = 0;
224
225   int _front_size = 0, _new_front_size;
226   _front[_front_size++] = _source;
227   _source->distance_from_source = 0;
228
229   do {
230     _new_front_size = 0;
231     iteration++;
232
233     for(int f = 0; f < _front_size; f++) {
234       v = _front[f];
235       for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
236         d = v->distance_from_source + e->positivized_length;
237         tv = e->terminal_vertex;
238         if(d < tv->distance_from_source) {
239           tv->distance_from_source = d;
240           tv->pred_edge_toward_source = e;
241           if(tv->iteration < iteration) {
242             _new_front[_new_front_size++] = tv;
243             tv->iteration = iteration;
244           }
245         }
246       }
247     }
248
249     tmp_front = _new_front;
250     _new_front = _front;
251     _front = tmp_front;
252
253     tmp_front_size = _new_front_size;
254     _new_front_size = _front_size;
255     _front_size = tmp_front_size;
256   } while(_front_size > 0);
257 }
258
259 void MTPGraph::find_best_paths(scalar_t *lengths) {
260   scalar_t total_length;
261   Vertex *v;
262   Edge *e;
263
264   for(int e = 0; e < _nb_edges; e++) {
265     _edges[e].length = lengths[e];
266     _edges[e].occupied = 0;
267     _edges[e].positivized_length = _edges[e].length;
268   }
269
270   // We use one iteration of find_shortest_path simply to propagate
271   // the distance to make all the edge lengths positive.
272   find_shortest_path();
273
274   do {
275     update_positivized_lengths();
276     force_positivized_lengths();
277     find_shortest_path();
278
279     total_length = 0.0;
280
281     // Do we reach the _sink?
282     if(_sink->pred_edge_toward_source) {
283       // If yes, compute the length of the best path
284       v = _sink;
285       while(v->pred_edge_toward_source) {
286         total_length += v->pred_edge_toward_source->length;
287         v = v->pred_edge_toward_source->origin_vertex;
288       }
289       // If that length is negative
290       if(total_length < 0.0) {
291 #ifdef VERBOSE
292         cerr << "Found a path of length " << total_length << endl;
293 #endif
294         // Invert all the edges along the best path
295         v = _sink;
296         while(v->pred_edge_toward_source) {
297           e = v->pred_edge_toward_source;
298           v = e->origin_vertex;
299           e->invert();
300           // This is the only place where we change the occupations of
301           // edges
302           e->occupied = 1 - e->occupied;
303         }
304       }
305     }
306
307   } while(total_length < 0.0);
308
309   // Put back the graph in its original state (i.e. invert edges which
310   // have been inverted in the process)
311   for(int k = 0; k < _nb_edges; k++) {
312     Edge *e = _edges + k;
313     if(e->occupied) { e->invert(); }
314   }
315 }
316
317 int MTPGraph::retrieve_one_path(Edge *e, Path *path) {
318   Edge *f, *next = 0;
319   int l = 0;
320
321   if(path) {
322     path->nodes[l++] = e->origin_vertex->id;
323     path->length = e->length;
324   } else l++;
325
326   while(e->terminal_vertex != _sink) {
327     if(path) {
328       path->nodes[l++] = e->terminal_vertex->id;
329       path->length += e->length;
330     } else l++;
331     int nb_choices = 0;
332     for(f = e->terminal_vertex->leaving_edges; f; f = f->next_leaving_edge) {
333       if(f->occupied) { nb_choices++; next = f; }
334       if(nb_choices == 0) {
335         cerr << "retrieve_one_path: Non-sink end point." << endl;
336         abort();
337       }
338       if(nb_choices > 1) {
339         cerr << "retrieve_one_path: Non node-disjoint paths." << endl;
340         abort();
341       }
342     }
343     e = next;
344   }
345
346   if(path) {
347     path->nodes[l++] = e->terminal_vertex->id;
348     path->length += e->length;
349   } else l++;
350
351   return l;
352 }
353
354 void MTPGraph::retrieve_disjoint_paths() {
355   Edge *e;
356
357   for(int p = 0; p < nb_paths; p++) delete paths[p];
358   delete[] paths;
359
360   nb_paths = 0;
361   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
362     if(e->occupied) { nb_paths++; }
363   }
364
365   paths = new Path *[nb_paths];
366
367   int p = 0;
368   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
369     if(e->occupied) {
370       int l = retrieve_one_path(e, 0);
371       paths[p] = new Path(l);
372       retrieve_one_path(e, paths[p]);
373       p++;
374     }
375   }
376 }