Repository navigation
Expand file tree
/
Copy pathPoint.cpp
More file actions
1505 lines (1360 loc) · 44.2 KB
/
Copy pathPoint.cpp
File metadata and controls
1505 lines (1360 loc) · 44.2 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
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
/**
* Metagenomics Canopy Clustering Implementation
*
* Copyright (C) 2013, 2014 Piotr Dworzynski (piotr@cbs.dtu.dk), Technical University of Denmark
* Copyright (C) 2018 Falk Hildebrand (falk.hildebrand@gmail.com), EMBL
* Copyright (C) 2020 Falk Hildebrand (falk.hildebrand@gmail.com), QIB/EI
* This file is part of Metagenomics Canopy Clustering Implementation.
*
* Metagenomics Canopy Clustering Implementation is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* Metagenomics Canopy Clustering Implementation is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <sstream>
#include <algorithm>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <functional>
#include <numeric>
#include <limits>
#include <deque>
#include <cstdint>
//#include <boost/bind.hpp>
//#include <boost/functional/hash.hpp>
//#include <boost/algorithm/string.hpp>
#include "Point.hpp"
#include "Log.hpp"
#include "Stats.hpp"
#include "ThreadPool.hpp"
using namespace std;
extern ProfileMeasureType profile_measure;
std::unique_ptr<Point> line2point(string line, bool sparseMat, int lcnt) {
std::unique_ptr<Point> pp(new Point(line, sparseMat, lcnt));
pp->seal();
return pp;
}
#ifdef _gzipread
namespace {
struct IndexedGzipChunk {
uint64_t compressed_begin;
uint64_t compressed_end;
uint64_t expected_uncompressed;
};
uint64_t read_little_endian_u64(std::istream& input) {
unsigned char bytes[8];
input.read(reinterpret_cast<char*>(bytes), sizeof(bytes));
if (!input) {
throw runtime_error("Truncated .gzi index");
}
uint64_t value = 0;
for (int i = 7; i >= 0; i--) {
value = (value << 8) | bytes[i];
}
return value;
}
bool load_indexed_gzip_chunks(const string& input_file_path, int num_threads,
vector<IndexedGzipChunk>& chunks, string& fallback_reason) {
const string index_path = input_file_path + ".gzi";
ifstream index(index_path.c_str(), ios::in | ios::binary);
if (!index) {
return false;
}
ifstream compressed(input_file_path.c_str(), ios::in | ios::binary);
compressed.seekg(0, ios::end);
const std::streamoff compressed_size_off = compressed.tellg();
if (compressed_size_off <= 0) {
fallback_reason = "Could not determine compressed input size";
return false;
}
const uint64_t compressed_size =
static_cast<uint64_t>(compressed_size_off);
try {
const string rtk_index_header = "RTK2_PAR_GZIP_INDEX_V1";
string index_prefix(rtk_index_header.size(), '\0');
index.read(&index_prefix[0],
static_cast<std::streamsize>(index_prefix.size()));
const bool is_rtk_index =
index.gcount() == static_cast<std::streamsize>(
rtk_index_header.size()) &&
index_prefix == rtk_index_header;
if (is_rtk_index) {
char line_ending = '\0';
index.get(line_ending);
if (line_ending == '\r') {
index.get(line_ending);
}
if (line_ending != '\n') {
throw runtime_error(
"Invalid RTK2 parallel-gzip index header");
}
vector<IndexedGzipChunk> member_chunks;
vector<uint64_t> uncompressed_lengths;
uint64_t expected_offset = 0;
string index_line;
while (getline(index, index_line)) {
if (index_line.empty()) {
continue;
}
istringstream fields(index_line);
uint64_t compressed_offset = 0;
uint64_t compressed_length = 0;
uint64_t uncompressed_length = 0;
if (!(fields >> compressed_offset >> compressed_length >>
uncompressed_length) || compressed_length == 0 ||
compressed_offset != expected_offset ||
compressed_offset > compressed_size ||
compressed_length >
compressed_size - compressed_offset) {
throw runtime_error(
"Invalid RTK2 parallel-gzip index row");
}
IndexedGzipChunk member;
member.compressed_begin = compressed_offset;
member.compressed_end =
compressed_offset + compressed_length;
member.expected_uncompressed = uncompressed_length;
member_chunks.push_back(member);
uncompressed_lengths.push_back(uncompressed_length);
expected_offset = member.compressed_end;
}
if (member_chunks.empty() || expected_offset != compressed_size) {
throw runtime_error(
"RTK2 parallel-gzip index does not cover the input");
}
const size_t target_tasks =
static_cast<size_t>(std::max(1, num_threads)) * 4U;
uint64_t total_uncompressed = 0;
for (uint64_t length : uncompressed_lengths) {
if (length >
std::numeric_limits<uint64_t>::max() -
total_uncompressed) {
throw runtime_error(
"RTK2 parallel-gzip size overflow");
}
total_uncompressed += length;
}
const uint64_t balanced_bytes = std::max<uint64_t>(1,
total_uncompressed / target_tasks +
(total_uncompressed % target_tasks != 0 ? 1U : 0U));
const uint64_t target_chunk_bytes =
std::min<uint64_t>(4U * 1024U * 1024U, balanced_bytes);
size_t begin_member = 0;
uint64_t chunk_uncompressed = 0;
for (size_t member_i = 0; member_i < member_chunks.size();
member_i++) {
chunk_uncompressed += uncompressed_lengths[member_i];
const bool close_chunk =
chunk_uncompressed >= target_chunk_bytes ||
member_i - begin_member + 1U >= 64U ||
member_i + 1U == member_chunks.size();
if (close_chunk) {
IndexedGzipChunk chunk;
chunk.compressed_begin =
member_chunks[begin_member].compressed_begin;
chunk.compressed_end =
member_chunks[member_i].compressed_end;
chunk.expected_uncompressed = chunk_uncompressed;
chunks.push_back(chunk);
begin_member = member_i + 1U;
chunk_uncompressed = 0;
}
}
return !chunks.empty();
}
index.clear();
index.seekg(0, ios::beg);
const uint64_t entry_count = read_little_endian_u64(index);
index.seekg(0, ios::end);
const std::streamoff index_size = index.tellg();
if (index_size < 8 ||
entry_count >
(static_cast<uint64_t>(index_size) - 8U) / 16U ||
static_cast<uint64_t>(index_size) !=
8U + entry_count * 16U) {
throw runtime_error("Invalid .gzi index length");
}
index.seekg(8, ios::beg);
vector<uint64_t> block_starts;
vector<uint64_t> uncompressed_starts;
block_starts.reserve(static_cast<size_t>(entry_count) + 1U);
uncompressed_starts.reserve(
static_cast<size_t>(entry_count) + 1U);
block_starts.push_back(0);
uncompressed_starts.push_back(0);
uint64_t previous_compressed = 0;
uint64_t previous_uncompressed = 0;
for (uint64_t entry_i = 0; entry_i < entry_count; entry_i++) {
const uint64_t compressed_offset =
read_little_endian_u64(index);
const uint64_t uncompressed_offset =
read_little_endian_u64(index);
if (compressed_offset == 0 && uncompressed_offset == 0) {
continue;
}
if (compressed_offset <= previous_compressed ||
uncompressed_offset <= previous_uncompressed ||
compressed_offset >= compressed_size) {
throw runtime_error("Invalid offsets in .gzi index");
}
block_starts.push_back(compressed_offset);
uncompressed_starts.push_back(uncompressed_offset);
previous_compressed = compressed_offset;
previous_uncompressed = uncompressed_offset;
}
if (block_starts.size() < 2) {
fallback_reason =
"Binary GZI contains only one gzip member; using sequential input";
return false;
}
const size_t block_count = block_starts.size();
const size_t target_tasks =
static_cast<size_t>(std::max(1, num_threads)) * 4U;
const size_t balanced_blocks =
(block_count + target_tasks - 1U) / target_tasks;
const size_t blocks_per_chunk =
std::max<size_t>(1, std::min<size_t>(64, balanced_blocks));
for (size_t begin_block = 0; begin_block < block_count;
begin_block += blocks_per_chunk) {
const size_t end_block =
std::min(block_count, begin_block + blocks_per_chunk);
IndexedGzipChunk chunk;
chunk.compressed_begin = block_starts[begin_block];
chunk.compressed_end = end_block < block_count ?
block_starts[end_block] : compressed_size;
chunk.expected_uncompressed = end_block < block_count ?
uncompressed_starts[end_block] -
uncompressed_starts[begin_block] :
std::numeric_limits<uint64_t>::max();
chunks.push_back(chunk);
}
}
catch (const std::exception& error) {
fallback_reason = string("Invalid .gzi index: ") + error.what() +
"; using sequential gzip input";
chunks.clear();
return false;
}
return !chunks.empty();
}
string decompress_indexed_gzip_chunk(const string& input_file_path,
const IndexedGzipChunk& chunk) {
const uint64_t compressed_length =
chunk.compressed_end - chunk.compressed_begin;
if (compressed_length == 0 ||
compressed_length > static_cast<uint64_t>(
std::numeric_limits<uInt>::max())) {
throw runtime_error("Invalid indexed gzip chunk size");
}
ifstream input(input_file_path.c_str(), ios::in | ios::binary);
input.seekg(static_cast<std::streamoff>(chunk.compressed_begin), ios::beg);
vector<unsigned char> compressed(static_cast<size_t>(compressed_length));
input.read(reinterpret_cast<char*>(compressed.data()),
static_cast<std::streamsize>(compressed.size()));
if (!input) {
throw runtime_error("Failed to read indexed gzip chunk");
}
string output;
output.reserve(compressed.size() * 2U);
size_t input_offset = 0;
char output_buffer[64U * 1024U];
while (input_offset < compressed.size()) {
z_stream stream;
std::memset(&stream, 0, sizeof(stream));
stream.next_in = compressed.data() + input_offset;
stream.avail_in =
static_cast<uInt>(compressed.size() - input_offset);
if (inflateInit2(&stream, 47) != Z_OK) {
throw runtime_error("Could not initialize indexed gzip decompression");
}
int inflate_result = Z_OK;
while (inflate_result == Z_OK) {
stream.next_out =
reinterpret_cast<Bytef*>(output_buffer);
stream.avail_out = static_cast<uInt>(sizeof(output_buffer));
inflate_result = inflate(&stream, Z_NO_FLUSH);
const size_t produced =
sizeof(output_buffer) - stream.avail_out;
output.append(output_buffer, produced);
}
const size_t consumed = static_cast<size_t>(stream.total_in);
inflateEnd(&stream);
if (inflate_result != Z_STREAM_END || consumed == 0) {
throw runtime_error("Invalid gzip member in indexed chunk");
}
input_offset += consumed;
}
if (chunk.expected_uncompressed !=
std::numeric_limits<uint64_t>::max() &&
output.size() != chunk.expected_uncompressed) {
throw runtime_error(
"Indexed gzip chunk has an unexpected uncompressed size");
}
return output;
}
void read_indexed_gzip(
const string& input_file_path, const vector<IndexedGzipChunk>& chunks,
ThreadPool& thread_pool, int num_threads,
const std::function<void(const string&)>& consume_line) {
const size_t max_in_flight = std::max<size_t>(1,
static_cast<size_t>(std::max(1, num_threads)) * 2U);
deque<std::future<string>> in_flight;
size_t next_chunk = 0;
string line_fragment;
auto submit_chunks = [&]() {
while (next_chunk < chunks.size() &&
in_flight.size() < max_in_flight) {
const IndexedGzipChunk chunk = chunks[next_chunk++];
in_flight.push_back(thread_pool.enqueue(
[input_file_path, chunk]() {
return decompress_indexed_gzip_chunk(
input_file_path, chunk);
}));
}
};
submit_chunks();
while (!in_flight.empty()) {
string decompressed = in_flight.front().get();
in_flight.pop_front();
submit_chunks();
size_t line_begin = 0;
for (;;) {
const size_t newline = decompressed.find('\n', line_begin);
if (newline == string::npos) {
line_fragment.append(decompressed, line_begin,
string::npos);
break;
}
if (line_fragment.empty()) {
consume_line(decompressed.substr(
line_begin, newline - line_begin));
}
else {
line_fragment.append(decompressed, line_begin,
newline - line_begin);
consume_line(line_fragment);
line_fragment.clear();
}
line_begin = newline + 1;
}
}
if (!line_fragment.empty()) {
consume_line(line_fragment);
}
}
} // namespace
#endif
void readMatrix(vector<Point*>& points,
vector<std::unique_ptr<Point>>& point_owners, string input_file_path,
bool sparseMat, int num_threads, bool dont_use_mmap) {
num_threads = std::max(1, num_threads);
ThreadPool& thread_pool =
get_global_thread_pool(static_cast<size_t>(num_threads));
int lcnt = 0;
bool header_read = false;
const size_t max_parse_in_flight =
static_cast<size_t>(num_threads) * 4U;
deque<std::future<std::unique_ptr<Point>>> parse_tasks;
auto commit_point = [&]() {
std::unique_ptr<Point> pp;
try {
pp = parse_tasks.front().get();
}
catch (const std::exception& error) {
cerr << error.what() << "\n";
exit(1);
}
parse_tasks.pop_front();
if (pp->lineCnt >= static_cast<int>(points.size())) {
points.resize(pp->lineCnt + 1, nullptr);
point_owners.resize(pp->lineCnt + 1);
}
points[pp->lineCnt] = pp.get();
point_owners[pp->lineCnt] = std::move(pp);
};
auto consume_line = [&](const string& line) {
if (!header_read) {
header_read = true;
return;
}
if (line.length() < 2) {
return;
}
const bool has_carriage_return =
!line.empty() && line.back() == '\r';
string normalized_line = has_carriage_return ?
line.substr(0, line.size() - 1U) : line;
parse_tasks.push_back(thread_pool.enqueue(
line2point, std::move(normalized_line), sparseMat, lcnt++));
if (parse_tasks.size() >= max_parse_in_flight) {
commit_point();
}
};
const bool is_gzip_input = isGZfile(input_file_path);
bool used_indexed_gzip = false;
#ifdef _gzipread
if (is_gzip_input && num_threads > 1) {
vector<IndexedGzipChunk> chunks;
string fallback_reason;
if (load_indexed_gzip_chunks(input_file_path, num_threads,
chunks, fallback_reason)) {
_log(logINFO) << "Reading indexed gzip input in parallel using "
<< chunks.size() << " chunks";
try {
read_indexed_gzip(input_file_path, chunks, thread_pool,
num_threads, consume_line);
used_indexed_gzip = true;
}
catch (const std::exception& error) {
cerr << "Parallel indexed gzip input failed: "
<< error.what() << "\n";
exit(1);
}
}
else if (!fallback_reason.empty()) {
_log(logWARN) << fallback_reason;
}
}
#endif
if (!used_indexed_gzip) {
std::unique_ptr<std::istream> point_file;
if (is_gzip_input) {
#ifdef _gzipread
point_file.reset(new igzstream(input_file_path.c_str(), ios::in));
_log(logINFO) << "Reading gzip input sequentially";
#else
cerr << "gzip not supported in your rtk build\n";
exit(50);
#endif
}
else {
point_file.reset(new ifstream(input_file_path.c_str()));
}
if (!point_file || !(*point_file)) {
cerr << "Could not open input matrix: " << input_file_path << "\n";
exit(1);
}
string line;
if (dont_use_mmap || is_gzip_input) {
_log(logINFO) << "Reading input matrix line by line";
while (getline(*point_file, line)) {
consume_line(line);
}
}
else {
_log(logINFO) << "Reading input matrix into memory";
vector<string> buffered_lines;
while (getline(*point_file, line)) {
buffered_lines.push_back(line);
}
for (const string& buffered_line : buffered_lines) {
consume_line(buffered_line);
}
}
}
if (!header_read) {
cerr << "Input matrix is empty\n";
return;
}
while (!parse_tasks.empty()) {
commit_point();
}
cerr << "Read " << lcnt << " rows\n";
}
Point::Point( Point* p, int deletedSmpls):sample_data(NULL),
#ifdef PRECARRAY
sample_data_pearson_precomputed(NULL),
#else
SumD(0),StdDev(0),
#endif
num_data_samples(p->num_data_samples), lineCnt(p->lineCnt),
precomputed(false), sparse(p->sparse){
(void)deletedSmpls;
id = p->id;
if (sparse) {
// Sparse keys retain their original sample indexes while
// num_data_samples records only the observations used for
// correlations. Copy the maps directly so those two concepts do not
// become conflated after autocorrelation filtering.
sp_data = p->sp_data;
}
else {
sample_data = new PRECISIONT[num_data_samples];
for (int i = 0; i < num_data_samples; i++) {
sample_data[i] = p->sample_data[i];
}
}
sp_data_rm = p->sp_data_rm;
if(p->precomputed ){
//The above if only checks if the point being copied has had its sample pearson data precomputed
//In fact it should never copy a non precomputed point
//Precomputing was added as a clumsy way to lower memory usage
#ifdef PRECARRAY
if (sparse) {
sp_data_precomp = p->sp_data_precomp;
}
else {
sample_data_pearson_precomputed = new PRECISIONT[num_data_samples];
for (int i = 0; i < num_data_samples; i++) {
sample_data_pearson_precomputed[i] = p->sample_data_pearson_precomputed[i];
}
}
#else
SumD = p->SumD; StdDev = p->StdDev;
#endif
precomputed = true;
} else {
#ifdef PRECARRAY
sample_data_pearson_precomputed = NULL;
#endif
precomputed = false;
}
}
Point::~Point() {
if (sample_data != NULL) {
delete[] sample_data;
}
#ifdef PRECARRAY
if (sample_data_pearson_precomputed != NULL) {
delete[] sample_data_pearson_precomputed; //Note that for some points this might be a null pointer, see constructor and delay_precomputing_pearson_data flag
}
#endif
}
Point::Point(string line,bool sp, int lc):sample_data(NULL),
#ifdef PRECARRAY
sample_data_pearson_precomputed(NULL),
#else
SumD(0), StdDev(0),
#endif
num_data_samples(0), lineCnt(lc), precomputed(false), sparse(sp)
{
auto parse_error = [&](const string& message) {
throw runtime_error("Invalid profile on input row " + to_string(lc + 2) + ": " + message);
};
if (line.empty()) {
parse_error("empty row");
}
if (line[line.size() - 1] == '\t') {
parse_error("trailing empty sample field");
}
stringstream ss;
ss << line;
int cnt2(-2);
const char sep = '\t';
string segments;
std::vector<PRECISIONT> sample_data_vector;
while (getline(ss, segments, sep)) {
cnt2++;
if (cnt2 == -1) {//this is the row ID
id = segments;
if (id.empty()) {
parse_error("empty profile ID");
}
continue;
}
char* end = NULL;
errno = 0;
const char* value = segments.c_str();
double parsed = strtod(value, &end);
if (segments.empty() || end == value || *end != '\0' || errno == ERANGE ||
!std::isfinite(parsed) || parsed < 0) {
parse_error("invalid non-negative numeric value '" + segments + "'");
}
const PRECISIONT stored_value = static_cast<PRECISIONT>(parsed);
if (!std::isfinite(stored_value)) {
parse_error("numeric value is outside the configured precision range");
}
sample_data_vector.push_back(stored_value);
}
if (sample_data_vector.empty()) {
parse_error("profile has no sample values");
}
num_data_samples = sample_data_vector.size();
sample_data = new PRECISIONT[num_data_samples];
num_data_samples = sample_data_vector.size();
for (size_t i = 0; i < sample_data_vector.size(); i++) {
sample_data[i] = sample_data_vector[i];
}
#ifdef PRECARRAY
sample_data_pearson_precomputed = NULL;
#endif
/*
char *next_token = NULL;
const char* delim = "\t";
//Copy line to private buffer - strtok will modify it
char* private_line = &line[0];// new char[strlen(line) + 1];
//strcpy_s(private_line, sizeof private_line, line);
//strcpy(private_line, line);
//_log(logDEBUG3)<< "Point constructor, got: \"" << line << "\"";
//Read gene id - first word in the line
//char* word = strtok_s(private_line, delim, &next_token);
char* word = strtok(private_line, delim);
id = string(word);
//_log(logDEBUG3)<< "Point constructor, point id: \"" << id << "\"";
//Fill vector with data samples
std::vector<PRECISIONT> sample_data_vector;
//sample_data_vector.reserve(700);
word = strtok(private_line, delim);
while( word != NULL ){
sample_data_vector.push_back((PRECISIONT)atof(word));
word = strtok(private_line, delim);
}
//Get number of samples for this point
num_data_samples = sample_data_vector.size();
//_log(logDEBUG3)<< "Point constructor, num data samples: \"" << num_data_samples << "\"";
//return;
//Allocate memory for sample_data (but not pearson precomputed)
//assert(num_data_samples > 0);
sample_data = new PRECISIONT[num_data_samples];
for(size_t i = 0; i < sample_data_vector.size(); i++){
sample_data[i] = sample_data_vector[i];
}
//Precomputing of point's pearson data should happen here, but it creates a huge memory spike when creating points of which many will be filtered out
//Now it is up to user to precompute these using allocate_and_precompute_pearson_data
//It is a bit clumsy but it does help with memory spikes
#ifdef PRECARRAY
sample_data_pearson_precomputed = NULL;
#endif
//delete[] private_line;
*/
}
vector<PRECISIONT> Point::rankSort(const PRECISIONT* v_temp, const size_t size) {
vector<pair<PRECISIONT, size_t> > v_sort(size);
for (size_t i = 0U; i < size; ++i) {
v_sort[i] = make_pair(v_temp[i], i);
}
sort(v_sort.begin(), v_sort.end());
vector<PRECISIONT> result(size);
for (size_t group_begin = 0; group_begin < size;) {
size_t group_end = group_begin + 1;
while (group_end < size && v_sort[group_end].first == v_sort[group_begin].first) {
group_end++;
}
const PRECISIONT average_rank = static_cast<PRECISIONT>(group_begin + group_end - 1) /
static_cast<PRECISIONT>(2);
for (size_t i = group_begin; i < group_end; ++i) {
result[v_sort[i].second] = average_rank;
}
group_begin = group_end;
}
return result;
}
void Point::seal() {
if (sparse && sample_data != NULL) {
for (int i = 0; i < num_data_samples; i++) {
// if (sample_data[i] != 0) {
if (sample_data[i] > 1e-15) { //take compputational inaccuracy into account..
sp_data[i] = sample_data[i];
}
}
delete[] sample_data;
sample_data = NULL;
}
}
void Point::convert_to_rank(){
vector<bool> removed_samples(num_data_samples, false);
convert_to_rank(removed_samples);
}
void Point::convert_to_rank(const vector<bool>& removed_samples){
if (removed_samples.size() != static_cast<size_t>(num_data_samples)) {
throw runtime_error("Rank conversion received an invalid sample-removal mask");
}
vector<PRECISIONT> original(num_data_samples, 0);
if (sample_data != NULL) {
for (int i = 0; i < num_data_samples; i++) {
original[i] = sample_data[i];
}
}
else if (sparse) {
for (auto value : sp_data) {
if (value.first >= 0 && value.first < num_data_samples) {
original[value.first] = value.second;
}
}
}
else {
throw runtime_error("Cannot rank a point without sample data");
}
vector<PRECISIONT> retained_values;
vector<int> retained_indexes;
retained_values.reserve(num_data_samples);
retained_indexes.reserve(num_data_samples);
for (int i = 0; i < num_data_samples; ++i) {
if (!removed_samples[i]) {
retained_values.push_back(original[i]);
retained_indexes.push_back(i);
}
}
if (retained_values.empty()) {
throw runtime_error("Cannot rank a profile after removing every sample");
}
vector<PRECISIONT> retained_ranks = rankSort(retained_values.data(), retained_values.size());
// Preserve full-profile ranks for removed samples so they can be restored
// for output, while clustering uses ranks recomputed over retained samples.
vector<PRECISIONT> ranked = rankSort(original.data(), original.size());
for (size_t i = 0; i < retained_indexes.size(); ++i) {
ranked[retained_indexes[i]] = retained_ranks[i];
}
if (sample_data != NULL) {
for (int i = 0; i < num_data_samples; i++) {
sample_data[i] = ranked[i];
}
}
else {
sp_data.clear();
for (int i = 0; i < num_data_samples; i++) {
if (ranked[i] > static_cast<PRECISIONT>(1e-15)) {
sp_data[i] = ranked[i];
}
}
}
precomputed = false;
}
void Point::precompute_pearson_data() {
//calc both for debugging..
#ifdef PRECARRAY
if (sparse) {
precompute_pearson_data_sparse();
}
else {
precompute_pearson_data_array();
}
#else
if (sparse) {
precompute_pearson_data_sparse_2();
}
else {
precompute_pearson_data_array_2();
}
#endif
precomputed = true;
}
void Point::restore_rm(int sr) {
for (auto x : sp_data_rm) {
if (sparse) {
sp_data[x.first] = x.second;
}
else {
sample_data[x.first] = x.second;
}
}
num_data_samples += sr;
}
void Point::pseudoRmSamples(const vector<bool> & rm, int sumRm) {
if (sparse) {
mvec::iterator x = sp_data.begin();
while(x != sp_data.end() ) {
if (rm[x->first]) {
sp_data_rm[x->first] = x->second;
x= sp_data.erase(x);
}
else {
x++;
}
}
}
else {
for (int i = 0; i < num_data_samples; i++) {
if (rm[i] && sample_data[i] > 0) {
sp_data_rm[i] = sample_data[i];
sample_data[i] = -1;
}
}
}
num_data_samples -= sumRm;
}
void Point::addToVec(vector<PRECISIONT>& sms) {
if ((int)sms.size() < num_data_samples) {
sms.resize(num_data_samples, 0);
}
if (sparse) {
for (auto x : sp_data) {
sms[x.first] += x.second;
}
}
else {
for (int i = 0; i < num_data_samples; i++) {
sms[i] += sample_data[i];
}
}
}
#ifndef PRECARRAY
PRECISIONT Point::getDist_precomp(Point* oth) {
double sum_XY(0);
if (sparse) {
const mvec& v1 =
sp_data.size() <= oth->sp_data.size() ? sp_data : oth->sp_data;
const mvec& v2 =
sp_data.size() <= oth->sp_data.size() ? oth->sp_data : sp_data;
for (const auto& x : v1) {
auto fnd = v2.find(x.first);
if (fnd == v2.end()) {//v2===Yi == 0
continue;
}
sum_XY += x.second * fnd->second;
}
}
else {
for (int i = 0; i < num_data_samples; i++)
{
// sum of elements of array X/ Y
sum_XY += sample_data[i] * oth->sample_data[i];
}
}
const double denominator_squared = StdDev * oth->StdDev;
if (!(denominator_squared > 0.0) ||
!std::isfinite(denominator_squared)) {
return std::numeric_limits<PRECISIONT>::infinity();
}
double correlation = ((double)num_data_samples * sum_XY - SumD * oth->SumD) /
sqrt(denominator_squared);
if (!std::isfinite(correlation)) {
return std::numeric_limits<PRECISIONT>::infinity();
}
correlation = std::max(-1.0, std::min(1.0, correlation));
return static_cast<PRECISIONT>(1.0 - correlation);
}
void Point::precompute_pearson_data_array_2() {
//Calculate sum and average of data samples
SumD = 0; StdDev = 0;
for (int i = 0; i < num_data_samples; i++) {
if (sample_data[i] < 0) {continue;}
SumD += sample_data[i];
}
//Calculate standard deviation of data samples
double factor_sum = 0;
for (int i = 0; i < num_data_samples; i++) {
if (sample_data[i] < 0) { continue; }
factor_sum += sample_data[i] * sample_data[i];
}
StdDev = ((double)num_data_samples * factor_sum) -
(SumD * SumD);
}
void Point::precompute_pearson_data_sparse_2() {
//Calculate sum and average of data samples
SumD = 0; StdDev = 0;
for (const auto& x : sp_data)
SumD += x.second;
//Calculate standard deviation of data samples
double factor_sum = 0;
for (const auto& x : sp_data)
factor_sum += x.second * x.second;
StdDev = ((double)num_data_samples * factor_sum) -
(SumD * SumD);
}
#else
void Point::precompute_pearson_data_array() {
//Calculate sum and average of data samples
double sum = 0, avg = 0, num_data_samples_d = num_data_samples;
for (int i = 0; i < num_data_samples; i++)
sum += sample_data[i];
avg = sum / num_data_samples_d;
//Calculate standard deviation of data samples
double factor_sum = 0;
for (int i = 0; i < num_data_samples; i++)
factor_sum += pow((sample_data[i] - avg), 2);
double stddev = 0;
stddev = sqrt(factor_sum / num_data_samples_d);
//Precompute pearson data
for (int i = 0; i < num_data_samples; i++) {
if (fabs(stddev) < 2 * std::numeric_limits<PRECISIONT>::min())
sample_data_pearson_precomputed[i] = 0;
else
double tmp = (sample_data[i] - avg) / (stddev * num_data_samples_d);
sample_data_pearson_precomputed[i] = (sample_data[i] - avg) / (stddev * num_data_samples_d);
}
}
void Point::precompute_pearson_data_sparse() {
//Calculate sum and average of data samples
double sum = 0, avg = 0, num_data_samples_d = num_data_samples;
for (auto x: sp_data)
sum += x.second;
avg = sum / num_data_samples_d;
//Calculate standard deviation of data samples
double factor_sum = 0;
for (auto x : sp_data)
factor_sum += pow((x.second - avg), 2);
double stddev = 0;
stddev = sqrt(factor_sum / num_data_samples_d);
//Precompute pearson data
for (auto x : sp_data){
if (fabs(stddev) > 2 * std::numeric_limits<PRECISIONT>::min()) {
sp_data_precomp[x.first] = (x.second - avg) / (stddev * num_data_samples_d);
}
}
}
#endif
void Point::allocate_and_precompute_pearson_data(){
#ifdef PRECARRAY
if(sample_data_pearson_precomputed != NULL){
//When this is thrown it means that the point on which this function is executing had already had it's sample_data allocated
//this function should only be called on Points with points not precomputed
throw "Precomputing already existing pearson data, this is a memory leak";
}
//Allocate and copy samples into array
sample_data_pearson_precomputed = new PRECISIONT[num_data_samples];
#endif