-
Notifications
You must be signed in to change notification settings - Fork 0
/
index_ssg.cpp
778 lines (711 loc) · 23.5 KB
/
index_ssg.cpp
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
#include "index_ssg.h"
#include <omp.h>
#include <bitset>
#include <boost/dynamic_bitset.hpp>
#include <chrono>
#include <cmath>
#include <queue>
#include "exceptions.h"
#include "parameters.h"
constexpr double kPi = std::acos(-1);
namespace efanna2e {
#define _CONTROL_NUM 100
IndexSSG::IndexSSG(const size_t dimension, const size_t n, Metric m,
Index *initializer)
: Index(dimension, n, m), initializer_{initializer} {}
IndexSSG::~IndexSSG() {}
void IndexSSG::Save(const char *filename) {
std::ofstream out(filename, std::ios::binary | std::ios::out);
assert(final_graph_.size() == nd_);
out.write((char *)&width, sizeof(unsigned));
unsigned n_ep=eps_.size();
out.write((char *)&n_ep, sizeof(unsigned));
out.write((char *)eps_.data(), n_ep*sizeof(unsigned));
for (unsigned i = 0; i < nd_; i++) {
unsigned GK = (unsigned)final_graph_[i].size();
out.write((char *)&GK, sizeof(unsigned));
out.write((char *)final_graph_[i].data(), GK * sizeof(unsigned));
}
out.close();
}
void IndexSSG::Load(const char *filename) {
std::ifstream in(filename, std::ios::binary);
in.read((char *)&width, sizeof(unsigned));
unsigned n_ep=0;
in.read((char *)&n_ep, sizeof(unsigned));
eps_.resize(n_ep);
in.read((char *)eps_.data(), n_ep*sizeof(unsigned));
// width=100;
unsigned cc = 0;
while (!in.eof()) {
unsigned k;
in.read((char *)&k, sizeof(unsigned));
if (in.eof()) break;
cc += k;
std::vector<unsigned> tmp(k);
in.read((char *)tmp.data(), k * sizeof(unsigned));
final_graph_.push_back(tmp);
}
cc /= nd_;
std::cerr << "Average Degree = " << cc << std::endl;
}
void IndexSSG::Load_nn_graph(const char *filename) {
std::ifstream in(filename, std::ios::binary);
unsigned k;
in.read((char *)&k, sizeof(unsigned));
//追溯到流的尾部,统计graph size
in.seekg(0, std::ios::end);
std::ios::pos_type ss = in.tellg();
size_t fsize = (size_t)ss;
size_t num = (unsigned)(fsize / (k + 1) / 4);
//回到流的头部
in.seekg(0, std::ios::beg);
final_graph_.resize(num);
final_graph_.reserve(num);
unsigned kk = (k + 3) / 4 * 4;
//读入KNN-Graph到final_graph
for (size_t i = 0; i < num; i++) {
in.seekg(4, std::ios::cur);
final_graph_[i].resize(k);
final_graph_[i].reserve(kk);
in.read((char *)final_graph_[i].data(), k * sizeof(unsigned));
}
in.close();
}
void IndexSSG::get_neighbors(const unsigned q, const Parameters ¶meter,
std::vector<Neighbor> &pool) {
boost::dynamic_bitset<> flags{nd_, 0};
unsigned L = parameter.Get<unsigned>("L");
flags[q] = true;
for (unsigned i = 0; i < final_graph_[q].size(); i++) {
unsigned nid = final_graph_[q][i];
for (unsigned nn = 0; nn < final_graph_[nid].size(); nn++) {
unsigned nnid = final_graph_[nid][nn];
if (flags[nnid]) continue;
flags[nnid] = true;
float dist = distance_->compare(data_ + dimension_ * q,
data_ + dimension_ * nnid, dimension_);
pool.push_back(Neighbor(nnid, dist, true));
if (pool.size() >= L) break;
}
if (pool.size() >= L) break;
}
}
void IndexSSG::get_neighbors(const float *query, const Parameters ¶meter,
std::vector<Neighbor> &retset,
std::vector<Neighbor> &fullset) {
unsigned L = parameter.Get<unsigned>("L");
retset.resize(L + 1);
std::vector<unsigned> init_ids(L);
// initializer_->Search(query, nullptr, L, parameter, init_ids.data());
std::mt19937 rng(rand());
GenRandom(rng, init_ids.data(), L, (unsigned)nd_);
boost::dynamic_bitset<> flags{nd_, 0};
L = 0;
for (unsigned i = 0; i < init_ids.size(); i++) {
unsigned id = init_ids[i];
if (id >= nd_) continue;
// std::cout<<id<<std::endl;
float dist = distance_->compare(data_ + dimension_ * (size_t)id, query,
(unsigned)dimension_);
retset[i] = Neighbor(id, dist, true);
flags[id] = 1;
L++;
}
std::sort(retset.begin(), retset.begin() + L);
int k = 0;
while (k < (int)L) {
int nk = L;
if (retset[k].flag) {
retset[k].flag = false;
unsigned n = retset[k].id;
for (unsigned m = 0; m < final_graph_[n].size(); ++m) {
unsigned id = final_graph_[n][m];
if (flags[id]) continue;
flags[id] = 1;
float dist = distance_->compare(query, data_ + dimension_ * (size_t)id,
(unsigned)dimension_);
Neighbor nn(id, dist, true);
fullset.push_back(nn);
if (dist >= retset[L - 1].distance) continue;
int r = InsertIntoPool(retset.data(), L, nn);
if (L + 1 < retset.size()) ++L;
if (r < nk) nk = r;
}
}
if (nk <= k)
k = nk;
else
++k;
}
}
void IndexSSG::init_graph(const Parameters ¶meters) {
//获取数据集特征中心点
float *center = new float[dimension_];
for (unsigned j = 0; j < dimension_; j++) center[j] = 0;
for (unsigned i = 0; i < nd_; i++) {
for (unsigned j = 0; j < dimension_; j++) {
center[j] += data_[i * dimension_ + j];
}
}
for (unsigned j = 0; j < dimension_; j++) {
center[j] /= nd_;
}
std::vector<Neighbor> tmp, pool;
// ep_ = rand() % nd_; // random initialize navigating point
//获取中心点在KNN-Graph中的最近邻点ep_
get_neighbors(center, parameters, tmp, pool);
ep_ = tmp[0].id; // For Compatibility
}
void IndexSSG::sync_prune(unsigned q, std::vector<Neighbor> &pool,
const Parameters ¶meters, float threshold,
SimpleNeighbor *cut_graph_) {
unsigned range = parameters.Get<unsigned>("R");
width = range;
unsigned start = 0;
boost::dynamic_bitset<> flags{nd_, 0};
for (unsigned i = 0; i < pool.size(); ++i) {
flags[pool[i].id] = 1;
}
for (unsigned nn = 0; nn < final_graph_[q].size(); nn++) {
unsigned id = final_graph_[q][nn];
if (flags[id]) continue;
float dist = distance_->compare(data_ + dimension_ * (size_t)q,
data_ + dimension_ * (size_t)id,
(unsigned)dimension_);
pool.push_back(Neighbor(id, dist, true));
}
std::sort(pool.begin(), pool.end());
std::vector<Neighbor> result;
if (pool[start].id == q) start++;
result.push_back(pool[start]);
while (result.size() < range && (++start) < pool.size()) {
auto &p = pool[start];
bool occlude = false;
for (unsigned t = 0; t < result.size(); t++) {
if (p.id == result[t].id) {
occlude = true;
break;
}
float djk = distance_->compare(data_ + dimension_ * (size_t)result[t].id,
data_ + dimension_ * (size_t)p.id,
(unsigned)dimension_);
float cos_ij = (p.distance + result[t].distance - djk) / 2 /
sqrt(p.distance * result[t].distance);
if (cos_ij > threshold) {
occlude = true;
break;
}
}
if (!occlude) result.push_back(p);
}
SimpleNeighbor *des_pool = cut_graph_ + (size_t)q * (size_t)range;
for (size_t t = 0; t < result.size(); t++) {
des_pool[t].id = result[t].id;
des_pool[t].distance = result[t].distance;
}
if (result.size() < range) {
des_pool[result.size()].distance = -1;
}
}
void IndexSSG::InterInsert(unsigned n, unsigned range, float threshold,
std::vector<std::mutex> &locks,
SimpleNeighbor *cut_graph_) {
SimpleNeighbor *src_pool = cut_graph_ + (size_t)n * (size_t)range;
for (size_t i = 0; i < range; i++) {
if (src_pool[i].distance == -1) break;
SimpleNeighbor sn(n, src_pool[i].distance);
size_t des = src_pool[i].id;
SimpleNeighbor *des_pool = cut_graph_ + des * (size_t)range;
std::vector<SimpleNeighbor> temp_pool;
int dup = 0;
{
LockGuard guard(locks[des]);
for (size_t j = 0; j < range; j++) {
if (des_pool[j].distance == -1) break;
if (n == des_pool[j].id) {
dup = 1;
break;
}
temp_pool.push_back(des_pool[j]);
}
}
if (dup) continue;
temp_pool.push_back(sn);
if (temp_pool.size() > range) {
std::vector<SimpleNeighbor> result;
unsigned start = 0;
std::sort(temp_pool.begin(), temp_pool.end());
result.push_back(temp_pool[start]);
while (result.size() < range && (++start) < temp_pool.size()) {
auto &p = temp_pool[start];
bool occlude = false;
for (unsigned t = 0; t < result.size(); t++) {
if (p.id == result[t].id) {
occlude = true;
break;
}
float djk = distance_->compare(
data_ + dimension_ * (size_t)result[t].id,
data_ + dimension_ * (size_t)p.id, (unsigned)dimension_);
float cos_ij = (p.distance + result[t].distance - djk) / 2 /
sqrt(p.distance * result[t].distance);
if (cos_ij > threshold) {
occlude = true;
break;
}
}
if (!occlude) result.push_back(p);
}
{
LockGuard guard(locks[des]);
for (unsigned t = 0; t < result.size(); t++) {
des_pool[t] = result[t];
}
if (result.size() < range) {
des_pool[result.size()].distance = -1;
}
}
} else {
LockGuard guard(locks[des]);
for (unsigned t = 0; t < range; t++) {
if (des_pool[t].distance == -1) {
des_pool[t] = sn;
if (t + 1 < range) des_pool[t + 1].distance = -1;
break;
}
}
}
}
}
void IndexSSG::Link(const Parameters ¶meters, SimpleNeighbor *cut_graph_) {
/*
std::cerr << "Graph Link" << std::endl;
unsigned progress = 0;
unsigned percent = 100;
unsigned step_size = nd_ / percent;
std::mutex progress_lock;
*/
unsigned range = parameters.Get<unsigned>("R");
std::vector<std::mutex> locks(nd_);
float angle = parameters.Get<float>("A");
float threshold = std::cos(angle / 180 * kPi);
//并行编程
#pragma omp parallel
{
// unsigned cnt = 0;
std::vector<Neighbor> pool, tmp;
#pragma omp for schedule(dynamic, 100)
for (unsigned n = 0; n < nd_; ++n) {
pool.clear();
tmp.clear();
//获取KNN-Graph每个节点近邻节点候选池POOL
get_neighbors(n, parameters, pool);
//POOL节点距离排序,利用angel(threshold)进行裁剪,控制每个节点满足range(最大出度)
sync_prune(n, pool, parameters, threshold, cut_graph_);
/*
cnt++;
if (cnt % step_size == 0) {
LockGuard g(progress_lock);
std::cout << progress++ << "/" << percent << " completed" << std::endl;
}
*/
}
#pragma omp for schedule(dynamic, 100)
for (unsigned n = 0; n < nd_; ++n) {
InterInsert(n, range, threshold, locks, cut_graph_);
}
}
}
void IndexSSG::Build(size_t n, const float *data,
const Parameters ¶meters) {
std::string nn_graph_path = parameters.Get<std::string>("nn_graph_path");
unsigned range = parameters.Get<unsigned>("R");
//加载KNN-graph到final_graph
Load_nn_graph(nn_graph_path.c_str());
data_ = data;
//Graph初始化
init_graph(parameters);
//构建SSG临时变量,nd_为节点数量,range为最大出度
SimpleNeighbor *cut_graph_ = new SimpleNeighbor[nd_ * (size_t)range];
//对KNN-Graph根据最大出度裁剪,初始化cut_graph_
Link(parameters, cut_graph_);
final_graph_.resize(nd_);
//重新调整final_graph,将cut_graph_数据填充到final_graph
for (size_t i = 0; i < nd_; i++) {
//每个节点对应的指针
SimpleNeighbor *pool = cut_graph_ + i * (size_t)range;
unsigned pool_size = 0;
for (unsigned j = 0; j < range; j++) {
if (pool[j].distance == -1) {
break;
}
pool_size = j;
}
++pool_size;
final_graph_[i].resize(pool_size);
for (unsigned j = 0; j < pool_size; j++) {
final_graph_[i][j] = pool[j].id;
}
}
//通过DFS_expand添加少量边强化final_graph图的连通性
DFS_expand(parameters);
unsigned max, min, avg;
max = 0;
min = nd_;
avg = 0;
//打印图的size,最大、最小、平均出度
for (size_t i = 0; i < nd_; i++) {
auto size = final_graph_[i].size();
max = max < size ? size : max;
min = min > size ? size : min;
avg += size;
}
avg /= 1.0 * nd_;
printf("Degree Statistics: Max = %d, Min = %d, Avg = %d\n",
max, min, avg);
/* Buggy!
strong_connect(parameters);
max = 0;
min = nd_;
avg = 0;
for (size_t i = 0; i < nd_; i++) {
auto size = final_graph_[i].size();
max = max < size ? size : max;
min = min > size ? size : min;
avg += size;
}
avg /= 1.0 * nd_;
printf("Degree Statistics(After TreeGrow): Max = %d, Min = %d, Avg = %d\n",
max, min, avg);
*/
has_built = true;
}
void IndexSSG::Search(const float *query, const float *x, size_t K,
const Parameters ¶meters, unsigned *indices) {
const unsigned L = parameters.Get<unsigned>("L_search");
data_ = x;
std::vector<Neighbor> retset(L + 1);
std::vector<unsigned> init_ids(L);
boost::dynamic_bitset<> flags{nd_, 0};
std::mt19937 rng(rand());
GenRandom(rng, init_ids.data(), L, (unsigned)nd_);
assert(eps_.size() < L);
for(unsigned i=0; i<eps_.size(); i++){
init_ids[i] = eps_[i];
}
for (unsigned i = 0; i < L; i++) {
unsigned id = init_ids[i];
float dist = distance_->compare(data_ + dimension_ * id, query,
(unsigned)dimension_);
retset[i] = Neighbor(id, dist, true);
flags[id] = true;
}
std::sort(retset.begin(), retset.begin() + L);
int k = 0;
while (k < (int)L) {
int nk = L;
if (retset[k].flag) {
retset[k].flag = false;
unsigned n = retset[k].id;
for (unsigned m = 0; m < final_graph_[n].size(); ++m) {
unsigned id = final_graph_[n][m];
if (flags[id]) continue;
flags[id] = 1;
float dist = distance_->compare(query, data_ + dimension_ * id,
(unsigned)dimension_);
if (dist >= retset[L - 1].distance) continue;
Neighbor nn(id, dist, true);
int r = InsertIntoPool(retset.data(), L, nn);
if (r < nk) nk = r;
}
}
if (nk <= k)
k = nk;
else
++k;
}
for (size_t i = 0; i < K; i++) {
indices[i] = retset[i].id;
}
}
void IndexSSG::SearchWithOptGraph(const float *query, size_t K,
const Parameters ¶meters,
unsigned *indices) {
unsigned L = parameters.Get<unsigned>("L_search");
DistanceFastL2 *dist_fast = (DistanceFastL2 *)distance_;
std::vector<Neighbor> retset(L + 1);
std::vector<unsigned> init_ids(L);
//高性能随机L个ID
std::mt19937 rng(rand());
GenRandom(rng, init_ids.data(), L, (unsigned)nd_);
assert(eps_.size() < L);
//从加载的导航节点读取ID,n_try=10
for(unsigned i=0; i<eps_.size(); i++){
init_ids[i] = eps_[i];
}
boost::dynamic_bitset<> flags{nd_, 0};
//数据缓存优化,预先读取init_ids数据到内存
for (unsigned i = 0; i < init_ids.size(); i++) {
unsigned id = init_ids[i];
if (id >= nd_) continue;
_mm_prefetch(opt_graph_ + node_size * id, _MM_HINT_T0);
}
L = 0;
//获取init_ids各节点与query的距离,结果retset
for (unsigned i = 0; i < init_ids.size(); i++) {
unsigned id = init_ids[i];
if (id >= nd_) continue;
float *x = (float *)(opt_graph_ + node_size * id);
float norm_x = *x;
x++;
float dist = dist_fast->compare(x, query, norm_x, (unsigned)dimension_);
retset[i] = Neighbor(id, dist, true);
flags[id] = true;
L++;
}
// std::cout<<L<<std::endl;
//对retset结果sort,从最近到最远距离
std::sort(retset.begin(), retset.begin() + L);
int k = 0;
while (k < (int)L) {
int nk = L;
//检索过的节点置为False
if (retset[k].flag) {
retset[k].flag = false;
//获取Retset ID缓存数据
unsigned n = retset[k].id;
_mm_prefetch(opt_graph_ + node_size * n + data_len, _MM_HINT_T0);
//获取Retset ID近邻点和其缓存数据
unsigned *neighbors = (unsigned *)(opt_graph_ + node_size * n + data_len);
unsigned MaxM = *neighbors;
neighbors++;
for (unsigned m = 0; m < MaxM; ++m)
_mm_prefetch(opt_graph_ + node_size * neighbors[m], _MM_HINT_T0);
//对Retset ID每个未检索过的近邻点,计算与query的距离
for (unsigned m = 0; m < MaxM; ++m) {
unsigned id = neighbors[m];
if (flags[id]) continue;
flags[id] = 1;
float *data = (float *)(opt_graph_ + node_size * id);
float norm = *data;
data++;
float dist =
dist_fast->compare(query, data, norm, (unsigned)dimension_);
//判断距离是否小于初始RetsetIDs中最大距离,是则插入该节点到RetsetIDs正确位置
if (dist >= retset[L - 1].distance) continue;
Neighbor nn(id, dist, true);
int r = InsertIntoPool(retset.data(), L, nn);
// if(L+1 < retset.size()) ++L;
if (r < nk) nk = r;
}
}
if (nk <= k)
k = nk;
else
++k;
}
//从RetsetIDS中取K个数据返回保存
for (size_t i = 0; i < K; i++) {
indices[i] = retset[i].id;
}
}
void IndexSSG::OptimizeGraph(float *data) { // use after build or load
data_ = data;
data_len = (dimension_ + 1) * sizeof(float);
neighbor_len = (width + 1) * sizeof(unsigned);
node_size = data_len + neighbor_len;
opt_graph_ = (char *)malloc(node_size * nd_);
DistanceFastL2 *dist_fast = (DistanceFastL2 *)distance_;
for (unsigned i = 0; i < nd_; i++) {
char *cur_node_offset = opt_graph_ + i * node_size;
float cur_norm = dist_fast->norm(data_ + i * dimension_, dimension_);
std::memcpy(cur_node_offset, &cur_norm, sizeof(float));
std::memcpy(cur_node_offset + sizeof(float), data_ + i * dimension_,
data_len - sizeof(float));
cur_node_offset += data_len;
unsigned k = final_graph_[i].size();
std::memcpy(cur_node_offset, &k, sizeof(unsigned));
std::memcpy(cur_node_offset + sizeof(unsigned), final_graph_[i].data(),
k * sizeof(unsigned));
std::vector<unsigned>().swap(final_graph_[i]);
}
free(data);
data_ = nullptr;
CompactGraph().swap(final_graph_);
}
void IndexSSG::DFS(boost::dynamic_bitset<> &flag,
std::vector<std::pair<unsigned, unsigned>> &edges,
unsigned root, unsigned &cnt) {
unsigned tmp = root;
std::stack<unsigned> s;
s.push(root);
if (!flag[root]) cnt++;
flag[root] = true;
while (!s.empty()) {
unsigned next = nd_ + 1;
for (unsigned i = 0; i < final_graph_[tmp].size(); i++) {
if (flag[final_graph_[tmp][i]] == false) {
next = final_graph_[tmp][i];
break;
}
}
// std::cout << next <<":"<<cnt <<":"<<tmp <<":"<<s.size()<< '\n';
if (next == (nd_ + 1)) {
unsigned head = s.top();
s.pop();
if (s.empty()) break;
tmp = s.top();
unsigned tail = tmp;
if (check_edge(head, tail)) {
edges.push_back(std::make_pair(head, tail));
}
continue;
}
tmp = next;
flag[tmp] = true;
s.push(tmp);
cnt++;
}
}
void IndexSSG::findroot(boost::dynamic_bitset<> &flag, unsigned &root,
const Parameters ¶meter) {
unsigned id = nd_;
for (unsigned i = 0; i < nd_; i++) {
if (flag[i] == false) {
id = i;
break;
}
}
if (id == nd_) return; // No Unlinked Node
std::vector<Neighbor> tmp, pool;
get_neighbors(data_ + dimension_ * id, parameter, tmp, pool);
std::sort(pool.begin(), pool.end());
bool found = false;
for (unsigned i = 0; i < pool.size(); i++) {
if (flag[pool[i].id]) {
// std::cout << pool[i].id << '\n';
root = pool[i].id;
found = true;
break;
}
}
if (!found) {
for (int retry = 0; retry < 1000; ++retry) {
unsigned rid = rand() % nd_;
if (flag[rid]) {
root = rid;
break;
}
}
}
final_graph_[root].push_back(id);
}
bool IndexSSG::check_edge(unsigned h, unsigned t) {
bool flag = true;
for (unsigned i = 0; i < final_graph_[h].size(); i++) {
if (t == final_graph_[h][i]) flag = false;
}
return flag;
}
void IndexSSG::strong_connect(const Parameters ¶meter) {
unsigned n_try = parameter.Get<unsigned>("n_try");
std::vector<std::pair<unsigned, unsigned>> edges_all;
std::mutex edge_lock;
#pragma omp parallel for
for (unsigned nt = 0; nt < n_try; nt++) {
unsigned root = rand() % nd_;
boost::dynamic_bitset<> flags{nd_, 0};
unsigned unlinked_cnt = 0;
std::vector<std::pair<unsigned, unsigned>> edges;
while (unlinked_cnt < nd_) {
DFS(flags, edges, root, unlinked_cnt);
// std::cout << unlinked_cnt << '\n';
if (unlinked_cnt >= nd_) break;
findroot(flags, root, parameter);
// std::cout << "new root"<<":"<<root << '\n';
}
LockGuard guard(edge_lock);
for (unsigned i = 0; i < edges.size(); i++) {
edges_all.push_back(edges[i]);
}
}
unsigned ecnt = 0;
for (unsigned e = 0; e < edges_all.size(); e++) {
unsigned start = edges_all[e].first;
unsigned end = edges_all[e].second;
unsigned flag = 1;
for (unsigned j = 0; j < final_graph_[start].size(); j++) {
if (end == final_graph_[start][j]) {
flag = 0;
}
}
if (flag) {
final_graph_[start].push_back(end);
ecnt++;
}
}
for (size_t i = 0; i < nd_; ++i) {
if (final_graph_[i].size() > width) {
width = final_graph_[i].size();
}
}
}
void IndexSSG::DFS_expand(const Parameters ¶meter) {
unsigned n_try = parameter.Get<unsigned>("n_try");
unsigned range = parameter.Get<unsigned>("R");
std::vector<unsigned> ids(nd_);
for(unsigned i=0; i<nd_; i++){
ids[i]=i;
}
//随机获取n_try=10个节点ID,random_shuffle每次随机结果一致?
std::random_shuffle(ids.begin(), ids.end());
for(unsigned i=0; i<n_try; i++){
eps_.push_back(ids[i]);
//std::cout << eps_[i] << '\n';
}
//并行编程
#pragma omp parallel for
//从每个选择的n_try个节点开始,利用DFS保证图是连通的
for(unsigned i=0; i<n_try; i++){
unsigned rootid = eps_[i];
//设置所有的节点连通标志位flag为0
boost::dynamic_bitset<> flags{nd_, 0};
std::queue<unsigned> myqueue;
myqueue.push(rootid);
flags[rootid]=true;
std::vector<unsigned> uncheck_set(1);
//只有所有节点连通标志位为1才退出循环
while(uncheck_set.size() >0){
//从导航根节点开始遍历近邻点,能遍历到的flag置为1
while(!myqueue.empty()){
unsigned q_front=myqueue.front();
myqueue.pop();
for(unsigned j=0; j<final_graph_[q_front].size(); j++){
unsigned child = final_graph_[q_front][j];
if(flags[child])continue;
flags[child] = true;
myqueue.push(child);
}
}
//取出所有未遍历到的节点至uncheck set
uncheck_set.clear();
for(unsigned j=0; j<nd_; j++){
if(flags[j])continue;
uncheck_set.push_back(j);
}
//对未连通的节点,判断图中连通的节点的近邻是否还小于出度限制,是则将未连通节点加到该节点近邻
if(uncheck_set.size()>0){
for(unsigned j=0; j<nd_; j++){
if(flags[j] && final_graph_[j].size()<range){
final_graph_[j].push_back(uncheck_set[0]);
break;
}
}
myqueue.push(uncheck_set[0]);
flags[uncheck_set[0]]=true;
}
}
}
}
} // namespace efanna2e