SeqAn3 3.4.0-rc.1
The Modern C++ library for sequence analysis.
Loading...
Searching...
No Matches
format_sam.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2006-2024 Knut Reinert & Freie Universität Berlin
2// SPDX-FileCopyrightText: 2016-2024 Knut Reinert & MPI für molekulare Genetik
3// SPDX-License-Identifier: BSD-3-Clause
4
10#pragma once
11
12#include <iterator>
13#include <ranges>
14#include <string>
15#include <vector>
16
35
36namespace seqan3
37{
38
104class format_sam : protected detail::format_sam_base
105{
106public:
110 // construction cannot be noexcept because this class has a std::string variable as a quality string buffer.
111 format_sam() = default;
112 format_sam(format_sam const &) = delete;
113 format_sam & operator=(format_sam const &) = delete;
114 format_sam(format_sam &&) = default;
116 ~format_sam() = default;
117
119
122 {"sam"},
123 };
124
125protected:
126 template <typename stream_type, // constraints checked by file
127 typename seq_legal_alph_type,
128 typename stream_pos_type,
129 typename seq_type, // other constraints checked inside function
130 typename id_type,
131 typename qual_type>
132 void read_sequence_record(stream_type & stream,
134 stream_pos_type & position_buffer,
135 seq_type & sequence,
136 id_type & id,
137 qual_type & qualities);
138
139 template <typename stream_type, // constraints checked by file
140 typename seq_type, // other constraints checked inside function
141 typename id_type,
142 typename qual_type>
143 void write_sequence_record(stream_type & stream,
144 sequence_file_output_options const & SEQAN3_DOXYGEN_ONLY(options),
145 seq_type && sequence,
146 id_type && id,
147 qual_type && qualities);
148
149 template <typename stream_type, // constraints checked by file
150 typename seq_legal_alph_type,
151 typename ref_seqs_type,
152 typename ref_ids_type,
153 typename stream_pos_type,
154 typename seq_type,
155 typename id_type,
156 typename ref_seq_type,
157 typename ref_id_type,
158 typename ref_offset_type,
159 typename cigar_type,
160 typename flag_type,
161 typename mapq_type,
162 typename qual_type,
163 typename mate_type,
164 typename tag_dict_type,
165 typename e_value_type,
166 typename bit_score_type>
167 void read_alignment_record(stream_type & stream,
169 ref_seqs_type & ref_seqs,
171 stream_pos_type & position_buffer,
172 seq_type & seq,
173 qual_type & qual,
174 id_type & id,
175 ref_seq_type & SEQAN3_DOXYGEN_ONLY(ref_seq),
176 ref_id_type & ref_id,
177 ref_offset_type & ref_offset,
178 cigar_type & cigar_vector,
179 flag_type & flag,
180 mapq_type & mapq,
181 mate_type & mate,
182 tag_dict_type & tag_dict,
183 e_value_type & SEQAN3_DOXYGEN_ONLY(e_value),
184 bit_score_type & SEQAN3_DOXYGEN_ONLY(bit_score));
185
186 template <typename stream_type,
187 typename header_type,
188 typename seq_type,
189 typename id_type,
190 typename ref_seq_type,
191 typename ref_id_type,
192 typename qual_type,
193 typename mate_type,
194 typename tag_dict_type,
195 typename e_value_type,
196 typename bit_score_type>
197 void write_alignment_record(stream_type & stream,
198 sam_file_output_options const & options,
199 header_type && header,
200 seq_type && seq,
201 qual_type && qual,
202 id_type && id,
203 ref_seq_type && SEQAN3_DOXYGEN_ONLY(ref_seq),
204 ref_id_type && ref_id,
206 std::vector<cigar> const & cigar_vector,
207 sam_flag const flag,
208 uint8_t const mapq,
209 mate_type && mate,
210 tag_dict_type && tag_dict,
211 e_value_type && SEQAN3_DOXYGEN_ONLY(e_value),
212 bit_score_type && SEQAN3_DOXYGEN_ONLY(bit_score));
213
214private:
216 std::string tmp_qual{};
217
219 static constexpr std::string_view dummy{};
220
222 sam_file_header<> default_header{};
223
226
228 std::string_view const & default_or(detail::ignore_t) const noexcept
229 {
230 return dummy;
231 }
232
234 template <typename t>
235 decltype(auto) default_or(t && v) const noexcept
236 {
237 return std::forward<t>(v);
238 }
239
240 template <arithmetic value_type>
241 void read_sam_dict_vector(seqan3::detail::sam_tag_variant & variant, std::string_view const str, value_type value);
242
243 void read_sam_byte_vector(seqan3::detail::sam_tag_variant & variant, std::string_view const str);
244
245 void read_sam_dict(std::string_view const tag_str, sam_tag_dictionary & target);
246
247 template <typename stream_it_t, std::ranges::forward_range field_type>
248 void write_range_or_asterisk(stream_it_t & stream_it, field_type && field_value);
249
250 template <typename stream_it_t>
251 void write_range_or_asterisk(stream_it_t & stream_it, char const * const field_value);
252
253 template <typename stream_it_t>
254 void write_tag_fields(stream_it_t & stream, sam_tag_dictionary const & tag_dict, char const separator);
255};
256
258template <typename stream_type, // constraints checked by file
259 typename seq_legal_alph_type,
260 typename stream_pos_type,
261 typename seq_type, // other constraints checked inside function
262 typename id_type,
263 typename qual_type>
264inline void format_sam::read_sequence_record(stream_type & stream,
266 stream_pos_type & position_buffer,
267 seq_type & sequence,
268 id_type & id,
269 qual_type & qualities)
270{
272
273 {
275 align_options,
276 std::ignore,
277 default_header,
278 position_buffer,
279 sequence,
280 qualities,
281 id,
282 std::ignore,
283 std::ignore,
284 std::ignore,
285 std::ignore,
286 std::ignore,
287 std::ignore,
288 std::ignore,
289 std::ignore,
290 std::ignore,
291 std::ignore);
292 }
293
294 if constexpr (!detail::decays_to_ignore_v<seq_type>)
295 if (std::ranges::distance(sequence) == 0)
296 throw parse_error{"The sequence information must not be empty."};
297 if constexpr (!detail::decays_to_ignore_v<id_type>)
298 {
299 if (std::ranges::distance(id) == 0)
300 throw parse_error{"The id information must not be empty."};
301 if (options.truncate_ids)
302 id = id | detail::take_until_and_consume(is_space) | ranges::to<id_type>();
303 }
304}
305
307template <typename stream_type, // constraints checked by file
308 typename seq_type, // other constraints checked inside function
309 typename id_type,
310 typename qual_type>
311inline void format_sam::write_sequence_record(stream_type & stream,
312 sequence_file_output_options const & SEQAN3_DOXYGEN_ONLY(options),
313 seq_type && sequence,
314 id_type && id,
315 qual_type && qualities)
316{
317 using default_mate_t = std::tuple<std::string_view, std::optional<int32_t>, int32_t>;
318
319 sam_file_output_options output_options;
320
322 output_options,
323 /*header*/ std::ignore,
324 /*seq*/ default_or(sequence),
325 /*qual*/ default_or(qualities),
326 /*id*/ default_or(id),
327 /*ref_seq*/ std::string_view{},
328 /*ref_id*/ std::string_view{},
329 /*ref_offset*/ -1,
330 /*cigar_vector*/ std::vector<cigar>{},
331 /*flag*/ sam_flag::none,
332 /*mapq*/ 0,
333 /*mate*/ default_mate_t{},
334 /*tag_dict*/ sam_tag_dictionary{},
335 /*e_value*/ 0,
336 /*bit_score*/ 0);
337}
338
340template <typename stream_type, // constraints checked by file
341 typename seq_legal_alph_type,
342 typename ref_seqs_type,
343 typename ref_ids_type,
344 typename stream_pos_type,
345 typename seq_type,
346 typename id_type,
347 typename ref_seq_type,
348 typename ref_id_type,
349 typename ref_offset_type,
350 typename cigar_type,
351 typename flag_type,
352 typename mapq_type,
353 typename qual_type,
354 typename mate_type,
355 typename tag_dict_type,
356 typename e_value_type,
357 typename bit_score_type>
358inline void format_sam::read_alignment_record(stream_type & stream,
360 ref_seqs_type & ref_seqs,
362 stream_pos_type & position_buffer,
363 seq_type & seq,
364 qual_type & qual,
365 id_type & id,
366 ref_seq_type & SEQAN3_DOXYGEN_ONLY(ref_seq),
367 ref_id_type & ref_id,
368 ref_offset_type & ref_offset,
369 cigar_type & cigar_vector,
370 flag_type & flag,
371 mapq_type & mapq,
372 mate_type & mate,
373 tag_dict_type & tag_dict,
374 e_value_type & SEQAN3_DOXYGEN_ONLY(e_value),
375 bit_score_type & SEQAN3_DOXYGEN_ONLY(bit_score))
376{
377 static_assert(detail::decays_to_ignore_v<ref_offset_type>
378 || detail::is_type_specialisation_of_v<ref_offset_type, std::optional>,
379 "The ref_offset must be a specialisation of std::optional.");
380
381 auto stream_it = detail::fast_istreambuf_iterator{*stream.rdbuf()};
382
383 auto stream_view = detail::istreambuf(stream);
384
385 int32_t ref_offset_tmp{}; // needed to read the ref_offset (int) beofre storing it in std::optional<uint32_t>
386 std::ranges::range_value_t<decltype(header.ref_ids())> ref_id_tmp{}; // in case mate is requested but ref_offset not
387
388 // Header
389 // -------------------------------------------------------------------------------------------------------------
390 if (is_char<'@'>(*stream_it)) // we always read the header if present
391 {
392 read_header(stream_view, header, ref_seqs, options);
393
394 if (std::ranges::begin(stream_view) == std::ranges::end(stream_view)) // file has no records
395 return;
396 }
397
398 // Store the current file position in the buffer.
399 position_buffer = stream.tellg();
400
401 // We don't know wether we have 11 or 12 fields, since the tags are optional.
402 // The last field will thus contain either the quality sequence
403 // or the quality sequence AND tags. This will be handled at the respective fields below.
404 stream_it.cache_record_into('\n', '\t', raw_record);
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(raw_record[0], id);
410
411 uint16_t flag_integral{};
412 read_arithmetic_field(raw_record[1], flag_integral);
413 flag = sam_flag{flag_integral};
414
415 read_forward_range_field(raw_record[2], ref_id_tmp);
416 check_and_assign_ref_id(ref_id, ref_id_tmp, header, ref_seqs);
417
418 read_arithmetic_field(raw_record[3], ref_offset_tmp);
419 --ref_offset_tmp; // SAM format is 1-based but SeqAn operates 0-based
420
421 if (ref_offset_tmp == -1)
422 ref_offset = std::nullopt; // indicates an unmapped read -> ref_offset is not set
423 else if (ref_offset_tmp > -1)
424 ref_offset = ref_offset_tmp;
425 else if (ref_offset_tmp < -1)
426 throw format_error{"No negative values are allowed for field::ref_offset."};
427
428 if constexpr (!detail::decays_to_ignore_v<mapq_type>)
429 read_arithmetic_field(raw_record[4], mapq);
430
431 // Field 6: CIGAR
432 // -------------------------------------------------------------------------------------------------------------
433 if constexpr (!detail::decays_to_ignore_v<cigar_type>)
434 cigar_vector = detail::parse_cigar(raw_record[5]);
435
436 // Field 7-9: (RNEXT PNEXT TLEN) = MATE
437 // -------------------------------------------------------------------------------------------------------------
438 if constexpr (!detail::decays_to_ignore_v<mate_type>)
439 {
440 std::ranges::range_value_t<decltype(header.ref_ids())> tmp_mate_ref_id{};
441 read_forward_range_field(raw_record[6], tmp_mate_ref_id); // RNEXT
442
443 if (tmp_mate_ref_id == "=") // indicates "same as ref id"
444 {
445 if constexpr (!detail::decays_to_ignore_v<ref_id_type>)
446 get<0>(mate) = ref_id;
447 else
448 check_and_assign_ref_id(get<0>(mate), ref_id_tmp, header, ref_seqs);
449 }
450 else
451 {
452 check_and_assign_ref_id(get<0>(mate), tmp_mate_ref_id, header, ref_seqs);
453 }
454
455 int32_t tmp_pnext{};
456 read_arithmetic_field(raw_record[7], tmp_pnext); // PNEXT
457
458 if (tmp_pnext > 0)
459 get<1>(mate) = --tmp_pnext; // SAM format is 1-based but SeqAn operates 0-based.
460 else if (tmp_pnext < 0)
461 throw format_error{"No negative values are allowed at the mate mapping position."};
462 // tmp_pnext == 0 indicates an unmapped mate -> do not fill std::optional get<1>(mate)
463
464 read_arithmetic_field(raw_record[8], get<2>(mate)); // TLEN
465 }
466
467 // Field 10: Sequence
468 // -------------------------------------------------------------------------------------------------------------
469 if constexpr (!detail::decays_to_ignore_v<seq_type>)
470 {
471 std::string_view const seq_str = raw_record[9];
472
473 if (!seq_str.starts_with('*')) // * indicates missing sequence information
474 {
475 seq.resize(seq_str.size());
476 constexpr auto is_legal_alph = char_is_valid_for<seq_legal_alph_type>;
477
478 for (size_t i = 0; i < seq_str.size(); ++i)
479 {
480 if (!is_legal_alph(seq_str[i]))
481 throw parse_error{std::string{"Encountered an unexpected letter: "} + "char_is_valid_for<"
482 + detail::type_name_as_string<seq_legal_alph_type>
483 + "> evaluated to false on " + detail::make_printable(seq_str[i])};
484
485 seq[i] = assign_char_to(seq_str[i], std::ranges::range_value_t<seq_type>{});
486 }
487 }
488 }
489
490 // Field 11: Quality
491 // -------------------------------------------------------------------------------------------------------------
492 // We don't know wether we have 11 or 12 fields, since the tags are optional.
493 // The last field will thus contain either the quality sequence
494 // or the quality sequence AND tags.
495 size_t tag_begin_pos = raw_record[10].find('\t');
496
497 std::string_view qualities =
498 (tag_begin_pos == std::string_view::npos) ? raw_record[10] : raw_record[10].substr(0, tag_begin_pos);
499
500 if constexpr (!detail::decays_to_ignore_v<qual_type>)
501 read_forward_range_field(qualities, qual);
502
503 if constexpr (!detail::decays_to_ignore_v<seq_type> && !detail::decays_to_ignore_v<qual_type>)
504 {
505 if (std::ranges::distance(seq) != 0 && std::ranges::distance(qual) != 0
506 && std::ranges::distance(seq) != std::ranges::distance(qual))
507 {
508 throw format_error{detail::to_string("Sequence length (",
509 std::ranges::distance(seq),
510 ") and quality length (",
511 std::ranges::distance(qual),
512 ") must be the same.")};
513 }
514 }
515
516 // All remaining optional fields if any: SAM tags dictionary
517 // -------------------------------------------------------------------------------------------------------------
518 if constexpr (!detail::decays_to_ignore_v<tag_dict_type>)
519 {
520 while (tag_begin_pos != std::string_view::npos) // read all tags if present
521 {
522 ++tag_begin_pos; // skip '\t'
523 size_t const tag_end_pos = raw_record[10].find('\t', tag_begin_pos);
524
525 char const * tag_begin = raw_record[10].begin() + tag_begin_pos;
526 char const * tag_end =
527 (tag_end_pos == std::string_view::npos) ? raw_record[10].end() : raw_record[10].begin() + tag_end_pos;
528
529 read_sam_dict(std::string_view{tag_begin, tag_end}, tag_dict);
530
531 tag_begin_pos = tag_end_pos;
532 }
533 }
534
535 assert(stream_it == std::default_sentinel_t{} || *stream_it == '\n');
536 ++stream_it; // Move from end of record to the beginning of the next or to the end of the stream.
537}
538
540template <typename stream_type,
541 typename header_type,
542 typename seq_type,
543 typename id_type,
544 typename ref_seq_type,
545 typename ref_id_type,
546 typename qual_type,
547 typename mate_type,
548 typename tag_dict_type,
549 typename e_value_type,
550 typename bit_score_type>
551inline void format_sam::write_alignment_record(stream_type & stream,
552 sam_file_output_options const & options,
553 header_type && header,
554 seq_type && seq,
555 qual_type && qual,
556 id_type && id,
557 ref_seq_type && SEQAN3_DOXYGEN_ONLY(ref_seq),
558 ref_id_type && ref_id,
560 std::vector<cigar> const & cigar_vector,
561 sam_flag const flag,
562 uint8_t const mapq,
563 mate_type && mate,
564 tag_dict_type && tag_dict,
565 e_value_type && SEQAN3_DOXYGEN_ONLY(e_value),
566 bit_score_type && SEQAN3_DOXYGEN_ONLY(bit_score))
567{
568 /* Note the following general things:
569 *
570 * - Given the SAM specifications, all fields may be empty
571 *
572 * - arithmetic values default to 0 while all others default to '*'
573 *
574 * - Because of the former, arithmetic values can be directly streamed
575 * into 'stream' as operator<< is defined for all arithmetic types
576 * and the default value (0) is also the SAM default.
577 *
578 * - All other non-arithmetic values need to be checked for emptiness
579 */
580
581 // ---------------------------------------------------------------------
582 // Type Requirements (as static asserts for user friendliness)
583 // ---------------------------------------------------------------------
584 static_assert((std::ranges::forward_range<seq_type> && alphabet<std::ranges::range_reference_t<seq_type>>),
585 "The seq object must be a std::ranges::forward_range over "
586 "letters that model seqan3::alphabet.");
587
588 static_assert((std::ranges::forward_range<id_type> && alphabet<std::ranges::range_reference_t<id_type>>),
589 "The id object must be a std::ranges::forward_range over "
590 "letters that model seqan3::alphabet.");
591
592 if constexpr (!detail::decays_to_ignore_v<ref_id_type>)
593 {
594 static_assert((std::ranges::forward_range<ref_id_type> || std::integral<std::remove_reference_t<ref_id_type>>
595 || detail::is_type_specialisation_of_v<std::remove_cvref_t<ref_id_type>, std::optional>),
596 "The ref_id object must be a std::ranges::forward_range "
597 "over letters that model seqan3::alphabet.");
598
599 if constexpr (std::integral<std::remove_cvref_t<ref_id_type>>
600 || detail::is_type_specialisation_of_v<std::remove_cvref_t<ref_id_type>, std::optional>)
601 static_assert(!detail::decays_to_ignore_v<header_type>,
602 "If you give indices as reference id information the header must also be present.");
603 }
604
605 static_assert((std::ranges::forward_range<qual_type> && alphabet<std::ranges::range_reference_t<qual_type>>),
606 "The qual object must be a std::ranges::forward_range "
607 "over letters that model seqan3::alphabet.");
608
610 "The mate object must be a std::tuple of size 3 with "
611 "1) a std::ranges::forward_range with a value_type modelling seqan3::alphabet, "
612 "2) a std::integral or std::optional<std::integral>, and "
613 "3) a std::integral.");
614
615 static_assert(
616 ((std::ranges::forward_range<decltype(std::get<0>(mate))>
617 || std::integral<std::remove_cvref_t<decltype(std::get<0>(mate))>>
618 || detail::is_type_specialisation_of_v<std::remove_cvref_t<decltype(std::get<0>(mate))>, std::optional>)
619 && (std::integral<std::remove_cvref_t<decltype(std::get<1>(mate))>>
620 || detail::is_type_specialisation_of_v<std::remove_cvref_t<decltype(std::get<1>(mate))>, std::optional>)
621 && std::integral<std::remove_cvref_t<decltype(std::get<2>(mate))>>),
622 "The mate object must be a std::tuple of size 3 with "
623 "1) a std::ranges::forward_range with a value_type modelling seqan3::alphabet, "
624 "2) a std::integral or std::optional<std::integral>, and "
625 "3) a std::integral.");
626
627 if constexpr (std::integral<std::remove_cvref_t<decltype(std::get<0>(mate))>>
628 || detail::is_type_specialisation_of_v<std::remove_cvref_t<decltype(std::get<0>(mate))>,
630 static_assert(!detail::decays_to_ignore_v<header_type>,
631 "If you give indices as mate reference id information the header must also be present.");
632
633 static_assert(std::same_as<std::remove_cvref_t<tag_dict_type>, sam_tag_dictionary>,
634 "The tag_dict object must be of type seqan3::sam_tag_dictionary.");
635
636 // ---------------------------------------------------------------------
637 // logical Requirements
638 // ---------------------------------------------------------------------
639 if constexpr (!detail::decays_to_ignore_v<header_type> && !detail::decays_to_ignore_v<ref_id_type>
640 && !std::integral<std::remove_reference_t<ref_id_type>>
641 && !detail::is_type_specialisation_of_v<std::remove_reference_t<ref_id_type>, std::optional>)
642 {
643
644 if (options.sam_require_header && !std::ranges::empty(ref_id))
645 {
646 auto id_it = header.ref_dict.end();
647
648 if constexpr (std::ranges::contiguous_range<decltype(ref_id)> && std::ranges::sized_range<decltype(ref_id)>
649 && std::ranges::borrowed_range<decltype(ref_id)>)
650 {
651 id_it = header.ref_dict.find(std::span{std::ranges::data(ref_id), std::ranges::size(ref_id)});
652 }
653 else
654 {
655 using header_ref_id_type = std::remove_reference_t<decltype(header.ref_ids()[0])>;
656
658 "The ref_id type is not convertible to the reference id information stored in the "
659 "reference dictionary of the header object.");
660
661 id_it = header.ref_dict.find(ref_id);
662 }
663
664 if (id_it == header.ref_dict.end()) // no reference id matched
665 throw format_error{detail::to_string("The ref_id '",
666 ref_id,
667 "' was not in the list of references:",
668 header.ref_ids())};
669 }
670 }
671
672 if (ref_offset.has_value() && (ref_offset.value() + 1) < 0)
673 throw format_error{"The ref_offset object must be a std::integral >= 0."};
674
675 // ---------------------------------------------------------------------
676 // Writing the Header on first call
677 // ---------------------------------------------------------------------
678 if constexpr (!detail::decays_to_ignore_v<header_type>)
679 {
680 if (options.sam_require_header && !header_was_written)
681 {
682 write_header(stream, options, header);
683 header_was_written = true;
684 }
685 }
686
687 // ---------------------------------------------------------------------
688 // Writing the Record
689 // ---------------------------------------------------------------------
690
691 detail::fast_ostreambuf_iterator stream_it{*stream.rdbuf()};
692 constexpr char separator{'\t'};
693
694 write_range_or_asterisk(stream_it, id);
695 *stream_it = separator;
696
697 stream_it.write_number(static_cast<uint16_t>(flag));
698 *stream_it = separator;
699
700 if constexpr (!detail::decays_to_ignore_v<ref_id_type>)
701 {
702 if constexpr (std::integral<std::remove_reference_t<ref_id_type>>)
703 {
704 write_range_or_asterisk(stream_it, (header.ref_ids())[ref_id]);
705 }
706 else if constexpr (detail::is_type_specialisation_of_v<std::remove_reference_t<ref_id_type>, std::optional>)
707 {
708 if (ref_id.has_value())
709 write_range_or_asterisk(stream_it, (header.ref_ids())[ref_id.value()]);
710 else
711 *stream_it = '*';
712 }
713 else
714 {
715 write_range_or_asterisk(stream_it, ref_id);
716 }
717 }
718 else
719 {
720 *stream_it = '*';
721 }
722
723 *stream_it = separator;
724
725 // SAM is 1 based, 0 indicates unmapped read if optional is not set
726 stream_it.write_number(ref_offset.value_or(-1) + 1);
727 *stream_it = separator;
728
729 stream_it.write_number(static_cast<unsigned>(mapq));
730 *stream_it = separator;
731
732 if (!std::ranges::empty(cigar_vector))
733 {
734 for (auto & c : cigar_vector) //TODO THIS IS PROBABLY TERRIBLE PERFORMANCE_WISE
735 stream_it.write_range(c.to_string());
736 }
737 else
738 {
739 *stream_it = '*';
740 }
741
742 *stream_it = separator;
743
744 if constexpr (std::integral<std::remove_reference_t<decltype(get<0>(mate))>>)
745 {
746 write_range_or_asterisk(stream_it, (header.ref_ids())[get<0>(mate)]);
747 }
748 else if constexpr (detail::is_type_specialisation_of_v<std::remove_reference_t<decltype(get<0>(mate))>,
750 {
751 if (get<0>(mate).has_value())
752 write_range_or_asterisk(stream_it, header.ref_ids()[get<0>(mate).value()]);
753 else
754 *stream_it = '*';
755 }
756 else
757 {
758 write_range_or_asterisk(stream_it, get<0>(mate));
759 }
760
761 *stream_it = separator;
762
763 if constexpr (detail::is_type_specialisation_of_v<std::remove_cvref_t<decltype(get<1>(mate))>, std::optional>)
764 {
765 // SAM is 1 based, 0 indicates unmapped read if optional is not set
766 stream_it.write_number(get<1>(mate).value_or(-1) + 1);
767 *stream_it = separator;
768 }
769 else
770 {
771 stream_it.write_number(get<1>(mate));
772 *stream_it = separator;
773 }
774
775 stream_it.write_number(get<2>(mate));
776 *stream_it = separator;
777
778 write_range_or_asterisk(stream_it, seq);
779 *stream_it = separator;
780
781 write_range_or_asterisk(stream_it, qual);
782
783 write_tag_fields(stream_it, tag_dict, separator);
784
785 stream_it.write_end_of_line(options.add_carriage_return);
786}
787
804template <arithmetic value_type>
805inline void format_sam::read_sam_dict_vector(seqan3::detail::sam_tag_variant & variant,
806 std::string_view const str,
807 value_type value)
808{
809 std::vector<value_type> tmp_vector{};
810 size_t start_pos{0};
811 size_t end_pos{0};
812
813 while (start_pos != std::string_view::npos)
814 {
815 end_pos = str.find(',', start_pos);
816 auto end = (end_pos == std::string_view::npos) ? str.end() : str.begin() + end_pos;
817 read_arithmetic_field(std::string_view{str.begin() + start_pos, end}, value);
818 tmp_vector.push_back(value);
819
820 start_pos = (end_pos == std::string_view::npos) ? end_pos : end_pos + 1;
821 }
822 variant = std::move(tmp_vector);
823}
824
836inline void format_sam::read_sam_byte_vector(seqan3::detail::sam_tag_variant & variant, std::string_view const str)
837{
838 std::vector<std::byte> tmp_vector{};
839 // std::from_chars cannot directly parse into a std::byte
840 uint8_t dummy_byte{};
841
842 if (str.size() % 2 != 0)
843 throw format_error{"[CORRUPTED SAM FILE] Hexadecimal tag must have even number of digits."};
844
845 // H encodes bytes in a hexadecimal format. Two hex values are stored for each byte as characters.
846 // E.g., '1' and 'A' need one byte each and are read as `\x1A`, which is 27 in decimal.
847 for (auto hex_begin = str.begin(), hex_end = str.begin() + 2; hex_begin != str.end(); hex_begin += 2, hex_end += 2)
848 {
849 auto res = std::from_chars(hex_begin, hex_end, dummy_byte, 16);
850
851 if (res.ec == std::errc::invalid_argument)
852 throw format_error{std::string("[CORRUPTED SAM FILE] The string '") + std::string(hex_begin, hex_end)
853 + "' could not be cast into type uint8_t."};
854
855 if (res.ec == std::errc::result_out_of_range)
856 throw format_error{std::string("[CORRUPTED SAM FILE] Casting '") + std::string(str)
857 + "' into type uint8_t would cause an overflow."};
858
859 tmp_vector.push_back(std::byte{dummy_byte});
860 }
861
862 variant = std::move(tmp_vector);
863}
864
880inline void format_sam::read_sam_dict(std::string_view const tag_str, sam_tag_dictionary & target)
881{
882 /* Every SAM tag has the format "[TAG]:[TYPE_ID]:[VALUE]", where TAG is a two letter
883 name tag which is converted to a unique integer identifier and TYPE_ID is one character in [A,i,Z,H,B,f]
884 describing the type for the upcoming VALUES. If TYPE_ID=='B' it signals an array of comma separated
885 VALUE's and the inner value type is identified by the character following ':', one of [cCsSiIf].
886 */
887 assert(tag_str.size() > 5);
888
889 uint16_t tag = static_cast<uint16_t>(tag_str[0]) << 8;
890 tag += static_cast<uint16_t>(tag_str[1]);
891
892 char type_id = tag_str[3];
893
894 switch (type_id)
895 {
896 case 'A': // char
897 {
898 assert(tag_str.size() == 6);
899 target[tag] = tag_str[5];
900 break;
901 }
902 case 'i': // int32_t
903 {
904 int32_t tmp;
905 read_arithmetic_field(tag_str.substr(5), tmp);
906 target[tag] = tmp;
907 break;
908 }
909 case 'f': // float
910 {
911 float tmp;
912 read_arithmetic_field(tag_str.substr(5), tmp);
913 target[tag] = tmp;
914 break;
915 }
916 case 'Z': // string
917 {
918 target[tag] = std::string{tag_str.substr(5)};
919 break;
920 }
921 case 'H':
922 {
923 read_sam_byte_vector(target[tag], tag_str.substr(5));
924 break;
925 }
926 case 'B': // Array. Value type depends on second char [cCsSiIf]
927 {
928 assert(tag_str.size() > 6);
929 char array_value_type_id = tag_str[5];
930
931 switch (array_value_type_id)
932 {
933 case 'c': // int8_t
934 read_sam_dict_vector(target[tag], tag_str.substr(7), int8_t{});
935 break;
936 case 'C': // uint8_t
937 read_sam_dict_vector(target[tag], tag_str.substr(7), uint8_t{});
938 break;
939 case 's': // int16_t
940 read_sam_dict_vector(target[tag], tag_str.substr(7), int16_t{});
941 break;
942 case 'S': // uint16_t
943 read_sam_dict_vector(target[tag], tag_str.substr(7), uint16_t{});
944 break;
945 case 'i': // int32_t
946 read_sam_dict_vector(target[tag], tag_str.substr(7), int32_t{});
947 break;
948 case 'I': // uint32_t
949 read_sam_dict_vector(target[tag], tag_str.substr(7), uint32_t{});
950 break;
951 case 'f': // float
952 read_sam_dict_vector(target[tag], tag_str.substr(7), float{});
953 break;
954 default:
955 throw format_error{std::string("The first character in the numerical ")
956 + "id of a SAM tag must be one of [cCsSiIf] but '" + array_value_type_id
957 + "' was given."};
958 }
959 break;
960 }
961 default:
962 throw format_error{std::string("The second character in the numerical id of a "
963 "SAM tag ([TAG]:[TYPE_ID]:[VALUE]) must be one of [A,i,Z,H,B,f] but '")
964 + type_id + "' was given."};
965 }
966}
967
975template <typename stream_it_t, std::ranges::forward_range field_type>
976inline void format_sam::write_range_or_asterisk(stream_it_t & stream_it, field_type && field_value)
977{
978 if (std::ranges::empty(field_value))
979 {
980 *stream_it = '*';
981 }
982 else
983 {
984 if constexpr (std::same_as<std::remove_cvref_t<std::ranges::range_reference_t<field_type>>, char>)
985 stream_it.write_range(field_value);
986 else // convert from alphabets to their character representation
987 stream_it.write_range(field_value | views::to_char);
988 }
989}
990
997template <typename stream_it_t>
998inline void format_sam::write_range_or_asterisk(stream_it_t & stream_it, char const * const field_value)
999{
1000 write_range_or_asterisk(stream_it, std::string_view{field_value});
1001}
1002
1010template <typename stream_it_t>
1011inline void
1012format_sam::write_tag_fields(stream_it_t & stream_it, sam_tag_dictionary const & tag_dict, char const separator)
1013{
1014 auto const stream_variant_fn = [&stream_it](auto && arg) // helper to print a std::variant
1015 {
1016 using T = std::remove_cvref_t<decltype(arg)>;
1017
1018 if constexpr (std::ranges::input_range<T>)
1019 {
1020 if constexpr (std::same_as<std::remove_cvref_t<std::ranges::range_reference_t<T>>, char>)
1021 {
1022 stream_it.write_range(arg);
1023 }
1024 else if constexpr (std::same_as<std::remove_cvref_t<std::ranges::range_reference_t<T>>, std::byte>)
1025 {
1026 if (!std::ranges::empty(arg))
1027 {
1028 stream_it.write_number(std::to_integer<uint8_t>(*std::ranges::begin(arg)));
1029
1030 for (auto && elem : arg | std::views::drop(1))
1031 {
1032 *stream_it = ',';
1033 stream_it.write_number(std::to_integer<uint8_t>(elem));
1034 }
1035 }
1036 }
1037 else
1038 {
1039 if (!std::ranges::empty(arg))
1040 {
1041 stream_it.write_number(*std::ranges::begin(arg));
1042
1043 for (auto && elem : arg | std::views::drop(1))
1044 {
1045 *stream_it = ',';
1046 stream_it.write_number(elem);
1047 }
1048 }
1049 }
1050 }
1051 else if constexpr (std::same_as<std::remove_cvref_t<T>, char>)
1052 {
1053 *stream_it = arg;
1054 }
1055 else // number
1056 {
1057 stream_it.write_number(arg);
1058 }
1059 };
1060
1061 for (auto & [tag, variant] : tag_dict)
1062 {
1063 *stream_it = separator;
1064
1065 char const char0 = tag / 256;
1066 char const char1 = tag % 256;
1067
1068 *stream_it = char0;
1069 *stream_it = char1;
1070 *stream_it = ':';
1071 *stream_it = detail::sam_tag_type_char[variant.index()];
1072 *stream_it = ':';
1073
1074 if (detail::sam_tag_type_char_extra[variant.index()] != '\0')
1075 {
1076 *stream_it = detail::sam_tag_type_char_extra[variant.index()];
1077 *stream_it = ',';
1078 }
1079
1080 std::visit(stream_variant_fn, variant);
1081 }
1082}
1083
1084} // namespace seqan3
Core alphabet concept and free function/type trait wrappers.
T begin(T... args)
The SAM format (tag).
Definition format_sam.hpp:105
~format_sam()=default
Defaulted.
format_sam & operator=(format_sam const &)=delete
Deleted. Header holds a unique_ptr.
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:121
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:311
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:551
format_sam(format_sam &&)=default
Defaulted.
format_sam & operator=(format_sam &&)=default
Defaulted.
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:358
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:264
format_sam(format_sam const &)=delete
Deleted. Header holds a unique_ptr.
format_sam()=default
Defaulted.
Stores the header information of SAM/BAM files.
Definition header.hpp:46
ref_ids_type & ref_ids()
The range of reference ids.
Definition header.hpp:140
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:179
The SAM tag dictionary class that stores all optional SAM fields.
Definition sam_tag_dictionary.hpp:327
T end(T... args)
Provides seqan3::detail::fast_ostreambuf_iterator.
T find(T... args)
Provides the seqan3::format_sam_base that can be inherited from.
T from_chars(T... args)
auto const to_char
A view that calls seqan3::to_char() on each element in the input range.
Definition to_char.hpp:60
constexpr auto assign_char_to
Assign a character to an alphabet object.
Definition alphabet/concept.hpp:517
sam_flag
An enum flag that describes the properties of an aligned read (given as a SAM record).
Definition sam_flag.hpp:73
@ none
None of the flags below are set.
@ flag
The alignment flag (bit information), uint16_t value.
@ ref_offset
Sequence (seqan3::field::ref_seq) relative start position (0-based), unsigned value.
@ ref_seq
The (reference) "sequence" information, usually a range of nucleotides or amino acids.
@ mapq
The mapping quality of the seqan3::field::seq alignment, usually a Phred-scaled score.
@ bit_score
The bit score (statistical significance indicator), 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.
constexpr auto is_char
Checks whether a given letter is the same as the template non-type argument.
Definition predicate.hpp:60
constexpr auto is_space
Checks whether c is a space character.
Definition predicate.hpp:122
seqan::stl::ranges::to to
Converts a range to a container. <dl class="no-api">This entity is not part of the SeqAn API....
Definition to.hpp:23
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:392
Provides the seqan3::sam_file_header class.
T index(T... args)
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.
The main SeqAn3 namespace.
Definition aligned_sequence_concept.hpp:26
SeqAn specific customisations in the standard namespace.
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.
T size(T... args)
Provides seqan3::views::slice.
T starts_with(T... args)
Thrown if information given to output format didn't match expectations.
Definition io/exception.hpp:88
Thrown if there is a parse error, such as reading an unexpected character from an input stream.
Definition io/exception.hpp:45
The options type defines various option members that influence the behaviour of all or some formats.
Definition sam_file/input_options.hpp:26
The options type defines various option members that influence the behavior of all or some formats.
Definition sam_file/output_options.hpp:23
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:27
bool sam_require_header
Whether to require a header for SAM files.
Definition sam_file/output_options.hpp:41
The options type defines various option members that influence the behaviour of all or some formats.
Definition sequence_file/input_options.hpp:24
bool truncate_ids
Read the ID string only up until the first whitespace character.
Definition sequence_file/input_options.hpp:26
The options type defines various option members that influence the behaviour of all or some formats.
Definition sequence_file/output_options.hpp:23
T substr(T... args)
Provides seqan3::views::take_until and seqan3::views::take_until_or_throw.
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)
Hide me