-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.cpp
More file actions
315 lines (288 loc) · 8.48 KB
/
graph.cpp
File metadata and controls
315 lines (288 loc) · 8.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/*
* Graph - resolution
*
* GNU General Publick License v3.0 (https://www.gnu.org/licenses/gpl-3.0.html)
*
* Graph is a simple library for solving a Path Finding problem on non-cyclic directed Graphs,
* being the output a list of Paths connecting Nodes.
* The algorithm, unlike other Shortest Path algorithms, doesn't compute the sum of costs
* between nodes of the Path, but computes the average. As a result, this algorithm is more
* suited for problems where interconnected nodes represent the same object or entity, and where
* the edge between two nodes represents the likelihood these two nodes correspond to the same entity.
*
* The algorithm, called ENBP (End-Node Back Propagation) is documented and to be published in paper
* form. This note will be uptated should the paper be accepted for publication.
*
* As Graph depends on other libraries, the user must adhere to and keep in place any
* licencing terms of those libraries:
*
* * OpenCV v3.0.0 (or any other version) (http://opencv.org)
*
* License Agreement for OpenCV
* ------------------------------------------------------------------------
* BSD 2-Clause License (http://opensource.org/licenses/bsd-license.php)
* The dependence of the "Non-free" module of OpenCV is excluded from VCD.
*
*/
// -- STL -- //
#include <iostream>
#include <iterator>
#include <chrono> // for high_resolution_clock
// -- OpenCV -- //
#include <opencv2/core/persistence.hpp>
// -- Project -- //
#include "graph.h"
using namespace std;
using namespace cv;
void Graph::computePaths(const cv::Mat& _weights, std::vector<Graph::Path>& _paths)
{
if (verbose)
std::cout << "Computing Paths from Graph(" << _weights.rows << " nodes):" << std::endl;
Mat rows, cols;
// Compute sums of matrix in cols and rows
reduce(_weights, rows, 1, CV_REDUCE_SUM, CV_32F);
reduce(_weights, cols, 0, CV_REDUCE_SUM, CV_32F);
// Find end-nodes with incoming edge
vector<int> finalNodes;
if(verbose)
cout << "Final nodes: " << endl;
for (int i = 0; i<numNodes; ++i)
{
if (rows.at<float>(i, 0) == 0.0f && cols.at<float>(0, i) != 0.0f) // rows==0 so there is no departing edge, and cols!=0 so there are incoming edges
{
finalNodes.push_back(i);
if (verbose)
cout << "\tNode " << i << endl;
}
}
// Iterate and create Paths
for (size_t i = 0; i<finalNodes.size(); ++i)
{
Path path;
iteration(path, finalNodes[i], _paths, _weights, cols);
}
// Reverse paths
for (size_t p = 0; p<_paths.size(); ++p)
{
_paths[p].reversePath();
if (verbose)
{
std::cout << "Path[" << p << "]";
_paths[p].printf();
}
}
}
Graph::Graph(const cv::Mat& _weights, bool _verbose):verbose(_verbose)
{
// Weights or likelihood should be a squared matrix
assert(!_weights.empty());
assert(_weights.cols == _weights.rows);
assert(_weights.type() == CV_32F);
// Number of nodes (Nodes here represent each element of the graph)
numNodes = _weights.cols;
// Compute paths using the weights matrix
computePaths(_weights, paths);
// ----------------------
// GREEDY ALGORITHM
// ----------------------
// Determine best Path, remove it and recompute Graph
int bestPathId = -1;
float bestWeight = 0.0f;
for (int i = 0; i<(int)paths.size(); ++i)
{
float val = paths[i].getWeight();
if (val > bestWeight)
{
bestWeight = val;
bestPathId = i;
}
}
if (paths.size() > 0)
{
if (verbose)
std::cout << "Best path: " << bestPathId << std::endl;
bestPaths.push_back(paths[bestPathId]);
// Find other best paths
vector<Path> currentPaths = paths;
int numNodesCurrent = numNodes;
int currentBestPathId = bestPathId;
Mat weightsCurrent = _weights;
while (true)
{
// Recompute matrix and create new Graph
Mat weightsRe;
Mat colsRe, rowsRe;
int numNodesBestPath = currentPaths[currentBestPathId].getNumNodes();
if (numNodesBestPath >= numNodesCurrent)
{
// No more nodes!
break;
}
else
{
// More nodes, select next best path
weightsCurrent.copyTo(weightsRe);
// Compose the weightsRe matrix
vector<int> nodesBestPath = currentPaths[currentBestPathId].getNodes();
if (verbose)
std::cout << "Removing nodes: ";
for (size_t n = 0; n<nodesBestPath.size(); ++n)
{
if (verbose)
std::cout << nodesBestPath[n] << " ";
weightsRe.row(nodesBestPath[n]).setTo(0.0f);
weightsRe.col(nodesBestPath[n]).setTo(0.0f);
}
if (verbose)
std::cout << std::endl;
vector<Path> remainingPaths;
/* for( size_t i=0; i<currentPaths.size(); ++i )
if( i != currentBestPathId )
remainingPaths.push_back( currentPaths[i] );
*/
computePaths(weightsRe, remainingPaths);
if (remainingPaths.size() > 0)
{
// Determine best Path, remove it and recompute Graph
int bestPathId = -1;
float bestWeight = 0.0f;
for (int i = 0; i<(int)remainingPaths.size(); ++i)
{
float val = remainingPaths[i].getWeight();
if (val > bestWeight)
{
bestWeight = val;
bestPathId = i;
}
}
bestPaths.push_back(remainingPaths[bestPathId]);
// Iterate
currentPaths = remainingPaths;
numNodesCurrent -= numNodesBestPath;
currentBestPathId = bestPathId;
weightsCurrent = weightsRe;
}
else
break;
}
}
}
// ----------------------
// Add isolated Nodes as (best) Paths
// ----------------------
for (int n = 0; n<numNodes; ++n)
{
// Check if this node can be found in any of the best paths
bool found = false;
for (size_t bp = 0; bp<bestPaths.size(); ++bp)
{
vector<int> nodes = bestPaths[bp].getNodes();
if (find(nodes.begin(), nodes.end(), n) != nodes.end())
{
found = true;
break;
}
}
if (found)
continue;
else
{
Path singleNodePath;
singleNodePath.addNode(n);
bestPaths.push_back(singleNodePath);
}
}
// Printf best paths
if (_verbose)
{
std::cout << "Best paths: " << std::endl;
for (size_t i = 0; i<bestPaths.size(); ++i)
{
std::cout << "[" << i << "] - ";
bestPaths[i].printf();
}
}
}
void Graph::iteration(Graph::Path _currentPath, int _currentNode, std::vector<Graph::Path>& _pathVector, const cv::Mat& _weights, const cv::Mat& _cols)
{
// Copy of current Path for have a static base path not modified in recursive iterations
Path currentPathCopy = _currentPath;
// Count number of backconnections
vector<int> backConnections;
for (int j = _currentNode; j >= 0; --j)
if (_weights.at<float>(j, _currentNode) > 0.0f)
backConnections.push_back(j);
// Create a path for each backconnection
for (size_t j = 0; j<backConnections.size(); ++j)
{
if (j == 0)
{
// The first connection updates the path, doesn't create a new one
_currentPath.addEdge(_currentNode, backConnections[j], _weights.at<float>(backConnections[j], _currentNode));
if (_cols.at<float>(0, backConnections[j]) == 0)
{
// If start node, insert into path
_pathVector.push_back(_currentPath);
}
else
{
// Recursive
iteration(_currentPath, backConnections[j], _pathVector, _weights, _cols);
}
}
else
{
// Add a new Path
Path path = currentPathCopy; // use currentPath instead of _currentPath because it might have been modified in the previous iteration
path.addEdge(_currentNode, backConnections[j], _weights.at<float>(backConnections[j], _currentNode));
if (_cols.at<float>(0, backConnections[j]) == 0)
{
// If end node, insert into path
_pathVector.push_back(path);
}
else
{
// Recursive
iteration(path, backConnections[j], _pathVector, _weights, _cols);
}
}
}
}
void Graph::Path::addNode(int id)
{
vector<int>::iterator it = find(nodes.begin(), nodes.end(), id);
if (it == nodes.end())
{
// not found: add
nodes.push_back(id);
}
}
void Graph::Path::reversePath()
{
std::reverse(nodes.begin(), nodes.end());
std::reverse(weights.begin(), weights.end());
}
void Graph::Path::addEdge(int id1, int id2, float w12)
{
addNode(id1);
addNode(id2);
addWeight(w12);
}
float Graph::Path::getWeight() const
{
float sum = 0;
for (size_t i = 0; i<weights.size(); ++i)
sum += weights[i];
if (weights.size() > 0)
sum /= weights.size();
return sum;
}
void Graph::Path::printf() const
{
cout << " - Nodes: ";
for (size_t i = 0; i<nodes.size(); ++i)
{
cout << nodes[i] << " ";
}
cout << "; Weight: " << getWeight() << endl;
}