-
Notifications
You must be signed in to change notification settings - Fork 4
/
transcode.cpp
2313 lines (2117 loc) · 101 KB
/
transcode.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
/*
Pheniqs : PHilology ENcoder wIth Quality Statistics
Copyright (C) 2018 Lior Galanti
NYU Center for Genetics and System Biology
Author: Lior Galanti <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
filter_incoming_qc_fail: should we process incoming qc_fail reads?
filter_outgoing_qc_fail: should we write qc_fail reads?
inherit_qc_fail: should outgoing reads inherit qc_fail flag from incoming?
*/
#include "transcode.h"
/* TranscodingDecoder */
TranscodingDecoder::TranscodingDecoder(const Value& ontology) try :
count(0),
pf_count(0),
pf_fraction(0),
sample_classifier(NULL) {
load_sample_decoding(ontology);
load_molecular_decoding(ontology);
load_cellular_decoding(ontology);
} catch(Error& error) {
error.push("TranscodingDecoder");
throw;
};
TranscodingDecoder::~TranscodingDecoder() {
if(sample_classifier != NULL) {
delete sample_classifier;
}
if(!molecular_classifier_array.empty()) {
for(auto& classifier : molecular_classifier_array) {
delete classifier;
}
}
if(!cellular_classifier_array.empty()) {
for(auto& classifier : cellular_classifier_array) {
delete classifier;
}
}
};
void TranscodingDecoder::load_sample_decoding(const Value& ontology) {
Value::ConstMemberIterator reference = ontology.FindMember("sample");
if(reference != ontology.MemberEnd()) {
load_sample_decoder(reference->value);
}
};
void TranscodingDecoder::load_sample_decoder(const Value& value) {
Algorithm algorithm(decode_value_by_key< Algorithm >("algorithm", value));
switch(algorithm) {
case Algorithm::PAMLD: {
sample_classifier = new PamlSampleDecoder(value);
break;
};
case Algorithm::MDD: {
sample_classifier = new MdSampleDecoder(value);
break;
};
case Algorithm::PASSTHROUGH: {
sample_classifier = new Classifier< Barcode >(value);
break;
};
default:
throw ConfigurationError("unsupported sample decoder algorithm " + to_string(algorithm));
break;
}
};
void TranscodingDecoder::load_molecular_decoding(const Value& ontology) {
Value::ConstMemberIterator reference = ontology.FindMember("molecular");
if(reference != ontology.MemberEnd()) {
if(reference->value.IsObject()) {
molecular_classifier_array.reserve(1);
load_molecular_decoder(reference->value);
} else if(reference->value.IsArray()) {
molecular_classifier_array.reserve(reference->value.Size());
for(const auto& element : reference->value.GetArray()) {
load_molecular_decoder(element);
}
}
}
molecular_classifier_array.shrink_to_fit();
};
void TranscodingDecoder::load_molecular_decoder(const Value& value) {
Algorithm algorithm(decode_value_by_key< Algorithm >("algorithm", value));
switch(algorithm) {
case Algorithm::PAMLD: {
molecular_classifier_array.emplace_back(new PamlMolecularDecoder(value));
break;
};
case Algorithm::MDD: {
molecular_classifier_array.emplace_back(new MdMolecularDecoder(value));
break;
};
case Algorithm::PASSTHROUGH: {
molecular_classifier_array.emplace_back(new Classifier< Barcode >(value));
break;
};
case Algorithm::NAIVE: {
molecular_classifier_array.emplace_back(new NaiveMolecularDecoder(value));
break;
};
default:
throw ConfigurationError("unsupported molecular decoder algorithm " + to_string(algorithm));
break;
}
};
void TranscodingDecoder::load_cellular_decoding(const Value& ontology) {
Value::ConstMemberIterator reference = ontology.FindMember("cellular");
if(reference != ontology.MemberEnd()) {
if(reference->value.IsObject()) {
cellular_classifier_array.reserve(1);
load_cellular_decoder(reference->value);
} else if(reference->value.IsArray()) {
cellular_classifier_array.reserve(reference->value.Size());
for(const auto& element : reference->value.GetArray()) {
load_cellular_decoder(element);
}
}
}
cellular_classifier_array.shrink_to_fit();
};
void TranscodingDecoder::load_cellular_decoder(const Value& value) {
Algorithm algorithm(decode_value_by_key< Algorithm >("algorithm", value));
switch(algorithm) {
case Algorithm::PAMLD: {
cellular_classifier_array.emplace_back(new PamlCellularDecoder(value));
break;
};
case Algorithm::MDD: {
cellular_classifier_array.emplace_back(new MdCellularDecoder(value));
break;
};
case Algorithm::PASSTHROUGH: {
cellular_classifier_array.emplace_back(new Classifier< Barcode >(value));
break;
};
default:
throw ConfigurationError("unsupported cellular decoder algorithm " + to_string(algorithm));
break;
}
};
void TranscodingDecoder::collect(const TranscodingDecoder& other) {
count += other.count;
pf_count += other.pf_count;
if(sample_classifier != NULL) {
sample_classifier->collect(*other.sample_classifier);
}
if(!molecular_classifier_array.empty()) {
for(size_t index(0); index < molecular_classifier_array.size(); ++index) {
molecular_classifier_array[index]->collect(*other.molecular_classifier_array[index]);
}
}
if(!cellular_classifier_array.empty()) {
for(size_t index(0); index < cellular_classifier_array.size(); ++index) {
cellular_classifier_array[index]->collect(*other.cellular_classifier_array[index]);
}
}
};
void TranscodingDecoder::finalize() {
pf_fraction = double(pf_count) / double(count);
if(sample_classifier != NULL) {
sample_classifier->finalize();
}
if(!molecular_classifier_array.empty()) {
for(auto& classifier : molecular_classifier_array) {
classifier->finalize();
}
}
if(!cellular_classifier_array.empty()) {
for(auto& classifier : cellular_classifier_array) {
classifier->finalize();
}
}
};
void TranscodingDecoder::encode(Value& container, Document& document) const {
/* add the outgoing statistics to report */
if(count > 0) {
Value element(kObjectType);
encode_key_value("count", count, element, document);
encode_key_value("pf count", pf_count, element, document);
encode_key_value("pf fraction", pf_fraction, element, document);
container.AddMember("outgoing", element.Move(), document.GetAllocator());
}
if(sample_classifier != NULL) {
Value element(kObjectType);
sample_classifier->encode(element, document);
container.AddMember("sample", element.Move(), document.GetAllocator());
}
if(!molecular_classifier_array.empty()) {
Value array(kArrayType);
for(auto& classifier : molecular_classifier_array) {
Value element(kObjectType);
classifier->encode(element, document);
array.PushBack(element.Move(), document.GetAllocator());
}
container.AddMember("molecular", array.Move(), document.GetAllocator());
}
if(!cellular_classifier_array.empty()) {
Value array(kArrayType);
for(auto& classifier : cellular_classifier_array) {
Value element(kObjectType);
classifier->encode(element, document);
array.PushBack(element.Move(), document.GetAllocator());
}
container.AddMember("cellular", array.Move(), document.GetAllocator());
}
};
/* Transcode */
static int32_t compute_inheritence_depth(const string& key, const unordered_map< string, Value* >& object_by_key, Document& document) {
int32_t depth(0);
auto record = object_by_key.find(key);
if(record != object_by_key.end()) {
Value* value = record->second;
if(!decode_value_by_key("depth", depth, *value)) {
string base_key;
if(decode_value_by_key("base", base_key, *value)) {
if(base_key != key) {
depth = compute_inheritence_depth(base_key, object_by_key, document) + 1;
encode_key_value("depth", depth, *value, document);
} else { throw ConfigurationError(key + " references itself as parent"); }
} else {
encode_key_value("depth", depth, *value, document);
}
}
} else { throw ConfigurationError("referencing an unknown parent " + key); }
return depth;
};
Transcode::Transcode(Document& operation) try :
Job(operation),
count(0),
pf_count(0),
pf_fraction(0),
end_of_input(false),
decoded_nucleotide_cardinality(0),
thread_pool({NULL, 0}),
multiplexer(NULL),
transcoding_decoder(NULL) {
} catch(Error& error) {
error.push("Transcode");
throw;
};
Transcode::~Transcode() {
if(thread_pool.pool != NULL) {
hts_tpool_destroy(thread_pool.pool);
}
for(auto feed : input_feed_by_index) {
delete feed;
}
for(auto feed : output_feed_by_index) {
delete feed;
}
input_feed_by_segment.clear();
input_feed_by_index.clear();
output_feed_by_index.clear();
delete multiplexer;
delete transcoding_decoder;
};
bool Transcode::pull(Read& read) {
vector< unique_lock< mutex > > feed_locks;
feed_locks.reserve(input_feed_by_index.size());
/* acquire a pull lock for all input feeds in a fixed order */
for(const auto feed : input_feed_by_index) {
feed_locks.push_back(feed->acquire_pull_lock());
}
/* pull into input read from input feeds */
for(size_t i(0); i < read.segment_cardinality(); ++i) {
if(!input_feed_by_segment[i]->pull(read[i])) {
end_of_input = true;
}
}
/* update input counters */
if(!end_of_input) {
++count;
if(!read.qcfail()) {
++pf_count;
}
}
/* release the locks on the input feeds in reverse order */
for(auto feed_lock(feed_locks.rbegin()); feed_lock != feed_locks.rend(); ++feed_lock) {
feed_lock->unlock();
}
return !end_of_input;
};
void Transcode::collect(const TranscodingThread& transcoding_thread) {
transcoding_decoder->collect(transcoding_thread.transcoding_decoder);
multiplexer->collect(transcoding_thread.multiplexer);
};
/* assemble */
void Transcode::assemble() {
Job::assemble();
apply_inheritance();
clean_json_object(instruction, instruction);
};
void Transcode::apply_inheritance() {
/* apply inheritence between decoders defined in the repository */
apply_repository_inheritence("decoder", instruction, instruction);
/* Apply inheritence in the indivitual classification categories */
apply_topic_inheritance("sample");
apply_topic_inheritance("molecular");
apply_topic_inheritance("cellular");
if(instruction.HasMember("transform")) {
if(!instruction.HasMember("template")) {
instruction.AddMember("template", Value(kObjectType).Move(), instruction.GetAllocator());
}
if(!instruction["template"].HasMember("transform")) {
instruction["template"].AddMember("transform", Value(kObjectType).Move(), instruction.GetAllocator());
}
merge_json_value(instruction["transform"], instruction["template"]["transform"], instruction);
}
/* Remove the decoder repository, it is no longer needed in the compiled instruction */
instruction.RemoveMember("decoder");
sort_json_value(instruction, instruction);
};
void Transcode::apply_repository_inheritence(const Value::Ch* key, Value& container, Document& document) {
if(container.IsObject()) {
Value::MemberIterator reference = container.FindMember(key);
if(reference != container.MemberEnd()) {
if(reference->value.IsObject()) {
/* map each object by key */
unordered_map< string, Value* > object_by_key;
for(auto& record : reference->value.GetObject()) {
if(!record.value.IsNull()) {
record.value.RemoveMember("depth");
object_by_key.emplace(make_pair(string(record.name.GetString(), record.name.GetStringLength()), &record.value));
}
}
/* compute the inheritence depth of each object and keep track of the max depth */
int32_t max_depth(0);
for(auto& record : object_by_key) {
try {
max_depth = max(max_depth, compute_inheritence_depth(record.first, object_by_key, document));
} catch(ConfigurationError& error) {
throw CommandLineError(record.first + " is " + error.message);
}
}
/* apply object inheritence down the tree */
int32_t depth(0);
for(int32_t i(1); i <= max_depth; ++i) {
for(auto& record : object_by_key) {
Value* value = record.second;
if(decode_value_by_key("depth", depth, *value) && depth == i) {
string base;
if(decode_value_by_key< string >("base", base, *value)) {
merge_json_value(*object_by_key[base], *value, document);
value->RemoveMember("base");
}
}
}
}
for(auto& record : object_by_key) {
record.second->RemoveMember("depth");
}
}
}
}
};
void Transcode::apply_topic_inheritance(const Value::Ch* key) {
if(instruction.IsObject()) {
Value::MemberIterator reference = instruction.FindMember(key);
if(reference != instruction.MemberEnd()) {
if(!reference->value.IsNull()) {
if(reference->value.IsObject()) {
try {
apply_decoder_inheritance(reference->value);
} catch(ConfigurationError& error) {
error.message.insert(0, string(key) + " decoder : ");
throw error;
}
} else if(reference->value.IsArray()) {
int32_t index(0);
try {
for(auto& element : reference->value.GetArray()) {
apply_decoder_inheritance(element);
++index;
}
} catch(ConfigurationError& error) {
error.message.insert(0, string(key) + " decoder at " + to_string(index) + " : ");
throw error;
}
}
}
}
}
};
void Transcode::apply_decoder_inheritance(Value& value) {
if(value.IsObject()) {
string base;
Value::ConstMemberIterator reference;
const Pointer decoder_repository_query("/decoder");
if(decode_value_by_key< string >("base", base, value)) {
const Value* decoder_repository(decoder_repository_query.Get(instruction));
if(decoder_repository != NULL) {
reference = decoder_repository->FindMember(base.c_str());
if(reference != decoder_repository->MemberEnd()) {
merge_json_value(reference->value, value, instruction);
} else { throw ConfigurationError("reference to an unknown base " + base); }
}
}
value.RemoveMember("base");
clean_json_value(value, instruction);
}
};
/* compile */
void Transcode::compile() {
ontology.CopyFrom(instruction, ontology.GetAllocator());
remove_disabled_from_json_value(ontology, ontology);
clean_json_object(ontology, ontology);
/* clear computed parameters */
ontology.RemoveMember("feed");
ontology.RemoveMember("input segment cardinality");
ontology.RemoveMember("output segment cardinality");
ontology.RemoveMember("program");
/* overlay on top of the default configuration */
apply_default_ontology(ontology);
/* overlay interactive parameters on top of the configuration */
apply_interactive_ontology(ontology);
/* compile a PG SAM header ontology with details about pheniqs */
compile_PG();
ontology.AddMember("feed", Value(kObjectType).Move(), ontology.GetAllocator());
compile_input();
compile_barcode_decoding();
compile_multiplexing_decoder();
compile_output();
compile_thread_model();
clean_json_object(ontology, ontology);
validate();
};
void Transcode::compile_PG() {
Value PG(kObjectType);
string buffer;
if(decode_value_by_key< string >("application name", buffer, ontology)) {
encode_key_value("ID", buffer, PG, ontology);
}
if(decode_value_by_key< string >("application name", buffer, ontology)) {
encode_key_value("PN", buffer, PG, ontology);
}
if(decode_value_by_key< string >("full command", buffer, ontology)) {
encode_key_value("CL", buffer, PG, ontology);
}
if(decode_value_by_key< string >("previous application", buffer, ontology)) {
encode_key_value("PP", buffer, PG, ontology);
}
if(decode_value_by_key< string >("application description", buffer, ontology)) {
encode_key_value("DS", buffer, PG, ontology);
}
if(decode_value_by_key< string >("application version", buffer, ontology)) {
encode_key_value("VN", buffer, PG, ontology);
}
ontology.AddMember(Value("program", ontology.GetAllocator()).Move(), PG.Move(), ontology.GetAllocator());
};
void Transcode::compile_input() {
int32_t total_threads(decode_value_by_key< int32_t >("threads", ontology));
int32_t htslib_threads;
if(!decode_value_by_key("htslib threads", htslib_threads, ontology)) {
htslib_threads = max(1, total_threads);
encode_key_value("htslib threads", htslib_threads, ontology, ontology);
}
/* Populate the input_feed_by_index and input_feed_by_segment arrays */
standardize_url_value_by_key("base input url", ontology, ontology, IoDirection::IN);
URL base(decode_value_by_key< URL >("base input url", ontology));
standardize_url_array_by_key("input", ontology, ontology, IoDirection::IN);
relocate_url_array_by_key("input", ontology, ontology, base);
/* Collect query parameters from all reoccurring references to the same path */
unordered_map< string, URL > url_by_path;
list< URL > feed_url_by_index(decode_value_by_key< list< URL > >("input", ontology));
for(auto& url : feed_url_by_index) {
auto record = url_by_path.find(url.path());
if(record == url_by_path.end()) {
url_by_path[url.path()] = url;
} else {
record->second.override_query(url);
}
}
for(auto& url : feed_url_by_index) {
url = url_by_path[url.path()];
}
encode_key_value("input", feed_url_by_index, ontology, ontology);
if(is_sense_input_layout()) {
compile_sensed_input();
} else {
compile_explicit_input();
}
/* validate leading_segment_index */
int32_t input_segment_cardinality(decode_value_by_key< int32_t >("input segment cardinality", ontology));
int32_t leading_segment_index(decode_value_by_key< int32_t >("leading segment index", ontology));
if(leading_segment_index >= input_segment_cardinality) {
throw ConfigurationError("leading segment index " + to_string(leading_segment_index) + " references non existing input segment");
}
vector< int32_t > min_input_length(input_segment_cardinality,0);
if(decode_value_by_key< vector< int32_t > >("min input length", min_input_length, ontology)) {
if(static_cast< int32_t >(min_input_length.size()) != input_segment_cardinality) {
throw ConfigurationError (
"min input length has " +
to_string(min_input_length.size()) +
" elements. must have " +
to_string(input_segment_cardinality) +
" elements, same as the number of input segments. Use a value of 0 to skip filtering a segment by length.");
}
} else {
encode_key_value("min input length", min_input_length, ontology, ontology);
}
};
void Transcode::compile_sensed_input() {
int32_t feed_index(0);
int32_t input_segment_cardinality(0);
int32_t buffer_capacity(decode_value_by_key< int32_t >("buffer capacity", ontology));
uint8_t input_phred_offset(decode_value_by_key< uint8_t >("input phred offset", ontology));
list< URL > explicit_url_array(decode_value_by_key< list< URL > >("input", ontology));
Platform platform(decode_value_by_key< Platform >("platform", ontology));
/* create a proxy for each unique feed
feed_proxy_by_index is ordered by the first appearance of the url */
list< FeedProxy > feed_proxy_by_index;
unordered_map< URL, FeedProxy* > feed_proxy_by_url;
for(const auto& url : explicit_url_array) {
if(feed_proxy_by_url.count(url) == 0) {
Value element(kObjectType);
encode_key_value("index", feed_index, element, ontology);
encode_key_value("url", url, element, ontology);
encode_key_value("direction", IoDirection::IN, element, ontology);
encode_key_value("platform", platform, element, ontology);
encode_key_value("capacity", buffer_capacity, element, ontology);
encode_key_value("resolution", 1, element, ontology);
encode_key_value("phred offset", input_phred_offset, element, ontology);
feed_proxy_by_index.emplace_back(element);
feed_proxy_by_url.emplace(make_pair(url, &feed_proxy_by_index.back()));
++feed_index;
}
}
load_thread_pool();
/* Detect the resolution of every feed
Count the number or consecutive reads with identical read id
The resolution is the number of segments of each read interleaved into the file
the read id of all interleaved blocks from all input feeds must match.
The sum of all uniqe input feed resolutions is the input segment cardinality */
unordered_map< URL, Feed* > feed_by_url;
unordered_map< URL, string > read_id_by_url;
for(auto& proxy : feed_proxy_by_index) {
Feed* feed(NULL);
int32_t resolution(0);
proxy.open();
Segment segment;
string feed_read_id;
switch(proxy.kind()) {
case FormatKind::FASTQ: {
FastqFeed* fastq_feed = new FastqFeed(proxy);
fastq_feed->set_thread_pool(&thread_pool);
fastq_feed->initiate();
fastq_feed->replenish();
if(fastq_feed->peek(segment, resolution)) {
++resolution;
feed_read_id.assign(segment.name.s, segment.name.l);
while (
fastq_feed->peek(segment, resolution) &&
feed_read_id.size() == segment.name.l &&
strncmp(feed_read_id.c_str(), segment.name.s, segment.name.l)
) { ++resolution; }
}
fastq_feed->calibrate_resolution(resolution);
feed = fastq_feed;
break;
};
case FormatKind::HTS: {
HtsFeed* hts_feed = new HtsFeed(proxy);
hts_feed->set_thread_pool(&thread_pool);
hts_feed->initiate();
hts_feed->replenish();
if(hts_feed->peek(segment, resolution)) {
feed_read_id.assign(segment.name.s, segment.name.l);
resolution = segment.total_segments();
}
hts_feed->calibrate_resolution(resolution);
/*
const HtsHead& head = ((HtsFeed*)feed)->get_header();
for(const auto& record : head.RG_by_id) {}
*/
feed = hts_feed;
break;
};
case FormatKind::DEV_NULL: {
throw ConfigurationError("/dev/null can not be used for input");
break;
};
default: {
throw ConfigurationError("unknown input format " + string(proxy.url));
break;
};
}
read_id_by_url[proxy.url] = feed_read_id;
input_feed_by_index.push_back(feed);
feed_by_url.emplace(make_pair(proxy.url, feed));
input_segment_cardinality += resolution;
};
/* Check that the read id of all interleaved blocks from all input feeds match. */
if(input_segment_cardinality > 1) {
string anchor_read_id;
URL anchor_url;
for(auto& record : read_id_by_url) {
if(anchor_read_id.empty()) {
anchor_url = record.first;
anchor_read_id = record.second;
} else if(anchor_read_id != record.second) {
throw ConfigurationError(string(anchor_url) + " and " + string(record.second) + " are out of sync");
}
}
}
encode_key_value("input segment cardinality", input_segment_cardinality, ontology, ontology);
input_feed_by_segment.reserve(input_segment_cardinality);
for(auto& feed : input_feed_by_index) {
for(int32_t i(0); i < feed->resolution(); ++i) {
input_feed_by_segment.push_back(feed);
}
}
list< URL > feed_url_by_segment;
for(auto& feed : input_feed_by_segment) {
feed_url_by_segment.push_back(feed->url);
}
encode_key_value("input", feed_url_by_segment, ontology, ontology);
encode_key_value("input feed", input_feed_by_index, ontology["feed"], ontology);
encode_key_value("input feed by segment", input_feed_by_segment, ontology["feed"], ontology);
};
void Transcode::compile_explicit_input() {
int32_t feed_index(0);
int32_t buffer_capacity(decode_value_by_key< int32_t >("buffer capacity", ontology));
uint8_t input_phred_offset(decode_value_by_key< uint8_t >("input phred offset", ontology));
list< URL > explicit_url_array(decode_value_by_key< list< URL > >("input", ontology));
Platform platform(decode_value_by_key< Platform >("platform", ontology));
/* encode the input segment cardinality */
encode_key_value("input segment cardinality", static_cast< int32_t>(explicit_url_array.size()), ontology, ontology);
list< URL > feed_url_by_index;
map< URL, int > feed_resolution;
for(const auto& url : explicit_url_array) {
auto record = feed_resolution.find(url);
if(record == feed_resolution.end()) {
feed_resolution[url] = 1;
feed_url_by_index.push_back(url);
} else { ++(record->second); }
}
unordered_map< URL, Value > feed_ontology_by_url;
for(const auto& url : feed_url_by_index) {
Value element(kObjectType);
int resolution(feed_resolution[url]);
encode_key_value("index", feed_index, element, ontology);
encode_key_value("url", url, element, ontology);
encode_key_value("direction", IoDirection::IN, element, ontology);
encode_key_value("platform", platform, element, ontology);
encode_key_value("capacity", buffer_capacity, element, ontology);
encode_key_value("resolution", resolution, element, ontology);
encode_key_value("phred offset", input_phred_offset, element, ontology);
feed_ontology_by_url.emplace(make_pair(url, std::move(element)));
++feed_index;
}
Value feed_by_segment_array(kArrayType);
for(const auto& url : explicit_url_array) {
Value feed_ontology(feed_ontology_by_url[url], ontology.GetAllocator());
feed_by_segment_array.PushBack(feed_ontology.Move(), ontology.GetAllocator());
}
ontology["feed"].RemoveMember("input feed by segment");
ontology["feed"].AddMember("input feed by segment", feed_by_segment_array.Move(), ontology.GetAllocator());
Value feed_by_index_array(kArrayType);
for(const auto& url : feed_url_by_index) {
feed_by_index_array.PushBack(feed_ontology_by_url[url].Move(), ontology.GetAllocator());
}
feed_ontology_by_url.clear();
ontology["feed"].RemoveMember("input feed");
ontology["feed"].AddMember("input feed", feed_by_index_array.Move(), ontology.GetAllocator());
};
void Transcode::compile_transformation(Value& value) {
/* add the default observation if one was not specificed.
default observation will treat every token as a segment */
if(value.IsObject()) {
Value::MemberIterator reference = value.FindMember("transform");
if(reference != value.MemberEnd()) {
if(reference->value.IsObject()) {
Value& transform_element(reference->value);
reference = transform_element.FindMember("token");
if(reference != transform_element.MemberEnd()) {
if(reference->value.IsArray()) {
size_t token_cardinality(reference->value.Size());
reference = transform_element.FindMember("knit");
if(reference == transform_element.MemberEnd() || reference->value.IsNull() || (reference->value.IsArray() && reference->value.Empty())) {
Value observation(kArrayType);
for(size_t i(0); i < token_cardinality; ++i) {
string element(to_string(i));
observation.PushBack(Value(element.c_str(), element.size(),ontology.GetAllocator()).Move(), ontology.GetAllocator());
}
transform_element.RemoveMember("knit");
transform_element.AddMember(Value("knit", ontology.GetAllocator()).Move(), observation.Move(), ontology.GetAllocator());
}
} else { throw ConfigurationError("transform token element is not an array"); }
} else { throw ConfigurationError("transform element is missing a token array"); }
}
}
}
};
void Transcode::compile_barcode_decoding() {
compile_topic("sample");
compile_topic("molecular");
compile_topic("cellular");
};
void Transcode::compile_topic(const Value::Ch* key) {
Value::MemberIterator reference = ontology.FindMember(key);
if(reference != ontology.MemberEnd()) {
if(!reference->value.IsNull()) {
ClassifierType classifier_type(ClassifierType::UNKNOWN);
Value decoder_template(kObjectType);
Value barcode_template(kObjectType);
from_string(key, classifier_type);
/* aseemble a decoder template */
string decoder_projection_uri(to_string(classifier_type));
decoder_projection_uri.append(":decoder");
const Value* decoder_projection(find_projection(decoder_projection_uri));
if(decoder_projection != NULL && !decoder_projection->IsNull()) {
merge_json_value(*decoder_projection, decoder_template, ontology);
}
/* aseemble a default decoder by projecting decoder template from the ontology root */
Value default_decoder(kObjectType);
project_json_value(decoder_template, ontology, default_decoder, ontology);
/* aseemble a barcode template */
string barcode_projection_uri(to_string(classifier_type));
barcode_projection_uri.append(":barcode");
const Value* barcode_projection(find_projection(barcode_projection_uri));
if(barcode_projection != NULL && !barcode_projection->IsNull()) {
merge_json_value(*barcode_projection, barcode_template, ontology);
}
/* aseemble a default barcode by projecting barcode template from the ontology root */
Value default_barcode(kObjectType);
project_json_value(barcode_template, ontology, default_barcode, ontology);
int32_t index(0);
if(reference->value.IsObject()) {
try {
compile_decoder(reference->value, index, default_decoder, default_barcode);
} catch(ConfigurationError& error) {
error.message.insert(0, string(key) + " decoder : ");
throw error;
}
} else if(reference->value.IsArray()) {
try {
for(auto& element : reference->value.GetArray()) {
compile_decoder(element, index, default_decoder, default_barcode);
}
} catch(ConfigurationError& error) {
error.message.insert(0, string(key) + " decoder at " + to_string(index) + " : ");
throw error;
}
}
clean_json_value(reference->value, ontology);
}
}
};
void Transcode::compile_decoder_transformation(Value& value) {
if(value.HasMember("transform")) {
compile_transformation(value);
Rule rule(decode_value_by_key< Rule >("transform", value));
int32_t input_segment_cardinality(decode_value_by_key< int32_t >("input segment cardinality", ontology));
/* validate all tokens refer to an existing input segment */
for(auto& token : rule.token_array) {
if(!(token.input_segment_index < input_segment_cardinality)) {
throw ConfigurationError("invalid input feed reference " + to_string(token.input_segment_index) + " in token " + to_string(token.index));
}
if(token.empty()) {
throw ConfigurationError("token " + string(token) + " is empty");
}
if(!token.constant()) {
throw ConfigurationError("token " + string(token) + " is not fixed width");
}
}
/* annotate the decoder with cardinality information from the transfortmation */
int32_t nucleotide_cardinality(0);
vector< int32_t > barcode_length(rule.output_segment_cardinality, 0);
for(auto& transform : rule.transform_array) {
barcode_length[transform.output_segment_index] += transform.length();
nucleotide_cardinality += transform.length();
}
encode_key_value("segment cardinality", rule.output_segment_cardinality, value, ontology);
encode_key_value("nucleotide cardinality", nucleotide_cardinality, value, ontology);
encode_key_value("barcode length", barcode_length, value, ontology);
double random_barcode_probability(0);
double random_barcode_probability_lower_bound(1.0 / double(pow(4, (nucleotide_cardinality))));
if(decode_value_by_key("random barcode probability", random_barcode_probability, value)) {
if(random_barcode_probability < random_barcode_probability_lower_bound) {
throw ConfigurationError("random barcode probability is smaller than lower bound");
}
} else {
encode_key_value("random barcode probability", random_barcode_probability_lower_bound, value, ontology);
}
/* verify nucleotide cardinality and uniqueness
and annotate each barcode element with the barcode segment cardinality */
Value::MemberIterator reference = value.FindMember("undetermined");
if(reference != value.MemberEnd()) {
if(!reference->value.IsNull()) {
Value& undetermined(reference->value);
/* explicitly define a null barcode segment for the right dimension in the undetermined */
Value barcode(kArrayType);
for(size_t i(0); i < barcode_length.size(); ++i) {
string sequence(barcode_length[i], '=');
barcode.PushBack(Value(sequence.c_str(), sequence.size(), ontology.GetAllocator()).Move(), ontology.GetAllocator());
}
undetermined.RemoveMember("barcode");
undetermined.AddMember(Value("barcode", ontology.GetAllocator()).Move(), barcode.Move(), ontology.GetAllocator());
encode_key_value("segment cardinality", rule.output_segment_cardinality, undetermined, ontology);
}
}
size_t segment_index(0);
string barcode_segment;
string barcode_sequence;
set< string > unique_barcode_sequence;
reference = value.FindMember("codec");
if(reference != value.MemberEnd()) {
if(reference->value.IsObject()) {
Value& codec(reference->value);
for(auto& record : codec.GetObject()) {
reference = record.value.FindMember("barcode");
if(reference != record.value.MemberEnd()) {
if(reference->value.Size() == barcode_length.size()) {
barcode_sequence.clear();
segment_index = 0;
for(const auto& element : reference->value.GetArray()) {
barcode_segment.assign(element.GetString(), element.GetStringLength());
if(static_cast< int32_t >(barcode_segment.size()) == barcode_length[segment_index]) {
barcode_sequence.append(barcode_segment);
++segment_index;
} else {
string key(record.name.GetString(), record.name.GetStringLength());
string message;
message.append("expected ");
message.append(to_string(barcode_length[segment_index]));
message.append(" but found ");
message.append(to_string(barcode_segment.size()));
message.append(" nucleotides in segment ");
message.append(to_string(segment_index));
message.append(" of barcode ");
message.append(key);
throw ConfigurationError(message);
}
}
if(!unique_barcode_sequence.count(barcode_sequence)) {
unique_barcode_sequence.emplace(barcode_sequence);
} else {
throw ConfigurationError("duplicate barcode sequence " + barcode_sequence);
}
} else {
string key(record.name.GetString(), record.name.GetStringLength());
string message;
message.append("expected ");
message.append(to_string(barcode_length.size()));
message.append(" segments but found ");
message.append(to_string(reference->value.Size()));
message.append(" in barcode ");
message.append(key);
throw ConfigurationError(message);
}
}
encode_key_value("segment cardinality", rule.output_segment_cardinality, record.value, ontology);
}
}
}
unique_barcode_sequence.clear();
}
};
void Transcode::compile_decoder(Value& value, int32_t& index, const Value& default_decoder, const Value& default_barcode) {
if(value.IsObject()) {
encode_key_value("index", index, value, ontology);
/* overlay on top of the default decoder */
merge_json_value(default_decoder, value, ontology);
clean_json_value(value, ontology);
/* compute default barcode induced by the codec */
Value default_codec_barcode(kObjectType);
project_json_value(default_barcode, value, default_codec_barcode, ontology);
/* apply barcode default on undetermined barcode or create it from the default if one was not explicitly specified */
Value::MemberIterator reference = value.FindMember("undetermined");
if(reference != value.MemberEnd()){
merge_json_value(default_codec_barcode, reference->value, ontology);
} else {
value.AddMember (
Value("undetermined", ontology.GetAllocator()).Move(),
Value(default_codec_barcode, ontology.GetAllocator()).Move(),
ontology.GetAllocator()
);
}
compile_decoder_transformation(value);
string buffer;
int32_t barcode_index(0);
double total_concentration(0);
set< string > unique_barcode_id;
double noise(decode_value_by_key< double >("noise", value));
reference = value.FindMember("undetermined");
if(reference != value.MemberEnd()){
encode_key_value("index", barcode_index, reference->value, ontology);
infer_PU(buffer, reference->value, true);
if(infer_ID(buffer, reference->value)) {
unique_barcode_id.emplace(buffer);
}
encode_key_value("concentration", noise, reference->value, ontology);
++barcode_index;
}
reference = value.FindMember("codec");
if(reference != value.MemberEnd()){
if(reference->value.IsObject()) {
Value& codec(reference->value);
for(auto& record : codec.GetObject()) {
merge_json_value(default_codec_barcode, record.value, ontology);
encode_key_value("index", barcode_index, record.value, ontology);
infer_PU(buffer, record.value);
if(infer_ID(buffer, record.value)) {
if(!unique_barcode_id.count(buffer)) {
unique_barcode_id.emplace(buffer);
} else {
string duplicate(record.name.GetString(), record.name.GetStringLength());
throw ConfigurationError("duplicate " + duplicate + " barcode");
}
}
double concentration(decode_value_by_key< double >("concentration", record.value));