-
Notifications
You must be signed in to change notification settings - Fork 15
/
api.cpp
1505 lines (1199 loc) · 57.4 KB
/
api.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
#include "api.hpp"
#include "biom.hpp"
#include "tree.hpp"
#include "unifrac.hpp"
#include "skbio_alt.hpp"
#include <fstream>
#include <iomanip>
#include <thread>
#include <cstring>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <lz4.h>
#define MMAP_FD_MASK 0x0fff
#define MMAP_FLAG 0x1000
/* O_NOATIME is defined at fcntl.h when supported */
#ifndef O_NOATIME
#define O_NOATIME 0
#endif
#define CHECK_FILE(filename, err) if(!is_file_exists(filename)) { \
return err; \
}
#define SET_METHOD(requested_method, err) Method method; \
if(std::strcmp(requested_method, "unweighted") == 0) \
method = unweighted; \
else if(std::strcmp(requested_method, "weighted_normalized") == 0) \
method = weighted_normalized; \
else if(std::strcmp(requested_method, "weighted_unnormalized") == 0) \
method = weighted_unnormalized; \
else if(std::strcmp(requested_method, "generalized") == 0) \
method = generalized; \
else if(std::strcmp(requested_method, "unweighted_fp32") == 0) \
method = unweighted_fp32; \
else if(std::strcmp(requested_method, "weighted_normalized_fp32") == 0) \
method = weighted_normalized_fp32; \
else if(std::strcmp(requested_method, "weighted_unnormalized_fp32") == 0) \
method = weighted_unnormalized_fp32; \
else if(std::strcmp(requested_method, "generalized_fp32") == 0) \
method = generalized_fp32; \
else { \
return err; \
}
#define PARSE_SYNC_TREE_TABLE(tree_filename, table_filename) std::ifstream ifs(tree_filename); \
std::string content = std::string(std::istreambuf_iterator<char>(ifs), \
std::istreambuf_iterator<char>()); \
su::BPTree tree = su::BPTree(content); \
su::biom table = su::biom(biom_filename); \
if(table.n_samples <= 0 | table.n_obs <= 0) { \
return table_empty; \
} \
std::string bad_id = su::test_table_ids_are_subset_of_tree(table, tree); \
if(bad_id != "") { \
return table_and_tree_do_not_overlap; \
} \
std::unordered_set<std::string> to_keep(table.obs_ids.begin(), \
table.obs_ids.end()); \
su::BPTree tree_sheared = tree.shear(to_keep).collapse();
using namespace su;
using namespace std;
// https://stackoverflow.com/a/19841704/19741
bool is_file_exists(const char *fileName) {
std::ifstream infile(fileName);
return infile.good();
}
void destroy_stripes(vector<double*> &dm_stripes, vector<double*> &dm_stripes_total, unsigned int n_samples,
unsigned int stripe_start, unsigned int stripe_stop) {
unsigned int n_rotations = (n_samples + 1) / 2;
if(stripe_stop == 0) {
for(unsigned int i = 0; i < n_rotations; i++) {
free(dm_stripes[i]);
if(dm_stripes_total[i] != NULL)
free(dm_stripes_total[i]);
}
} else {
// if a stripe_stop is specified, and if we're in the stripe window, do not free
// dm_stripes. this is done as the pointers in dm_stripes are assigned to the partial_mat_t
// and subsequently freed in destroy_partial_mat. but, we do need to free dm_stripes_total
// if appropriate
for(unsigned int i = stripe_start; i < stripe_stop; i++) {
if(dm_stripes_total[i] != NULL)
free(dm_stripes_total[i]);
}
}
}
void initialize_mat(mat_t* &result, biom &table, bool is_upper_triangle) {
result = (mat_t*)malloc(sizeof(mat));
result->n_samples = table.n_samples;
result->cf_size = su::comb_2(table.n_samples);
result->is_upper_triangle = is_upper_triangle;
result->sample_ids = (char**)malloc(sizeof(char*) * result->n_samples);
result->condensed_form = (double*)malloc(sizeof(double) * su::comb_2(table.n_samples));
for(unsigned int i = 0; i < result->n_samples; i++) {
size_t len = table.sample_ids[i].length();
result->sample_ids[i] = (char*)malloc(sizeof(char) * len + 1);
table.sample_ids[i].copy(result->sample_ids[i], len);
result->sample_ids[i][len] = '\0';
}
}
void initialize_results_vec(r_vec* &result, biom& table){
// Stores results for Faith PD
result = (r_vec*)malloc(sizeof(results_vec));
result->n_samples = table.n_samples;
result->values = (double*)malloc(sizeof(double) * result->n_samples);
result->sample_ids = (char**)malloc(sizeof(char*) * result->n_samples);
for(unsigned int i = 0; i < result->n_samples; i++) {
size_t len = table.sample_ids[i].length();
result->sample_ids[i] = (char*)malloc(sizeof(char) * len + 1);
table.sample_ids[i].copy(result->sample_ids[i], len);
result->sample_ids[i][len] = '\0';
result->values[i] = 0;
}
}
void initialize_mat_no_biom(mat_t* &result, char** sample_ids, unsigned int n_samples, bool is_upper_triangle) {
result = (mat_t*)malloc(sizeof(mat));
result->n_samples = n_samples;
result->cf_size = su::comb_2(n_samples);
result->is_upper_triangle = is_upper_triangle;
result->sample_ids = (char**)malloc(sizeof(char*) * result->n_samples);
result->condensed_form = (double*)malloc(sizeof(double) * su::comb_2(n_samples));
for(unsigned int i = 0; i < n_samples; i++) {
result->sample_ids[i] = strdup(sample_ids[i]);
}
}
template<class TReal, class TMat>
void initialize_mat_full_no_biom_T(TMat* &result, const char* const * sample_ids, unsigned int n_samples,
const char *mmap_dir /* if NULL or "", use malloc */) {
result = (TMat*)malloc(sizeof(mat));
result->n_samples = n_samples;
uint64_t n_samples_64 = result->n_samples; // force 64bit to avoit overflow problems
result->sample_ids = (char**)malloc(sizeof(char*) * n_samples_64);
result->flags=0;
if (mmap_dir!=NULL) {
if (mmap_dir[0]==0) mmap_dir = NULL; // easier to have a simple test going on
}
uint64_t msize = sizeof(TReal) * n_samples_64 * n_samples_64;
if (mmap_dir==NULL) {
result->matrix = (TReal*)malloc(msize);
} else {
std::string mmap_template(mmap_dir);
mmap_template+="/su_mmap_XXXXXX";
// note: mkostemp will update mmap_template in place
int fd=mkostemp((char *) mmap_template.c_str(), O_NOATIME );
if (fd<0) {
result->matrix = NULL;
// leave error handling to the caller
} else {
// remove the file name, so it will be destroyed on close
unlink(mmap_template.c_str());
// make it big enough
ftruncate(fd,msize);
// now can be used, just like a malloc-ed buffer
result->matrix = (TReal*)mmap(NULL, msize,PROT_READ|PROT_WRITE, MAP_SHARED|MAP_NORESERVE, fd, 0);
result->flags=(uint32_t(fd) & MMAP_FD_MASK) | MMAP_FLAG;
}
}
for(unsigned int i = 0; i < n_samples; i++) {
result->sample_ids[i] = strdup(sample_ids[i]);
}
}
void initialize_partial_mat(partial_mat_t* &result, biom &table, std::vector<double*> &dm_stripes,
unsigned int stripe_start, unsigned int stripe_stop, bool is_upper_triangle) {
result = (partial_mat_t*)malloc(sizeof(partial_mat));
result->n_samples = table.n_samples;
result->sample_ids = (char**)malloc(sizeof(char*) * result->n_samples);
for(unsigned int i = 0; i < result->n_samples; i++) {
size_t len = table.sample_ids[i].length();
result->sample_ids[i] = (char*)malloc(sizeof(char) * len + 1);
table.sample_ids[i].copy(result->sample_ids[i], len);
result->sample_ids[i][len] = '\0';
}
result->stripes = (double**)malloc(sizeof(double*) * (stripe_stop - stripe_start));
result->stripe_start = stripe_start;
result->stripe_stop = stripe_stop;
result->is_upper_triangle = is_upper_triangle;
result->stripe_total = dm_stripes.size();
for(unsigned int i = stripe_start; i < stripe_stop; i++) {
result->stripes[i - stripe_start] = dm_stripes[i];
}
}
void destroy_results_vec(r_vec** result) {
// for Faith PD
for(unsigned int i = 0; i < (*result)->n_samples; i++) {
free((*result)->sample_ids[i]);
};
free((*result)->sample_ids);
free((*result)->values);
free(*result);
}
void destroy_mat(mat_t** result) {
for(unsigned int i = 0; i < (*result)->n_samples; i++) {
free((*result)->sample_ids[i]);
};
free((*result)->sample_ids);
if (((*result)->condensed_form)!=NULL) {
free((*result)->condensed_form);
}
free(*result);
}
template<class TMat, class TReal>
inline void destroy_mat_full_T(TMat** result) {
for(uint32_t i = 0; i < (*result)->n_samples; i++) {
free((*result)->sample_ids[i]);
};
free((*result)->sample_ids);
if (((*result)->matrix)!=NULL) {
if (((*result)->flags & MMAP_FLAG) == 0) {
free((*result)->matrix);
} else {
uint64_t n_samples = (*result)->n_samples;
munmap((*result)->matrix, sizeof(TReal)*n_samples*n_samples);
int fd = (*result)->flags & MMAP_FD_MASK;
close(fd);
}
(*result)->matrix=NULL;
}
free(*result);
}
void destroy_mat_full_fp64(mat_full_fp64_t** result) {
destroy_mat_full_T<mat_full_fp64_t,double>(result);
}
void destroy_mat_full_fp32(mat_full_fp32_t** result) {
destroy_mat_full_T<mat_full_fp32_t,float>(result);
}
void destroy_partial_mat(partial_mat_t** result) {
for(unsigned int i = 0; i < (*result)->n_samples; i++) {
if((*result)->sample_ids[i] != NULL)
free((*result)->sample_ids[i]);
};
if((*result)->sample_ids != NULL)
free((*result)->sample_ids);
unsigned int n_stripes = (*result)->stripe_stop - (*result)->stripe_start;
for(unsigned int i = 0; i < n_stripes; i++)
if((*result)->stripes[i] != NULL)
free((*result)->stripes[i]);
if((*result)->stripes != NULL)
free((*result)->stripes);
free(*result);
}
void destroy_partial_dyn_mat(partial_dyn_mat_t** result) {
for(unsigned int i = 0; i < (*result)->n_samples; i++) {
if((*result)->sample_ids[i] != NULL)
free((*result)->sample_ids[i]);
};
if((*result)->sample_ids != NULL)
free((*result)->sample_ids);
unsigned int n_stripes = (*result)->stripe_stop - (*result)->stripe_start;
for(unsigned int i = 0; i < n_stripes; i++)
if((*result)->stripes[i] != NULL)
free((*result)->stripes[i]);
if((*result)->stripes != NULL)
free((*result)->stripes);
if((*result)->offsets != NULL)
free((*result)->offsets);
if((*result)->filename != NULL)
free((*result)->filename);
free(*result);
}
void set_tasks(std::vector<su::task_parameters> &tasks,
double alpha,
unsigned int n_samples,
unsigned int stripe_start,
unsigned int stripe_stop,
bool bypass_tips,
unsigned int nthreads) {
// compute from start to the max possible stripe if stop doesn't make sense
if(stripe_stop <= stripe_start)
stripe_stop = (n_samples + 1) / 2;
/* chunking strategy is to balance as much as possible. eg if there are 15 stripes
* and 4 threads, our goal is to assign 4 stripes to 3 threads, and 3 stripes to one thread.
*
* we use the remaining the chunksize for bins which cannot be full maximally
*/
unsigned int fullchunk = ((stripe_stop - stripe_start) + nthreads - 1) / nthreads; // this computes the ceiling
unsigned int smallchunk = (stripe_stop - stripe_start) / nthreads;
unsigned int n_fullbins = (stripe_stop - stripe_start) % nthreads;
if(n_fullbins == 0)
n_fullbins = nthreads;
unsigned int start = stripe_start;
for(unsigned int tid = 0; tid < nthreads; tid++) {
tasks[tid].tid = tid;
tasks[tid].start = start; // stripe start
tasks[tid].bypass_tips = bypass_tips;
if(tid < n_fullbins) {
tasks[tid].stop = start + fullchunk; // stripe end
start = start + fullchunk;
} else {
tasks[tid].stop = start + smallchunk; // stripe end
start = start + smallchunk;
}
tasks[tid].n_samples = n_samples;
tasks[tid].g_unifrac_alpha = alpha;
}
}
compute_status partial(const char* biom_filename, const char* tree_filename,
const char* unifrac_method, bool variance_adjust, double alpha, bool bypass_tips,
unsigned int nthreads, unsigned int stripe_start, unsigned int stripe_stop,
partial_mat_t** result) {
CHECK_FILE(biom_filename, table_missing)
CHECK_FILE(tree_filename, tree_missing)
SET_METHOD(unifrac_method, unknown_method)
PARSE_SYNC_TREE_TABLE(tree_filename, table_filename)
// we resize to the largest number of possible stripes even if only computing
// partial, however we do not allocate arrays for non-computed stripes so
// there is a little memory waste here but should be on the order of
// 8 bytes * N samples per vector.
std::vector<double*> dm_stripes((table.n_samples + 1) / 2);
std::vector<double*> dm_stripes_total((table.n_samples + 1) / 2);
if(nthreads > dm_stripes.size()) {
fprintf(stderr, "More threads were requested than stripes. Using %d threads.\n", dm_stripes.size());
nthreads = dm_stripes.size();
}
std::vector<su::task_parameters> tasks(nthreads);
std::vector<std::thread> threads(nthreads);
if(((table.n_samples + 1) / 2) < stripe_stop) {
fprintf(stderr, "Stopping stripe is out-of-bounds, max %d\n", (table.n_samples + 1) / 2);
exit(EXIT_FAILURE);
}
set_tasks(tasks, alpha, table.n_samples, stripe_start, stripe_stop, bypass_tips, nthreads);
su::process_stripes(table, tree_sheared, method, variance_adjust, dm_stripes, dm_stripes_total, threads, tasks);
initialize_partial_mat(*result, table, dm_stripes, stripe_start, stripe_stop, true); // true -> is_upper_triangle
destroy_stripes(dm_stripes, dm_stripes_total, table.n_samples, stripe_start, stripe_stop);
return okay;
}
compute_status faith_pd_one_off(const char* biom_filename, const char* tree_filename,
r_vec** result){
CHECK_FILE(biom_filename, table_missing)
CHECK_FILE(tree_filename, tree_missing)
PARSE_SYNC_TREE_TABLE(tree_filename, table_filename)
initialize_results_vec(*result, table);
// compute faithpd
su::faith_pd(table, tree_sheared, std::ref((*result)->values));
return okay;
}
compute_status one_off(const char* biom_filename, const char* tree_filename,
const char* unifrac_method, bool variance_adjust, double alpha,
bool bypass_tips, unsigned int nthreads, mat_t** result) {
CHECK_FILE(biom_filename, table_missing)
CHECK_FILE(tree_filename, tree_missing)
SET_METHOD(unifrac_method, unknown_method)
PARSE_SYNC_TREE_TABLE(tree_filename, table_filename)
const unsigned int stripe_stop = (table.n_samples + 1) / 2;
std::vector<double*> dm_stripes(stripe_stop);
std::vector<double*> dm_stripes_total(stripe_stop);
if(nthreads > dm_stripes.size()) {
fprintf(stderr, "More threads were requested than stripes. Using %d threads.\n", dm_stripes.size());
nthreads = dm_stripes.size();
}
std::vector<su::task_parameters> tasks(nthreads);
std::vector<std::thread> threads(nthreads);
set_tasks(tasks, alpha, table.n_samples, 0, stripe_stop, bypass_tips, nthreads);
su::process_stripes(table, tree_sheared, method, variance_adjust, dm_stripes, dm_stripes_total, threads, tasks);
initialize_mat(*result, table, true); // true -> is_upper_triangle
for(unsigned int tid = 0; tid < threads.size(); tid++) {
threads[tid] = std::thread(su::stripes_to_condensed_form,
std::ref(dm_stripes),
table.n_samples,
std::ref((*result)->condensed_form),
tasks[tid].start,
tasks[tid].stop);
}
for(unsigned int tid = 0; tid < threads.size(); tid++) {
threads[tid].join();
}
destroy_stripes(dm_stripes, dm_stripes_total, table.n_samples, 0, 0);
return okay;
}
// TMat mat_full_fp32_t
template<class TReal, class TMat>
compute_status one_off_matrix_T(const char* biom_filename, const char* tree_filename,
const char* unifrac_method, bool variance_adjust, double alpha,
bool bypass_tips, unsigned int nthreads,
const char *mmap_dir,
TMat** result) {
if (mmap_dir!=NULL) {
if (mmap_dir[0]==0) mmap_dir = NULL; // easier to have a simple test going on
}
CHECK_FILE(biom_filename, table_missing)
CHECK_FILE(tree_filename, tree_missing)
SET_METHOD(unifrac_method, unknown_method)
PARSE_SYNC_TREE_TABLE(tree_filename, table_filename)
const unsigned int stripe_stop = (table.n_samples + 1) / 2;
partial_mat_t *partial_mat = NULL;
{
std::vector<double*> dm_stripes(stripe_stop);
std::vector<double*> dm_stripes_total(stripe_stop);
std::vector<su::task_parameters> tasks(nthreads);
std::vector<std::thread> threads(nthreads);
set_tasks(tasks, alpha, table.n_samples, 0, stripe_stop, bypass_tips, nthreads);
su::process_stripes(table, tree_sheared, method, variance_adjust, dm_stripes, dm_stripes_total, threads, tasks);
initialize_partial_mat(partial_mat, table, dm_stripes, 0, stripe_stop, true); // true -> is_upper_triangle
if ((partial_mat==NULL) || (partial_mat->stripes==NULL) || (partial_mat->sample_ids==NULL) ) {
fprintf(stderr, "Memory allocation error! (initialize_partial_mat)\n");
exit(EXIT_FAILURE);
}
destroy_stripes(dm_stripes, dm_stripes_total, table.n_samples, 0, stripe_stop);
}
initialize_mat_full_no_biom_T<TReal,TMat>(*result, partial_mat->sample_ids, partial_mat->n_samples,mmap_dir);
if (((*result)==NULL) || ((*result)->matrix==NULL) || ((*result)->sample_ids==NULL) ) {
fprintf(stderr, "Memory allocation error! (initialize_mat)\n");
exit(EXIT_FAILURE);
}
{
MemoryStripes ps(partial_mat->stripes);
const uint32_t tile_size = (mmap_dir==NULL) ? \
(128/sizeof(TReal)) : /* keep it small for memory access, to fit in chip cache */ \
(4096/sizeof(TReal)); /* make it larger for mmap, as the limiting factor is swapping */
su::stripes_to_matrix_T<TReal>(ps, partial_mat->n_samples, partial_mat->stripe_total, (*result)->matrix, tile_size);
}
destroy_partial_mat(&partial_mat);
return okay;
}
compute_status one_off_matrix(const char* biom_filename, const char* tree_filename,
const char* unifrac_method, bool variance_adjust, double alpha,
bool bypass_tips, unsigned int nthreads,
const char *mmap_dir,
mat_full_fp64_t** result) {
return one_off_matrix_T<double,mat_full_fp64_t>(biom_filename,tree_filename,unifrac_method,variance_adjust,alpha,bypass_tips,nthreads,mmap_dir,result);
}
compute_status one_off_matrix_fp32(const char* biom_filename, const char* tree_filename,
const char* unifrac_method, bool variance_adjust, double alpha,
bool bypass_tips, unsigned int nthreads,
const char *mmap_dir,
mat_full_fp32_t** result) {
return one_off_matrix_T<float,mat_full_fp32_t>(biom_filename,tree_filename,unifrac_method,variance_adjust,alpha,bypass_tips,nthreads,mmap_dir,result);
}
inline compute_status is_fp64(const std::string &method_string, const std::string &format_string, bool &fp64) {
if (format_string == "hdf5_fp32") {
fp64 = false;
} else if (format_string == "hdf5_fp64") {
fp64 = true;
} else if (format_string == "hdf5") {
if ((method_string=="unweighted_fp32") || (method_string=="weighted_normalized_fp32") || (method_string=="weighted_unnormalized_fp32") || (method_string=="generalized_fp32")) {
fp64 = false;
} else if ((method_string=="unweighted") || (method_string=="weighted_normalized") || (method_string=="weighted_unnormalized") || (method_string=="generalized")) {
fp64 = true;
} else {
return unknown_method;
}
} else {
return unknown_method;
}
return okay;
}
compute_status unifrac_to_file(const char* biom_filename, const char* tree_filename, const char* out_filename,
const char* unifrac_method, bool variance_adjust, double alpha,
bool bypass_tips, unsigned int threads, const char* format,
unsigned int pcoa_dims, const char *mmap_dir)
{
bool fp64;
compute_status rc = is_fp64(unifrac_method, format, fp64);
if (rc==okay) {
if (fp64) {
mat_full_fp64_t* result;
rc = one_off_matrix(biom_filename, tree_filename,
unifrac_method, variance_adjust, alpha,
bypass_tips, threads, mmap_dir,
&result);
if (rc==okay) {
// we have no alternative to hdf5 right now
IOStatus iostatus = write_mat_from_matrix_hdf5(out_filename, result, pcoa_dims);
destroy_mat_full_fp64(&result);
if (iostatus!=write_okay) rc=output_error;
}
} else {
mat_full_fp32_t* result;
rc = one_off_matrix_fp32(biom_filename, tree_filename,
unifrac_method, variance_adjust, alpha,
bypass_tips, threads, mmap_dir,
&result);
if (rc==okay) {
// we have no alternative to hdf5 right now
IOStatus iostatus = write_mat_from_matrix_hdf5_fp32(out_filename, result, pcoa_dims);
destroy_mat_full_fp32(&result);
if (iostatus!=write_okay) rc=output_error;
}
}
}
return rc;
}
IOStatus write_mat(const char* output_filename, mat_t* result) {
std::ofstream output;
output.open(output_filename);
uint64_t comb_N = su::comb_2(result->n_samples);
uint64_t comb_N_minus = 0;
double v;
for(unsigned int i = 0; i < result->n_samples; i++)
output << "\t" << result->sample_ids[i];
output << std::endl;
for(unsigned int i = 0; i < result->n_samples; i++) {
output << result->sample_ids[i];
for(unsigned int j = 0; j < result->n_samples; j++) {
if(i < j) { // upper triangle
comb_N_minus = su::comb_2(result->n_samples - i);
v = result->condensed_form[comb_N - comb_N_minus + (j - i - 1)];
} else if (i > j) { // lower triangle
comb_N_minus = su::comb_2(result->n_samples - j);
v = result->condensed_form[comb_N - comb_N_minus + (i - j - 1)];
} else {
v = 0.0;
}
output << std::setprecision(16) << "\t" << v;
}
output << std::endl;
}
output.close();
return write_okay;
}
IOStatus write_mat_from_matrix(const char* output_filename, mat_full_fp64_t* result) {
const double *buf2d = result->matrix;
std::ofstream output;
output.open(output_filename);
double v;
const uint64_t n_samples_64 = result->n_samples; // 64-bit to avoid overflow
for(unsigned int i = 0; i < result->n_samples; i++)
output << "\t" << result->sample_ids[i];
output << std::endl;
for(unsigned int i = 0; i < result->n_samples; i++) {
output << result->sample_ids[i];
for(unsigned int j = 0; j < result->n_samples; j++) {
v = buf2d[i*n_samples_64+j];
output << std::setprecision(16) << "\t" << v;
}
output << std::endl;
}
output.close();
return write_okay;
}
herr_t write_hdf5_string(hid_t output_file_id,const char *dname, const char *str)
{
// this is the convoluted way to store a string
// Will use the FORTRAN forma, so we do not depend on null termination
hid_t filetype_id = H5Tcopy (H5T_FORTRAN_S1);
H5Tset_size(filetype_id, strlen(str));
hid_t memtype_id = H5Tcopy (H5T_C_S1);
H5Tset_size(memtype_id, strlen(str)+1);
hsize_t dims[1] = {1};
hid_t dataspace_id = H5Screate_simple (1, dims, NULL);
hid_t dataset_id = H5Dcreate(output_file_id,dname, filetype_id, dataspace_id, H5P_DEFAULT, H5P_DEFAULT,
H5P_DEFAULT);
herr_t status = H5Dwrite(dataset_id, memtype_id, H5S_ALL, H5S_ALL, H5P_DEFAULT, str);
H5Dclose(dataset_id);
H5Sclose(dataspace_id);
H5Tclose(memtype_id);
H5Tclose(filetype_id);
return status;
}
// Internal: Make sure TReal and real_id match
template<class TReal, class TMat>
IOStatus write_mat_from_matrix_hdf5_T(const char* output_filename, TMat * result, hid_t real_id, unsigned int pcoa_dims) {
/* Create a new file using default properties. */
hid_t output_file_id = H5Fcreate(output_filename, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
if (output_file_id<0) return write_error;
// simple header
if (write_hdf5_string(output_file_id,"format","BDSM")<0) {
H5Fclose (output_file_id);
return write_error;
}
if (write_hdf5_string(output_file_id,"version","2020.12")<0) {
H5Fclose (output_file_id);
return write_error;
}
// save the ids
{
hsize_t dims[1];
dims[0] = result->n_samples;
hid_t dataspace_id = H5Screate_simple(1, dims, NULL);
// this is the convoluted way to store an array of strings
hid_t datatype_id = H5Tcopy(H5T_C_S1);
H5Tset_size(datatype_id,H5T_VARIABLE);
hid_t dcpl_id = H5Pcreate (H5P_DATASET_CREATE);
hid_t dataset_id = H5Dcreate1(output_file_id, "order", datatype_id, dataspace_id, dcpl_id);
herr_t status = H5Dwrite(dataset_id, datatype_id, H5S_ALL, H5S_ALL,
H5P_DEFAULT, result->sample_ids);
H5Dclose(dataset_id);
H5Tclose(datatype_id);
H5Sclose(dataspace_id);
H5Pclose(dcpl_id);
// check status after cleanup, for simplicity
if (status<0) {
H5Fclose (output_file_id);
return write_error;
}
}
// save the matrix
{
hsize_t dims[2];
dims[0] = result->n_samples;
dims[1] = result->n_samples;
hid_t dataspace_id = H5Screate_simple(2, dims, NULL);
hid_t dcpl_id = H5Pcreate (H5P_DATASET_CREATE);
hid_t dataset_id = H5Dcreate2(output_file_id, "matrix",real_id, dataspace_id,
H5P_DEFAULT, dcpl_id, H5P_DEFAULT);
herr_t status = H5Dwrite(dataset_id, real_id, H5S_ALL, H5S_ALL, H5P_DEFAULT,
result->matrix);
H5Pclose(dcpl_id);
H5Dclose(dataset_id);
H5Sclose(dataspace_id);
// check status after cleanup, for simplicity
if (status<0) {
H5Fclose (output_file_id);
return write_error;
}
}
if (pcoa_dims>0) {
// compute pcoa and save it in the file
// use inplace variant to keep memory use in check; we don't need matrix anymore
TReal * eigenvalues;
TReal * samples;
TReal * proportion_explained;
su::pcoa_inplace(result->matrix, result->n_samples, pcoa_dims, eigenvalues, samples, proportion_explained);
if (write_hdf5_string(output_file_id,"pcoa_method","FSVD")<0) {
H5Fclose (output_file_id);
return write_error;
}
// save the eigenvalues
{
hsize_t dims[1];
dims[0] = pcoa_dims;
hid_t dataspace_id = H5Screate_simple(1, dims, NULL);
hid_t dcpl_id = H5Pcreate (H5P_DATASET_CREATE);
hid_t dataset_id = H5Dcreate2(output_file_id, "pcoa_eigvals",real_id, dataspace_id,
H5P_DEFAULT, dcpl_id, H5P_DEFAULT);
herr_t status = H5Dwrite(dataset_id, real_id, H5S_ALL, H5S_ALL, H5P_DEFAULT,
eigenvalues);
H5Pclose(dcpl_id);
H5Dclose(dataset_id);
H5Sclose(dataspace_id);
// check status after cleanup, for simplicity
if (status<0) {
H5Fclose (output_file_id);
free(samples);
free(proportion_explained);
free(eigenvalues);
return write_error;
}
}
// save the proportion_explained
{
hsize_t dims[1];
dims[0] = pcoa_dims;
hid_t dataspace_id = H5Screate_simple(1, dims, NULL);
hid_t dcpl_id = H5Pcreate (H5P_DATASET_CREATE);
hid_t dataset_id = H5Dcreate2(output_file_id, "pcoa_proportion_explained",real_id, dataspace_id,
H5P_DEFAULT, dcpl_id, H5P_DEFAULT);
herr_t status = H5Dwrite(dataset_id, real_id, H5S_ALL, H5S_ALL, H5P_DEFAULT,
proportion_explained);
H5Pclose(dcpl_id);
H5Dclose(dataset_id);
H5Sclose(dataspace_id);
// check status after cleanup, for simplicity
if (status<0) {
H5Fclose (output_file_id);
free(samples);
free(proportion_explained);
free(eigenvalues);
return write_error;
}
}
// save the samples
{
hsize_t dims[2];
dims[0] = result->n_samples;
dims[1] = pcoa_dims;
hid_t dataspace_id = H5Screate_simple(2, dims, NULL);
hid_t dcpl_id = H5Pcreate (H5P_DATASET_CREATE);
hid_t dataset_id = H5Dcreate2(output_file_id, "pcoa_samples",real_id, dataspace_id,
H5P_DEFAULT, dcpl_id, H5P_DEFAULT);
herr_t status = H5Dwrite(dataset_id, real_id, H5S_ALL, H5S_ALL, H5P_DEFAULT,
samples);
H5Pclose(dcpl_id);
H5Dclose(dataset_id);
H5Sclose(dataspace_id);
// check status after cleanup, for simplicity
if (status<0) {
H5Fclose (output_file_id);
free(samples);
free(proportion_explained);
free(eigenvalues);
return write_error;
}
}
free(samples);
free(proportion_explained);
free(eigenvalues);
}
H5Fclose (output_file_id);
return write_okay;
}
// Internal: Make sure TReal and real_id match
template<class TReal, class TMat>
IOStatus write_mat_hdf5_T(const char* output_filename, mat_t* result,hid_t real_id, unsigned int pcoa_dims) {
// compute the matrix
TMat mat_full;
mat_full.n_samples = result->n_samples;
const uint64_t n_samples = result->n_samples;
mat_full.flags = 0;
mat_full.matrix = (TReal*) malloc(n_samples*n_samples*sizeof(TReal));
if (mat_full.matrix==NULL) {
return open_error; // we don't have a better error code
}
mat_full.sample_ids = result->sample_ids; // just link
condensed_form_to_matrix_T(result->condensed_form, n_samples, mat_full.matrix);
IOStatus err = write_mat_from_matrix_hdf5_T<TReal,TMat>(output_filename, &mat_full, real_id, pcoa_dims);
free(mat_full.matrix);
return err;
}
IOStatus write_mat_hdf5(const char* output_filename, mat_t* result, unsigned int pcoa_dims) {
return write_mat_hdf5_T<double,mat_full_fp64_t>(output_filename,result,H5T_IEEE_F64LE,pcoa_dims);
}
IOStatus write_mat_hdf5_fp32(const char* output_filename, mat_t* result, unsigned int pcoa_dims) {
return write_mat_hdf5_T<float,mat_full_fp32_t>(output_filename,result,H5T_IEEE_F32LE,pcoa_dims);
}
IOStatus write_mat_from_matrix_hdf5(const char* output_filename, mat_full_fp64_t* result, unsigned int pcoa_dims) {
return write_mat_from_matrix_hdf5_T<double,mat_full_fp64_t>(output_filename,result,H5T_IEEE_F64LE,pcoa_dims);
}
IOStatus write_mat_from_matrix_hdf5_fp32(const char* output_filename, mat_full_fp32_t* result, unsigned int pcoa_dims) {
return write_mat_from_matrix_hdf5_T<float,mat_full_fp32_t>(output_filename,result,H5T_IEEE_F32LE,pcoa_dims);
}
IOStatus write_vec(const char* output_filename, r_vec* result) {
std::ofstream output;
output.open(output_filename);
// write sample ids in first column of file and faith's pd in second column
output << "#SampleID\tfaith_pd" << std::endl;
for(unsigned int i = 0; i < result->n_samples; i++) {
output << result->sample_ids[i];
output << std::setprecision(16) << "\t" << result->values[i];
output << std::endl;
}
output.close();
return write_okay;
}
IOStatus write_partial(const char* output_filename, const partial_mat_t* result) {
int fd = open(output_filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR );
if (fd==-1) return write_error;
int cnt = -1;
uint32_t n_stripes = result->stripe_stop - result->stripe_start;
uint32_t sample_id_length = 0;
for(unsigned int i = 0; i < result->n_samples; i++) {
sample_id_length += strlen(result->sample_ids[i])+1;
}
{
char * const samples_buf = (char *)malloc(sample_id_length);
char *samples_ptr = samples_buf;
/* sample IDs */
for(unsigned int i = 0; i < result->n_samples; i++) {
uint32_t length = strlen(result->sample_ids[i])+1;
memcpy(samples_ptr,result->sample_ids[i],length);
samples_ptr+= length;
}
int max_compressed = LZ4_compressBound(sample_id_length);
char * const cmp_buf = (char *)malloc(max_compressed);
int sample_id_length_compressed = LZ4_compress_default(samples_buf,cmp_buf,sample_id_length,max_compressed);
if (sample_id_length_compressed<1) {close(fd); return open_error;}
uint32_t header[8];
header[0] = PARTIAL_MAGIC_V2;
header[1] = result->n_samples;
header[2] = n_stripes;
header[3] = result->stripe_start;
header[4] = result->stripe_total;
header[5] = result->is_upper_triangle;
header[6] = sample_id_length;
header[7] = sample_id_length_compressed;
cnt=write(fd,header, 8 * sizeof(uint32_t));
if (cnt<1) {close(fd); return write_error;}
cnt=write(fd,cmp_buf, sample_id_length_compressed);
if (cnt<1) {close(fd); return write_error;}
free(cmp_buf);
free(samples_buf);
}
{
int max_compressed = LZ4_compressBound(sizeof(double) * result->n_samples);
char * const cmp_buf_raw = (char *)malloc(max_compressed+sizeof(uint32_t));
char * const cmp_buf = cmp_buf_raw + sizeof(uint32_t);
/* stripe information */
for(unsigned int i = 0; i < n_stripes; i++) {
int cmp_size = LZ4_compress_default((const char *) result->stripes[i],cmp_buf,sizeof(double) * result->n_samples,max_compressed);
if (cmp_size<1) {close(fd); return open_error;}
uint32_t *cmp_buf_size_p = (uint32_t *)cmp_buf_raw;
*cmp_buf_size_p = cmp_size;
cnt=write(fd, cmp_buf_raw, cmp_size+sizeof(uint32_t));
if (cnt<1) {return write_error;}
}
free(cmp_buf_raw);
}
/* footer */
{
uint32_t header[1];
header[0] = PARTIAL_MAGIC_V2;
cnt=write(fd,header, 1 * sizeof(uint32_t));
if (cnt<1) {close(fd); return open_error;}
}
close(fd);
return write_okay;
}
IOStatus _is_partial_file(const char* input_filename) {
int fd = open(input_filename, O_RDONLY );
if (fd==-1) return open_error;
uint32_t header[1];
int cnt = read(fd,header,sizeof(uint32_t));
close(fd);
if (cnt!=sizeof(uint32_t)) return magic_incompatible;
if ( header[0] != PARTIAL_MAGIC_V2) return magic_incompatible;
return read_okay;