-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBuild_cBiK.cpp
1472 lines (1259 loc) · 55.5 KB
/
Build_cBiK.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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* File: Build_cBiK.cpp
* Author: carlos
*
* Created on January 16, 2018, 3:28 PM
*/
#include "Build_cBiK.h"
Build_cBiK::Build_cBiK(string datasetName) {
this->datasetName = datasetName;
loadDataset();
create_cBiK();
export_cBiK();
}
Build_cBiK::Build_cBiK() {
}
string Build_cBiK::toLower(string &palabra) {
string str;
for (string::size_type i=0; i<palabra.length(); i++){
str = str + tolower(palabra[i],loc);
}
return str;
}
void Build_cBiK::load_cBiK(string datasetName) {
this->datasetName = datasetName;
/**************************************************************************/
/********************** CARGAR HASHMAP(KEY,ID) **************************/
/**************************************************************************/
cout << "CARGANDO HASHMAP >> " << "cBiK_"+datasetName+"_hashmap" << endl;
ifstream lecturaHashMap;
lecturaHashMap.open("cBiK_"+datasetName+"_hashmap",ios::in);
//HASHING PALABRA-ID
int contTkn=0;
string keyHash = "";
int idHash = 0;
//Se lee cada linea del archivo de texto
for(string linea; getline(lecturaHashMap, linea); ) {
stringstream registro(linea);
contTkn = 0;
keyHash = "";
idHash = 0;
//Lee cada elemento de la linea
for (string dato; getline(registro, dato, ' '); ) {
if(contTkn == 0) {
//PALABRA
keyHash = dato;
}else if(contTkn == 1) {
//ID
idHash = stoi(dato);
}
contTkn++;
}
hashMapKeys[keyHash] = idHash;
}
lecturaHashMap.close();
cout << "TOTAL PALABRAS:" << hashMapKeys.size() << endl;
this->numKeys = hashMapKeys.size();
/**************************************************************************/
/************************** CARGAR PUNTOS *******************************/
/**************************************************************************/
cout << "CARGANDO PUNTOS >> " << "cBiK_"+datasetName+"_points" << endl;
long long int totalObjects = 0;
ifstream lecturaPalabras;
lecturaPalabras.open("cBiK_"+datasetName+"_points",ios::in);
//Se lee cada linea del archivo de texto
for(string linea; getline(lecturaPalabras, linea); ) {
totalObjects++;
}
lecturaPalabras.close();
cout << "Total de objetos >> " << totalObjects << endl;
lecturaPalabras.open("cBiK_"+datasetName+"_points",ios::in);
//arreglo para guardar los puntos
double **coordinates;
coordinates = new double *[totalObjects];
for(int i = 0; i<totalObjects; i++) {
coordinates[i] = new double[2];//dos dimensiones
}
//HASHING PALABRA-ID
int contToken=0;
int i=0;
int idKey = 0;
//Se lee cada linea del archivo de texto
for(string linea; getline(lecturaPalabras, linea); ) {
stringstream registro(linea);
contToken = 0;
//Lee cada elemento de la linea
for (string dato; getline(registro, dato, ' '); ) {
if(contToken == 0) {
//LATITUD
coordinates[i][0] = stod(dato);
}else if(contToken == 1) {
//LONGITUD
coordinates[i][1] = stod(dato);
}
contToken++;
}
i++;
}
lecturaPalabras.close();
nodosKdTree.resize(totalObjects);
for (int i = 0; i < nodosKdTree.size(); i++) {
nodosKdTree[i] = NodeSKQ(&(coordinates[i][0]));
}
/**************************************************************************/
/********************** CARGAR BITMAP MAPA ******************************/
/**************************************************************************/
cout << "CARGANDO BITMAP MAPA >> " << "cBiK_"+datasetName+"_map.sdsl" << endl;
load_from_file(mapa, "cBiK_"+datasetName+"_map.sdsl");
cout << "\t NUMERO ELEMENTOS MAPA >> " << mapa.size()*0.5 << endl;
//Se crea el rank del bitmap del mapa
mapRank_1 = rank_support_v<1>(&mapa);
/**************************************************************************/
/********************** CARGAR BITMAP KEYWORDS **************************/
/**************************************************************************/
cout << "CARGANDO BITMAP KEYWORDS >> " << "cBiK_"+datasetName+"_keywords.sdsl" << endl;
load_from_file(sdVectorKeywords, "cBiK_"+datasetName+"_keywords.sdsl");
cout << "\t NUMERO ELEMENTOS KEYWORDS >> " << sdVectorKeywords.size() << endl;
/**************************************************************************/
/********************** CARGAR BITMAP SUMMARY ***************************/
/**************************************************************************/
cout << "CARGANDO BITMAP SUMMARY >> " << "cBiK_"+datasetName+"_summary.sdsl" << endl;
load_from_file(sdVectorResume, "cBiK_"+datasetName+"_summary.sdsl");
cout << "\t NUMERO ELEMENTOS SUMMARY >> " << sdVectorResume.size() << endl;
}
void Build_cBiK::export_cBiK() {
/**************************************************************************/
/********************** EXPORTAR HASHMAP(KEY,ID) **************************/
/**************************************************************************/
cout << "EXPORTANDO HASHMAP >> " << "cBiK_"+datasetName+"_hashmap" << endl;
ofstream archivoHM("cBiK_"+datasetName+"_hashmap");
for (auto& x: hashMapKeys) {
archivoHM << x.first << " " << x.second << endl;
}
archivoHM.close();
/**************************************************************************/
/************************** EXPORTAR PUNTOS *******************************/
/**************************************************************************/
cout << "EXPORTANDO PUNTOS >> " << "cBiK_"+datasetName+"_points" << endl;
ofstream archivoP("cBiK_"+datasetName+"_points");
for(int i=0; i<nodosKdTree.size(); i++) {
archivoP << setprecision(16) << nodosKdTree[i].coordenadas[0] << " " << nodosKdTree[i].coordenadas[1] << endl;
}
archivoP.close();
/**************************************************************************/
/********************** EXPORTAR BITMAP MAPA ******************************/
/**************************************************************************/
cout << "EXPORTANDO BITMAP MAPA >> " << "cBiK_"+datasetName+"_map.sdsl" << endl;
store_to_file(mapa, "cBiK_"+datasetName+"_map.sdsl");
/**************************************************************************/
/********************** EXPORTAR BITMAP KEYWORDS **************************/
/**************************************************************************/
cout << "EXPORTANDO BITMAP KEYWORDS >> " << "cBiK_"+datasetName+"_keywords.sdsl" << endl;
store_to_file(sdVectorKeywords, "cBiK_"+datasetName+"_keywords.sdsl");
/**************************************************************************/
/********************** EXPORTAR BITMAP SUMMARY ***************************/
/**************************************************************************/
cout << "EXPORTANDO BITMAP SUMMARY >> " << "cBiK_"+datasetName+"_summary.sdsl" << endl;
store_to_file(sdVectorResume, "cBiK_"+datasetName+"_summary.sdsl");
}
void Build_cBiK::loadDataset() {
long long int totalObjects = 0;
cout << "LEYENDO DATASET >> " << datasetName << endl;
/**************************************************************************/
/*************************** CUENTA OBJETOS *******************************/
/**************************************************************************/
ifstream lecturaPalabras;
lecturaPalabras.open(datasetName,ios::in);
//Se lee cada linea del archivo de texto
for(string linea; getline(lecturaPalabras, linea); ) {
totalObjects++;
}
lecturaPalabras.close();
cout << "Total de objetos >> " << totalObjects << endl;
/**************************************************************************/
/*************************** CARGAR OBJETOS *******************************/
/**************************************************************************/
lecturaPalabras.open(datasetName,ios::in);
//arreglo para guardar los puntos
double **coordinates;
coordinates = new double *[totalObjects];
for(int i = 0; i<totalObjects; i++) {
coordinates[i] = new double[2];//dos dimensiones
}
//arreglo para guardar las palabras claves
vector< vector<int> > indexKeys;
//HASHING PALABRA-ID
int contToken=0;
int i=0;
int idKey = 0;
vector<int> arregloClaves;
std::unordered_map<std::string,int>::const_iterator got;
//Se lee cada linea del archivo de texto
for(string linea; getline(lecturaPalabras, linea); ) {
stringstream registro(linea);
contToken = 0;
arregloClaves.clear();
//Lee cada elemento de la linea
for (string dato; getline(registro, dato, ' '); ) {
if(contToken == 2) {
//LATITUD
coordinates[i][0] = stod(dato);
}else if(contToken == 3) {
//LONGITUD
coordinates[i][1] = stod(dato);
}else if(contToken > 3){
//PALABRAS CLAVES
string laPalabra = toLower(dato);
got = hashMapKeys.find(laPalabra);
if(got == hashMapKeys.end()) {
//No existe la palabra
hashMapKeys[laPalabra] = idKey;
arregloClaves.push_back(idKey);
idKey++;
}else {
//Ya existe, se agrega al arreglo
arregloClaves.push_back(got->second);
}
}
contToken++;
}
indexKeys.push_back(arregloClaves);
i++;
}
lecturaPalabras.close();
/**************************************************************************/
/*************************** VECTOR nodosSKQ*******************************/
/**************************************************************************/
cout << "TOTAL PALABRAS:" << hashMapKeys.size() << endl;
this->numKeys = hashMapKeys.size();
//Se guardan las coordenadas y las palabras en un objeto
this->nodosSKQ.clear();
this->nodosSKQ.resize(totalObjects);
for (int i = 0; i < this->nodosSKQ.size(); i++) {
this->nodosSKQ[i] = NodeSKQ(&(coordinates[i][0]), (indexKeys[i]));
}
}
void Build_cBiK::create_cBiK(){
cout << "\nCREANDO INDICE cBiK >> " << endl;
struct timeval iniTime2, endTime2;
double secs;
//Marco el tiempo de inicio
gettimeofday(&iniTime2, NULL);
vector<NodeSKQ>& coordinates = this->nodosSKQ;
const long numDimensions = 2;//numero de dimensiones
//Inicializa y ordena la referencia del arreglo
vector< vector<NodeSKQ> > references(numDimensions, vector<NodeSKQ>(coordinates.size()));
vector<NodeSKQ> temporary(coordinates.size());
for (long i = 0; i < references.size(); i++) {
initializeReference(coordinates, references.at(i));
mergeSort(references[i], temporary, 0, references[i].size() - 1, i, numDimensions);
}
//Elimine las referencias a coordenadas duplicadas mediante una pasada a través de cada matriz de referencia.
vector<long> end(references.size());
for (long i = 0; i < end.size(); i++) {
end[i] = removeDuplicates(references[i], i, numDimensions);
}
//Verifique que se elimino la misma cantidad de referencias de cada matriz de referencia.
for (long i = 0; i < end.size() - 1; i++) {
for (long j = i + 1; j < end.size(); j++) {
if (end.at(i) != end.at(j)) {
cout << "reference removal error" << endl;
exit(1);
}
}
}
//Se crea el arreglo final
long long int totalSize = (end.at(0) + 1);
nodosKdTree.resize(totalSize);
//Se crea el mapa del doble de la cantidad de elementos
//La mitad es para el mapeo de nodos internos y hojas, la otra mitad es para indicar los nodos con resumenes
mapa = bit_vector(totalSize*2,0);
cout << "\t...CONSTRUYENDO iKD-TREE >> " << endl;
//Crea el KD-Tree por Medianas y marca el mapa
buildKdTree(references, temporary, 0, end.at(0), numDimensions, 0);
//Crea el constructor del arreglo compacto de palabras claves
sd_vector_builder localCompactKeywords((totalSize*numKeys), vectorKeys.size());
//Se copian las palabras claves al arreglo compacto
for (set<long long int>::iterator it=vectorKeys.begin(); it!=vectorKeys.end(); ++it) {
localCompactKeywords.set(*it);
}
//Se limpia el contenido de vectorKeys para ahorrar memoria
vectorKeys.clear();
//Crea el arreglo compacto de palabras claves
sd_vector<> sdKeywords(localCompactKeywords);
sdVectorKeywords = sdKeywords;
//Se crea el rank del bitmap del mapa
mapRank_1 = rank_support_v<1> (&mapa);
long long int nodosInterno = mapRank_1(mapa.size()*0.5);
cout << "\t...CONSTRUYENDO SUMMARY >> " << endl;
//Se cuentan los bits resumenes encendido para crear el arreglo
set<int> totalBitsResumen = generateResume(0, totalSize-1);
totalBitsResumen.clear();
cout << "\t...CONSTRUYENDO COMPACT SUMMARY >> " << endl;
//cout << "TOTAL DE UNOS:" << vectorResumeFinal.size() << endl;
long long int nodosInternosResumen = mapRank_1(mapa.size());
//Crea el arreglo compacto de resumenes
sd_vector_builder localCompactResume(((nodosInternosResumen-nodosInterno)*2*numKeys), vectorResumeFinal.size());
//Copia los bits del arreglo compacto
int i = 0;
for (set<long long int>::iterator it=vectorResumeFinal.begin(); it!=vectorResumeFinal.end(); ++it) {
localCompactResume.set(*it);
}
//Se limpia el contenido de vectorResumeFinal para ahorrar memoria
vectorResumeFinal.clear();
sd_vector<> sdResume(localCompactResume);
sdVectorResume = sdResume;
//marco el tiempo final
gettimeofday(&endTime2, NULL);
secs = timeval_diff(&endTime2, &iniTime2);
printf("Tiempo: %.16g microseg -- %.16g miliseg -- %.16g seg\n", secs * 1000000.0, secs * 1000.0, secs);
cout << endl;
// Verify the k-d tree and report the number of KdNodes.
/*long numberOfNodes = root->verifyKdTree(numDimensions, 0);
cout << endl << "Number of nodes = " << numberOfNodes << endl;*/
}
/*
* Initialize a reference array by creating references into the coordinates array.
*
* calling parameters:
*
* coordinates - a vector<NodeSKQ> of pointers to each of the (x, y, z, w...) tuples
* reference - a vector<NodeSKQ> that represents one of the reference arrays
*/
void Build_cBiK::initializeReference(vector<NodeSKQ>& coordinates, vector<NodeSKQ>& reference) {
for (long j = 0; j < coordinates.size(); j++) {
reference.at(j) = coordinates.at(j);
}
}
/*
* The superKeyCompare method compares two double arrays in all k dimensions,
* and uses the sorting or partition coordinate as the most significant dimension.
*
* calling parameters:
*
* a - a double*
* b - a double*
* p - the most significant dimension
* dim - the number of dimensions
*
* returns: a double result of comparing two double arrays
*/
double Build_cBiK::superKeyCompare(const double *a, const double *b, const long p, const long dim) {
double diff = 0;
for (long i = 0; i < dim; i++) {
long r = i + p;
// A fast alternative to the modulus operator for (i + p) < 2 * dim.
r = (r < dim) ? r : r - dim;
diff = a[r] - b[r];
if (diff != 0) {
break;
}
}
return diff;
}
/*
* The mergeSort function recursively subdivides the array to be sorted
* then merges the elements. Adapted from Robert Sedgewick's "Algorithms
* in C++" p. 166. Addison-Wesley, Reading, MA, 1992.
*
* calling parameters:
*
* reference - a vector<NodeSKQ> that represents the reference array to sort
* temporary - a temporary array into which to copy intermediate results;
* this array must be as large as the reference array
* low - the start index of the region of the reference array to sort
* high - the high index of the region of the reference array to sort
* p - the sorting partition (x, y, z, w...)
* dim - the number of dimensions
* depth - the depth of subdivision
*/
void Build_cBiK::mergeSort(vector<NodeSKQ> &reference, vector<NodeSKQ>& temporary, const long low, const long high, const long p, const long dim) {
long i, j, k;
if (high > low) {
// Evite el desbordamiento al calcular la mediana.
const long mid = low + ((high - low) >> 1);
// Recursivamente subdivide las mitades inferior y superior de la matriz.
mergeSort(reference, temporary, low, mid, p, dim);
mergeSort(reference, temporary, mid + 1, high, p, dim);
// Combina los resultados para este nivel de subdivisión.
for (i = mid + 1; i > low; i--) {
temporary[i - 1] = reference[i - 1];
}
for (j = mid; j < high; j++) {
temporary[mid + (high - j)] = reference[j + 1]; // Evite el desbordamiento de direcciones.
}
for (k = low; k <= high; k++) {
if(superKeyCompare(temporary[i].coordenadas, temporary[j].coordenadas, p, dim) < 0) {
reference[k] = temporary[i++];
}else {
reference[k] = temporary[j--];
}
}
}
}
/*
* Check the validity of the merge sort and remove duplicates from a reference array.
*
* calling parameters:
*
* reference - a vector<NodeSKQ> that represents one of the reference arrays
* i - the leading dimension for the super key
* dim - the number of dimensions
*
* returns: the end index of the reference array following removal of duplicate elements
*/
long Build_cBiK::removeDuplicates(vector<NodeSKQ>& reference, const long i, const long dim) {
long end = 0;
for (long j = 1; j < reference.size(); j++) {
double compare = superKeyCompare(reference[j].coordenadas, reference[j - 1].coordenadas, i, dim);
if (compare < 0) {
cout << "merge sort failure: superKeyCompare(ref[" << j << "], ref["
<< j - 1 << "], (" << i << ") = " << compare << endl;
exit(1);
} else if (compare > 0) {
reference[++end] = reference[j];
}
}
return end;
}
/*
* This function builds a k-d tree by recursively partitioning the
* reference arrays and adding kdNodes to the tree. These arrays
* are permuted cyclically for successive levels of the tree in
* order that sorting occur on x, y, z, w...
*
* calling parameters:
*
* references - a vector< vector<NodeSKQ> > of pointers to each of the (x, y, z, w...) tuples
* temporary - a vector<NodeSKQ> that is used as a temporary array
* start - start element of the reference arrays
* end - end element of the reference arrays
* dim - the number of dimensions
* depth - the depth in the tree
*
* returns: a KdNode pointer to the root of the k-d tree
*/
void Build_cBiK::buildKdTree(vector< vector<NodeSKQ> >& references, vector<NodeSKQ>& temporary, const long start, const long end, const long dim, const long depth) {
// The axis permutes as x, y, z, w... and addresses the referenced data.
long axis = depth % dim;
if (end == start) {
//Se agrega la key al punto, siempre es una hoja
nodosKdTree[end] = references[0][end];
//Se copian las palabras claves segun la posicion del futuro arreglo de bits
for(int i=0; i<nodosKdTree[end].palabras.size(); i++) {
vectorKeys.insert((end*numKeys)+nodosKdTree[end].palabras[i]);
}
//cout << "Start: " << start << endl;
} else if (end == start + 1) {
// Two references were passed to this function in sorted order, so store the start
// element at this level of the tree and store the end element as the > child.
nodosKdTree[start] = references[0][start];
nodosKdTree[end] = references[0][end];
//Marco los nodos internos en el mapa
mapa[start] = 1;
//Se copian las palabras claves segun la posicion del futuro arreglo de bits
for(int i=0; i<nodosKdTree[start].palabras.size(); i++) {
vectorKeys.insert((start*numKeys)+nodosKdTree[start].palabras[i]);
}
for(int i=0; i<nodosKdTree[end].palabras.size(); i++) {
vectorKeys.insert((end*numKeys)+nodosKdTree[end].palabras[i]);
}
//cout << "Start: " << start << " End: " << end << endl;
} else if (end == start + 2) {
// Three references were passed to this function in sorted order, so
// store the median element at this level of the tree, store the start
// element as the < child and store the end element as the > child.
nodosKdTree[start + 1] = references[0][start + 1];
nodosKdTree[start] = references[0][start];
nodosKdTree[end] = references[0][end];
//Marco los nodos internos en el mapa
mapa[start + 1] = 1;
//Se copian las palabras claves segun la posicion del futuro arreglo de bits
for(int i=0; i<nodosKdTree[(start + 1)].palabras.size(); i++) {
vectorKeys.insert(((start + 1)*numKeys)+nodosKdTree[(start + 1)].palabras[i]);
}
for(int i=0; i<nodosKdTree[start].palabras.size(); i++) {
vectorKeys.insert((start*numKeys)+nodosKdTree[start].palabras[i]);
}
for(int i=0; i<nodosKdTree[end].palabras.size(); i++) {
vectorKeys.insert((end*numKeys)+nodosKdTree[end].palabras[i]);
}
//cout << "Start: " << start << " Start + 1: " << (start+1) << " End: " << end << endl;
} else if (end > start + 2) {
// More than three references were passed to this function, so
// the median element of references[0] is chosen as the tuple about
// which the other reference arrays will be partitioned. Avoid
// overflow when computing the median.
const long median = start + ((end - start) / 2);
//Se guardan los puntos de la mediana del arreglo
nodosKdTree[median] = references[0][median];
//Marco los nodos internos en el mapa
mapa[median] = 1;
//Marco los nodos internos que tienen resumenes explicitos sumando la cantidad de elementos
mapa[median+nodosKdTree.size()] = 1;
//Se copian las palabras claves segun la posicion del futuro arreglo de bits
for(int i=0; i<nodosKdTree[median].palabras.size(); i++) {
vectorKeys.insert((median*numKeys)+nodosKdTree[median].palabras[i]);
}
//cout << "Median: " << median << endl;
// Copy references[0] to the temporary array before partitioning.
for (long i = start; i <= end; i++) {
temporary[i] = references[0][i];
}
// Process each of the other reference arrays in a priori sorted order
// and partition it by comparing super keys. Store the result from
// references[i] in references[i-1], thus permuting the reference
// arrays. Skip the element of references[i] that that references
// a point that equals the point that is stored in the new k-d node.
long lower, upper, lowerSave, upperSave;
for (long i = 1; i < dim; i++) {
// Process one reference array. Compare once only.
lower = start - 1;
upper = median;
for (long j = start; j <= end; j++) {
double compare = superKeyCompare(references[i][j].coordenadas, nodosKdTree[median].coordenadas, axis, dim);
if (compare < 0) {
references[i - 1][++lower] = references[i][j];
} else if (compare > 0) {
references[i - 1][++upper] = references[i][j];
}
}
// Check the new indices for the reference array.
if (lower < start || lower >= median) {
cout << "incorrect range for lower at depth = " << depth << " : start = "
<< start << " lower = " << lower << " median = " << median << endl;
exit(1);
}
if (upper <= median || upper > end) {
cout << "incorrect range for upper at depth = " << depth << " : median = "
<< median << " upper = " << upper << " end = " << end << endl;
exit(1);
}
if (i > 1 && lower != lowerSave) {
cout << " lower = " << lower << " != lowerSave = " << lowerSave << endl;
exit(1);
}
if (i > 1 && upper != upperSave) {
cout << " upper = " << upper << " != upperSave = " << upperSave << endl;
exit(1);
}
lowerSave = lower;
upperSave = upper;
}
// Copy the temporary array to references[dim-1] to finish permutation.
for (long i = start; i <= end; i++) {
references[dim - 1][i] = temporary[i];
}
// Recursively build the < branch of the tree.
buildKdTree(references, temporary, start, lower, dim, depth + 1);
// Recursively build the > branch of the tree.
buildKdTree(references, temporary, median + 1, upper, dim, depth + 1);
} else if (end < start) {
// This is an illegal condition that should never occur, so test for it last.
cout << "error has occurred at depth = " << depth << " : end = " << end
<< " < start = " << start << endl;
exit(1);
}
}
long long int Build_cBiK::getNewSummaryIndex(int i) {
long long int nodosInternos = mapRank_1(mapa.size()*0.5);
long long int posResumen = mapRank_1(i+nodosKdTree.size());
return 2*numKeys*(posResumen-nodosInternos);
}
set<int> Build_cBiK::generateResume(int start, int end) {
set<int> vectorRetorno;
if (end == start) {
//Se agrega la key al punto, siempre es una hoja
for(int i=0; i<nodosKdTree[end].palabras.size(); i++) {
vectorRetorno.insert(nodosKdTree[end].palabras[i]);
}
} else if (end == start + 1) {
//Padre start
//HD end
//variable pos tiene la posicion del bit de inicio del correspondiente resumen
for(int i=0; i<nodosKdTree[end].palabras.size(); i++) {
vectorRetorno.insert(nodosKdTree[end].palabras[i]);
}
} else if (end == start + 2) {
//Padre start + 1
//HI start
//HD end
for(int i=0; i<nodosKdTree[start].palabras.size(); i++) {
vectorRetorno.insert(nodosKdTree[start].palabras[i]);
}
for(int i=0; i<nodosKdTree[end].palabras.size(); i++) {
vectorRetorno.insert(nodosKdTree[end].palabras[i]);
}
} else if (end > start + 2) {
// Padre median
const long median = start + ((end - start) / 2);
long long int pos = getNewSummaryIndex(median);
// Recursively build the < branch of the tree.
set<int> resumenI = generateResume(start, median-1);
//Copio el hijo izquierdo
int hijoI = (start+median-1) * 0.5;
for(int i=0; i<nodosKdTree[hijoI].palabras.size(); i++) {
resumenI.insert(nodosKdTree[hijoI].palabras[i]);
}
//Agrego al vector de resumenes las posiciones del resumen izquierdo
for (set<int>::iterator it=resumenI.begin(); it!=resumenI.end(); ++it){
vectorRetorno.insert(*it);
vectorResumeFinal.insert(pos+*it);
}
resumenI.clear();
// Recursively build the > branch of the tree.
set<int> resumenD = generateResume(median + 1, end);
//Copio el hijo derecho
int hijoD = (median + 1 + end) * 0.5;
for(int i=0; i<nodosKdTree[hijoD].palabras.size(); i++) {
resumenD.insert(nodosKdTree[hijoD].palabras[i]);
}
//Agrego al vector de resumenes las posiciones del resumen derecho
for (set<int>::iterator it=resumenD.begin(); it!=resumenD.end(); ++it){
vectorRetorno.insert(*it);
vectorResumeFinal.insert(pos+numKeys+*it);
}
resumenD.clear();
} else if (end < start) {
// This is an illegal condition that should never occur, so test for it last.
cout << "error has occurred at : end = " << end << " < start = " << start << endl;
exit(1);
}
return vectorRetorno;
}
double Build_cBiK::searchEuclideanDistance(const double* p1, const double* p2) {
//calcula la distancia para dos dimensiones
return (p2[0] - p1[0])*(p2[0] - p1[0]) + (p2[1] - p1[1])*(p2[1] - p1[1]);
}
bool Build_cBiK::checkKeywords(vector<int> query, int pos) {
bool resp = true;
int i=0;
long long int posInicial = pos*numKeys;
while(i<query.size() && resp){
if(sdVectorKeywords[(posInicial+query[i])] == 0) {
resp = false;
}
i++;
}
return resp;
}
bool Build_cBiK::checkSummaryLeft(vector<int> query, int pos, int start, int end) {
bool resp = true;
if(mapa[pos] == 0) {
//Es una hoja
resp = false;
}else {
//Es un nodo interno, se revisa si es un un nodo interno final
if (end == start) {
//Siempre es una hoja, no tiene resumen
resp = false;
} else if (end == start + 1) {
//NI start
//HD end
//No tiene resumen izquierdo
resp = false;
} else if (end == start + 2) {
//NI start + 1
//HI start
//HD end
//El resumen izquierdo corresponde a la keyword del HI
int i=0;
long long int posInicial = start*numKeys;
while(i<query.size() && resp){
if(sdVectorKeywords[(posInicial+query[i])] == 0) {
resp = false;
}
i++;
}
} else if (end > start + 2) {
//NI pos
//El resumen izquierdo corresponde al summary de pos
int i=0;
long long int posInicial = getNewSummaryIndex(pos);
while(i<query.size() && resp){
if(sdVectorResume[(posInicial+query[i])] == 0) {
resp = false;
}
i++;
}
} else if (end < start) {
// This is an illegal condition that should never occur, so test for it last.
cout << "error has occurred at : end = " << end << " < start = " << start << endl;
exit(1);
}
}
return resp;
}
bool Build_cBiK::checkSummaryRight(vector<int> query, int pos, int start, int end) {
bool resp = true;
if(mapa[pos] == 0) {
//Es una hoja
resp = false;
}else {
//Es un nodo interno, se revisa si es un un nodo interno final
if (end == start) {
//Siempre es una hoja, no tiene resumen
resp = false;
} else if (end == start + 1) {
//NI start
//HD end
//El resumen derecho corresponde a la keyword del HD
int i=0;
long long int posInicial = end*numKeys;
while(i<query.size() && resp){
if(sdVectorKeywords[(posInicial+query[i])] == 0) {
resp = false;
}
i++;
}
} else if (end == start + 2) {
//NI start + 1
//HI start
//HD end
//El resumen derecho corresponde a la keyword del HD
int i=0;
long long int posInicial = end*numKeys;
while(i<query.size() && resp){
if(sdVectorKeywords[(posInicial+query[i])] == 0) {
resp = false;
}
i++;
}
} else if (end > start + 2) {
//NI pos
//El resumen derecho corresponde al summary de pos
int i=0;
long long int posInicial = getNewSummaryIndex(pos);
while(i<query.size() && resp){
if(sdVectorResume[(posInicial+numKeys+query[i])] == 0) {
resp = false;
}
i++;
}
} else if (end < start) {
// This is an illegal condition that should never occur, so test for it last.
cout << "error has occurred at : end = " << end << " < start = " << start << endl;
exit(1);
}
}
return resp;
}
double Build_cBiK::timeval_diff(struct timeval *a, struct timeval *b){
return
(double)(a->tv_sec + (double)a->tv_usec/1000000) -
(double)(b->tv_sec + (double)b->tv_usec/1000000);
}
void Build_cBiK::printMapa() {
//printTree();
cout << endl;
cout << "******************************* MAPA *******************************" << endl;
cout << "Largo mapa:" << mapa.size()*0.5 << endl;
cout<< "Mapa size original: " << size_in_bytes(mapa)<< endl;
//cout << mapa << endl;
cout << "***************************** KEYWORDS *****************************" << endl;
cout << "Largo:" << sdVectorKeywords.size() << endl;
cout<< "[keywords size]: " << size_in_bytes(sdVectorKeywords)<< endl;
/*for(int i=0; i<mapa.size()*0.5; i++) {
for(int j=0; j<numKeys; j++) {
cout << sdVectorKeywords[(i*numKeys)+j];
}
cout << endl;
}*/
//cout << sdVectorKeywords << endl;
cout << endl;
cout << "***************************** RESUMENES ****************************" << endl;
cout << "Largo:" << sdVectorResume.size() << endl;
cout<< "[Resume size]: " << size_in_bytes(sdVectorResume)<< endl;
/*long long int nodosInterno = mapRank_1(mapa.size()*0.5);
long long int nodosInternosResumen = mapRank_1(mapa.size());
for(int i=0; i<(nodosInternosResumen-nodosInterno); i++) {
for(int j=0; j<numKeys; j++) {
cout << sdVectorResume[(i*2*numKeys)+j];
}
cout << " - ";
for(int j=0; j<numKeys; j++) {
cout << sdVectorResume[(i*2*numKeys)+j+numKeys];
}
cout << endl;
}*/
//cout << sdVectorResume << endl;
cout << endl;
}
void Build_cBiK::printVector() {
/*cout << endl;
cout << "****************************** VECTOR ******************************" << endl;
for (int i = 0; i < nodosKdTree.size(); i++) {
cout << i << ".- ";
printTuple(nodosKdTree[i].coordenadas);
cout << " - ";
//Imprime las keys propias del punto
cout << *nodosKdTree[i].palabras << endl;
}
cout << "********************************************************************" << endl;
cout << endl;*/
}
void Build_cBiK::printTree() {
cout << endl;
cout << "************************** ARBOL KD-TREE ***************************" << endl;
printKdTree(0, (nodosKdTree.size() - 1), 0);
cout << "********************************************************************" << endl;
cout << endl;
}
void Build_cBiK::printKdTree(int start, int end, int depth) {
int mid = (start + end) / 2;
if (end > mid) {
printKdTree(mid + 1, end, depth + 1);
}
for (int i = 0; i < depth; i++) {
cout << " ";
}
cout << start << "," << end << " Pos:" << mid << " == ";
printTuple(nodosKdTree[mid].coordenadas);
cout << " == ";
int pos = numKeys*mid;
for(int i=0; i<numKeys; i++) {
if(sdVectorKeywords[i+pos] == 1) {
cout << "1";
}else {
cout << "0";
}
}
/*for(int i=0; i<numKeys ; i++) {
bool existe = false;
for(int j=0; j<nodosKdTree[mid].palabras.size(); j++) {
//cout << "Revisa: " << nodosKdTree[mid].palabras[j] << " - " << i << endl;
if(nodosKdTree[mid].palabras[j] == i) {
existe = true;
}
}
if(existe) {
cout << "1";
}else {
cout << "0";
}
}*/
cout << endl;
if (start < mid) {
printKdTree(start, mid - 1, depth + 1);
}
}
void Build_cBiK::printTuple(double* tuple) {
printf("%.16g, %.16g", tuple[0], tuple[1]);
//cout << "(" << tuple[0] << "," << tuple[1] << ")";
}
void Build_cBiK::printKeys(vector<bit_vector> arrBits) {
for(int i=0; i<arrBits.size(); i++) {
cout << "(" << arrBits[i] << ")";
}
}
void Build_cBiK::printKey(bit_vector arrBits) {
cout << "(" << arrBits << ")";
}
double Build_cBiK::rangeQuery(const double* query, const vector<std::string> &queryKey) {
//struct timeval iniTime2, endTime2;
//double secs;
//Atributos basicos para la busqueda
int start = 0;