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 offset_type,
160 typename ref_seq_type,
161 typename ref_id_type,
162 typename ref_offset_type,
163 typename cigar_type,
164 typename flag_type,
165 typename mapq_type,
166 typename qual_type,
167 typename mate_type,
168 typename tag_dict_type,
169 typename e_value_type,
170 typename bit_score_type>
171 void read_alignment_record(stream_type & stream,
172 sam_file_input_options<seq_legal_alph_type> const & SEQAN3_DOXYGEN_ONLY(options),
173 ref_seqs_type & ref_seqs,
175 stream_pos_type & position_buffer,
176 seq_type & seq,
177 qual_type & qual,
178 id_type & id,
179 offset_type & offset,
180 ref_seq_type & SEQAN3_DOXYGEN_ONLY(ref_seq),
181 ref_id_type & ref_id,
182 ref_offset_type & ref_offset,
183 cigar_type & cigar_vector,
184 flag_type & flag,
185 mapq_type & mapq,
186 mate_type & mate,
187 tag_dict_type & tag_dict,
188 e_value_type & SEQAN3_DOXYGEN_ONLY(e_value),
189 bit_score_type & SEQAN3_DOXYGEN_ONLY(bit_score));
190
191 template <typename stream_type,
192 typename header_type,
193 typename seq_type,
194 typename id_type,
195 typename ref_seq_type,
196 typename ref_id_type,
197 typename qual_type,
198 typename mate_type,
199 typename tag_dict_type,
200 typename e_value_type,
201 typename bit_score_type>
202 void write_alignment_record(stream_type & stream,
203 sam_file_output_options const & options,
204 header_type && header,
205 seq_type && seq,
206 qual_type && qual,
207 id_type && id,
208 int32_t const offset,
209 ref_seq_type && SEQAN3_DOXYGEN_ONLY(ref_seq),
210 ref_id_type && ref_id,
211 std::optional<int32_t> ref_offset,
212 std::vector<cigar> const & cigar_vector,
213 sam_flag const flag,
214 uint8_t const mapq,
215 mate_type && mate,
216 tag_dict_type && tag_dict,
217 e_value_type && SEQAN3_DOXYGEN_ONLY(e_value),
218 bit_score_type && SEQAN3_DOXYGEN_ONLY(bit_score));
219
220private:
223
225 static constexpr std::string_view dummy{};
226
229
232
235 {
236 return dummy;
237 }
238
240 template <typename t>
241 decltype(auto) default_or(t && v) const noexcept
242 {
243 return std::forward<t>(v);
244 }
245
246 template <typename stream_view_type, arithmetic value_type>
247 void
248 read_sam_dict_vector(seqan3::detail::sam_tag_variant & variant, stream_view_type && stream_view, value_type value);
249
250 template <typename stream_view_type>
251 void read_sam_byte_vector(seqan3::detail::sam_tag_variant & variant, stream_view_type && stream_view);
252
253 template <typename stream_view_type>
254 void read_sam_dict_field(stream_view_type && stream_view, sam_tag_dictionary & target);
255
256 template <typename stream_it_t, std::ranges::forward_range field_type>
257 void write_range_or_asterisk(stream_it_t & stream_it, field_type && field_value);
258
259 template <typename stream_it_t>
260 void write_range_or_asterisk(stream_it_t & stream_it, char const * const field_value);
261
262 template <typename stream_it_t>
263 void write_tag_fields(stream_it_t & stream, sam_tag_dictionary const & tag_dict, char const separator);
264};
265
267template <typename stream_type, // constraints checked by file
268 typename seq_legal_alph_type,
269 typename stream_pos_type,
270 typename seq_type, // other constraints checked inside function
271 typename id_type,
272 typename qual_type>
273inline void format_sam::read_sequence_record(stream_type & stream,
275 stream_pos_type & position_buffer,
276 seq_type & sequence,
277 id_type & id,
278 qual_type & qualities)
279{
281
282 {
284 align_options,
285 std::ignore,
287 position_buffer,
288 sequence,
289 qualities,
290 id,
291 std::ignore,
292 std::ignore,
293 std::ignore,
294 std::ignore,
295 std::ignore,
296 std::ignore,
297 std::ignore,
298 std::ignore,
299 std::ignore,
300 std::ignore,
301 std::ignore);
302 }
303
304 if constexpr (!detail::decays_to_ignore_v<seq_type>)
305 if (std::ranges::distance(sequence) == 0)
306 throw parse_error{"The sequence information must not be empty."};
307 if constexpr (!detail::decays_to_ignore_v<id_type>)
308 if (std::ranges::distance(id) == 0)
309 throw parse_error{"The id information must not be empty."};
310
311 if (options.truncate_ids)
312 id = id | detail::take_until_and_consume(is_space) | ranges::to<id_type>();
313}
314
316template <typename stream_type, // constraints checked by file
317 typename seq_type, // other constraints checked inside function
318 typename id_type,
319 typename qual_type>
320inline void format_sam::write_sequence_record(stream_type & stream,
321 sequence_file_output_options const & SEQAN3_DOXYGEN_ONLY(options),
322 seq_type && sequence,
323 id_type && id,
324 qual_type && qualities)
325{
326 using default_mate_t = std::tuple<std::string_view, std::optional<int32_t>, int32_t>;
327
328 sam_file_output_options output_options;
329
331 output_options,
332 /*header*/ std::ignore,
333 /*seq*/ default_or(sequence),
334 /*qual*/ default_or(qualities),
335 /*id*/ default_or(id),
336 /*offset*/ 0,
337 /*ref_seq*/ std::string_view{},
338 /*ref_id*/ std::string_view{},
339 /*ref_offset*/ -1,
340 /*cigar_vector*/ std::vector<cigar>{},
341 /*flag*/ sam_flag::none,
342 /*mapq*/ 0,
343 /*mate*/ default_mate_t{},
344 /*tag_dict*/ sam_tag_dictionary{},
345 /*e_value*/ 0,
346 /*bit_score*/ 0);
347}
348
350template <typename stream_type, // constraints checked by file
351 typename seq_legal_alph_type,
352 typename ref_seqs_type,
353 typename ref_ids_type,
354 typename stream_pos_type,
355 typename seq_type,
356 typename id_type,
357 typename offset_type,
358 typename ref_seq_type,
359 typename ref_id_type,
360 typename ref_offset_type,
361 typename cigar_type,
362 typename flag_type,
363 typename mapq_type,
364 typename qual_type,
365 typename mate_type,
366 typename tag_dict_type,
367 typename e_value_type,
368 typename bit_score_type>
369inline void
371 sam_file_input_options<seq_legal_alph_type> const & SEQAN3_DOXYGEN_ONLY(options),
372 ref_seqs_type & ref_seqs,
374 stream_pos_type & position_buffer,
375 seq_type & seq,
376 qual_type & qual,
377 id_type & id,
378 offset_type & offset,
379 ref_seq_type & SEQAN3_DOXYGEN_ONLY(ref_seq),
380 ref_id_type & ref_id,
381 ref_offset_type & ref_offset,
382 cigar_type & cigar_vector,
383 flag_type & flag,
384 mapq_type & mapq,
385 mate_type & mate,
386 tag_dict_type & tag_dict,
387 e_value_type & SEQAN3_DOXYGEN_ONLY(e_value),
388 bit_score_type & SEQAN3_DOXYGEN_ONLY(bit_score))
389{
390 static_assert(detail::decays_to_ignore_v<ref_offset_type>
391 || detail::is_type_specialisation_of_v<ref_offset_type, std::optional>,
392 "The ref_offset must be a specialisation of std::optional.");
393
394 auto stream_view = detail::istreambuf(stream);
395 auto field_view = stream_view | detail::take_until_or_throw_and_consume(is_char<'\t'>);
396
397 int32_t ref_offset_tmp{}; // needed to read the ref_offset (int) beofre storing it in std::optional<uint32_t>
398 std::ranges::range_value_t<decltype(header.ref_ids())> ref_id_tmp{}; // in case mate is requested but ref_offset not
399
400 // Header
401 // -------------------------------------------------------------------------------------------------------------
402 if (is_char<'@'>(*std::ranges::begin(stream_view))) // we always read the header if present
403 {
404 read_header(stream_view, header, ref_seqs);
405
406 if (std::ranges::begin(stream_view) == std::ranges::end(stream_view)) // file has no records
407 return;
408 }
409
410 // Store the current file position in the buffer.
411 position_buffer = stream.tellg();
412
413 // Fields 1-5: ID FLAG REF_ID REF_OFFSET MAPQ
414 // -------------------------------------------------------------------------------------------------------------
415 if constexpr (!detail::decays_to_ignore_v<id_type>)
416 read_forward_range_field(field_view, id);
417 else
418 detail::consume(field_view);
419
420 uint16_t flag_integral{};
421 read_arithmetic_field(field_view, flag_integral);
422 flag = sam_flag{flag_integral};
423
424 read_forward_range_field(field_view, ref_id_tmp);
425 check_and_assign_ref_id(ref_id, ref_id_tmp, header, ref_seqs);
426
427 read_arithmetic_field(field_view, ref_offset_tmp);
428 --ref_offset_tmp; // SAM format is 1-based but SeqAn operates 0-based
429
430 if (ref_offset_tmp == -1)
431 ref_offset = std::nullopt; // indicates an unmapped read -> ref_offset is not set
432 else if (ref_offset_tmp > -1)
433 ref_offset = ref_offset_tmp;
434 else if (ref_offset_tmp < -1)
435 throw format_error{"No negative values are allowed for field::ref_offset."};
436
437 if constexpr (!detail::decays_to_ignore_v<mapq_type>)
438 read_arithmetic_field(field_view, mapq);
439 else
440 detail::consume(field_view);
441
442 // Field 6: CIGAR
443 // -------------------------------------------------------------------------------------------------------------
444 if constexpr (!detail::decays_to_ignore_v<cigar_type>)
445 {
446 if (!is_char<'*'>(*std::ranges::begin(stream_view))) // no cigar information given
447 {
448 int32_t ref_length{}, seq_length{}; // length of aligned part for ref and query
449 std::tie(cigar_vector, ref_length, seq_length) = detail::parse_cigar(field_view);
450 int32_t soft_clipping_end{};
451 int32_t offset_tmp{};
452 transfer_soft_clipping_to(cigar_vector, offset_tmp, soft_clipping_end);
453 offset = offset_tmp;
454 }
455 else
456 {
457 ++std::ranges::begin(field_view); // skip '*'
458 }
459 }
460 else
461 {
462 detail::consume(field_view);
463 }
464
465 // Field 7-9: (RNEXT PNEXT TLEN) = MATE
466 // -------------------------------------------------------------------------------------------------------------
467 if constexpr (!detail::decays_to_ignore_v<mate_type>)
468 {
469 std::ranges::range_value_t<decltype(header.ref_ids())> tmp_mate_ref_id{};
470 read_forward_range_field(field_view, tmp_mate_ref_id); // RNEXT
471
472 if (tmp_mate_ref_id == "=") // indicates "same as ref id"
473 {
474 if constexpr (!detail::decays_to_ignore_v<ref_id_type>)
475 get<0>(mate) = ref_id;
476 else
477 check_and_assign_ref_id(get<0>(mate), ref_id_tmp, header, ref_seqs);
478 }
479 else
480 {
481 check_and_assign_ref_id(get<0>(mate), tmp_mate_ref_id, header, ref_seqs);
482 }
483
484 int32_t tmp_pnext{};
485 read_arithmetic_field(field_view, tmp_pnext); // PNEXT
486
487 if (tmp_pnext > 0)
488 get<1>(mate) = --tmp_pnext; // SAM format is 1-based but SeqAn operates 0-based.
489 else if (tmp_pnext < 0)
490 throw format_error{"No negative values are allowed at the mate mapping position."};
491 // tmp_pnext == 0 indicates an unmapped mate -> do not fill std::optional get<1>(mate)
492
493 read_arithmetic_field(field_view, get<2>(mate)); // TLEN
494 }
495 else
496 {
497 for (size_t i = 0; i < 3u; ++i)
498 {
499 detail::consume(field_view);
500 }
501 }
502
503 // Field 10: Sequence
504 // -------------------------------------------------------------------------------------------------------------
505 if (!is_char<'*'>(*std::ranges::begin(stream_view))) // sequence information is given
506 {
507 constexpr auto is_legal_alph = char_is_valid_for<seq_legal_alph_type>;
508 auto seq_stream =
509 field_view
511 [is_legal_alph](char const c) // enforce legal alphabet
512 {
513 if (!is_legal_alph(c))
514 throw parse_error{std::string{"Encountered an unexpected letter: "} + "char_is_valid_for<"
515 + detail::type_name_as_string<seq_legal_alph_type>
516 + "> evaluated to false on " + detail::make_printable(c)};
517 return c;
518 });
519
520 if constexpr (detail::decays_to_ignore_v<seq_type>)
521 {
522 detail::consume(seq_stream);
523 }
524 else
525 {
526 read_forward_range_field(seq_stream, seq);
527 }
528 }
529 else
530 {
531 ++std::ranges::begin(field_view); // skip '*'
532 }
533
534 // Field 11: Quality
535 // -------------------------------------------------------------------------------------------------------------
536 auto const tab_or_end = is_char<'\t'> || is_char<'\r'> || is_char<'\n'>;
537 auto qual_view = stream_view | detail::take_until_or_throw(tab_or_end);
538 if constexpr (!detail::decays_to_ignore_v<qual_type>)
539 read_forward_range_field(qual_view, qual);
540 else
541 detail::consume(qual_view);
542
543 if constexpr (!detail::decays_to_ignore_v<seq_type> && !detail::decays_to_ignore_v<qual_type>)
544 {
545 if (std::ranges::distance(seq) != 0 && std::ranges::distance(qual) != 0
546 && std::ranges::distance(seq) != std::ranges::distance(qual))
547 {
548 throw format_error{detail::to_string("Sequence length (",
549 std::ranges::distance(seq),
550 ") and quality length (",
551 std::ranges::distance(qual),
552 ") must be the same.")};
553 }
554 }
555
556 // All remaining optional fields if any: SAM tags dictionary
557 // -------------------------------------------------------------------------------------------------------------
558 while (is_char<'\t'>(*std::ranges::begin(stream_view))) // read all tags if present
559 {
560 ++std::ranges::begin(stream_view); // skip tab
561 auto stream_until_tab_or_end = stream_view | detail::take_until_or_throw(tab_or_end);
562 if constexpr (!detail::decays_to_ignore_v<tag_dict_type>)
563 read_sam_dict_field(stream_until_tab_or_end, tag_dict);
564 else
565 detail::consume(stream_until_tab_or_end);
566 }
567
568 detail::consume(stream_view | detail::take_until(!(is_char<'\r'> || is_char<'\n'>))); // consume new line
569}
570
572template <typename stream_type,
573 typename header_type,
574 typename seq_type,
575 typename id_type,
576 typename ref_seq_type,
577 typename ref_id_type,
578 typename qual_type,
579 typename mate_type,
580 typename tag_dict_type,
581 typename e_value_type,
582 typename bit_score_type>
583inline void format_sam::write_alignment_record(stream_type & stream,
584 sam_file_output_options const & options,
585 header_type && header,
586 seq_type && seq,
587 qual_type && qual,
588 id_type && id,
589 int32_t const offset,
590 ref_seq_type && SEQAN3_DOXYGEN_ONLY(ref_seq),
591 ref_id_type && ref_id,
592 std::optional<int32_t> ref_offset,
593 std::vector<cigar> const & cigar_vector,
594 sam_flag const flag,
595 uint8_t const mapq,
596 mate_type && mate,
597 tag_dict_type && tag_dict,
598 e_value_type && SEQAN3_DOXYGEN_ONLY(e_value),
599 bit_score_type && SEQAN3_DOXYGEN_ONLY(bit_score))
600{
601 /* Note the following general things:
602 *
603 * - Given the SAM specifications, all fields may be empty
604 *
605 * - arithmetic values default to 0 while all others default to '*'
606 *
607 * - Because of the former, arithmetic values can be directly streamed
608 * into 'stream' as operator<< is defined for all arithmetic types
609 * and the default value (0) is also the SAM default.
610 *
611 * - All other non-arithmetic values need to be checked for emptiness
612 */
613
614 // ---------------------------------------------------------------------
615 // Type Requirements (as static asserts for user friendliness)
616 // ---------------------------------------------------------------------
617 static_assert((std::ranges::forward_range<seq_type> && alphabet<std::ranges::range_reference_t<seq_type>>),
618 "The seq object must be a std::ranges::forward_range over "
619 "letters that model seqan3::alphabet.");
620
621 static_assert((std::ranges::forward_range<id_type> && alphabet<std::ranges::range_reference_t<id_type>>),
622 "The id object must be a std::ranges::forward_range over "
623 "letters that model seqan3::alphabet.");
624
625 if constexpr (!detail::decays_to_ignore_v<ref_id_type>)
626 {
627 static_assert((std::ranges::forward_range<ref_id_type> || std::integral<std::remove_reference_t<ref_id_type>>
628 || detail::is_type_specialisation_of_v<std::remove_cvref_t<ref_id_type>, std::optional>),
629 "The ref_id object must be a std::ranges::forward_range "
630 "over letters that model seqan3::alphabet.");
631
632 if constexpr (std::integral<std::remove_cvref_t<ref_id_type>>
633 || detail::is_type_specialisation_of_v<std::remove_cvref_t<ref_id_type>, std::optional>)
634 static_assert(!detail::decays_to_ignore_v<header_type>,
635 "If you give indices as reference id information the header must also be present.");
636 }
637
638 static_assert((std::ranges::forward_range<qual_type> && alphabet<std::ranges::range_reference_t<qual_type>>),
639 "The qual object must be a std::ranges::forward_range "
640 "over letters that model seqan3::alphabet.");
641
643 "The mate object must be a std::tuple of size 3 with "
644 "1) a std::ranges::forward_range with a value_type modelling seqan3::alphabet, "
645 "2) a std::integral or std::optional<std::integral>, and "
646 "3) a std::integral.");
647
648 static_assert(
649 ((std::ranges::forward_range<decltype(std::get<0>(mate))>
650 || std::integral<std::remove_cvref_t<decltype(std::get<0>(mate))>>
651 || detail::is_type_specialisation_of_v<
652 std::remove_cvref_t<decltype(std::get<0>(mate))>,
653 std::optional>)&&(std::integral<std::remove_cvref_t<decltype(std::get<1>(mate))>>
654 || detail::is_type_specialisation_of_v<
655 std::remove_cvref_t<decltype(std::get<1>(mate))>,
656 std::optional>)&&std::integral<std::remove_cvref_t<decltype(std::get<2>(mate))>>),
657 "The mate object must be a std::tuple of size 3 with "
658 "1) a std::ranges::forward_range with a value_type modelling seqan3::alphabet, "
659 "2) a std::integral or std::optional<std::integral>, and "
660 "3) a std::integral.");
661
662 if constexpr (std::integral<std::remove_cvref_t<decltype(std::get<0>(mate))>>
663 || detail::is_type_specialisation_of_v<std::remove_cvref_t<decltype(std::get<0>(mate))>,
665 static_assert(!detail::decays_to_ignore_v<header_type>,
666 "If you give indices as mate reference id information the header must also be present.");
667
668 static_assert(std::same_as<std::remove_cvref_t<tag_dict_type>, sam_tag_dictionary>,
669 "The tag_dict object must be of type seqan3::sam_tag_dictionary.");
670
671 // ---------------------------------------------------------------------
672 // logical Requirements
673 // ---------------------------------------------------------------------
674 if constexpr (!detail::decays_to_ignore_v<header_type> && !detail::decays_to_ignore_v<ref_id_type>
675 && !std::integral<std::remove_reference_t<ref_id_type>>
676 && !detail::is_type_specialisation_of_v<std::remove_reference_t<ref_id_type>, std::optional>)
677 {
678
679 if (options.sam_require_header && !std::ranges::empty(ref_id))
680 {
681 auto id_it = header.ref_dict.end();
682
683 if constexpr (std::ranges::contiguous_range<decltype(ref_id)> && std::ranges::sized_range<decltype(ref_id)>
684 && std::ranges::borrowed_range<decltype(ref_id)>)
685 {
686 id_it = header.ref_dict.find(std::span{std::ranges::data(ref_id), std::ranges::size(ref_id)});
687 }
688 else
689 {
690 using header_ref_id_type = std::remove_reference_t<decltype(header.ref_ids()[0])>;
691
693 "The ref_id type is not convertible to the reference id information stored in the "
694 "reference dictionary of the header object.");
695
696 id_it = header.ref_dict.find(ref_id);
697 }
698
699 if (id_it == header.ref_dict.end()) // no reference id matched
700 throw format_error{detail::to_string("The ref_id '",
701 ref_id,
702 "' was not in the list of references:",
703 header.ref_ids())};
704 }
705 }
706
707 if (ref_offset.has_value() && (ref_offset.value() + 1) < 0)
708 throw format_error{"The ref_offset object must be a std::integral >= 0."};
709
710 // ---------------------------------------------------------------------
711 // Writing the Header on first call
712 // ---------------------------------------------------------------------
713 if constexpr (!detail::decays_to_ignore_v<header_type>)
714 {
716 {
717 write_header(stream, options, header);
718 header_was_written = true;
719 }
720 }
721
722 // ---------------------------------------------------------------------
723 // Writing the Record
724 // ---------------------------------------------------------------------
725
726 detail::fast_ostreambuf_iterator stream_it{*stream.rdbuf()};
727 constexpr char separator{'\t'};
728
729 write_range_or_asterisk(stream_it, id);
730 *stream_it = separator;
731
732 stream_it.write_number(static_cast<uint16_t>(flag));
733 *stream_it = separator;
734
735 if constexpr (!detail::decays_to_ignore_v<ref_id_type>)
736 {
737 if constexpr (std::integral<std::remove_reference_t<ref_id_type>>)
738 {
739 write_range_or_asterisk(stream_it, (header.ref_ids())[ref_id]);
740 }
741 else if constexpr (detail::is_type_specialisation_of_v<std::remove_reference_t<ref_id_type>, std::optional>)
742 {
743 if (ref_id.has_value())
744 write_range_or_asterisk(stream_it, (header.ref_ids())[ref_id.value()]);
745 else
746 *stream_it = '*';
747 }
748 else
749 {
751 }
752 }
753 else
754 {
755 *stream_it = '*';
756 }
757
758 *stream_it = separator;
759
760 // SAM is 1 based, 0 indicates unmapped read if optional is not set
761 stream_it.write_number(ref_offset.value_or(-1) + 1);
762 *stream_it = separator;
763
764 stream_it.write_number(static_cast<unsigned>(mapq));
765 *stream_it = separator;
766
767 if (!std::ranges::empty(cigar_vector))
768 {
769 for (auto & c : cigar_vector) //TODO THIS IS PROBABLY TERRIBLE PERFORMANCE_WISE
770 stream_it.write_range(c.to_string());
771 }
772 else
773 {
774 *stream_it = '*';
775 }
776
777 *stream_it = separator;
778
779 if constexpr (std::integral<std::remove_reference_t<decltype(get<0>(mate))>>)
780 {
781 write_range_or_asterisk(stream_it, (header.ref_ids())[get<0>(mate)]);
782 }
783 else if constexpr (detail::is_type_specialisation_of_v<std::remove_reference_t<decltype(get<0>(mate))>,
785 {
786 if (get<0>(mate).has_value())
787 write_range_or_asterisk(stream_it, header.ref_ids()[get<0>(mate).value()]);
788 else
789 *stream_it = '*';
790 }
791 else
792 {
793 write_range_or_asterisk(stream_it, get<0>(mate));
794 }
795
796 *stream_it = separator;
797
798 if constexpr (detail::is_type_specialisation_of_v<std::remove_cvref_t<decltype(get<1>(mate))>, std::optional>)
799 {
800 // SAM is 1 based, 0 indicates unmapped read if optional is not set
801 stream_it.write_number(get<1>(mate).value_or(-1) + 1);
802 *stream_it = separator;
803 }
804 else
805 {
806 stream_it.write_number(get<1>(mate));
807 *stream_it = separator;
808 }
809
810 stream_it.write_number(get<2>(mate));
811 *stream_it = separator;
812
813 write_range_or_asterisk(stream_it, seq);
814 *stream_it = separator;
815
816 write_range_or_asterisk(stream_it, qual);
817
818 write_tag_fields(stream_it, tag_dict, separator);
819
820 stream_it.write_end_of_line(options.add_carriage_return);
821}
822
840template <typename stream_view_type, arithmetic value_type>
842 stream_view_type && stream_view,
843 value_type value)
844{
845 std::vector<value_type> tmp_vector;
846 while (std::ranges::begin(stream_view) != std::ranges::end(stream_view)) // not fully consumed yet
847 {
848 read_arithmetic_field(stream_view | detail::take_until(is_char<','>), value);
849 tmp_vector.push_back(value);
850
851 if (is_char<','>(*std::ranges::begin(stream_view)))
852 ++std::ranges::begin(stream_view); // skip ','
853 }
854 variant = std::move(tmp_vector);
855}
856
870template <typename stream_view_type>
871inline void format_sam::read_sam_byte_vector(seqan3::detail::sam_tag_variant & variant, stream_view_type && stream_view)
872{
873 std::vector<std::byte> tmp_vector;
874 std::byte value;
875
876 while (std::ranges::begin(stream_view) != std::ranges::end(stream_view)) // not fully consumed yet
877 {
878 try
879 {
880 read_byte_field(stream_view | detail::take_exactly_or_throw(2), value);
881 }
882 catch (std::exception const & e)
883 {
884 throw format_error{"Hexadecimal tag has an uneven number of digits!"};
885 }
886
887 tmp_vector.push_back(value);
888 }
889
890 variant = std::move(tmp_vector);
891}
892
910template <typename stream_view_type>
911inline void format_sam::read_sam_dict_field(stream_view_type && stream_view, sam_tag_dictionary & target)
912{
913 /* Every SAM tag has the format "[TAG]:[TYPE_ID]:[VALUE]", where TAG is a two letter
914 name tag which is converted to a unique integer identifier and TYPE_ID is one character in [A,i,Z,H,B,f]
915 describing the type for the upcoming VALUES. If TYPE_ID=='B' it signals an array of comma separated
916 VALUE's and the inner value type is identified by the character following ':', one of [cCsSiIf].
917 */
918 uint16_t tag = static_cast<uint16_t>(*std::ranges::begin(stream_view)) << 8;
919 ++std::ranges::begin(stream_view); // skip char read before
920 tag += static_cast<uint16_t>(*std::ranges::begin(stream_view));
921 ++std::ranges::begin(stream_view); // skip char read before
922 ++std::ranges::begin(stream_view); // skip ':'
923 char type_id = *std::ranges::begin(stream_view);
924 ++std::ranges::begin(stream_view); // skip char read before
925 ++std::ranges::begin(stream_view); // skip ':'
926
927 switch (type_id)
928 {
929 case 'A': // char
930 {
931 target[tag] = static_cast<char>(*std::ranges::begin(stream_view));
932 ++std::ranges::begin(stream_view); // skip char that has been read
933 break;
934 }
935 case 'i': // int32_t
936 {
937 int32_t tmp;
938 read_arithmetic_field(stream_view, tmp);
939 target[tag] = tmp;
940 break;
941 }
942 case 'f': // float
943 {
944 float tmp;
945 read_arithmetic_field(stream_view, tmp);
946 target[tag] = tmp;
947 break;
948 }
949 case 'Z': // string
950 {
951 target[tag] = stream_view | ranges::to<std::string>();
952 break;
953 }
954 case 'H':
955 {
956 read_sam_byte_vector(target[tag], stream_view);
957 break;
958 }
959 case 'B': // Array. Value type depends on second char [cCsSiIf]
960 {
961 char array_value_type_id = *std::ranges::begin(stream_view);
962 ++std::ranges::begin(stream_view); // skip char read before
963 ++std::ranges::begin(stream_view); // skip first ','
964
965 switch (array_value_type_id)
966 {
967 case 'c': // int8_t
968 read_sam_dict_vector(target[tag], stream_view, int8_t{});
969 break;
970 case 'C': // uint8_t
971 read_sam_dict_vector(target[tag], stream_view, uint8_t{});
972 break;
973 case 's': // int16_t
974 read_sam_dict_vector(target[tag], stream_view, int16_t{});
975 break;
976 case 'S': // uint16_t
977 read_sam_dict_vector(target[tag], stream_view, uint16_t{});
978 break;
979 case 'i': // int32_t
980 read_sam_dict_vector(target[tag], stream_view, int32_t{});
981 break;
982 case 'I': // uint32_t
983 read_sam_dict_vector(target[tag], stream_view, uint32_t{});
984 break;
985 case 'f': // float
986 read_sam_dict_vector(target[tag], stream_view, float{});
987 break;
988 default:
989 throw format_error{std::string("The first character in the numerical ")
990 + "id of a SAM tag must be one of [cCsSiIf] but '" + array_value_type_id
991 + "' was given."};
992 }
993 break;
994 }
995 default:
996 throw format_error{std::string("The second character in the numerical id of a "
997 "SAM tag must be one of [A,i,Z,H,B,f] but '")
998 + type_id + "' was given."};
999 }
1000}
1001
1009template <typename stream_it_t, std::ranges::forward_range field_type>
1010inline void format_sam::write_range_or_asterisk(stream_it_t & stream_it, field_type && field_value)
1011{
1012 if (std::ranges::empty(field_value))
1013 {
1014 *stream_it = '*';
1015 }
1016 else
1017 {
1018 if constexpr (std::same_as<std::remove_cvref_t<std::ranges::range_reference_t<field_type>>, char>)
1019 stream_it.write_range(field_value);
1020 else // convert from alphabets to their character representation
1021 stream_it.write_range(field_value | views::to_char);
1022 }
1023}
1024
1031template <typename stream_it_t>
1032inline void format_sam::write_range_or_asterisk(stream_it_t & stream_it, char const * const field_value)
1033{
1034 write_range_or_asterisk(stream_it, std::string_view{field_value});
1035}
1036
1044template <typename stream_it_t>
1045inline void
1046format_sam::write_tag_fields(stream_it_t & stream_it, sam_tag_dictionary const & tag_dict, char const separator)
1047{
1048 auto const stream_variant_fn = [&stream_it](auto && arg) // helper to print a std::variant
1049 {
1050 using T = std::remove_cvref_t<decltype(arg)>;
1051
1052 if constexpr (std::ranges::input_range<T>)
1053 {
1054 if constexpr (std::same_as<std::remove_cvref_t<std::ranges::range_reference_t<T>>, char>)
1055 {
1056 stream_it.write_range(arg);
1057 }
1058 else if constexpr (std::same_as<std::remove_cvref_t<std::ranges::range_reference_t<T>>, std::byte>)
1059 {
1060 if (!std::ranges::empty(arg))
1061 {
1062 stream_it.write_number(std::to_integer<uint8_t>(*std::ranges::begin(arg)));
1063
1064 for (auto && elem : arg | std::views::drop(1))
1065 {
1066 *stream_it = ',';
1067 stream_it.write_number(std::to_integer<uint8_t>(elem));
1068 }
1069 }
1070 }
1071 else
1072 {
1073 if (!std::ranges::empty(arg))
1074 {
1075 stream_it.write_number(*std::ranges::begin(arg));
1076
1077 for (auto && elem : arg | std::views::drop(1))
1078 {
1079 *stream_it = ',';
1080 stream_it.write_number(elem);
1081 }
1082 }
1083 }
1084 }
1085 else if constexpr (std::same_as<std::remove_cvref_t<T>, char>)
1086 {
1087 *stream_it = arg;
1088 }
1089 else // number
1090 {
1091 stream_it.write_number(arg);
1092 }
1093 };
1094
1095 for (auto & [tag, variant] : tag_dict)
1096 {
1097 *stream_it = separator;
1098
1099 char const char0 = tag / 256;
1100 char const char1 = tag % 256;
1101
1102 *stream_it = char0;
1103 *stream_it = char1;
1104 *stream_it = ':';
1105 *stream_it = detail::sam_tag_type_char[variant.index()];
1106 *stream_it = ':';
1107
1108 if (detail::sam_tag_type_char_extra[variant.index()] != '\0')
1109 {
1110 *stream_it = detail::sam_tag_type_char_extra[variant.index()];
1111 *stream_it = ',';
1112 }
1113
1114 std::visit(stream_variant_fn, variant);
1115 }
1116}
1117
1118} // 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:636
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:263
void transfer_soft_clipping_to(std::vector< cigar > const &cigar_vector, int32_t &sc_begin, int32_t &sc_end) const
Transfer soft clipping information from the cigar_vector to sc_begin and sc_end.
Definition: format_sam_base.hpp:150
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:231
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:299
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:203
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:228
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:234
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, int32_t const offset, 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:583
~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:871
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:320
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:1046
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:841
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:911
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:225
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:1010
bool ref_info_present_in_header
Tracks whether reference information (@SR tag) were found in the SAM header.
Definition: format_sam.hpp:231
decltype(auto) default_or(t &&v) const noexcept
brief Returns the input unchanged.
Definition: format_sam.hpp:241
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:273
std::string tmp_qual
Stores quality values temporarily if seq and qual information are combined (not supported by SAM yet)...
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, offset_type &offset, 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:370
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.
@ offset
Sequence (seqan3::field::seq) relative start position (0-based), unsigned value.
@ 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)