SeqAn3  3.0.3
The Modern C++ library for sequence analysis.
format_sam.hpp
Go to the documentation of this file.
1 // -----------------------------------------------------------------------------------------------------
2 // Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin
3 // Copyright (c) 2016-2020, 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 <seqan3/std/algorithm>
16 #include <seqan3/std/concepts>
17 #include <iterator>
18 #include <seqan3/std/ranges>
19 #include <string>
20 #include <vector>
21 
51 
52 namespace seqan3
53 {
54 
127 class format_sam : private detail::format_sam_base
128 {
129 public:
133  // construction cannot be noexcept because this class has a std::string variable as a quality string buffer.
134  format_sam() = default;
135  format_sam(format_sam const &) = default;
136  format_sam & operator=(format_sam const &) = default;
137  format_sam(format_sam &&) = default;
138  format_sam & operator=(format_sam &&) = default;
139  ~format_sam() = default;
141 
144  {
145  { "sam" },
146  };
147 
148 protected:
149  template <typename stream_type, // constraints checked by file
150  typename seq_legal_alph_type, bool seq_qual_combined,
151  typename seq_type, // other constraints checked inside function
152  typename id_type,
153  typename qual_type>
154  void read_sequence_record(stream_type & stream,
156  seq_type & sequence,
157  id_type & id,
158  qual_type & qualities);
159 
160  template <typename stream_type, // constraints checked by file
161  typename seq_type, // other constraints checked inside function
162  typename id_type,
163  typename qual_type>
164  void write_sequence_record(stream_type & stream,
165  sequence_file_output_options const & SEQAN3_DOXYGEN_ONLY(options),
166  seq_type && sequence,
167  id_type && id,
168  qual_type && qualities);
169 
170  template <typename stream_type, // constraints checked by file
171  typename seq_legal_alph_type,
172  typename ref_seqs_type,
173  typename ref_ids_type,
174  typename seq_type,
175  typename id_type,
176  typename offset_type,
177  typename ref_seq_type,
178  typename ref_id_type,
179  typename ref_offset_type,
180  typename align_type,
181  typename cigar_type,
182  typename flag_type,
183  typename mapq_type,
184  typename qual_type,
185  typename mate_type,
186  typename tag_dict_type,
187  typename e_value_type,
188  typename bit_score_type>
189  void read_alignment_record(stream_type & stream,
190  alignment_file_input_options<seq_legal_alph_type> const & SEQAN3_DOXYGEN_ONLY(options),
191  ref_seqs_type & ref_seqs,
193  seq_type & seq,
194  qual_type & qual,
195  id_type & id,
196  offset_type & offset,
197  ref_seq_type & SEQAN3_DOXYGEN_ONLY(ref_seq),
198  ref_id_type & ref_id,
199  ref_offset_type & ref_offset,
200  align_type & align,
201  cigar_type & cigar_vector,
202  flag_type & flag,
203  mapq_type & mapq,
204  mate_type & mate,
205  tag_dict_type & tag_dict,
206  e_value_type & SEQAN3_DOXYGEN_ONLY(e_value),
207  bit_score_type & SEQAN3_DOXYGEN_ONLY(bit_score));
208 
209  template <typename stream_type,
210  typename header_type,
211  typename seq_type,
212  typename id_type,
213  typename ref_seq_type,
214  typename ref_id_type,
215  typename align_type,
216  typename qual_type,
217  typename mate_type,
218  typename tag_dict_type,
219  typename e_value_type,
220  typename bit_score_type>
221  void write_alignment_record(stream_type & stream,
222  alignment_file_output_options const & options,
223  header_type && header,
224  seq_type && seq,
225  qual_type && qual,
226  id_type && id,
227  int32_t const offset,
228  ref_seq_type && SEQAN3_DOXYGEN_ONLY(ref_seq),
229  ref_id_type && ref_id,
230  std::optional<int32_t> ref_offset,
231  align_type && align,
232  std::vector<cigar> const & cigar_vector,
233  sam_flag const flag,
234  uint8_t const mapq,
235  mate_type && mate,
236  tag_dict_type && tag_dict,
237  e_value_type && SEQAN3_DOXYGEN_ONLY(e_value),
238  bit_score_type && SEQAN3_DOXYGEN_ONLY(bit_score));
239 
240 private:
242  std::string tmp_qual{};
243 
245  static constexpr std::string_view dummy{};
246 
248  alignment_file_header<> default_header{};
249 
251  bool ref_info_present_in_header{false};
252 
254  std::string_view const & default_or(detail::ignore_t) const noexcept
255  {
256  return dummy;
257  }
258 
260  template <typename t>
261  decltype(auto) default_or(t && v) const noexcept
262  {
263  return std::forward<t>(v);
264  }
265 
266  using format_sam_base::read_field; // inherit read_field functions from format_base explicitly
267 
268  template <typename stream_view_type, typename value_type>
269  void read_sam_dict_vector(seqan3::detail::sam_tag_variant & variant,
270  stream_view_type && stream_view,
271  value_type value);
272 
273  template <typename stream_view_type>
274  void read_field(stream_view_type && stream_view, sam_tag_dictionary & target);
275 
276  template <typename stream_it_t, std::ranges::forward_range field_type>
277  void write_range_or_asterisk(stream_it_t & stream_it, field_type && field_value);
278 
279  template <typename stream_it_t>
280  void write_range_or_asterisk(stream_it_t & stream_it, char const * const field_value);
281 
282  template <typename stream_it_t>
283  void write_tag_fields(stream_it_t & stream, sam_tag_dictionary const & tag_dict, char const separator);
284 };
285 
287 template <typename stream_type, // constraints checked by file
288  typename seq_legal_alph_type, bool seq_qual_combined,
289  typename seq_type, // other constraints checked inside function
290  typename id_type,
291  typename qual_type>
292 inline void format_sam::read_sequence_record(stream_type & stream,
294  seq_type & sequence,
295  id_type & id,
296  qual_type & qualities)
297 {
299 
300  if constexpr (seq_qual_combined)
301  {
302  tmp_qual.clear();
303  read_alignment_record(stream, align_options, std::ignore, default_header, sequence, tmp_qual, id,
304  std::ignore, std::ignore, std::ignore, std::ignore, std::ignore, std::ignore,
305  std::ignore, std::ignore, std::ignore, std::ignore, std::ignore, std::ignore);
306 
307  for (auto sit = tmp_qual.begin(), dit = std::ranges::begin(sequence); sit != tmp_qual.end(); ++sit, ++dit)
308  get<1>(*dit).assign_char(*sit);
309  }
310  else
311  {
312  read_alignment_record(stream, align_options, std::ignore, default_header, sequence, qualities, id,
313  std::ignore, std::ignore, std::ignore, std::ignore, std::ignore, std::ignore,
314  std::ignore, std::ignore, std::ignore, std::ignore, std::ignore, std::ignore);
315  }
316 
317  if constexpr (!detail::decays_to_ignore_v<seq_type>)
318  if (std::ranges::distance(sequence) == 0)
319  throw parse_error{"The sequence information must not be empty."};
320  if constexpr (!detail::decays_to_ignore_v<id_type>)
321  if (std::ranges::distance(id) == 0)
322  throw parse_error{"The id information must not be empty."};
323 
324  if (options.truncate_ids)
325  id = id | views::take_until_and_consume(is_space) | views::to<id_type>;
326 }
327 
329 template <typename stream_type, // constraints checked by file
330  typename seq_type, // other constraints checked inside function
331  typename id_type,
332  typename qual_type>
333 inline void format_sam::write_sequence_record(stream_type & stream,
334  sequence_file_output_options const & SEQAN3_DOXYGEN_ONLY(options),
335  seq_type && sequence,
336  id_type && id,
337  qual_type && qualities)
338 {
339  using default_align_t = std::pair<std::span<gapped<char>>, std::span<gapped<char>>>;
340  using default_mate_t = std::tuple<std::string_view, std::optional<int32_t>, int32_t>;
341 
342  alignment_file_output_options output_options;
343 
344  write_alignment_record(stream,
345  output_options,
346  /*header*/ std::ignore,
347  /*seq*/ default_or(sequence),
348  /*qual*/ default_or(qualities),
349  /*id*/ default_or(id),
350  /*offset*/ 0,
351  /*ref_seq*/ std::string_view{},
352  /*ref_id*/ std::string_view{},
353  /*ref_offset*/ -1,
354  /*align*/ default_align_t{},
355  /*cigar_vector*/ std::vector<cigar>{},
356  /*flag*/ sam_flag::none,
357  /*mapq*/ 0,
358  /*mate*/ default_mate_t{},
359  /*tag_dict*/ sam_tag_dictionary{},
360  /*e_value*/ 0,
361  /*bit_score*/ 0);
362 }
363 
365 template <typename stream_type, // constraints checked by file
366  typename seq_legal_alph_type,
367  typename ref_seqs_type,
368  typename ref_ids_type,
369  typename seq_type,
370  typename id_type,
371  typename offset_type,
372  typename ref_seq_type,
373  typename ref_id_type,
374  typename ref_offset_type,
375  typename align_type,
376  typename cigar_type,
377  typename flag_type,
378  typename mapq_type,
379  typename qual_type,
380  typename mate_type,
381  typename tag_dict_type,
382  typename e_value_type,
383  typename bit_score_type>
384 inline void format_sam::read_alignment_record(stream_type & stream,
385  alignment_file_input_options<seq_legal_alph_type> const & SEQAN3_DOXYGEN_ONLY(options),
386  ref_seqs_type & ref_seqs,
388  seq_type & seq,
389  qual_type & qual,
390  id_type & id,
391  offset_type & offset,
392  ref_seq_type & SEQAN3_DOXYGEN_ONLY(ref_seq),
393  ref_id_type & ref_id,
394  ref_offset_type & ref_offset,
395  align_type & align,
396  cigar_type & cigar_vector,
397  flag_type & flag,
398  mapq_type & mapq,
399  mate_type & mate,
400  tag_dict_type & tag_dict,
401  e_value_type & SEQAN3_DOXYGEN_ONLY(e_value),
402  bit_score_type & SEQAN3_DOXYGEN_ONLY(bit_score))
403 {
404  static_assert(detail::decays_to_ignore_v<ref_offset_type> ||
405  detail::is_type_specialisation_of_v<ref_offset_type, std::optional>,
406  "The ref_offset must be a specialisation of std::optional.");
407 
408  auto stream_view = views::istreambuf(stream);
409  auto field_view = stream_view | views::take_until_or_throw_and_consume(is_char<'\t'>);
410 
411  // these variables need to be stored to compute the ALIGNMENT
412  int32_t ref_offset_tmp{};
413  std::ranges::range_value_t<decltype(header.ref_ids())> ref_id_tmp{};
414  [[maybe_unused]] int32_t offset_tmp{};
415  [[maybe_unused]] int32_t soft_clipping_end{};
416  [[maybe_unused]] std::vector<cigar> tmp_cigar_vector{};
417  [[maybe_unused]] int32_t ref_length{0}, seq_length{0}; // length of aligned part for ref and query
418 
419  // Header
420  // -------------------------------------------------------------------------------------------------------------
421  if (is_char<'@'>(*std::ranges::begin(stream_view))) // we always read the header if present
422  {
423  read_header(stream_view, header, ref_seqs);
424 
425  if (std::ranges::begin(stream_view) == std::ranges::end(stream_view)) // file has no records
426  return;
427  }
428 
429  // Fields 1-5: ID FLAG REF_ID REF_OFFSET MAPQ
430  // -------------------------------------------------------------------------------------------------------------
431  read_field(field_view, id);
432 
433  uint16_t flag_integral{};
434  read_field(field_view, flag_integral);
435  flag = sam_flag{flag_integral};
436 
437  read_field(field_view, ref_id_tmp);
438  check_and_assign_ref_id(ref_id, ref_id_tmp, header, ref_seqs);
439 
440  read_field(field_view, ref_offset_tmp);
441  --ref_offset_tmp; // SAM format is 1-based but SeqAn operates 0-based
442 
443  if (ref_offset_tmp == -1)
444  ref_offset = std::nullopt; // indicates an unmapped read -> ref_offset is not set
445  else if (ref_offset_tmp > -1)
446  ref_offset = ref_offset_tmp;
447  else if (ref_offset_tmp < -1)
448  throw format_error{"No negative values are allowed for field::ref_offset."};
449 
450  read_field(field_view, mapq);
451 
452  // Field 6: CIGAR
453  // -------------------------------------------------------------------------------------------------------------
454  if constexpr (!detail::decays_to_ignore_v<align_type> || !detail::decays_to_ignore_v<cigar_type>)
455  {
456  if (!is_char<'*'>(*std::ranges::begin(stream_view))) // no cigar information given
457  {
458  std::tie(tmp_cigar_vector, ref_length, seq_length) = parse_cigar(field_view);
459  transfer_soft_clipping_to(tmp_cigar_vector, offset_tmp, soft_clipping_end);
460  // the actual cigar_vector is swapped with tmp_cigar_vector at the end to avoid copying
461  }
462  else
463  {
464  std::ranges::next(std::ranges::begin(field_view)); // skip '*'
465  }
466  }
467  else
468  {
469  detail::consume(field_view);
470  }
471 
472  offset = offset_tmp;
473 
474  // Field 7-9: (RNEXT PNEXT TLEN) = MATE
475  // -------------------------------------------------------------------------------------------------------------
476  if constexpr (!detail::decays_to_ignore_v<mate_type>)
477  {
478  std::ranges::range_value_t<decltype(header.ref_ids())> tmp_mate_ref_id{};
479  read_field(field_view, tmp_mate_ref_id); // RNEXT
480 
481  if (tmp_mate_ref_id == "=") // indicates "same as ref id"
482  {
483  if constexpr (!detail::decays_to_ignore_v<ref_id_type>)
484  get<0>(mate) = ref_id;
485  else
486  check_and_assign_ref_id(get<0>(mate), ref_id_tmp, header, ref_seqs);
487  }
488  else
489  {
490  check_and_assign_ref_id(get<0>(mate), tmp_mate_ref_id, header, ref_seqs);
491  }
492 
493  int32_t tmp_pnext{};
494  read_field(field_view, tmp_pnext); // PNEXT
495 
496  if (tmp_pnext > 0)
497  get<1>(mate) = --tmp_pnext; // SAM format is 1-based but SeqAn operates 0-based.
498  else if (tmp_pnext < 0)
499  throw format_error{"No negative values are allowed at the mate mapping position."};
500  // tmp_pnext == 0 indicates an unmapped mate -> do not fill std::optional get<1>(mate)
501 
502  read_field(field_view, get<2>(mate)); // TLEN
503  }
504  else
505  {
506  for (size_t i = 0; i < 3u; ++i)
507  {
508  detail::consume(field_view);
509  }
510  }
511 
512  // Field 10: Sequence
513  // -------------------------------------------------------------------------------------------------------------
514  if (!is_char<'*'>(*std::ranges::begin(stream_view))) // sequence information is given
515  {
516  auto constexpr is_legal_alph = char_is_valid_for<seq_legal_alph_type>;
517  auto seq_stream = field_view | std::views::transform([is_legal_alph] (char const c) // enforce legal alphabet
518  {
519  if (!is_legal_alph(c))
520  throw parse_error{std::string{"Encountered an unexpected letter: "} +
521  "char_is_valid_for<" +
522  detail::type_name_as_string<seq_legal_alph_type> +
523  "> evaluated to false on " +
524  detail::make_printable(c)};
525  return c;
526  });
527 
528  if constexpr (detail::decays_to_ignore_v<seq_type>)
529  {
530  if constexpr (!detail::decays_to_ignore_v<align_type>)
531  {
532  static_assert(sequence_container<std::remove_reference_t<decltype(get<1>(align))>>,
533  "If you want to read ALIGNMENT but not SEQ, the alignment"
534  " object must store a sequence container at the second (query) position.");
535 
536  if (!tmp_cigar_vector.empty()) // only parse alignment if cigar information was given
537  {
538 
539  auto tmp_iter = std::ranges::begin(seq_stream);
540  std::ranges::advance(tmp_iter, offset_tmp);
541 
542  for (; seq_length > 0; --seq_length) // seq_length is not needed anymore
543  {
544  get<1>(align).push_back(std::ranges::range_value_t<decltype(get<1>(align))>{}.assign_char(*tmp_iter));
545  ++tmp_iter;
546  }
547 
548  std::ranges::advance(tmp_iter, soft_clipping_end);
549  }
550  else
551  {
552  get<1>(align) = std::remove_reference_t<decltype(get<1>(align))>{}; // empty container
553  }
554  }
555  else
556  {
557  detail::consume(seq_stream);
558  }
559  }
560  else
561  {
562  read_field(seq_stream, seq);
563 
564  if constexpr (!detail::decays_to_ignore_v<align_type>)
565  {
566  if (!tmp_cigar_vector.empty()) // if no alignment info is given, the field::alignment should remain empty
567  {
568  assign_unaligned(get<1>(align),
569  seq | views::slice(static_cast<decltype(std::ranges::size(seq))>(offset_tmp),
570  std::ranges::size(seq) - soft_clipping_end));
571  }
572  }
573  }
574  }
575  else
576  {
577  std::ranges::next(std::ranges::begin(field_view)); // skip '*'
578  }
579 
580  // Field 11: Quality
581  // -------------------------------------------------------------------------------------------------------------
582  auto const tab_or_end = is_char<'\t'> || is_char<'\r'> || is_char<'\n'>;
583  read_field(stream_view | views::take_until_or_throw(tab_or_end), qual);
584 
585  if constexpr (!detail::decays_to_ignore_v<seq_type> && !detail::decays_to_ignore_v<qual_type>)
586  {
587  if (std::ranges::distance(seq) != 0 && std::ranges::distance(qual) != 0 &&
588  std::ranges::distance(seq) != std::ranges::distance(qual))
589  {
590  throw format_error{detail::to_string("Sequence length (", std::ranges::distance(seq),
591  ") and quality length (", std::ranges::distance(qual),
592  ") must be the same.")};
593  }
594  }
595 
596  // All remaining optional fields if any: SAM tags dictionary
597  // -------------------------------------------------------------------------------------------------------------
598  while (is_char<'\t'>(*std::ranges::begin(stream_view))) // read all tags if present
599  {
600  std::ranges::next(std::ranges::begin(stream_view)); // skip tab
601  read_field(stream_view | views::take_until_or_throw(tab_or_end), tag_dict);
602  }
603 
604  detail::consume(stream_view | views::take_until(!(is_char<'\r'> || is_char<'\n'>))); // consume new line
605 
606  // DONE READING - wrap up
607  // -------------------------------------------------------------------------------------------------------------
608  // Alignment object construction
609  // Note that the query sequence in get<1>(align) has already been filled while reading Field 10.
610  if constexpr (!detail::decays_to_ignore_v<align_type>)
611  {
612  int32_t ref_idx{(ref_id_tmp.empty()/*unmapped read?*/) ? -1 : 0};
613 
614  if constexpr (!detail::decays_to_ignore_v<ref_seqs_type>)
615  {
616  if (!ref_id_tmp.empty())
617  {
618  assert(header.ref_dict.count(ref_id_tmp) != 0); // taken care of in check_and_assign_ref_id()
619  ref_idx = header.ref_dict[ref_id_tmp]; // get index for reference sequence
620  }
621  }
622 
623  construct_alignment(align, tmp_cigar_vector, ref_idx, ref_seqs, ref_offset_tmp, ref_length);
624  }
625 
626  if constexpr (!detail::decays_to_ignore_v<cigar_type>)
627  std::swap(cigar_vector, tmp_cigar_vector);
628 }
629 
631 template <typename stream_type,
632  typename header_type,
633  typename seq_type,
634  typename id_type,
635  typename ref_seq_type,
636  typename ref_id_type,
637  typename align_type,
638  typename qual_type,
639  typename mate_type,
640  typename tag_dict_type,
641  typename e_value_type,
642  typename bit_score_type>
643 inline void format_sam::write_alignment_record(stream_type & stream,
644  alignment_file_output_options const & options,
645  header_type && header,
646  seq_type && seq,
647  qual_type && qual,
648  id_type && id,
649  int32_t const offset,
650  ref_seq_type && SEQAN3_DOXYGEN_ONLY(ref_seq),
651  ref_id_type && ref_id,
652  std::optional<int32_t> ref_offset,
653  align_type && align,
654  std::vector<cigar> const & cigar_vector,
655  sam_flag const flag,
656  uint8_t const mapq,
657  mate_type && mate,
658  tag_dict_type && tag_dict,
659  e_value_type && SEQAN3_DOXYGEN_ONLY(e_value),
660  bit_score_type && SEQAN3_DOXYGEN_ONLY(bit_score))
661 {
662  /* Note the following general things:
663  *
664  * - Given the SAM specifications, all fields may be empty
665  *
666  * - arithmetic values default to 0 while all others default to '*'
667  *
668  * - Because of the former, arithmetic values can be directly streamed
669  * into 'stream' as operator<< is defined for all arithmetic types
670  * and the default value (0) is also the SAM default.
671  *
672  * - All other non-arithmetic values need to be checked for emptiness
673  */
674 
675  // ---------------------------------------------------------------------
676  // Type Requirements (as static asserts for user friendliness)
677  // ---------------------------------------------------------------------
678  static_assert((std::ranges::forward_range<seq_type> &&
679  alphabet<std::ranges::range_reference_t<seq_type>>),
680  "The seq object must be a std::ranges::forward_range over "
681  "letters that model seqan3::alphabet.");
682 
683  static_assert((std::ranges::forward_range<id_type> &&
684  alphabet<std::ranges::range_reference_t<id_type>>),
685  "The id object must be a std::ranges::forward_range over "
686  "letters that model seqan3::alphabet.");
687 
688  if constexpr (!detail::decays_to_ignore_v<ref_id_type>)
689  {
690  static_assert((std::ranges::forward_range<ref_id_type> ||
691  std::integral<std::remove_reference_t<ref_id_type>> ||
692  detail::is_type_specialisation_of_v<std::remove_cvref_t<ref_id_type>, std::optional>),
693  "The ref_id object must be a std::ranges::forward_range "
694  "over letters that model seqan3::alphabet.");
695 
696  if constexpr (std::integral<std::remove_cvref_t<ref_id_type>> ||
697  detail::is_type_specialisation_of_v<std::remove_cvref_t<ref_id_type>, std::optional>)
698  static_assert(!detail::decays_to_ignore_v<header_type>,
699  "If you give indices as reference id information the header must also be present.");
700  }
701 
703  "The align object must be a std::pair of two ranges whose "
704  "value_type is comparable to seqan3::gap");
705 
706  static_assert((std::tuple_size_v<std::remove_cvref_t<align_type>> == 2 &&
707  std::equality_comparable_with<gap, std::ranges::range_reference_t<decltype(std::get<0>(align))>> &&
708  std::equality_comparable_with<gap, std::ranges::range_reference_t<decltype(std::get<1>(align))>>),
709  "The align object must be a std::pair of two ranges whose "
710  "value_type is comparable to seqan3::gap");
711 
712  static_assert((std::ranges::forward_range<qual_type> &&
713  alphabet<std::ranges::range_reference_t<qual_type>>),
714  "The qual object must be a std::ranges::forward_range "
715  "over letters that model seqan3::alphabet.");
716 
718  "The mate object must be a std::tuple of size 3 with "
719  "1) a std::ranges::forward_range with a value_type modelling seqan3::alphabet, "
720  "2) a std::integral or std::optional<std::integral>, and "
721  "3) a std::integral.");
722 
723  static_assert(((std::ranges::forward_range<decltype(std::get<0>(mate))> ||
724  std::integral<std::remove_cvref_t<decltype(std::get<0>(mate))>> ||
725  detail::is_type_specialisation_of_v<std::remove_cvref_t<decltype(std::get<0>(mate))>, std::optional>) &&
726  (std::integral<std::remove_cvref_t<decltype(std::get<1>(mate))>> ||
727  detail::is_type_specialisation_of_v<std::remove_cvref_t<decltype(std::get<1>(mate))>, std::optional>) &&
728  std::integral<std::remove_cvref_t<decltype(std::get<2>(mate))>>),
729  "The mate object must be a std::tuple of size 3 with "
730  "1) a std::ranges::forward_range with a value_type modelling seqan3::alphabet, "
731  "2) a std::integral or std::optional<std::integral>, and "
732  "3) a std::integral.");
733 
734  if constexpr (std::integral<std::remove_cvref_t<decltype(std::get<0>(mate))>> ||
735  detail::is_type_specialisation_of_v<std::remove_cvref_t<decltype(std::get<0>(mate))>, std::optional>)
736  static_assert(!detail::decays_to_ignore_v<header_type>,
737  "If you give indices as mate reference id information the header must also be present.");
738 
739  static_assert(std::same_as<std::remove_cvref_t<tag_dict_type>, sam_tag_dictionary>,
740  "The tag_dict object must be of type seqan3::sam_tag_dictionary.");
741 
742  // ---------------------------------------------------------------------
743  // logical Requirements
744  // ---------------------------------------------------------------------
745  if constexpr (!detail::decays_to_ignore_v<header_type> &&
746  !detail::decays_to_ignore_v<ref_id_type> &&
747  !std::integral<std::remove_reference_t<ref_id_type>> &&
748  !detail::is_type_specialisation_of_v<std::remove_reference_t<ref_id_type>, std::optional>)
749  {
750 
751  if (options.sam_require_header && !std::ranges::empty(ref_id))
752  {
753  auto id_it = header.ref_dict.end();
754 
755  if constexpr (std::ranges::contiguous_range<decltype(ref_id)> &&
756  std::ranges::sized_range<decltype(ref_id)> &&
757  std::ranges::borrowed_range<decltype(ref_id)>)
758  {
759  id_it = header.ref_dict.find(std::span{std::ranges::data(ref_id), std::ranges::size(ref_id)});
760  }
761  else
762  {
763  using header_ref_id_type = std::remove_reference_t<decltype(header.ref_ids()[0])>;
764 
766  "The ref_id type is not convertible to the reference id information stored in the "
767  "reference dictionary of the header object.");
768 
769  id_it = header.ref_dict.find(ref_id);
770  }
771 
772  if (id_it == header.ref_dict.end()) // no reference id matched
773  throw format_error{detail::to_string("The ref_id '", ref_id, "' was not in the list of references:",
774  header.ref_ids())};
775  }
776  }
777 
778  if (ref_offset.has_value() && (ref_offset.value() + 1) < 0)
779  throw format_error{"The ref_offset object must be an std::integral >= 0."};
780 
781  // ---------------------------------------------------------------------
782  // Writing the Header on first call
783  // ---------------------------------------------------------------------
784  if constexpr (!detail::decays_to_ignore_v<header_type>)
785  {
786  if (options.sam_require_header && !header_was_written)
787  {
788  write_header(stream, options, header);
789  header_was_written = true;
790  }
791  }
792 
793  // ---------------------------------------------------------------------
794  // Writing the Record
795  // ---------------------------------------------------------------------
796 
797  detail::fast_ostreambuf_iterator stream_it{*stream.rdbuf()};
798  constexpr char separator{'\t'};
799 
800  write_range_or_asterisk(stream_it, id);
801  *stream_it = separator;
802 
803  stream_it.write_number(static_cast<uint16_t>(flag));
804  *stream_it = separator;
805 
806  if constexpr (!detail::decays_to_ignore_v<ref_id_type>)
807  {
808  if constexpr (std::integral<std::remove_reference_t<ref_id_type>>)
809  {
810  write_range_or_asterisk(stream_it, (header.ref_ids())[ref_id]);
811  }
812  else if constexpr (detail::is_type_specialisation_of_v<std::remove_reference_t<ref_id_type>, std::optional>)
813  {
814  if (ref_id.has_value())
815  write_range_or_asterisk(stream_it, (header.ref_ids())[ref_id.value()]);
816  else
817  *stream_it = '*';
818  }
819  else
820  {
821  write_range_or_asterisk(stream_it, ref_id);
822  }
823  }
824  else
825  {
826  *stream_it = '*';
827  }
828 
829  *stream_it = separator;
830 
831  // SAM is 1 based, 0 indicates unmapped read if optional is not set
832  stream_it.write_number(ref_offset.value_or(-1) + 1);
833  *stream_it = separator;
834 
835  stream_it.write_number(static_cast<unsigned>(mapq));
836  *stream_it = separator;
837 
838  if (!std::ranges::empty(cigar_vector))
839  {
840  for (auto & c : cigar_vector) //TODO THIS IS PROBABLY TERRIBLE PERFORMANCE_WISE
841  stream_it.write_range(c.to_string());
842  }
843  else if (!std::ranges::empty(get<0>(align)) && !std::ranges::empty(get<1>(align)))
844  {
845  // compute possible distance from alignment end to sequence end
846  // which indicates soft clipping at the end.
847  // This should be replace by a free count_gaps function for
848  // aligned sequences which is more efficient if possible.
849  size_t off_end{std::ranges::size(seq) - offset};
850  for (auto chr : get<1>(align))
851  if (chr == gap{})
852  ++off_end;
853 
854  // Might happen if get<1>(align) doesn't correspond to the reference.
855  assert(off_end >= std::ranges::size(get<1>(align)));
856  off_end -= std::ranges::size(get<1>(align));
857 
858  write_range_or_asterisk(stream_it, detail::get_cigar_string(align, offset, off_end));
859  }
860  else
861  {
862  *stream_it = '*';
863  }
864 
865  *stream_it = separator;
866 
867  if constexpr (std::integral<std::remove_reference_t<decltype(get<0>(mate))>>)
868  {
869  write_range_or_asterisk(stream_it, (header.ref_ids())[get<0>(mate)]);
870  }
871  else if constexpr (detail::is_type_specialisation_of_v<std::remove_reference_t<decltype(get<0>(mate))>, std::optional>)
872  {
873  if (get<0>(mate).has_value())
874  // value_or(0) instead of value() (which is equivalent here) as a
875  // workaround for a ubsan false-positive in GCC8: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90058
876  write_range_or_asterisk(stream_it, header.ref_ids()[get<0>(mate).value_or(0)]);
877  else
878  *stream_it = '*';
879  }
880  else
881  {
882  write_range_or_asterisk(stream_it, get<0>(mate));
883  }
884 
885  *stream_it = separator;
886 
887  if constexpr (detail::is_type_specialisation_of_v<std::remove_cvref_t<decltype(get<1>(mate))>, std::optional>)
888  {
889  // SAM is 1 based, 0 indicates unmapped read if optional is not set
890  stream_it.write_number(get<1>(mate).value_or(-1) + 1);
891  *stream_it = separator;
892  }
893  else
894  {
895  stream_it.write_number(get<1>(mate));
896  *stream_it = separator;
897  }
898 
899  stream_it.write_number(get<2>(mate));
900  *stream_it = separator;
901 
902  write_range_or_asterisk(stream_it, seq);
903  *stream_it = separator;
904 
905  write_range_or_asterisk(stream_it, qual);
906 
907  write_tag_fields(stream_it, tag_dict, separator);
908 
909  stream_it.write_end_of_line(options.add_carriage_return);
910 }
911 
912 
930 template <typename stream_view_type, typename value_type>
931 inline void format_sam::read_sam_dict_vector(seqan3::detail::sam_tag_variant & variant,
932  stream_view_type && stream_view,
933  value_type value)
934 {
935  std::vector<value_type> tmp_vector;
936  while (std::ranges::begin(stream_view) != ranges::end(stream_view)) // not fully consumed yet
937  {
938  read_field(stream_view | views::take_until(is_char<','>), value);
939  tmp_vector.push_back(value);
940 
941  if (is_char<','>(*std::ranges::begin(stream_view)))
942  std::ranges::next(std::ranges::begin(stream_view)); // skip ','
943  }
944  variant = std::move(tmp_vector);
945 }
946 
964 template <typename stream_view_type>
965 inline void format_sam::read_field(stream_view_type && stream_view, sam_tag_dictionary & target)
966 {
967  /* Every SAM tag has the format "[TAG]:[TYPE_ID]:[VALUE]", where TAG is a two letter
968  name tag which is converted to a unique integer identifier and TYPE_ID is one character in [A,i,Z,H,B,f]
969  describing the type for the upcoming VALUES. If TYPE_ID=='B' it signals an array of comma separated
970  VALUE's and the inner value type is identified by the character following ':', one of [cCsSiIf].
971  */
972  uint16_t tag = static_cast<uint16_t>(*std::ranges::begin(stream_view)) << 8;
973  std::ranges::next(std::ranges::begin(stream_view)); // skip char read before
974  tag += static_cast<uint16_t>(*std::ranges::begin(stream_view));
975  std::ranges::next(std::ranges::begin(stream_view)); // skip char read before
976  std::ranges::next(std::ranges::begin(stream_view)); // skip ':'
977  char type_id = *std::ranges::begin(stream_view);
978  std::ranges::next(std::ranges::begin(stream_view)); // skip char read before
979  std::ranges::next(std::ranges::begin(stream_view)); // skip ':'
980 
981  switch (type_id)
982  {
983  case 'A' : // char
984  {
985  target[tag] = static_cast<char>(*std::ranges::begin(stream_view));
986  std::ranges::next(std::ranges::begin(stream_view)); // skip char that has been read
987  break;
988  }
989  case 'i' : // int32_t
990  {
991  int32_t tmp;
992  read_field(stream_view, tmp);
993  target[tag] = tmp;
994  break;
995  }
996  case 'f' : // float
997  {
998  float tmp;
999  read_field(stream_view, tmp);
1000  target[tag] = tmp;
1001  break;
1002  }
1003  case 'Z' : // string
1004  {
1005  target[tag] = stream_view | views::to<std::string>;
1006  break;
1007  }
1008  case 'H' :
1009  {
1010  // TODO
1011  break;
1012  }
1013  case 'B' : // Array. Value type depends on second char [cCsSiIf]
1014  {
1015  char array_value_type_id = *std::ranges::begin(stream_view);
1016  std::ranges::next(std::ranges::begin(stream_view)); // skip char read before
1017  std::ranges::next(std::ranges::begin(stream_view)); // skip first ','
1018 
1019  switch (array_value_type_id)
1020  {
1021  case 'c' : // int8_t
1022  read_sam_dict_vector(target[tag], stream_view, int8_t{});
1023  break;
1024  case 'C' : // uint8_t
1025  read_sam_dict_vector(target[tag], stream_view, uint8_t{});
1026  break;
1027  case 's' : // int16_t
1028  read_sam_dict_vector(target[tag], stream_view, int16_t{});
1029  break;
1030  case 'S' : // uint16_t
1031  read_sam_dict_vector(target[tag], stream_view, uint16_t{});
1032  break;
1033  case 'i' : // int32_t
1034  read_sam_dict_vector(target[tag], stream_view, int32_t{});
1035  break;
1036  case 'I' : // uint32_t
1037  read_sam_dict_vector(target[tag], stream_view, uint32_t{});
1038  break;
1039  case 'f' : // float
1040  read_sam_dict_vector(target[tag], stream_view, float{});
1041  break;
1042  default:
1043  throw format_error{std::string("The first character in the numerical ") +
1044  "id of a SAM tag must be one of [cCsSiIf] but '" + array_value_type_id +
1045  "' was given."};
1046  }
1047  break;
1048  }
1049  default:
1050  throw format_error{std::string("The second character in the numerical id of a "
1051  "SAM tag must be one of [A,i,Z,H,B,f] but '") + type_id + "' was given."};
1052  }
1053 }
1054 
1062 template <typename stream_it_t, std::ranges::forward_range field_type>
1063 inline void format_sam::write_range_or_asterisk(stream_it_t & stream_it, field_type && field_value)
1064 {
1065  if (std::ranges::empty(field_value))
1066  {
1067  *stream_it = '*';
1068  }
1069  else
1070  {
1071  if constexpr (std::same_as<std::remove_cvref_t<std::ranges::range_reference_t<field_type>>, char>)
1072  stream_it.write_range(field_value);
1073  else // convert from alphabets to their character representation
1074  stream_it.write_range(field_value | views::to_char);
1075  }
1076 }
1077 
1084 template <typename stream_it_t>
1085 inline void format_sam::write_range_or_asterisk(stream_it_t & stream_it, char const * const field_value)
1086 {
1087  write_range_or_asterisk(stream_it, std::string_view{field_value});
1088 }
1089 
1097 template <typename stream_it_t>
1098 inline void format_sam::write_tag_fields(stream_it_t & stream_it, sam_tag_dictionary const & tag_dict, char const separator)
1099 {
1100  auto const stream_variant_fn = [&stream_it] (auto && arg) // helper to print an std::variant
1101  {
1102  using T = std::remove_cvref_t<decltype(arg)>;
1103 
1104  if constexpr (std::ranges::input_range<T>)
1105  {
1106  if constexpr (std::same_as<std::remove_cvref_t<std::ranges::range_reference_t<T>>, char>)
1107  {
1108  stream_it.write_range(arg);
1109  }
1110  else if constexpr (std::same_as<std::remove_cvref_t<std::ranges::range_reference_t<T>>, std::byte>)
1111  {
1112  if (!std::ranges::empty(arg))
1113  {
1114  stream_it.write_number(std::to_integer<uint8_t>(*std::ranges::begin(arg)));
1115 
1116  for (auto && elem : arg | views::drop(1))
1117  {
1118  *stream_it = ',';
1119  stream_it.write_number(std::to_integer<uint8_t>(elem));
1120  }
1121  }
1122  }
1123  else
1124  {
1125  if (!std::ranges::empty(arg))
1126  {
1127  stream_it.write_number(*std::ranges::begin(arg));
1128 
1129  for (auto && elem : arg | views::drop(1))
1130  {
1131  *stream_it = ',';
1132  stream_it.write_number(elem);
1133  }
1134  }
1135  }
1136  }
1137  else if constexpr (std::same_as<std::remove_cvref_t<T>, char>)
1138  {
1139  *stream_it = arg;
1140  }
1141  else // number
1142  {
1143  stream_it.write_number(arg);
1144  }
1145  };
1146 
1147  for (auto & [tag, variant] : tag_dict)
1148  {
1149  *stream_it = separator;
1150 
1151  char const char0 = tag / 256;
1152  char const char1 = tag % 256;
1153 
1154  *stream_it = char0;
1155  *stream_it = char1;
1156  *stream_it = ':';
1157  *stream_it = detail::sam_tag_type_char[variant.index()];
1158  *stream_it = ':';
1159 
1160  if (detail::sam_tag_type_char_extra[variant.index()] != '\0')
1161  {
1162  *stream_it = detail::sam_tag_type_char_extra[variant.index()];
1163  *stream_it = ',';
1164  }
1165 
1166  std::visit(stream_variant_fn, variant);
1167  }
1168 }
1169 
1170 } // namespace seqan3
Adaptations of algorithms from the Ranges TS.
Provides seqan3::alignment_file_input_format and auxiliary classes.
Provides seqan3::alignment_file_input_options.
Provides seqan3::alignment_file_output_format and auxiliary classes.
Provides seqan3::alignment_file_output_options.
Core alphabet concept and free function/type trait wrappers.
T begin(T... args)
Provides seqan3::views::char_to.
Stores the header information of alignment files.
Definition: header.hpp:33
std::unordered_map< key_type, int32_t, std::hash< key_type >, 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:158
ref_ids_type & ref_ids()
The range of reference ids.
Definition: header.hpp:119
The SAM format (tag).
Definition: format_sam.hpp:128
format_sam & operator=(format_sam const &)=default
Defaulted.
void read_sequence_record(stream_type &stream, sequence_file_input_options< seq_legal_alph_type, seq_qual_combined > const &options, 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:292
void read_alignment_record(stream_type &stream, alignment_file_input_options< seq_legal_alph_type > const &options, ref_seqs_type &ref_seqs, alignment_file_header< ref_ids_type > &header, 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, align_type &align, 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:384
~format_sam()=default
format_sam & operator=(format_sam &&)=default
Defaulted.
void write_alignment_record(stream_type &stream, alignment_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, align_type &&align, 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:643
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:144
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:333
format_sam(format_sam &&)=default
Defaulted.
format_sam()=default
Defaulted.
format_sam(format_sam const &)=default
Defaulted.
The alphabet of a gap character '-'.
Definition: gap.hpp:37
The SAM tag dictionary class that stores all optional SAM fields.
Definition: sam_tag_dictionary.hpp:326
T clear(T... args)
The Concepts library.
Provides various transformation traits used by the range module.
Auxiliary for pretty printing of exception messages.
Provides type traits for working with templates.
T end(T... args)
Provides concepts for core language types and relations that don't have concepts in C++20 (yet).
Provides seqan3::detail::fast_ostreambuf_iterator.
Provides the seqan3::format_sam_base that can be inherited from.
sam_flag
An enum flag that describes the properties of an aligned read (given as a SAM record).
Definition: misc.hpp:73
@ none
None of the flags below are set.
constexpr auto to_char
Return the char representation of an alphabet object.
Definition: concept.hpp:328
constexpr auto is_space
Checks whether c is a space character.
Definition: predicate.hpp:144
@ 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.
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: traits.hpp:434
constexpr size_t size
The size of a type pack.
Definition: traits.hpp:150
constexpr auto drop
A view adaptor that returns all elements after n from the underlying range (or an empty range if the ...
Definition: drop.hpp:170
constexpr auto slice
A view adaptor that returns a half-open interval on the underlying range.
Definition: slice.hpp:141
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.hpp:614
constexpr auto istreambuf
A view factory that returns a view over the stream buffer of an input stream.
Definition: istreambuf.hpp:114
constexpr auto take_until
A view adaptor that returns elements from the underlying range until the functor evaluates to true (o...
Definition: take_until.hpp:600
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.hpp:642
auto const move
A view that turns lvalue-references into rvalue-references.
Definition: move.hpp:70
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.hpp:628
Provides the seqan3::alignment_file_header class.
Provides seqan3::detail::ignore_output_iterator for writing to null stream.
T index(T... args)
The generic alphabet concept that covers most data types used in ranges.
Resolves to std::ranges::implicitly_convertible_to<type1, type2>(). <dl class="no-api">This entity i...
A more refined container concept than seqan3::container.
The generic concept for a (biological) sequence.
Whether a type behaves like a tuple.
Provides helper data structures for the seqan3::alignment_file_output.
Provides various utility functions.
Provides seqan3::views::istreambuf.
The main SeqAn3 namespace.
Definition: aligned_sequence_concept.hpp:29
T push_back(T... args)
Provides various utility functions.
Adaptations of concepts from the Ranges TS.
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.
The options type defines various option members that influence the behaviour of all or some formats.
Definition: input_options.hpp:24
The options type defines various option members that influence the behavior of all or some formats.
Definition: output_options.hpp:23
bool sam_require_header
Whether to require a header for SAM files.
Definition: output_options.hpp:41
bool add_carriage_return
The default plain text line-ending is "\n", but on Windows an additional carriage return is recommend...
Definition: output_options.hpp:27
Thrown if information given to output format didn't match expectations.
Definition: exception.hpp:88
Thrown if there is a parse error, such as reading an unexpected character from an input stream.
Definition: exception.hpp:48
The options type defines various option members that influence the behaviour of all or some formats.
Definition: input_options.hpp:26
bool truncate_ids
Read the ID string only up until the first whitespace character.
Definition: input_options.hpp:28
The options type defines various option members that influence the behaviour of all or some formats.
Definition: output_options.hpp:22
Exposes the value_type of another type.
Definition: pre.hpp:58
T swap(T... args)
Provides seqan3::views::take_until and seqan3::views::take_until_or_throw.
T tie(T... args)
Provides seqan3::views::to.
Provides seqan3::views::to_char.
T tuple_size_v
Provides traits to inspect some information of a type, for example its name.
Provides character predicates for tokenisation.
Provides seqan3::tuple_like.
T visit(T... args)