forked from AlexCristian/Naive_Bayes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
NB.cpp
1463 lines (1142 loc) · 44.3 KB
/
NB.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
//
// NB.cpp
// NB_C++
//
// Created by Alexandru Cristian on 06/04/2017.
//
//
#include "NB.hpp"
bool NB::OUTPUT_FULL_LOG_LIKELIHOOD = true;
NB::Debug NB::debug_flag = NB::Debug::NO_LOG;
NB::NB(int _kmer_size, path _save_dir, int _nthreads) {
nthreads = _nthreads;
debug_flag = Debug::NO_LOG;
kmer_size = _kmer_size;
save_dir = _save_dir;
load_start_index = 0;
}
NB::~NB() {
for(unordered_map<string, Class<int>* >::iterator iter = classes.begin();
iter != classes.end(); iter++)
delete iter->second;
}
void NB::setMaxOutputSize(uint64_t row, uint64_t col){
output_max_row = row;
output_max_col = col;
}
void NB::loadTrain(){
vector<path> res = Diskutil::getItemsInDir(save_dir);
for(vector<path>::iterator iter = res.begin(); iter != res.end(); iter++){
if(!Diskutil::hasFileExtension(*iter, Diskutil::SAVE_FILE_EXT)){
continue;
}
string filename = iter->filename().native();
string cls_s = filename.substr(0,filename.rfind('-'));
addClass(new Class<int>(cls_s, kmer_size, *iter));
}
}
void NB::loadClassify(){
nthreads -= 1;
vector<path> res = Diskutil::getItemsInDir(save_dir);
for(vector<path>::iterator iter = res.begin(); iter != res.end(); iter++){
if(!Diskutil::hasFileExtension(*iter, Diskutil::SAVE_FILE_EXT)){
continue;
}
training_genomes.push_back(make_pair(*iter,0));
}
if(training_genomes.size() == 0){
cout << "Error: No training data found." << endl;
exit(1);
}
std::sort(training_genomes.begin(), training_genomes.end(),
[](const std::pair<path, uint64_t>& a,
const std::pair<path, uint64_t>& b) {
return a.first < b.first;
});
// calculate the estimated size of each training data
for (auto& pair : training_genomes) {
auto path = pair.first;
uint64_t file_size = Diskutil::getFileSize(path);
size_t num_kmer = file_size / (Class<int>::getMapElementSize());
pair.second = Class<int>::getEstimatedClassBytes(num_kmer);
}
}
size_t NB::extractHeader(string& inputFile){
const std::string input_fasta_file = inputFile;
const std::string output_header_prefix = temp_dir + "/0_";
const std::string output_header_extension = "_f.hd";
const std::string output_max_extension = ".max";
size_t total_headers = 0;
int inFileDescriptor = open(input_fasta_file.c_str(), O_RDONLY);
if (inFileDescriptor == -1) {
std::cerr << "Error opening file: " << input_fasta_file << std::endl;
return 0;
}
// Get the file size
size_t fileSize = lseek(inFileDescriptor, 0, SEEK_END);
lseek(inFileDescriptor, 0, SEEK_SET);
// Map the input file into memory
char* fileMemory = static_cast<char*>(mmap(nullptr, fileSize, PROT_READ, MAP_PRIVATE, inFileDescriptor, 0));
if (fileMemory == MAP_FAILED) {
std::cerr << "Error mapping file into memory." << std::endl;
close(inFileDescriptor);
return 0;
}
// Extract headers
std::vector<std::string> headers;
char* lineStart = fileMemory;
for (size_t offset = 0; offset < fileSize; ++offset) {
if (fileMemory[offset] == '\n') {
// Found a newline character
std::string line(lineStart, fileMemory + offset - lineStart);
if (!line.empty() && line[0] == '>') {
// Found a header line
headers.push_back(line.substr(1)); // Remove the '>' character
total_headers++;
}
lineStart = fileMemory + offset + 1; // Move the lineStart pointer
}
}
// Write headers to the output binary files
size_t currentHeadersWritten = 0;
size_t fileIndex = 1;
std::ofstream headerFile;
std::ofstream maxFile;
size_t remainingHeaders = headers.size();
for (const std::string& header : headers) {
if (currentHeadersWritten == 0) {
// Need to open a new output file
if (headerFile.is_open()) {
headerFile.close();
}
string currentMaxOutputFile = temp_dir + "/" + std::to_string(fileIndex) + output_max_extension;
maxFile.open(currentMaxOutputFile, std::ios::binary);
std::string currentHeaderOutputFile = output_header_prefix + std::to_string(fileIndex) + output_header_extension;
headerFile.open(currentHeaderOutputFile, std::ios::binary);
if (!headerFile.is_open() || !maxFile.is_open()) {
std::cerr << "Error opening output file: " << currentHeaderOutputFile << " and " << currentMaxOutputFile << std::endl;
munmap(fileMemory, fileSize);
close(inFileDescriptor);
return 0;
}
fileIndex += output_max_row;
}
size_t headerSize = header.size();
headerFile.write(reinterpret_cast<const char*>(&headerSize), sizeof(headerSize));
headerFile.write(header.c_str(), headerSize);
++currentHeadersWritten;
--remainingHeaders;
// Check if the maximum limit for headers per file is reached
if (currentHeadersWritten >= output_max_row || remainingHeaders == 0) {
std::vector<double> matrix_data(currentHeadersWritten * 2, 2.0);
maxFile.write(reinterpret_cast<const char*>(matrix_data.data()), matrix_data.size() * sizeof(double));
maxFile.close();
headerFile.close();
currentHeadersWritten = 0;
}
}
// Clean up
munmap(fileMemory, fileSize);
close(inFileDescriptor);
return total_headers;
}
void NB::setTempDir(const string& _temp_dir){
temp_dir = _temp_dir;
}
void NB::save(){
for(unordered_map<string, Class<int>* >::iterator iter = classes.begin();
iter != classes.end(); iter++){
if(iter->second->loaded()){
iter->second->save();
}
}
}
void NB::addClass(Class<int>* cl){
classes[cl->getId()] = cl;
}
Class<int>* NB::getClass(string cl_id){
if(classes.find(cl_id) == classes.end()){
return NULL;
}
return classes[cl_id];
}
int NB::getKmerSize(){
return kmer_size;
}
int NB::getThreadNumber(){
return nthreads;
}
path NB::getSavedir(){
return save_dir;
}
void NB::addClassToUpdateQueue(Class<int>* cl){
classesToProcess.push(cl);
}
void NB::setWriteBufferSize(size_t size){
write_buffer_height = size;
}
void NB::initializeOutputBuffer(){
if(NB::OUTPUT_FULL_LOG_LIKELIHOOD){
outputs.resize(write_buffer_height, vector<double>(cls_size + 2, 2));
}else{
outputs.resize(write_buffer_height, vector<double>(2, 2));
}
}
void NB::classifyThreadController(){
while(true){
unique_lock<std::mutex> job_lock(classify_job_lock);
if(classifyJobs.empty()){
jobUpdateStatus.wait(job_lock, [this] { return !classifyJobs.empty() || job_done;});
}
if(job_done && classifyJobs.empty()){
return;
}
classifyJob job = classifyJobs.front();
classifyJobs.pop();
job_lock.unlock();
unordered_map<int, int> *kmer = new unordered_map<int, int>();
Diskutil::countKmer(*kmer, kmer_size, *(get<0>(job)), get<2>(job), get<3>(job));
{
lock_guard<mutex> lock(num_seq_kmer_counted_access);
num_seq_kmer_processed += 1;
if(waiting_for_kmer_counting && num_seq_kmer_processed == num_seq_kmer_processed){
num_seq_kmer_counted_cv.notify_one();
}
}
if(kmer->size() == 0){
NB::outputs[(get<1>(job) - start_seq_index) % write_buffer_height][0] = -1;
} else {
Genome genome(".", ".");
pair<int, double> predicted_class = make_pair(0,0);
genome.setKmerCounts(kmer);
for(uint64_t i = 0; i < cls_size; i++){
string filename = training_genomes[load_start_index-cls_size+i].first.filename().native();
string cls_s = filename.substr(0,filename.rfind('-'));
Class<int>* cl = classes[cls_s];
double result = genome.computeClassificationNumerator(cl);
if(NB::OUTPUT_FULL_LOG_LIKELIHOOD){
NB::outputs[(get<1>(job) - start_seq_index) % write_buffer_height][i+2] = result;
}
if(result > predicted_class.second || predicted_class.second == 0){
predicted_class.first = load_start_index-cls_size+i;
predicted_class.second = result;
}
}
NB::outputs[(get<1>(job) - start_seq_index) % write_buffer_height][0] = predicted_class.first;
NB::outputs[(get<1>(job) - start_seq_index) % write_buffer_height][1] = predicted_class.second;
genome.resetKmerCounts();
}
delete kmer;
lock_guard<mutex> output_update_lock(output_mtx);
processed_seq_num++;
if(processed_seq_num % write_buffer_height == 0){
output_cv.notify_one();
}
}
}
void NB::startClassifyThreads(){
initializeOutputBuffer();
job_done = false;
for(uint64_t i=0; i<nthreads; i++){
threads.push_back(thread(&NB::classifyThreadController, this));
}
}
void NB::queueClassifyJob(vector<char>& buffer, tuple<uint64_t, uint64_t, uint64_t>& sequence_data){
if(start_seq_index == 0){
start_seq_index = get<2>(sequence_data);
}
num_seq_kmer_processing += 1;
// write to CSV if exceeds buffer size
if((get<2>(sequence_data) - start_seq_index) % write_buffer_height == 0 && get<2>(sequence_data) != start_seq_index){
unique_lock<mutex> output_lock(output_mtx);
if(processed_seq_num % write_buffer_height != 0){
output_cv.wait(output_lock, [this]{ return processed_seq_num % write_buffer_height == 0;});
}
if(!finished_writing){
mutex mtx;
unique_lock<mutex> lock(mtx);
write_done_cv.wait(lock, [this]{ return finished_writing;});
}
if (outputs_write.size() > 0) {
unique_lock<mutex> write_lock(output_modify);
write_done_cv.wait(write_lock, [this]{ return outputs_write.size() == 0;});
}
swap(outputs, outputs_write);
finished_writing = false;
start_write_cv.notify_one();
initializeOutputBuffer();
}
classifyJob job(&buffer, get<2>(sequence_data), get<0>(sequence_data), get<1>(sequence_data));
lock_guard<mutex> lock(classify_job_lock);
classifyJobs.push(job);
jobUpdateStatus.notify_one();
}
void NB::getClassMemoryUsage(uint64_t& class_avg_bytes, uint64_t& class_max_bytes){
for(auto it = training_genomes.begin(); it != training_genomes.end(); it++){
uint64_t class_bytes = it->second;
class_avg_bytes += class_bytes;
if(class_bytes > class_max_bytes){
class_max_bytes = class_bytes;
}
}
class_avg_bytes /= training_genomes.size();
}
void NB::getStringSeqHeaders(vector<string>& seq_headers, const string& file_name) {
// Open the binary file for reading
std::ifstream file(file_name, std::ios::binary);
if (!file.is_open()) {
std::cerr << "Error opening file: " << file_name << std::endl;
return;
}
while (!file.eof()) {
// Read the size of the next string
size_t size;
if (!file.read(reinterpret_cast<char*>(&size), sizeof(size))) {
if (file.eof()) {
break; // Reached the end of the file
} else {
std::cerr << "Error reading size from file." << std::endl;
return;
}
}
// Read the string data
std::vector<char> buffer(size);
if (!file.read(buffer.data(), size)) {
std::cerr << "Error reading string data from file." << std::endl;
return;
}
// Append the extracted string to the vector
seq_headers.emplace_back(buffer.begin(), buffer.end());
}
// Close the file
file.close();
}
void NB::getStringClassHeaders(vector<string>& cls_headers, vector<pair<void*, size_t>>& maps, vector<size_t>& offsets, vector<size_t>& cols) {
for(size_t i = 0; i < maps.size(); i++){
size_t total_headers = *reinterpret_cast<size_t*>(maps[i].first) - 2 ;
cols[i] = total_headers;
char* data_ptr = reinterpret_cast<char*>(maps[i].first) + sizeof(size_t); // Move past the total_headers value
for (size_t i = 0; i < total_headers; ++i) {
size_t header_length = *reinterpret_cast<size_t*>(data_ptr);
data_ptr += sizeof(size_t); // Move past the header_length value
std::string header(data_ptr, header_length);
data_ptr += header_length; // Move past the actual header data
cls_headers.push_back(header);
}
offsets[i] = data_ptr - reinterpret_cast<char*>(maps[i].first);
}
}
void NB::concatenateCSVByColumns(const std::vector<std::string>& inputFiles, const std::string& output_prefix, const std::size_t& sequence_num) {
vector<string> seq_headers;
getStringSeqHeaders(seq_headers, inputFiles[0]);
// load all the data into mmap
vector<pair<void*, size_t>> fileMaps(inputFiles.size() - 1);
for (size_t i = 0; i < fileMaps.size(); ++i) {
std::string filename = inputFiles[i+1];
// Open the file
int fileDescriptor = open(filename.c_str(), O_RDONLY);
if (fileDescriptor == -1) {
std::cerr << "Error opening file: " << filename << std::endl;
return;
}
// Get the file size
struct stat fileInfo;
if (fstat(fileDescriptor, &fileInfo) == -1) {
std::cerr << "Error getting file size: " << filename << std::endl;
close(fileDescriptor);
return;
}
// Map the file into memory
void* fileMap = mmap(nullptr, fileInfo.st_size, PROT_READ, MAP_PRIVATE, fileDescriptor, 0);
if (fileMap == MAP_FAILED) {
std::cerr << "Error mapping file to memory: " << filename << std::endl;
close(fileDescriptor);
return;
}
fileMaps[i] = pair<void*, size_t>(fileMap, fileInfo.st_size);
// Close the file descriptor
close(fileDescriptor);
}
// extract the class headers
vector<string> cls_headers;
vector<size_t> maps_start(inputFiles.size()-1,0);
vector<size_t> file_col_num(inputFiles.size()-1,0);
getStringClassHeaders(cls_headers, fileMaps, maps_start, file_col_num);
int num_csv = cls_headers.size() / output_max_col;
bool is_frag = cls_headers.size() % output_max_col != 0;
if (is_frag) num_csv++;
size_t start_file_index = 0;
size_t skip_cols = 0;
// pair<start_index, num_cols>
vector<pair<size_t, size_t>> write_start_pos(fileMaps.size(), pair<size_t, size_t>(0,0));
for(size_t j = 0; j < file_col_num.size(); j++){
write_start_pos[j] = make_pair(maps_start[j] + (2 * sizeof(double)), file_col_num[j]);
}
for (double i = 0; i < num_csv; i++){
size_t class_num = last_written_class_index + 2 + i*output_max_col;
string output_name = output_prefix + "_" + std::to_string(class_num) + "_" + to_string(sequence_num) + ".csv";
size_t new_start_file_index = start_file_index;
size_t num_files = 0;
size_t cols_cnt = 0;
if (skip_cols != 0){
write_start_pos[start_file_index].first += (skip_cols * sizeof(double));
size_t offset = (write_start_pos[start_file_index].first - maps_start[start_file_index]) / sizeof(double) - 2;
write_start_pos[start_file_index].second = file_col_num[start_file_index] - offset;
skip_cols = 0;
}
for(size_t j = start_file_index; j < fileMaps.size(); j++){
if (write_start_pos[j].second + cols_cnt > output_max_col){
num_files++;
size_t col_to_write = output_max_col - cols_cnt;
write_start_pos[j].second = col_to_write;
skip_cols = col_to_write;
cols_cnt = output_max_col;
break;
}
else{
cols_cnt += write_start_pos[j].second;
new_start_file_index++;
num_files++;
}
}
bool is_binary = false;
// the last csv file whose size is smaller than output_max_col
if (i + 1 >= num_csv && is_frag && load_start_index < training_genomes.size()){
output_name = temp_dir + "/concat_" + to_string(sequence_num) + ".tmp";
is_binary = true;
}
std::ofstream outputFile(output_name);
if (!outputFile.is_open()) {
std::cerr << "Error opening output file." << std::endl;
return;
}
if (is_binary){
size_t index = fileMaps.size() - 1;
void* file_to_write = fileMaps[index].first;
size_t cls_num = file_col_num[index] % output_max_col + 2;
outputFile.write(reinterpret_cast<const char*>(&cls_num), sizeof(cls_num));
for(size_t j = file_col_num[index] - cls_num + 2; j < file_col_num[index]; j++){
size_t header_size = cls_headers[j].size();
outputFile.write(reinterpret_cast<const char*>(&header_size), sizeof(header_size));
outputFile.write(cls_headers[j].c_str(), header_size);
}
outputFile.write(reinterpret_cast<char*>(file_to_write + maps_start[index]), 2 * sizeof(double));
for(size_t row = 0; row < seq_headers.size(); row++){
size_t skipping_bytes = (2 + file_col_num[index]) * sizeof(double) * row;
skipping_bytes += write_start_pos[index].first;
outputFile.write(reinterpret_cast<char*>(file_to_write + skipping_bytes), (2 * sizeof(double)));
outputFile.write(reinterpret_cast<char*>(file_to_write + skipping_bytes), (write_start_pos[index].second) * sizeof(double));
}
outputFile.close();
return;
}
outputFile << "sequence_header,";
for(size_t j = i * output_max_col; j < cls_headers.size() && j < (i+1) * output_max_col; j++){
outputFile << cls_headers[j] << ",";
}
outputFile << "\n";
for(size_t row = 0; row < seq_headers.size(); row++){
outputFile << seq_headers[row] << ",";
size_t total_cols_written = 0;
size_t iter = start_file_index + num_files;
for(size_t current_map = start_file_index; current_map < iter; current_map++){
size_t skipping_bytes = (2 + file_col_num[current_map]) * sizeof(double) * row;
double* data_ptr = reinterpret_cast<double*>(fileMaps[current_map].first + write_start_pos[current_map].first + skipping_bytes);
size_t cols_to_write = write_start_pos[current_map].second;
for(size_t col = 0; col < cols_to_write; col++){
if(*data_ptr > 0){
if(current_map == start_file_index){
outputFile << "invalid sequence" << ",\n";
}
data_ptr+=cols_to_write;
total_cols_written = 0;
break;
}
outputFile << *data_ptr << ",";
data_ptr ++;
total_cols_written++;
}
if (total_cols_written == cols_cnt){
outputFile << "\n";
total_cols_written = 0;
}
}
}
outputFile.close();
start_file_index = new_start_file_index;
}
for (size_t i = 0; i < fileMaps.size(); i++) {
munmap(fileMaps[i].first, fileMaps[i].second);
}
}
void NB::waitCalculatingAllKmers(){
if(num_seq_kmer_processing != 0){
unique_lock<mutex> lock(num_seq_kmer_counted_access);
waiting_for_kmer_counting = true;
if(num_seq_kmer_processing != num_seq_kmer_processed){
num_seq_kmer_counted_cv.wait(lock, [this] { return num_seq_kmer_processing == num_seq_kmer_processed; });
}
waiting_for_kmer_counting = false;
lock.unlock();
}
}
string NB::getAppendFiles(int filter_number, std::vector<std::string>& file_names, const std::string& directory) {
string class_header_file = "";
DIR* dir = opendir(directory.c_str());
if (dir) {
struct dirent* ent;
while ((ent = readdir(dir)) != nullptr) {
std::string file_name = ent->d_name;
if (class_header_file == "") {
std::string pattern = std::to_string(output_class_index) + R"(\.clshd)";
std::regex regexPattern(pattern);
if (std::regex_match(file_name, regexPattern)) {
class_header_file = temp_dir + "/" + file_name;
}
}
if (file_name != "." && file_name != ".." && file_name.find(".tmp") != std::string::npos && file_name.find(std::to_string(filter_number) + "_") == 0) {
file_name = temp_dir + "/" + file_name;
file_names.push_back(file_name);
}
}
closedir(dir);
// Sort the files based on the numbers after "_"
std::sort(file_names.begin(), file_names.end(), [this](const std::string& a, const std::string& b) {
std::string aStr = a.substr(a.rfind('_') + 1);
std::string bStr = b.substr(b.rfind('_') + 1);
int aNum = std::stoi(aStr);
int bNum = std::stoi(bStr);
return aNum < bNum;
});
} else {
std::cerr << "Error opening directory." << std::endl;
}
return class_header_file;
}
void NB::loadMaxResults(vector<pair<int,string>>& max_files, vector<vector<double>>& max_list){
for (const auto& element : max_files) {
string file_path = element.second;
// Open the file for reading
int fd = open(file_path.c_str(), O_RDONLY);
if (fd == -1) {
std::cerr << "Error opening file: " << file_path << std::endl;
continue;
}
// Get the file size
off_t file_size = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
// Map the file into memory
void* file_memory = mmap(nullptr, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (file_memory == MAP_FAILED) {
std::cerr << "Error mapping file: " << file_path << std::endl;
close(fd);
continue;
}
size_t max_size = file_size / sizeof(double);
double* max_ptr = reinterpret_cast<double*>(file_memory);
max_list.emplace_back(max_size); // Add an empty vector<double>
std::vector<double>& max = max_list.back(); // Get a reference to the added vector
// Populate the new vector
for (size_t i = 0; i < max_size; ++i) {
max[i] = max_ptr[i];
}
munmap(file_memory, file_size); // Unmap the file
// Close the file (the mapped memory remains valid)
close(fd);
}
}
void NB::compareAndWriteMax(vector<double> max_vector, vector<double>& compare_vector, const std::string& filepath) {
// Open the output file for writing
std::ofstream outFile(filepath, std::ios::binary);
if (!outFile) {
std::cerr << "Failed to open output file: " << filepath << std::endl;
return;
}
// Iterate through odd-indexed values, compare, and modify compare_vector
for (size_t i = 1; i < max_vector.size(); i += 2) {
double index = max_vector[i-1];
double value = max_vector[i];
if (value > compare_vector[i] && value <= 0) {
// If max_vector's odd-indexed value is greater, modify compare_vector
compare_vector[i] = value;
compare_vector[i - 1] = index;
}
}
// Write the modified compare_vector to the output file
outFile.write(reinterpret_cast<const char*>(compare_vector.data()), sizeof(double) * max_vector.size());
// Close the output file
outFile.close();
}
void NB::fullAppend(std::vector<std::string>& inputFiles, const std::string& outputFile, string class_header_file) {
size_t col = 2;
uint64_t totalBytesWritten = 0;
int outputFileIndex = 1;
size_t header_size;
vector<char> buffer;
std::ifstream classHeaderFile(class_header_file, std::ios::binary | std::ios::ate);
// Get the file size
header_size = classHeaderFile.tellg();
classHeaderFile.seekg(0, std::ios::beg);
// Read the entire file content into a vector
buffer.resize(header_size);
if (!classHeaderFile.read(buffer.data(), header_size)) {
std::cerr << "Error reading file." << std::endl;
return;
}
// Process the file content from the buffer
const char* ptr = buffer.data();
const char* endPtr = ptr + header_size;
while (ptr < endPtr) {
size_t size;
std::memcpy(&size, ptr, sizeof(size));
ptr += sizeof(size);
if (ptr + size <= endPtr) {
col++;
ptr += size;
} else {
// Incomplete string data, handle the error as needed
break;
}
}
classHeaderFile.close();
vector<pair<int,string>> max_files;
getMaxFiles(max_files);
vector<vector<double>> max_list;
loadMaxResults(max_files, max_list);
size_t max_result_index = 0;
vector<double> new_max_result(output_max_row * 2, 0);
size_t new_result_size = 0;
uint64_t MAX_FILE_SIZE = (output_max_row * col) * sizeof(double);
std::string currentOutputFile = outputFile + "_" + std::to_string(outputFileIndex) + "_f.tmp";
// Append the input files to the output file(s) with a byte limit
std::ofstream outFile(currentOutputFile, std::ios::binary | std::ios::app);
if (outFile.is_open()) {
// Write the number of strings as uint64_t
outFile.write(reinterpret_cast<const char*>(&col), sizeof(col));
outFile.write(buffer.data(), header_size);
// Use mmap to load each input file and append its contents
for (const std::string& inputFile : inputFiles) {
int fd = open(inputFile.c_str(), O_RDONLY);
if (fd != -1) {
struct stat stat_buf;
fstat(fd, &stat_buf);
size_t fileSize = static_cast<size_t>(stat_buf.st_size);
void* fileMemory = mmap(nullptr, fileSize, PROT_READ, MAP_PRIVATE, fd, 0);
size_t num_row = fileSize / (col * sizeof(double));
double* doubleArray = static_cast<double*>(fileMemory);
for (size_t i = 0; i < num_row; i++) {
double first_column = doubleArray[col * i];
double second_column = doubleArray[col * i + 1];
new_max_result[2 * new_result_size] = first_column;
new_max_result[2 * new_result_size + 1] = second_column;
new_result_size++;
if (new_result_size == output_max_row) {
compareAndWriteMax(max_list[max_result_index], new_max_result, max_files[max_result_index].second);
new_result_size = 0;
max_result_index++;
}
}
size_t file_bytes_left = fileSize;
while (file_bytes_left != 0) {
// Determine how many bytes can be written to the current output file
size_t bytesToWrite = std::min(fileSize, MAX_FILE_SIZE - totalBytesWritten);
if (bytesToWrite % col != 0 && bytesToWrite < fileSize) {
// Adjust bytesToWrite to the nearest multiple of col
bytesToWrite = (bytesToWrite / col) * col;
}
if (bytesToWrite > file_bytes_left) {
bytesToWrite = file_bytes_left;
}
// Write the data to the current output file
outFile.write(reinterpret_cast<const char*>(fileMemory), bytesToWrite);
// Update the total bytes written and check if a new output file is needed
totalBytesWritten += bytesToWrite;
file_bytes_left -= bytesToWrite;
if (totalBytesWritten >= MAX_FILE_SIZE && file_bytes_left != 0) {
outFile.close();
totalBytesWritten = 0;
outputFileIndex += output_max_row;
currentOutputFile = outputFile + "_" + std::to_string(outputFileIndex) + "_f.tmp";
outFile.open(currentOutputFile, std::ios::binary | std::ios::app);
if (!outFile.is_open()) {
std::cerr << "Failed to open a new output file." << std::endl;
return;
}
outFile.write(reinterpret_cast<const char*>(&col), sizeof(col));
outFile.write(buffer.data(), header_size);
}
}
munmap(fileMemory, fileSize);
close(fd);
if (remove(inputFile.c_str()) != 0) {
std::cerr << "Error: Failed to delete temporary file: " << inputFile << std::endl;
}
} else {
std::cerr << "Failed to open input file: " << inputFile << std::endl;
return;
}
}
if (max_result_index < max_files.size()){
compareAndWriteMax(max_list[max_result_index], new_max_result, max_files[max_result_index].second);
}
outFile.close();
}
if (remove(class_header_file.c_str()) != 0) {
std::cerr << "Error: Failed to delete temporary file: " << class_header_file << std::endl;
}
}
void NB::maxAppend(std::vector<std::string>& inputFiles) {
size_t col = 2;
vector<pair<int,string>> max_files;
getMaxFiles(max_files);
vector<vector<double>> max_list;
loadMaxResults(max_files, max_list);
size_t max_result_index = 0;
vector<double> new_max_result(output_max_row * 2, 0);
size_t new_result_size = 0;
uint64_t MAX_FILE_SIZE = (output_max_row * col) * sizeof(double);
// Use mmap to load each input file and append its contents
for (const std::string& inputFile : inputFiles) {
int fd = open(inputFile.c_str(), O_RDONLY);
if (fd != -1) {
struct stat stat_buf;
fstat(fd, &stat_buf);
size_t fileSize = static_cast<size_t>(stat_buf.st_size);
void* fileMemory = mmap(nullptr, fileSize, PROT_READ, MAP_PRIVATE, fd, 0);
size_t num_row = fileSize / (col * sizeof(double));
double* doubleArray = static_cast<double*>(fileMemory);
for (size_t i = 0; i < num_row; i++) {
double first_column = doubleArray[col * i];
double second_column = doubleArray[col * i + 1];
new_max_result[2 * new_result_size] = first_column;
new_max_result[2 * new_result_size + 1] = second_column;
new_result_size++;
if (new_result_size == output_max_row) {
compareAndWriteMax(max_list[max_result_index], new_max_result, max_files[max_result_index].second);
new_result_size = 0;
max_result_index++;
}
}
munmap(fileMemory, fileSize);
close(fd);
if (remove(inputFile.c_str()) != 0) {
std::cerr << "Error: Failed to delete temporary file: " << inputFile << std::endl;
}
} else {
std::cerr << "Failed to open input file: " << inputFile << std::endl;
return;
}
}
if (max_result_index < max_files.size()){
compareAndWriteMax(max_list[max_result_index], new_max_result, max_files[max_result_index].second);
}
}
void NB::getConcatFiles(std::unordered_map<size_t, std::vector<std::string>>& file_groups, const std::string& directory) {
DIR* dir = opendir(directory.c_str());
if (dir) {
struct dirent* ent;
while ((ent = readdir(dir)) != nullptr) {
std::string file_name = ent->d_name;
std::smatch match;
int group_number = -1;
if (std::regex_search(file_name, match, std::regex(R"(^(concat_(\d+)\.tmp))"))) {
group_number = std::stoi(match[2]);
} else if (std::regex_search(file_name, match, std::regex(R"(\d+_(\d+)_f\.(tmp|hd))"))) {
group_number = std::stoi(match[1]);
}
if (group_number >= 0) {
file_groups[group_number].push_back(file_name);
}
}
closedir(dir);
// Sort files within each group
for (auto& kv : file_groups) {
std::sort(kv.second.begin(), kv.second.end(), [](const std::string& file1, const std::string& file2) {
float num1, num2 = 0;
std::smatch match1, match2;
if (std::regex_search(file1, match1, std::regex(R"_(\d+)_"))) {
num1 = std::stoi(match1[0]);
}
if (std::regex_search(file2, match2, std::regex(R"_(\d+)_"))) {
num2 = std::stoi(match2[0]);
}
// Add 0.5 to the value of "concat_" files before sorting
if (file1.find("concat_") == 0) {
num1 += 0.5;
}
if (file2.find("concat_") == 0) {
num2 += 0.5;
}
return num1 < num2;
});
}
for (auto& kv : file_groups) {
for (auto& file : kv.second) {
file = directory + "/" + file;
}
}
} else {
std::cerr << "Error opening directory." << std::endl;
}
}
void NB::concatenateCSVs(string& output_name){
unordered_map<size_t, vector<string>> file_groups;
getConcatFiles(file_groups, temp_dir);
for(auto it = file_groups.begin(); it != file_groups.end(); it++){
string output_prefix = output_name;
concatenateCSVByColumns(it->second, output_prefix, it->first);
}