SeqAn3 3.3.0-rc.1
The Modern C++ library for sequence analysis.
format_sam.hpp
Go to the documentation of this file.
1// -----------------------------------------------------------------------------------------------------
2// Copyright (c) 2006-2022, Knut Reinert & Freie Universität Berlin
3// Copyright (c) 2016-2022, Knut Reinert & MPI für molekulare Genetik
4// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
5// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
6// -----------------------------------------------------------------------------------------------------
7
13#pragma once
14
15#include <iterator>
16#include <ranges>
17#include <string>
18#include <vector>
19
38
39namespace seqan3
40{
41
108{
109public:
113 // construction cannot be noexcept because this class has a std::string variable as a quality string buffer.
114 format_sam() = default;
115 format_sam(format_sam const &) = default;
116 format_sam & operator=(format_sam const &) = default;
117 format_sam(format_sam &&) = default;
119 ~format_sam() = default;
120
122
125 {"sam"},
126 };
127
128protected:
129 template <typename stream_type, // constraints checked by file
130 typename seq_legal_alph_type,
131 typename stream_pos_type,
132 typename seq_type, // other constraints checked inside function
133 typename id_type,
134 typename qual_type>
135 void read_sequence_record(stream_type & stream,
137 stream_pos_type & position_buffer,
138 seq_type & sequence,
139 id_type & id,
140 qual_type & qualities);
141
142 template <typename stream_type, // constraints checked by file
143 typename seq_type, // other constraints checked inside function
144 typename id_type,
145 typename qual_type>
146 void write_sequence_record(stream_type & stream,
147 sequence_file_output_options const & SEQAN3_DOXYGEN_ONLY(options),
148 seq_type && sequence,
149 id_type && id,
150 qual_type && qualities);
151
152 template <typename stream_type, // constraints checked by file
153 typename seq_legal_alph_type,
154 typename ref_seqs_type,
155 typename ref_ids_type,
156 typename stream_pos_type,
157 typename seq_type,
158 typename id_type,
159 typename ref_seq_type,
160 typename ref_id_type,
161 typename ref_offset_type,
162 typename cigar_type,
163 typename flag_type,
164 typename mapq_type,
165 typename qual_type,
166 typename mate_type,
167 typename tag_dict_type,
168 typename e_value_type,
169 typename bit_score_type>
170 void read_alignment_record(stream_type & stream,
171 sam_file_input_options<seq_legal_alph_type> const & SEQAN3_DOXYGEN_ONLY(options),
172 ref_seqs_type & ref_seqs,
174 stream_pos_type & position_buffer,
175 seq_type & seq,
176 qual_type & qual,
177 id_type & id,
178 ref_seq_type & SEQAN3_DOXYGEN_ONLY(ref_seq),
179 ref_id_type & ref_id,
180 ref_offset_type & ref_offset,
181 cigar_type & cigar_vector,
182 flag_type & flag,
183 mapq_type & mapq,
184 mate_type & mate,
185 tag_dict_type & tag_dict,
186 e_value_type & SEQAN3_DOXYGEN_ONLY(e_value),
187 bit_score_type & SEQAN3_DOXYGEN_ONLY(bit_score));
188
189 template <typename stream_type,
190 typename header_type,
191 typename seq_type,
192 typename id_type,
193 typename ref_seq_type,
194 typename ref_id_type,
195 typename qual_type,
196 typename mate_type,
197 typename tag_dict_type,
198 typename e_value_type,
199 typename bit_score_type>
200 void write_alignment_record(stream_type & stream,
201 sam_file_output_options const & options,
202 header_type && header,
203 seq_type && seq,
204 qual_type && qual,
205 id_type && id,
206 ref_seq_type && SEQAN3_DOXYGEN_ONLY(ref_seq),
207 ref_id_type && ref_id,
208 std::optional<int32_t> ref_offset,
209 std::vector<cigar> const & cigar_vector,
210 sam_flag const flag,
211 uint8_t const mapq,
212 mate_type && mate,
213 tag_dict_type && tag_dict,
214 e_value_type && SEQAN3_DOXYGEN_ONLY(e_value),
215 bit_score_type && SEQAN3_DOXYGEN_ONLY(bit_score));
216
217private:
220
222 static constexpr std::string_view dummy{};
223
226
229
232 {
233 return dummy;
234 }
235
237 template <typename t>
238 decltype(auto) default_or(t && v) const noexcept
239 {
240 return std::forward<t>(v);
241 }
242
243 template <typename stream_view_type, arithmetic value_type>
244 void
245 read_sam_dict_vector(seqan3::detail::sam_tag_variant & variant, stream_view_type && stream_view, value_type value);
246
247 template <typename stream_view_type>
248 void read_sam_byte_vector(seqan3::detail::sam_tag_variant & variant, stream_view_type && stream_view);
249
250 template <typename stream_view_type>
251 void read_sam_dict_field(stream_view_type && stream_view, sam_tag_dictionary & target);
252
253 template <typename stream_it_t, std::ranges::forward_range field_type>
254 void write_range_or_asterisk(stream_it_t & stream_it, field_type && field_value);
255
256 template <typename stream_it_t>
257 void write_range_or_asterisk(stream_it_t & stream_it, char const * const field_value);
258
259 template <typename stream_it_t>
260 void write_tag_fields(stream_it_t & stream, sam_tag_dictionary const & tag_dict, char const separator);
261};
262
264template <typename stream_type, // constraints checked by file
265 typename seq_legal_alph_type,
266 typename stream_pos_type,
267 typename seq_type, // other constraints checked inside function
268 typename id_type,
269 typename qual_type>
270inline void format_sam::read_sequence_record(stream_type & stream,
272 stream_pos_type & position_buffer,
273 seq_type & sequence,
274 id_type & id,
275 qual_type & qualities)
276{
278
279 {
281 align_options,
282 std::ignore,
284 position_buffer,
285 sequence,
286 qualities,
287 id,
288 std::ignore,
289 std::ignore,
290 std::ignore,
291 std::ignore,
292 std::ignore,
293 std::ignore,
294 std::ignore,
295 std::ignore,
296 std::ignore,
297 std::ignore);
298 }
299
300 if constexpr (!detail::decays_to_ignore_v<seq_type>)
301 if (std::ranges::distance(sequence) == 0)
302 throw parse_error{"The sequence information must not be empty."};
303 if constexpr (!detail::decays_to_ignore_v<id_type>)
304 if (std::ranges::distance(id) == 0)
305 throw parse_error{"The id information must not be empty."};
306
307 if (options.truncate_ids)
308 id = id | detail::take_until_and_consume(is_space) | ranges::to<id_type>();
309}
310
312template <typename stream_type, // constraints checked by file
313 typename seq_type, // other constraints checked inside function
314 typename id_type,
315 typename qual_type>
316inline void format_sam::write_sequence_record(stream_type & stream,
317 sequence_file_output_options const & SEQAN3_DOXYGEN_ONLY(options),
318 seq_type && sequence,
319 id_type && id,
320 qual_type && qualities)
321{
322 using default_mate_t = std::tuple<std::string_view, std::optional<int32_t>, int32_t>;
323
324 sam_file_output_options output_options;
325
327 output_options,
328 /*header*/ std::ignore,
329 /*seq*/ default_or(sequence),
330 /*qual*/ default_or(qualities),
331 /*id*/ default_or(id),
332 /*ref_seq*/ std::string_view{},
333 /*ref_id*/ std::string_view{},
334 /*ref_offset*/ -1,
335 /*cigar_vector*/ std::vector<cigar>{},
336 /*flag*/ sam_flag::none,
337 /*mapq*/ 0,
338 /*mate*/ default_mate_t{},
339 /*tag_dict*/ sam_tag_dictionary{},
340 /*e_value*/ 0,
341 /*bit_score*/ 0);
342}
343
345template <typename stream_type, // constraints checked by file
346 typename seq_legal_alph_type,
347 typename ref_seqs_type,
348 typename ref_ids_type,
349 typename stream_pos_type,
350 typename seq_type,
351 typename id_type,
352 typename ref_seq_type,
353 typename ref_id_type,
354 typename ref_offset_type,
355 typename cigar_type,
356 typename flag_type,
357 typename mapq_type,
358 typename qual_type,
359 typename mate_type,
360 typename tag_dict_type,
361 typename e_value_type,
362 typename bit_score_type>
363inline void
365 sam_file_input_options<seq_legal_alph_type> const & SEQAN3_DOXYGEN_ONLY(options),
366 ref_seqs_type & ref_seqs,
368 stream_pos_type & position_buffer,
369 seq_type & seq,
370 qual_type & qual,
371 id_type & id,
372 ref_seq_type & SEQAN3_DOXYGEN_ONLY(ref_seq),
373 ref_id_type & ref_id,
374 ref_offset_type & ref_offset,
375 cigar_type & cigar_vector,
376 flag_type & flag,
377 mapq_type & mapq,
378 mate_type & mate,
379 tag_dict_type & tag_dict,
380 e_value_type & SEQAN3_DOXYGEN_ONLY(e_value),
381 bit_score_type & SEQAN3_DOXYGEN_ONLY(bit_score))
382{
383 static_assert(detail::decays_to_ignore_v<ref_offset_type>
384 || detail::is_type_specialisation_of_v<ref_offset_type, std::optional>,
385 "The ref_offset must be a specialisation of std::optional.");
386
387 auto stream_view = detail::istreambuf(stream);
388 auto field_view = stream_view | detail::take_until_or_throw_and_consume(is_char<'\t'>);
389
390 int32_t ref_offset_tmp{}; // needed to read the ref_offset (int) beofre storing it in std::optional<uint32_t>
391 std::ranges::range_value_t<decltype(header.ref_ids())> ref_id_tmp{}; // in case mate is requested but ref_offset not
392
393 // Header
394 // -------------------------------------------------------------------------------------------------------------
395 if (is_char<'@'>(*std::ranges::begin(stream_view))) // we always read the header if present
396 {
397 read_header(stream_view, header, ref_seqs);
398
399 if (std::ranges::begin(stream_view) == std::ranges::end(stream_view)) // file has no records
400 return;
401 }
402
403 // Store the current file position in the buffer.
404 position_buffer = stream.tellg();
405
406 // Fields 1-5: ID FLAG REF_ID REF_OFFSET MAPQ
407 // -------------------------------------------------------------------------------------------------------------
408 if constexpr (!detail::decays_to_ignore_v<id_type>)
409 read_forward_range_field(field_view, id);
410 else
411 detail::consume(field_view);
412
413 uint16_t flag_integral{};
414 read_arithmetic_field(field_view, flag_integral);
415 flag = sam_flag{flag_integral};
416
417 read_forward_range_field(field_view, ref_id_tmp);
418 check_and_assign_ref_id(ref_id, ref_id_tmp, header, ref_seqs);
419
420 read_arithmetic_field(field_view, ref_offset_tmp);
421 --ref_offset_tmp; // SAM format is 1-based but SeqAn operates 0-based
422
423 if (ref_offset_tmp == -1)
424 ref_offset = std::nullopt; // indicates an unmapped read -> ref_offset is not set
425 else if (ref_offset_tmp > -1)
426 ref_offset = ref_offset_tmp;
427 else if (ref_offset_tmp < -1)
428 throw format_error{"No negative values are allowed for field::ref_offset."};
429
430 if constexpr (!detail::decays_to_ignore_v<mapq_type>)
431 read_arithmetic_field(field_view, mapq);
432 else
433 detail::consume(field_view);
434
435 // Field 6: CIGAR
436 // -------------------------------------------------------------------------------------------------------------
437 if constexpr (!detail::decays_to_ignore_v<cigar_type>)
438 {
439 if (!is_char<'*'>(*std::ranges::begin(stream_view))) // no cigar information given
440 {
441 int32_t ref_length{}, seq_length{}; // length of aligned part for ref and query
442 std::tie(cigar_vector, ref_length, seq_length) = detail::parse_cigar(field_view);
443 }
444 else
445 {
446 ++std::ranges::begin(field_view); // skip '*'
447 }
448 }
449 else
450 {
451 detail::consume(field_view);
452 }
453
454 // Field 7-9: (RNEXT PNEXT TLEN) = MATE
455 // -------------------------------------------------------------------------------------------------------------
456 if constexpr (!detail::decays_to_ignore_v<mate_type>)
457 {
458 std::ranges::range_value_t<decltype(header.ref_ids())> tmp_mate_ref_id{};
459 read_forward_range_field(field_view, tmp_mate_ref_id); // RNEXT
460
461 if (tmp_mate_ref_id == "=") // indicates "same as ref id"
462 {
463 if constexpr (!detail::decays_to_ignore_v<ref_id_type>)
464 get<0>(mate) = ref_id;
465 else
466 check_and_assign_ref_id(get<0>(mate), ref_id_tmp, header, ref_seqs);
467 }
468 else
469 {
470 check_and_assign_ref_id(get<0>(mate), tmp_mate_ref_id, header, ref_seqs);
471 }
472
473 int32_t tmp_pnext{};
474 read_arithmetic_field(field_view, tmp_pnext); // PNEXT
475
476 if (tmp_pnext > 0)
477 get<1>(mate) = --tmp_pnext; // SAM format is 1-based but SeqAn operates 0-based.
478 else if (tmp_pnext < 0)
479 throw format_error{"No negative values are allowed at the mate mapping position."};
480 // tmp_pnext == 0 indicates an unmapped mate -> do not fill std::optional get<1>(mate)
481
482 read_arithmetic_field(field_view, get<2>(mate)); // TLEN
483 }
484 else
485 {
486 for (size_t i = 0; i < 3u; ++i)
487 {
488 detail::consume(field_view);
489 }
490 }
491
492 // Field 10: Sequence
493 // -------------------------------------------------------------------------------------------------------------
494 if (!is_char<'*'>(*std::ranges::begin(stream_view))) // sequence information is given
495 {
496 constexpr auto is_legal_alph = char_is_valid_for<seq_legal_alph_type>;
497 auto seq_stream =
498 field_view
500 [is_legal_alph](char const c) // enforce legal alphabet
501 {
502 if (!is_legal_alph(c))
503 throw parse_error{std::string{"Encountered an unexpected letter: "} + "char_is_valid_for<"
504 + detail::type_name_as_string<seq_legal_alph_type>
505 + "> evaluated to false on " + detail::make_printable(c)};
506 return c;
507 });
508
509 if constexpr (detail::decays_to_ignore_v<seq_type>)
510 {
511 detail::consume(seq_stream);
512 }
513 else
514 {
515 read_forward_range_field(seq_stream, seq);
516 }
517 }
518 else
519 {
520 ++std::ranges::begin(field_view); // skip '*'
521 }
522
523 // Field 11: Quality
524 // -------------------------------------------------------------------------------------------------------------
525 auto const tab_or_end = is_char<'\t'> || is_char<'\r'> || is_char<'\n'>;
526 auto qual_view = stream_view | detail::take_until_or_throw(tab_or_end);
527 if constexpr (!detail::decays_to_ignore_v<qual_type>)
528 read_forward_range_field(qual_view, qual);
529 else
530 detail::consume(qual_view);
531
532 if constexpr (!detail::decays_to_ignore_v<seq_type> && !detail::decays_to_ignore_v<qual_type>)
533 {
534 if (std::ranges::distance(seq) != 0 && std::ranges::distance(qual) != 0
535 && std::ranges::distance(seq) != std::ranges::distance(qual))
536 {
537 throw format_error{detail::to_string("Sequence length (",
538 std::ranges::distance(seq),
539 ") and quality length (",
540 std::ranges::distance(qual),
541 ") must be the same.")};
542 }
543 }
544
545 // All remaining optional fields if any: SAM tags dictionary
546 // -------------------------------------------------------------------------------------------------------------
547 while (is_char<'\t'>(*std::ranges::begin(stream_view))) // read all tags if present
548 {
549 ++std::ranges::begin(stream_view); // skip tab
550 auto stream_until_tab_or_end = stream_view | detail::take_until_or_throw(tab_or_end);
551 if constexpr (!detail::decays_to_ignore_v<tag_dict_type>)
552 read_sam_dict_field(stream_until_tab_or_end, tag_dict);
553 else
554 detail::consume(stream_until_tab_or_end);
555 }
556
557 detail::consume(stream_view | detail::take_until(!(is_char<'\r'> || is_char<'\n'>))); // consume new line
558}
559
561template <typename stream_type,
562 typename header_type,
563 typename seq_type,
564 typename id_type,
565 typename ref_seq_type,
566 typename ref_id_type,
567 typename qual_type,
568 typename mate_type,
569 typename tag_dict_type,
570 typename e_value_type,
571 typename bit_score_type>
572inline void format_sam::write_alignment_record(stream_type & stream,
573 sam_file_output_options const & options,
574 header_type && header,
575 seq_type && seq,
576 qual_type && qual,
577 id_type && id,
578 ref_seq_type && SEQAN3_DOXYGEN_ONLY(ref_seq),
579 ref_id_type && ref_id,
580 std::optional<int32_t> ref_offset,
581 std::vector<cigar> const & cigar_vector,
582 sam_flag const flag,
583 uint8_t const mapq,
584 mate_type && mate,
585 tag_dict_type && tag_dict,
586 e_value_type && SEQAN3_DOXYGEN_ONLY(e_value),
587 bit_score_type && SEQAN3_DOXYGEN_ONLY(bit_score))
588{
589 /* Note the following general things:
590 *
591 * - Given the SAM specifications, all fields may be empty
592 *
593 * - arithmetic values default to 0 while all others default to '*'
594 *
595 * - Because of the former, arithmetic values can be directly streamed
596 * into 'stream' as operator<< is defined for all arithmetic types
597 * and the default value (0) is also the SAM default.
598 *
599 * - All other non-arithmetic values need to be checked for emptiness
600 */
601
602 // ---------------------------------------------------------------------
603 // Type Requirements (as static asserts for user friendliness)
604 // ---------------------------------------------------------------------
605 static_assert((std::ranges::forward_range<seq_type> && alphabet<std::ranges::range_reference_t<seq_type>>),
606 "The seq object must be a std::ranges::forward_range over "
607 "letters that model seqan3::alphabet.");
608
609 static_assert((std::ranges::forward_range<id_type> && alphabet<std::ranges::range_reference_t<id_type>>),
610 "The id object must be a std::ranges::forward_range over "
611 "letters that model seqan3::alphabet.");
612
613 if constexpr (!detail::decays_to_ignore_v<ref_id_type>)
614 {
615 static_assert((std::ranges::forward_range<ref_id_type> || std::integral<std::remove_reference_t<ref_id_type>>
616 || detail::is_type_specialisation_of_v<std::remove_cvref_t<ref_id_type>, std::optional>),
617 "The ref_id object must be a std::ranges::forward_range "
618 "over letters that model seqan3::alphabet.");
619
620 if constexpr (std::integral<std::remove_cvref_t<ref_id_type>>
621 || detail::is_type_specialisation_of_v<std::remove_cvref_t<ref_id_type>, std::optional>)
622 static_assert(!detail::decays_to_ignore_v<header_type>,
623 "If you give indices as reference id information the header must also be present.");
624 }
625
626 static_assert((std::ranges::forward_range<qual_type> && alphabet<std::ranges::range_reference_t<qual_type>>),
627 "The qual object must be a std::ranges::forward_range "
628 "over letters that model seqan3::alphabet.");
629
631 "The mate object must be a std::tuple of size 3 with "
632 "1) a std::ranges::forward_range with a value_type modelling seqan3::alphabet, "
633 "2) a std::integral or std::optional<std::integral>, and "
634 "3) a std::integral.");
635
636 static_assert(
637 ((std::ranges::forward_range<decltype(std::get<0>(mate))>
638 || std::integral<std::remove_cvref_t<decltype(std::get<0>(mate))>>
639 || detail::is_type_specialisation_of_v<
640 std::remove_cvref_t<decltype(std::get<0>(mate))>,
641 std::optional>)&&(std::integral<std::remove_cvref_t<decltype(std::get<1>(mate))>>
642 || detail::is_type_specialisation_of_v<
643 std::remove_cvref_t<decltype(std::get<1>(mate))>,
644 std::optional>)&&std::integral<std::remove_cvref_t<decltype(std::get<2>(mate))>>),
645 "The mate object must be a std::tuple of size 3 with "
646 "1) a std::ranges::forward_range with a value_type modelling seqan3::alphabet, "
647 "2) a std::integral or std::optional<std::integral>, and "
648 "3) a std::integral.");
649
650 if constexpr (std::integral<std::remove_cvref_t<decltype(std::get<0>(mate))>>
651 || detail::is_type_specialisation_of_v<std::remove_cvref_t<decltype(std::get<0>(mate))>,
653 static_assert(!detail::decays_to_ignore_v<header_type>,
654 "If you give indices as mate reference id information the header must also be present.");
655
656 static_assert(std::same_as<std::remove_cvref_t<tag_dict_type>, sam_tag_dictionary>,
657 "The tag_dict object must be of type seqan3::sam_tag_dictionary.");
658
659 // ---------------------------------------------------------------------
660 // logical Requirements
661 // ---------------------------------------------------------------------
662 if constexpr (!detail::decays_to_ignore_v<header_type> && !detail::decays_to_ignore_v<ref_id_type>
663 && !std::integral<std::remove_reference_t<ref_id_type>>
664 && !detail::is_type_specialisation_of_v<std::remove_reference_t<ref_id_type>, std::optional>)
665 {
666
667 if (options.sam_require_header && !std::ranges::empty(ref_id))
668 {
669 auto id_it = header.ref_dict.end();
670
671 if constexpr (std::ranges::contiguous_range<decltype(ref_id)> && std::ranges::sized_range<decltype(ref_id)>
672 && std::ranges::borrowed_range<decltype(ref_id)>)
673 {
674 id_it = header.ref_dict.find(std::span{std::ranges::data(ref_id), std::ranges::size(ref_id)});
675 }
676 else
677 {
678 using header_ref_id_type = std::remove_reference_t<decltype(header.ref_ids()[0])>;
679
681 "The ref_id type is not convertible to the reference id information stored in the "
682 "reference dictionary of the header object.");
683
684 id_it = header.ref_dict.find(ref_id);
685 }
686
687 if (id_it == header.ref_dict.end()) // no reference id matched
688 throw format_error{detail::to_string("The ref_id '",
689 ref_id,
690 "' was not in the list of references:",
691 header.ref_ids())};
692 }
693 }
694
695 if (ref_offset.has_value() && (ref_offset.value() + 1) < 0)
696 throw format_error{"The ref_offset object must be a std::integral >= 0."};
697
698 // ---------------------------------------------------------------------
699 // Writing the Header on first call
700 // ---------------------------------------------------------------------
701 if constexpr (!detail::decays_to_ignore_v<header_type>)
702 {
704 {
705 write_header(stream, options, header);
706 header_was_written = true;
707 }
708 }
709
710 // ---------------------------------------------------------------------
711 // Writing the Record
712 // ---------------------------------------------------------------------
713
714 detail::fast_ostreambuf_iterator stream_it{*stream.rdbuf()};
715 constexpr char separator{'\t'};
716
717 write_range_or_asterisk(stream_it, id);
718 *stream_it = separator;
719
720 stream_it.write_number(static_cast<uint16_t>(flag));
721 *stream_it = separator;
722
723 if constexpr (!detail::decays_to_ignore_v<ref_id_type>)
724 {
725 if constexpr (std::integral<std::remove_reference_t<ref_id_type>>)
726 {
727 write_range_or_asterisk(stream_it, (header.ref_ids())[ref_id]);
728 }
729 else if constexpr (detail::is_type_specialisation_of_v<std::remove_reference_t<ref_id_type>, std::optional>)
730 {
731 if (ref_id.has_value())
732 write_range_or_asterisk(stream_it, (header.ref_ids())[ref_id.value()]);
733 else
734 *stream_it = '*';
735 }
736 else
737 {
739 }
740 }
741 else
742 {
743 *stream_it = '*';
744 }
745
746 *stream_it = separator;
747
748 // SAM is 1 based, 0 indicates unmapped read if optional is not set
749 stream_it.write_number(ref_offset.value_or(-1) + 1);
750 *stream_it = separator;
751
752 stream_it.write_number(static_cast<unsigned>(mapq));
753 *stream_it = separator;
754
755 if (!std::ranges::empty(cigar_vector))
756 {
757 for (auto & c : cigar_vector) //TODO THIS IS PROBABLY TERRIBLE PERFORMANCE_WISE
758 stream_it.write_range(c.to_string());
759 }
760 else
761 {
762 *stream_it = '*';
763 }
764
765 *stream_it = separator;
766
767 if constexpr (std::integral<std::remove_reference_t<decltype(get<0>(mate))>>)
768 {
769 write_range_or_asterisk(stream_it, (header.ref_ids())[get<0>(mate)]);
770 }
771 else if constexpr (detail::is_type_specialisation_of_v<std::remove_reference_t<decltype(get<0>(mate))>,
773 {
774 if (get<0>(mate).has_value())
775 write_range_or_asterisk(stream_it, header.ref_ids()[get<0>(mate).value()]);
776 else
777 *stream_it = '*';
778 }
779 else
780 {
781 write_range_or_asterisk(stream_it, get<0>(mate));
782 }
783
784 *stream_it = separator;
785
786 if constexpr (detail::is_type_specialisation_of_v<std::remove_cvref_t<decltype(get<1>(mate))>, std::optional>)
787 {
788 // SAM is 1 based, 0 indicates unmapped read if optional is not set
789 stream_it.write_number(get<1>(mate).value_or(-1) + 1);
790 *stream_it = separator;
791 }
792 else
793 {
794 stream_it.write_number(get<1>(mate));
795 *stream_it = separator;
796 }
797
798 stream_it.write_number(get<2>(mate));
799 *stream_it = separator;
800
801 write_range_or_asterisk(stream_it, seq);
802 *stream_it = separator;
803
804 write_range_or_asterisk(stream_it, qual);
805
806 write_tag_fields(stream_it, tag_dict, separator);
807
808 stream_it.write_end_of_line(options.add_carriage_return);
809}
810
828template <typename stream_view_type, arithmetic value_type>
830 stream_view_type && stream_view,
831 value_type value)
832{
833 std::vector<value_type> tmp_vector;
834 while (std::ranges::begin(stream_view) != std::ranges::end(stream_view)) // not fully consumed yet
835 {
836 read_arithmetic_field(stream_view | detail::take_until(is_char<','>), value);
837 tmp_vector.push_back(value);
838
839 if (is_char<','>(*std::ranges::begin(stream_view)))
840 ++std::ranges::begin(stream_view); // skip ','
841 }
842 variant = std::move(tmp_vector);
843}
844
858template <typename stream_view_type>
859inline void format_sam::read_sam_byte_vector(seqan3::detail::sam_tag_variant & variant, stream_view_type && stream_view)
860{
861 std::vector<std::byte> tmp_vector;
862 std::byte value;
863
864 while (std::ranges::begin(stream_view) != std::ranges::end(stream_view)) // not fully consumed yet
865 {
866 try
867 {
868 read_byte_field(stream_view | detail::take_exactly_or_throw(2), value);
869 }
870 catch (std::exception const & e)
871 {
872 throw format_error{"Hexadecimal tag has an uneven number of digits!"};
873 }
874
875 tmp_vector.push_back(value);
876 }
877
878 variant = std::move(tmp_vector);
879}
880
898template <typename stream_view_type>
899inline void format_sam::read_sam_dict_field(stream_view_type && stream_view, sam_tag_dictionary & target)
900{
901 /* Every SAM tag has the format "[TAG]:[TYPE_ID]:[VALUE]", where TAG is a two letter
902 name tag which is converted to a unique integer identifier and TYPE_ID is one character in [A,i,Z,H,B,f]
903 describing the type for the upcoming VALUES. If TYPE_ID=='B' it signals an array of comma separated
904 VALUE's and the inner value type is identified by the character following ':', one of [cCsSiIf].
905 */
906 uint16_t tag = static_cast<uint16_t>(*std::ranges::begin(stream_view)) << 8;
907 ++std::ranges::begin(stream_view); // skip char read before
908 tag += static_cast<uint16_t>(*std::ranges::begin(stream_view));
909 ++std::ranges::begin(stream_view); // skip char read before
910 ++std::ranges::begin(stream_view); // skip ':'
911 char type_id = *std::ranges::begin(stream_view);
912 ++std::ranges::begin(stream_view); // skip char read before
913 ++std::ranges::begin(stream_view); // skip ':'
914
915 switch (type_id)
916 {
917 case 'A': // char
918 {
919 target[tag] = static_cast<char>(*std::ranges::begin(stream_view));
920 ++std::ranges::begin(stream_view); // skip char that has been read
921 break;
922 }
923 case 'i': // int32_t
924 {
925 int32_t tmp;
926 read_arithmetic_field(stream_view, tmp);
927 target[tag] = tmp;
928 break;
929 }
930 case 'f': // float
931 {
932 float tmp;
933 read_arithmetic_field(stream_view, tmp);
934 target[tag] = tmp;
935 break;
936 }
937 case 'Z': // string
938 {
939 target[tag] = stream_view | ranges::to<std::string>();
940 break;
941 }
942 case 'H':
943 {
944 read_sam_byte_vector(target[tag], stream_view);
945 break;
946 }
947 case 'B': // Array. Value type depends on second char [cCsSiIf]
948 {
949 char array_value_type_id = *std::ranges::begin(stream_view);
950 ++std::ranges::begin(stream_view); // skip char read before
951 ++std::ranges::begin(stream_view); // skip first ','
952
953 switch (array_value_type_id)
954 {
955 case 'c': // int8_t
956 read_sam_dict_vector(target[tag], stream_view, int8_t{});
957 break;
958 case 'C': // uint8_t
959 read_sam_dict_vector(target[tag], stream_view, uint8_t{});
960 break;
961 case 's': // int16_t
962 read_sam_dict_vector(target[tag], stream_view, int16_t{});
963 break;
964 case 'S': // uint16_t
965 read_sam_dict_vector(target[tag], stream_view, uint16_t{});
966 break;
967 case 'i': // int32_t
968 read_sam_dict_vector(target[tag], stream_view, int32_t{});
969 break;
970 case 'I': // uint32_t
971 read_sam_dict_vector(target[tag], stream_view, uint32_t{});
972 break;
973 case 'f': // float
974 read_sam_dict_vector(target[tag], stream_view, float{});
975 break;
976 default:
977 throw format_error{std::string("The first character in the numerical ")
978 + "id of a SAM tag must be one of [cCsSiIf] but '" + array_value_type_id
979 + "' was given."};
980 }
981 break;
982 }
983 default:
984 throw format_error{std::string("The second character in the numerical id of a "
985 "SAM tag must be one of [A,i,Z,H,B,f] but '")
986 + type_id + "' was given."};
987 }
988}
989
997template <typename stream_it_t, std::ranges::forward_range field_type>
998inline void format_sam::write_range_or_asterisk(stream_it_t & stream_it, field_type && field_value)
999{
1000 if (std::ranges::empty(field_value))
1001 {
1002 *stream_it = '*';
1003 }
1004 else
1005 {
1006 if constexpr (std::same_as<std::remove_cvref_t<std::ranges::range_reference_t<field_type>>, char>)
1007 stream_it.write_range(field_value);
1008 else // convert from alphabets to their character representation
1009 stream_it.write_range(field_value | views::to_char);
1010 }
1011}
1012
1019template <typename stream_it_t>
1020inline void format_sam::write_range_or_asterisk(stream_it_t & stream_it, char const * const field_value)
1021{
1022 write_range_or_asterisk(stream_it, std::string_view{field_value});
1023}
1024
1032template <typename stream_it_t>
1033inline void
1034format_sam::write_tag_fields(stream_it_t & stream_it, sam_tag_dictionary const & tag_dict, char const separator)
1035{
1036 auto const stream_variant_fn = [&stream_it](auto && arg) // helper to print a std::variant
1037 {
1038 using T = std::remove_cvref_t<decltype(arg)>;
1039
1040 if constexpr (std::ranges::input_range<T>)
1041 {
1042 if constexpr (std::same_as<std::remove_cvref_t<std::ranges::range_reference_t<T>>, char>)
1043 {
1044 stream_it.write_range(arg);
1045 }
1046 else if constexpr (std::same_as<std::remove_cvref_t<std::ranges::range_reference_t<T>>, std::byte>)
1047 {
1048 if (!std::ranges::empty(arg))
1049 {
1050 stream_it.write_number(std::to_integer<uint8_t>(*std::ranges::begin(arg)));
1051
1052 for (auto && elem : arg | std::views::drop(1))
1053 {
1054 *stream_it = ',';
1055 stream_it.write_number(std::to_integer<uint8_t>(elem));
1056 }
1057 }
1058 }
1059 else
1060 {
1061 if (!std::ranges::empty(arg))
1062 {
1063 stream_it.write_number(*std::ranges::begin(arg));
1064
1065 for (auto && elem : arg | std::views::drop(1))
1066 {
1067 *stream_it = ',';
1068 stream_it.write_number(elem);
1069 }
1070 }
1071 }
1072 }
1073 else if constexpr (std::same_as<std::remove_cvref_t<T>, char>)
1074 {
1075 *stream_it = arg;
1076 }
1077 else // number
1078 {
1079 stream_it.write_number(arg);
1080 }
1081 };
1082
1083 for (auto & [tag, variant] : tag_dict)
1084 {
1085 *stream_it = separator;
1086
1087 char const char0 = tag / 256;
1088 char const char1 = tag % 256;
1089
1090 *stream_it = char0;
1091 *stream_it = char1;
1092 *stream_it = ':';
1093 *stream_it = detail::sam_tag_type_char[variant.index()];
1094 *stream_it = ':';
1095
1096 if (detail::sam_tag_type_char_extra[variant.index()] != '\0')
1097 {
1098 *stream_it = detail::sam_tag_type_char_extra[variant.index()];
1099 *stream_it = ',';
1100 }
1101
1102 std::visit(stream_variant_fn, variant);
1103 }
1104}
1105
1106} // namespace seqan3
Core alphabet concept and free function/type trait wrappers.
T begin(T... args)
Functionally the same as std::ostreambuf_iterator, but offers writing a range more efficiently.
Definition: fast_ostreambuf_iterator.hpp:40
The alignment base format.
Definition: format_sam_base.hpp:45
void check_and_assign_ref_id(ref_id_type &ref_id, ref_id_tmp_type &ref_id_tmp, header_type &header, ref_seqs_type &)
Checks for known reference ids or adds a new reference is and assigns a reference id to ref_id.
Definition: format_sam_base.hpp:108
void write_header(stream_t &stream, sam_file_output_options const &options, header_type &header)
Writes the SAM header.
Definition: format_sam_base.hpp:625
void read_arithmetic_field(stream_view_t &&stream_view, arithmetic_target_type &arithmetic_target)
Reads arithmetic fields using std::from_chars.
Definition: format_sam_base.hpp:252
void read_forward_range_field(stream_view_type &&stream_view, target_range_type &target)
Reads a range by copying from stream_view to target, converting values with seqan3::views::char_to.
Definition: format_sam_base.hpp:220
bool header_was_written
A variable that tracks whether the content of header has been written or not.
Definition: format_sam_base.hpp:66
void read_header(stream_view_type &&stream_view, sam_file_header< ref_ids_type > &hdr, ref_seqs_type &)
Reads the SAM header.
Definition: format_sam_base.hpp:288
void read_byte_field(stream_view_t &&stream_view, std::byte &byte_target)
Reads std::byte fields using std::from_chars.
Definition: format_sam_base.hpp:192
The SAM format (tag).
Definition: format_sam.hpp:108
sam_file_header default_header
The default header for the alignment format.
Definition: format_sam.hpp:225
std::string_view const & default_or(detail::ignore_t) const noexcept
brief Returns a reference to dummy if passed a std::ignore.
Definition: format_sam.hpp:231
~format_sam()=default
Defaulted.
format_sam & operator=(format_sam const &)=default
Defaulted.
void read_sam_byte_vector(seqan3::detail::sam_tag_variant &variant, stream_view_type &&stream_view)
Reads a list of byte pairs as it is the case for SAM tag byte arrays.
Definition: format_sam.hpp:859
static std::vector< std::string > file_extensions
The valid file extensions for this format; note that you can modify this value.
Definition: format_sam.hpp:124
void write_sequence_record(stream_type &stream, sequence_file_output_options const &options, seq_type &&sequence, id_type &&id, qual_type &&qualities)
Write the given fields to the specified stream.
Definition: format_sam.hpp:316
void write_alignment_record(stream_type &stream, sam_file_output_options const &options, header_type &&header, seq_type &&seq, qual_type &&qual, id_type &&id, ref_seq_type &&ref_seq, ref_id_type &&ref_id, std::optional< int32_t > ref_offset, std::vector< cigar > const &cigar_vector, sam_flag const flag, uint8_t const mapq, mate_type &&mate, tag_dict_type &&tag_dict, e_value_type &&e_value, bit_score_type &&bit_score)
Write the given fields to the specified stream.
Definition: format_sam.hpp:572
format_sam(format_sam &&)=default
Defaulted.
void write_tag_fields(stream_it_t &stream, sam_tag_dictionary const &tag_dict, char const separator)
Writes the optional fields of the seqan3::sam_tag_dictionary.
Definition: format_sam.hpp:1034
format_sam & operator=(format_sam &&)=default
Defaulted.
void read_sam_dict_vector(seqan3::detail::sam_tag_variant &variant, stream_view_type &&stream_view, value_type value)
Reads a list of values separated by comma as it is the case for SAM tag arrays.
Definition: format_sam.hpp:829
void read_sam_dict_field(stream_view_type &&stream_view, sam_tag_dictionary &target)
Reads the optional tag fields into the seqan3::sam_tag_dictionary.
Definition: format_sam.hpp:899
static constexpr std::string_view dummy
An empty dummy container to pass to align_format.write() such that an empty field is written.
Definition: format_sam.hpp:222
void read_alignment_record(stream_type &stream, sam_file_input_options< seq_legal_alph_type > const &options, ref_seqs_type &ref_seqs, sam_file_header< ref_ids_type > &header, stream_pos_type &position_buffer, seq_type &seq, qual_type &qual, id_type &id, ref_seq_type &ref_seq, ref_id_type &ref_id, ref_offset_type &ref_offset, cigar_type &cigar_vector, flag_type &flag, mapq_type &mapq, mate_type &mate, tag_dict_type &tag_dict, e_value_type &e_value, bit_score_type &bit_score)
Read from the specified stream and back-insert into the given field buffers.
Definition: format_sam.hpp:364
void write_range_or_asterisk(stream_it_t &stream_it, field_type &&field_value)
Writes a field value to the stream.
Definition: format_sam.hpp:998
bool ref_info_present_in_header
Tracks whether reference information (@SR tag) were found in the SAM header.
Definition: format_sam.hpp:228
decltype(auto) default_or(t &&v) const noexcept
brief Returns the input unchanged.
Definition: format_sam.hpp:238
void read_sequence_record(stream_type &stream, sequence_file_input_options< seq_legal_alph_type > const &options, stream_pos_type &position_buffer, seq_type &sequence, id_type &id, qual_type &qualities)
Read from the specified stream and back-insert into the given field buffers.
Definition: format_sam.hpp:270
std::string tmp_qual
Stores quality values temporarily if seq and qual information are combined (not supported by SAM yet)...
Definition: format_sam.hpp:219
format_sam()=default
Defaulted.
format_sam(format_sam const &)=default
Defaulted.
Stores the header information of SAM/BAM files.
Definition: header.hpp:34
ref_ids_type & ref_ids()
The range of reference ids.
Definition: header.hpp:143
std::unordered_map< key_type, int32_t, key_hasher, detail::view_equality_fn > ref_dict
The mapping of reference id to position in the ref_ids() range and the ref_id_info range.
Definition: header.hpp:182
The SAM tag dictionary class that stores all optional SAM fields.
Definition: sam_tag_dictionary.hpp:343
Provides seqan3::detail::fast_ostreambuf_iterator.
Provides the seqan3::format_sam_base that can be inherited from.
auto const to_char
A view that calls seqan3::to_char() on each element in the input range.
Definition: to_char.hpp:63
constexpr void consume(rng_t &&rng)
Iterate over a range (consumes single-pass input ranges).
Definition: core/range/detail/misc.hpp:28
sam_flag
An enum flag that describes the properties of an aligned read (given as a SAM record).
Definition: sam_flag.hpp:76
constexpr std::tuple< std::vector< cigar >, int32_t, int32_t > parse_cigar(cigar_input_type &&cigar_input)
Parses a cigar string into a vector of operation-count pairs (e.g. (M, 3)).
Definition: io/sam_file/detail/cigar.hpp:94
constexpr char sam_tag_type_char_extra[12]
Each types SAM tag type extra char id. Index corresponds to the seqan3::detail::sam_tag_variant types...
Definition: sam_tag_dictionary.hpp:45
constexpr char sam_tag_type_char[12]
Each SAM tag type char identifier. Index corresponds to the seqan3::detail::sam_tag_variant types.
Definition: sam_tag_dictionary.hpp:42
@ none
None of the flags below are set.
constexpr auto take_until
A view adaptor that returns elements from the underlying range until the functor evaluates to true (o...
Definition: take_until_view.hpp:560
constexpr auto take_exactly_or_throw
A view adaptor that returns the first size elements from the underlying range and also exposes size i...
Definition: take_exactly_view.hpp:590
constexpr auto take_until_or_throw_and_consume
A view adaptor that returns elements from the underlying range until the functor evaluates to true (t...
Definition: take_until_view.hpp:602
constexpr auto take_until_and_consume
A view adaptor that returns elements from the underlying range until the functor evaluates to true (o...
Definition: take_until_view.hpp:588
constexpr auto take_until_or_throw
A view adaptor that returns elements from the underlying range until the functor evaluates to true (t...
Definition: take_until_view.hpp:574
constexpr auto istreambuf
A view factory that returns a view over the stream buffer of an input stream.
Definition: istreambuf_view.hpp:107
@ flag
The alignment flag (bit information), uint16_t value.
@ ref_offset
Sequence (seqan3::field::ref_seq) relative start position (0-based), unsigned value.
@ mapq
The mapping quality of the seqan3::field::seq alignment, usually a Phred-scaled score.
@ mate
The mate pair information given as a std::tuple of reference name, offset and template length.
@ ref_id
The identifier of the (reference) sequence that seqan3::field::seq was aligned to.
@ seq
The "sequence", usually a range of nucleotides or amino acids.
@ qual
The qualities, usually in Phred score notation.
std::string make_printable(char const c)
Returns a printable value for the given character c.
Definition: pretty_print.hpp:48
constexpr auto is_space
Checks whether c is a space character.
Definition: predicate.hpp:125
typename decltype(detail::split_after< i >(list_t{}))::second_type drop
Return a seqan3::type_list of the types in the input type list, except the first n.
Definition: type_list/traits.hpp:395
decltype(detail::transform< trait_t >(list_t{})) transform
Apply a transformation trait to every type in the list and return a seqan3::type_list of the results.
Definition: type_list/traits.hpp:470
constexpr size_t size
The size of a type pack.
Definition: type_pack/traits.hpp:146
Provides the seqan3::sam_file_header class.
The generic alphabet concept that covers most data types used in ranges.
Checks whether from can be implicityly converted to to.
The generic concept for a (biological) sequence.
Whether a type behaves like a tuple.
Auxiliary functions for the SAM IO.
Provides seqan3::detail::istreambuf.
std::string to_string(value_type &&... values)
Streams all parameters via the seqan3::debug_stream and returns a concatenated string.
Definition: to_string.hpp:29
The main SeqAn3 namespace.
Definition: aligned_sequence_concept.hpp:29
T push_back(T... args)
Provides seqan3::sam_file_input_format and auxiliary classes.
Provides seqan3::sam_file_output_options.
Provides helper data structures for the seqan3::sam_file_output.
Provides the seqan3::sam_tag_dictionary class and auxiliaries.
Provides seqan3::sequence_file_input_format and auxiliary classes.
Provides seqan3::sequence_file_output_options.
Provides seqan3::views::slice.
Thrown if information given to output format didn't match expectations.
Definition: io/exception.hpp:91
Thrown if there is a parse error, such as reading an unexpected character from an input stream.
Definition: io/exception.hpp:48
The options type defines various option members that influence the behaviour of all or some formats.
Definition: sam_file/input_options.hpp:27
The options type defines various option members that influence the behavior of all or some formats.
Definition: sam_file/output_options.hpp:26
bool add_carriage_return
The default plain text line-ending is "\n", but on Windows an additional carriage return is recommend...
Definition: sam_file/output_options.hpp:30
bool sam_require_header
Whether to require a header for SAM files.
Definition: sam_file/output_options.hpp:44
The options type defines various option members that influence the behaviour of all or some formats.
Definition: sequence_file/input_options.hpp:27
bool truncate_ids
Read the ID string only up until the first whitespace character.
Definition: sequence_file/input_options.hpp:29
The options type defines various option members that influence the behaviour of all or some formats.
Definition: sequence_file/output_options.hpp:26
Provides seqan3::views::take_until and seqan3::views::take_until_or_throw.
T tie(T... args)
Provides seqan3::ranges::to.
Provides seqan3::views::to_char.
Provides traits to inspect some information of a type, for example its name.
Provides seqan3::tuple_like.
T visit(T... args)