KQuickShift.cc
13.7 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <stdexcept>
#include <map>
#include <set>
#include <list>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <queue>
#include <cmath>
#include <cstdio>
#include <cassert>
using namespace std;
//---------------------------------------------------------------------------------
template <class OutType, class InType>
OutType stream_cast(const InType & t)
{
stringstream ss;
ss << t; // first insert value to stream
OutType result; // value will be converted to OutType
ss >> result; // write value to result
return result;}
//---------------------------------------------------------------------------------
class ParametersClass{
public:
ParametersClass():mSimilarityMatrixFileName(""),
mBinaryTree(false),
mDebug(false){}
void Init(int argc, char** argv){
vector<string> options;
for (int i=1;i<argc;i++) options.push_back(argv[i]);
for (vector<string>::iterator it=options.begin();it!=options.end();++it)
{
if ((*it)=="-h" || (*it)=="--help") {cerr<<"Usage: "<<argv[0]<<endl
<<"-sm <similarity matrix file name>"<<endl
<<"-b <force binary tree>"<<endl
<<"[-d <debug flag> (default: false)]"<<endl;
throw exception();}
else if ((*it)=="-sm") mSimilarityMatrixFileName=(*(++it));
else if ((*it)=="-b") mBinaryTree=true;
else if ((*it)=="-d") mDebug=true;
else {cerr<<"Unrecognized parameter: "<<(*it)<<"."<<endl;throw exception();}
}
//check constraints
if (mSimilarityMatrixFileName=="") {cerr<<"Missing param -sm "<<endl;throw exception();}
}
public:
string mSimilarityMatrixFileName;
bool mBinaryTree;
bool mDebug;
};
ParametersClass PARAM;
//---------------------------------------------------------------------------------
class MatrixClass{
friend ostream& operator<<(ostream& out,const MatrixClass& aM){aM.Output(out);return out;}
public:
MatrixClass():mRowSize(0),mColSize(0),mM(0){}
~MatrixClass(){Clear();}
MatrixClass(unsigned aRowSize,unsigned aColSize){Init(aRowSize,aColSize);}
void operator=(const MatrixClass& aMat){
mRowSize=aMat.mRowSize;
mColSize=aMat.mColSize;
Init(mRowSize,mColSize);
for (unsigned i=0;i<mRowSize;i++)
for(unsigned j=0;j<mColSize;++j)
mM[i][j]=aMat.mM[i][j];
}
MatrixClass(const MatrixClass& aMat){
(*this)=aMat;
}
void Init(unsigned aRowSize, unsigned aColSize){
mRowSize=aRowSize;
mColSize=aColSize;
mM=new double*[mRowSize];
for (unsigned i=0;i<mRowSize;++i){
mM[i]=new double[mColSize];
for (unsigned j=0; j<mColSize;++j)
mM[i][j]=0;
}
}
void Import(const string& aFileName){
ifstream fin;
fin.open(aFileName.c_str());
if (!fin){cerr<<"Cannot open file: "<<aFileName<<endl;throw exception();}
string line;
int counter_i, counter_j;
//read size
counter_i=0;counter_j=0;
while(getline(fin,line)){
if (line!=""){
stringstream ss;
ss<<line;
int temp_counter_j=counter_j;
counter_j=0;
while(ss.good()){
string value_str;
ss>>value_str;
if (value_str!="") counter_j++;
}
if (temp_counter_j!=0)
if (temp_counter_j!=counter_j) {cerr<<">ERROR: Non constant column size"<<endl;throw exception();}
counter_i++;
}
}
fin.close();
//init zero matrix
Init(counter_i,counter_j);
//read matrix from file
fin.open(aFileName.c_str());
counter_i=0;
while(getline(fin,line)){
if (line!=""){
stringstream ss;
ss<<line;
counter_j=0;
while(ss.good()){
string value_str;
ss>>value_str;
if (value_str!="") {
mM[counter_i][counter_j]=stream_cast<double>(value_str);
counter_j++;
}
}
counter_i++;
}
}
}
void Clear(){
for (unsigned i=0;i<mRowSize; i++) delete[] mM[i];
delete[] mM;
}
unsigned ColSize()const{return mColSize;}
unsigned RowSize()const{return mRowSize;}
ostream& Output(ostream& out)const{
const MatrixClass& M=*this;
for (unsigned i=0;i<mRowSize;i++){
for(unsigned j=0;j<mColSize;++j)
out<<M(i,j)<<" ";
out<<endl;
}
return out;
}
double& operator()(unsigned i, unsigned j){assert(i<mRowSize && j<mColSize); return mM[i][j];}
double operator()(unsigned i, unsigned j)const{assert(i<mRowSize && j<mColSize); return mM[i][j];}
protected:
unsigned mRowSize;
unsigned mColSize;
double** mM;
};
//---------------------------------------------------------------------------------
class VectorClass{
friend ostream& operator<<(ostream& out,const VectorClass& aV){aV.Output(out);return out;}
public:
VectorClass(){}
VectorClass(unsigned aSize){Init(aSize);}
void operator=(const VectorClass& aVector){
mV=aVector.mV;
}
VectorClass(const VectorClass& aVector){
(*this)=aVector;
}
VectorClass(const vector<double>& aVector){
mV=aVector;
}
void Init(unsigned aSize){
mV.clear();
for (unsigned i=0;i<aSize;++i)
mV.push_back(-1);
}
void Import(const string& aFileName){
mV.clear();
ifstream fin;
fin.open(aFileName.c_str());
if (!fin){cerr<<"Cannot open file: "<<aFileName<<endl;throw exception();}
string line;
//read size
while(getline(fin,line)){
if (line!=""){
stringstream ss;
ss<<line;
while(ss.good()){
string value_str;
ss>>value_str;
if (value_str!="") mV.push_back(stream_cast<double>(value_str));
}
}
}
fin.close();
}
void Clear(){mV.clear();}
unsigned Size()const{return mV.size();}
ostream& Output(ostream& out)const{
for (unsigned i=0;i<Size();i++)
out<<mV[i]<<" ";
return out;
}
void PushBack(double aValue){mV.push_back(aValue);}
double& operator[](unsigned i){assert(i<Size()); return mV[i];}
double operator[](unsigned i)const{assert(i<Size()); return mV[i];}
double Sum()const{
double avg=0;
for (unsigned i=0;i<Size();i++) avg+=mV[i];
return avg;
}
double Mean()const{
return Sum()/Size();
}
double StandardDeviation()const{
double avg=Mean();
double sd=0;
for (unsigned i=0;i<Size();i++) sd+=(mV[i]-avg)*(mV[i]-avg);
sd=sd/(Size()-1);
sd=sqrt(sd);
return sd;
}
double Order(double aOrder)const{
vector<double> v(mV);
sort(v.begin(),v.end());
if (aOrder==0) return v[0];
else if (aOrder==1) return v[v.size()-1];
else return v[stream_cast<unsigned>((double)Size()*aOrder)];
}
double Median()const{
return Order(.5);
}
double MedianAbsoluteDifference()const{
double median=Median();
VectorClass v;
for (unsigned i=0;i<Size();i++) v.PushBack(fabs(mV[i]-median));
return v.Median();
}
double Min()const{
return Order(0);
}
double Max()const{
return Order(1);
}
VectorClass RemoveNulls(){
VectorClass v;
for (unsigned i=0;i<Size();i++) if(mV[i]!=-1) v.PushBack(mV[i]);
return v;
}
ostream& OutputStatistics(ostream& out){
VectorClass v=RemoveNulls();
if (v.Size()>0){
out<<"num: "<<v.Size()<<" sum: "<<v.Sum()<<" avg: "<<v.Mean()<<" sd: "<<v.StandardDeviation();
out<<" min: "<<v.Min()<<" Q.05: "<<v.Order(.05)<<" Q.25: "<<v.Order(.25)<<" Q.5: "<<v.Median()<<" Q.75: "<<v.Order(.75)<<" Q.95: "<<v.Order(.95)<<" max: "<<v.Max();
} else {}
return out;
}
protected:
vector<double> mV;
};
//---------------------------------------------------------------------------------
double Similarity2Distance(unsigned i,unsigned j, const MatrixClass& aM){
return 1-aM(i,j)/sqrt(aM(i,i)*aM(j,j));
}
//---------------------------------------------------------------------------------
class PairwiseSimilarityClass{
friend ostream& operator<<(ostream& out, const PairwiseSimilarityClass& aM){aM.Output(out);return out;}
public:
PairwiseSimilarityClass(){}
void KQuickShift(){
SortSimilarityIndexMatrix();
ComputeCentrality();
BuildChildParentMap();
BuildTree();
if (PARAM.mBinaryTree) {
BinarizeChildParentMap();
}
}
void Import(){
mSimilarityMatrix.Import(PARAM.mSimilarityMatrixFileName);
}
void Output(ostream& out)const{
out<<"Matrix:"<<endl;
out<<mSimilarityMatrix<<endl;
}
void SortSimilarityIndexMatrix(){
SortSimilarityIndexMatrix(mSimilarityMatrix.ColSize());
}
void SortSimilarityIndexMatrix(unsigned aRange){
mSortedSimilarityIndexMatrix.Init(mSimilarityMatrix.RowSize(),aRange);
//for each row in similarity matrix
for (unsigned i=0;i<mSimilarityMatrix.RowSize();i++){
//sort row according to similarity value in descending order (i.e. greater similarities first) and preserving index information
vector<pair<double,unsigned> > row;
for (unsigned j=0;j<(unsigned)mSimilarityMatrix.ColSize();j++){
row.push_back(make_pair(mSimilarityMatrix(i,j),j));
}
partial_sort(row.begin(),row.begin()+aRange,row.end(),greater<pair<double,unsigned> >());
for (unsigned j=0;j<aRange;j++){
unsigned element_index=row[j].second;//retrieve the index of the sorted element
mSortedSimilarityIndexMatrix(i,j)=element_index;
}//for column in similarity matrix
}//for row
}
void ComputeCentrality(){
//centrality is the sum of the similarities row-wise
for (unsigned i=0;i<mSimilarityMatrix.RowSize();i++){
double centrality=0;
for (unsigned j=0;j<mSimilarityMatrix.ColSize();j++){
centrality+=mSimilarityMatrix(i,j);
}
mCentrality.push_back(centrality);
}
}
unsigned FindNearestMoreCentralNeighbour(unsigned i){
unsigned max_i=mSortedSimilarityIndexMatrix(i,0);
double max_v=mCentrality[max_i];
for (unsigned j=0;j<mSimilarityMatrix.RowSize();j++){
unsigned current_i=mSortedSimilarityIndexMatrix(i,j);
double current_v=mCentrality[current_i];
if (max_v<current_v){
max_i=current_i;
max_v=current_v;
break;
}
}
return max_i;
}
void BuildChildParentMap(){
//connect each element to the closest neighbour with higher centrality (which becomes its parent)
for (unsigned i=0;i<mSimilarityMatrix.RowSize();i++){
unsigned p=Parent(i);
mParentMap.push_back(p);
}
}
unsigned Parent(unsigned i){
unsigned parent=0;
if (mParentMap.size()>i) parent=mParentMap[i];
else parent=FindNearestMoreCentralNeighbour(i);
return parent;
}
const unsigned Parent(unsigned i)const{
return mParentMap[i];
}
void BuildTree(){
//init
mTree.clear();
for (unsigned i=0;i<mSimilarityMatrix.RowSize();i++){
mTree.push_back(vector<unsigned>());
}
//for each vertex find parent
for (unsigned i=0;i<mSimilarityMatrix.RowSize();i++){
unsigned child=i;
unsigned parent=Parent(child);
//add child to parent
mTree[parent].push_back(child);
}
}
void BinarizeChildParentMap(){
vector<unsigned> new_parent_map(mParentMap);//copy parent map
//for each vertex
for (unsigned i=0;i<mSimilarityMatrix.RowSize();i++){
unsigned parent=Parent(i);
//if a parent has more than 2 children...
if (mTree[parent].size()>2){
//sort siblings by centrality
vector<pair<double,unsigned> > siblings_list;
for(unsigned j=0;j<mTree[parent].size();j++){
unsigned child=mTree[parent][j];
double centrality=mCentrality[child];
siblings_list.push_back(make_pair(centrality,child));
}
sort(siblings_list.begin(),siblings_list.end());
//rewire parent relationship with new linear order between siblings
for(unsigned j=0;j<siblings_list.size()-1;j++){
unsigned child=siblings_list[j].second;
unsigned new_parent=siblings_list[j+1].second;
new_parent_map[child]=new_parent;//update parent map
}
//note: top central child is already wired to correct parent
}
}
mParentMap=new_parent_map;
}
void FindPath(){
for (unsigned i=0;i<mSimilarityMatrix.RowSize();i++){
vector<unsigned> path=FindPath(i);
mPathsList.push_back(path);
}
}
vector<unsigned> FindPath(unsigned i){
unsigned current=i;
vector<unsigned> path;
path.push_back(current);
unsigned parent=Parent(current);
while (parent!=current){
path.push_back(parent);
current=parent;
parent=Parent(current);
}
return path;
}
double PathDistance(unsigned i, unsigned j){
if(i==j) return 0;
//start from root
assert(mPathsList[i].size()>0);
assert(mPathsList[j].size()>0);
int it=mPathsList[i].size()-1;
int jt=mPathsList[j].size()-1;
//go down until ii and jj differ
while(it>=0 && jt>=0 && mPathsList[i][it]==mPathsList[j][jt]){it-=1;jt-=1;}
//compute distance
double dist_i=0;
for(int ii=0;ii<=it;ii++)
dist_i+=Similarity2Distance(mPathsList[i][ii],mPathsList[i][ii+1],mSimilarityMatrix);
double dist_j=0;
for(int jj=0;jj<=jt;jj++)
dist_j+=Similarity2Distance(mPathsList[j][jj],mPathsList[j][jj+1],mSimilarityMatrix);
return dist_i+dist_j;
}
void Save(){
SaveParent();
}
void SaveParent()
{
string fname=PARAM.mSimilarityMatrixFileName+".tree";
ofstream fout(fname.c_str());
assert(fout);
OutputParent(fout);
fout.close();
}
void OutputPaths(ostream& out)const{
for (unsigned i=0;i<mSimilarityMatrix.RowSize();i++){
out<<i<<" ";
for (unsigned j=0;j<mPathsList[i].size();j++)
out<<mPathsList[i][j]<<" ";
out<<endl;
}
}
void OutputParent(ostream& out)const{
for (unsigned i=0;i<mSimilarityMatrix.RowSize();i++){
out<<i<<" "<<Parent(i)<<endl;
}
}
public:
vector<unsigned> mParentMap;
vector<vector<unsigned> > mPathsList;
vector<vector<unsigned> > mTree;
vector<double> mCentrality;
MatrixClass mSimilarityMatrix;
MatrixClass mSortedSimilarityIndexMatrix;
};
//---------------------------------------------------------------------------------
int main(int argc, char** argv){
try
{
srand(time(NULL));
PARAM.Init(argc,argv);
PairwiseSimilarityClass S;
S.Import();
S.KQuickShift();
S.Save();
}
catch(exception& e)
{
cerr<<e.what();
}
return 0;
}