• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

MikkelSchubert / adapterremoval / #102

18 Apr 2025 01:14PM UTC coverage: 67.126% (-0.06%) from 67.186%
#102

push

travis-ci

web-flow
support normalizing (merged) reverse inserts (#128)

This implements part of #68

0 of 16 new or added lines in 3 files covered. (0.0%)

3 existing lines in 1 file now uncovered.

9697 of 14446 relevant lines covered (67.13%)

3061.02 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/userconfig.cpp
1
// SPDX-License-Identifier: GPL-3.0-or-later
2
// SPDX-FileCopyrightText: 2011 Stinus Lindgreen <stinus@binf.ku.dk>
3
// SPDX-FileCopyrightText: 2014 Mikkel Schubert <mikkelsch@gmail.com>
4
#include "userconfig.hpp"  // declarations
5
#include "alignment.hpp"   // for alignment_info
6
#include "commontypes.hpp" // for string_vec, DEV_STDOUT, DEV_STDERR, ...
7
#include "debug.hpp"       // for AR_REQUIRE, AR_FAIL
8
#include "errors.hpp"      // for fastq_error
9
#include "fastq.hpp"       // for ACGT, ACGT::indices, ACGT::values
10
#include "fastq_enc.hpp"   // for PHRED_SCORE_MAX
11
#include "licenses.hpp"    // for LICENSES
12
#include "logging.hpp"     // for log_stream, error, set_level, set_colors, info
13
#include "main.hpp"        // for HELPTEXT, NAME, VERSION
14
#include "output.hpp"      // for DEV_NULL, output_files, output_file
15
#include "progress.hpp"    // for progress_type, progress_type::simple, progr...
16
#include "sequence.hpp"    // for dna_sequence
17
#include "simd.hpp"        // for size_t, name, supported, instruction_set
18
#include "strutils.hpp"    // for shell_escape, str_to_u32
19
#include <algorithm>       // for find, max, min
20
#include <cerrno>          // for errno
21
#include <cmath>           // for pow
22
#include <cstdlib>         // for getenv
23
#include <cstring>         // for size_t, strerror, strcmp
24
#include <filesystem>      // for weakly_canonical
25
#include <limits>          // for numeric_limits
26
#include <stdexcept>       // for invalid_argument
27
#include <string>          // for string, basic_string, operator==, operator+
28
#include <string_view>     // for string_view
29
#include <tuple>           // for get, tuple
30
#include <unistd.h>        // for access, isatty, R_OK, STDERR_FILENO
31

32
namespace adapterremoval {
33

34
namespace {
35

36
const char* HELPTEXT =
37
  "This program searches for and removes remnant adapter sequences, poly-X "
38
  "tails and low-quality base from FASTQ reads. For detailed explanation of "
39
  "the parameters, please refer to the man page. For comments, suggestions "
40
  "and feedback please use\n"
41
  "\n"
42
  "  https://github.com/MikkelSchubert/adapterremoval/issues/new\n"
43
  "\n"
44
  "If you use the program, please cite the paper\n"
45
  "\n"
46
  "  Schubert, Lindgreen, and Orlando (2016). AdapterRemoval v2: rapid\n"
47
  "  adapter trimming, identification, and read merging. BMC Research\n"
48
  "  Notes, 12;9(1):88. https://doi.org/10.1186/s13104-016-1900-2\n"
49
  "\n"
50
  "Use the filename '-' to read from STDIN or to write to STDOUT. If the same "
51
  "filenames are used for two or more of the --out-* options (excluding "
52
  "--out-json and --out-html), then the combined output is written to that "
53
  "file in interleaved mode.\n";
54

55
////////////////////////////////////////////////////////////////////////////////
56
// Helper functions
57

58
std::pair<unsigned, unsigned>
59
parse_trim_argument(const string_vec& values)
×
60
{
61
  unsigned mate_1 = 0;
×
62
  unsigned mate_2 = 0;
×
63

64
  switch (values.size()) {
×
65
    case 1:
×
66
      mate_1 = str_to_u32(values.front());
×
67
      mate_2 = mate_1;
×
68
      break;
×
69

70
    case 2:
×
71
      mate_1 = str_to_u32(values.front());
×
72
      mate_2 = str_to_u32(values.back());
×
73
      break;
×
74

75
    default:
×
76
      throw std::invalid_argument("please specify exactly one or two values");
×
77
  }
78

79
  return { mate_1, mate_2 };
×
80
}
81

82
bool
83
parse_poly_x_option(const std::string& key,
×
84
                    const string_vec& values,
85
                    std::string& out)
86
{
87
  out.clear();
×
88
  if (values.empty()) {
×
89
    out = "ACGT";
×
90
    return true;
91
  }
92

93
  std::array<bool, ACGT::indices> enabled = {};
×
94
  for (const auto& value : values) {
×
95
    for (const auto nuc : to_upper(value)) {
×
96
      switch (nuc) {
×
97
        case 'A':
×
98
        case 'C':
×
99
        case 'G':
×
100
        case 'T':
×
101
          enabled.at(ACGT::to_index(nuc)) = true;
×
102
          break;
×
103

104
        default:
×
105
          log::error() << "Option " << key << " called with invalid value "
×
106
                       << shell_escape(value) << ". Only A, C, G, and T are "
×
107
                       << "permitted!";
×
108

109
          return false;
×
110
      }
111
    }
112
  }
113

114
  for (const auto nuc : ACGT::values) {
×
115
    if (enabled.at(ACGT::to_index(nuc))) {
×
116
      out.push_back(nuc);
×
117
    }
118
  }
119

120
  return true;
121
}
122

123
bool
124
parse_counts(const argparse::parser& args,
×
125
             const std::string& key,
126
             uint64_t& out)
127
{
128
  const auto sink = args.value(std::string{ key });
×
129
  if (sink.empty()) {
×
130
    return true;
131
  }
132

133
  uint64_t unit = 1;
×
134
  std::string sink_without_unit = sink;
×
135
  if (sink.back() < '0' || sink.back() > '9') {
×
136
    switch (sink.back()) {
×
137
      case 'k':
138
      case 'K':
139
        unit = 1000;
140
        break;
141

142
      case 'm':
×
143
      case 'M':
×
144
        unit = 1000'000;
×
145
        break;
×
146

147
      case 'g':
×
148
      case 'G':
×
149
        unit = 1000'000'000;
×
150
        break;
×
151

152
      default:
×
153
        log::error() << "Invalid unit in command-line option " << key
×
154
                     << shell_escape(sink);
×
155
        return false;
×
156
    }
157

158
    sink_without_unit.pop_back();
×
159
  }
160

161
  try {
×
162
    // This should not be able to overflow as log2(2^32 * 1e9) ~= 62,
163
    // but will need to be changed if we want to allow large raw numbers
164
    out = static_cast<uint64_t>(str_to_u32(sink_without_unit)) * unit;
×
165
  } catch (const std::invalid_argument&) {
×
166
    log::error() << "Invalid value in command-line option --sink "
×
167
                 << shell_escape(sink);
×
168
    return false;
×
169
  }
×
170

171
  return true;
×
172
}
173

174
bool
175
check_no_clobber(const std::string& label,
×
176
                 const string_vec& in_files,
177
                 const output_file& out_file)
178
{
179
  for (const auto& in_file : in_files) {
×
180
    if (in_file == out_file.name && in_file != DEV_NULL) {
×
181
      log::error() << "Input file would be overwritten: " << label << " "
×
182
                   << in_file;
×
183
      return false;
×
184
    }
185
  }
186

187
  return true;
×
188
}
189

190
/** Replace the STDIN pseudo-filename with the device path */
191
void
192
normalize_input_file(std::string& filename)
×
193
{
194
  if (filename == DEV_PIPE) {
×
195
    filename = DEV_STDIN;
×
196
  }
197
}
198

199
/** Replace the STDIN pseudo-filename with the device path */
200
void
201
normalize_output_file(std::string& filename)
×
202
{
203
  if (filename == DEV_PIPE) {
×
204
    filename = DEV_STDOUT;
×
205
  }
206
}
207

208
void
209
append_normalized_input_files(string_pair_vec& out, const string_vec& filenames)
×
210
{
211
  for (const auto& filename : filenames) {
×
212
    try {
×
213
      out.emplace_back(std::filesystem::weakly_canonical(filename), filename);
×
214
    } catch (const std::filesystem::filesystem_error&) {
×
215
      // Permission errors are handled by the explicit access checks below
216
      out.emplace_back(filename, filename);
×
217
    }
×
218
  }
219
}
220

221
bool
222
check_input_files(const string_vec& filenames_1, const string_vec& filenames_2)
×
223
{
224
  string_pair_vec filenames;
×
225
  append_normalized_input_files(filenames, filenames_1);
×
226
  append_normalized_input_files(filenames, filenames_2);
×
227
  std::sort(filenames.begin(), filenames.end());
×
228

229
  bool any_errors = false;
230
  for (size_t i = 1; i < filenames.size(); ++i) {
×
231
    const auto& it_0 = filenames.at(i - 1);
×
232
    const auto& it_1 = filenames.at(i);
×
233

234
    if (it_0.second == it_1.second) {
×
235
      log::error() << "Input file " << log_escape(it_0.second)
×
236
                   << " has been specified multiple times using --in-file1 "
237
                      "and/or --in-file2";
×
238
      any_errors = true;
×
239
    } else if (it_0.first == it_1.first) {
×
240
      log::error() << "The path of input file " << log_escape(it_0.second)
×
241
                   << " and the path of input " << "file "
×
242
                   << log_escape(it_1.second) << " both point to the file "
×
243
                   << log_escape(it_0.first);
×
244
      any_errors = true;
×
245
    }
246
  }
247

248
  for (const auto& it : filenames) {
×
249
    if (access(it.second.c_str(), R_OK)) {
×
250
      log::error() << "Cannot access input file " << log_escape(it.second)
×
251
                   << ": " << std::strerror(errno);
×
252
      any_errors = true;
×
253
    }
254
  }
255

256
  return !any_errors;
×
257
}
258

259
bool
260
check_output_files(const std::string& label,
×
261
                   const string_vec& filenames,
262
                   const output_files& output_files)
263
{
264

265
  if (!check_no_clobber(label, filenames, output_files.unidentified_1)) {
×
266
    return false;
267
  }
268

269
  if (!check_no_clobber(label, filenames, output_files.unidentified_2)) {
×
270
    return false;
271
  }
272

273
  for (const auto& sample : output_files.samples()) {
×
274
    for (size_t i = 0; i < sample.size(); ++i) {
×
275
      if (!check_no_clobber(label, filenames, sample.file(i))) {
×
276
        return false;
×
277
      }
278
    }
279
  }
280

281
  return true;
×
282
}
283

284
/**
285
 * Tries to parse a simple command-line argument while ignoring the validity
286
 * of the overall command-line. This is only intended to make pre-configured
287
 * logging output consistent with post-configured output if possible.
288
 */
289
std::string
290
try_parse_argument(const string_vec& args,
×
291
                   const std::string& key,
292
                   const std::string& fallback)
293
{
294
  auto it = std::find(args.begin(), args.end(), key);
×
295
  if (it != args.end() && (it + 1) != args.end()) {
×
296
    return *(it + 1);
×
297
  }
298

299
  return fallback;
×
300
}
301

302
/** Returns vector of keys for output files that have been set by the user. */
303
string_vec
304
user_supplied_keys(const argparse::parser& argparser, const string_vec& keys)
×
305
{
306
  string_vec result;
×
307
  for (const auto& key : keys) {
×
308
    if (argparser.is_set(key)) {
×
309
      result.push_back(key);
×
310
    }
311
  }
312

313
  return result;
×
314
}
×
315

316
////////////////////////////////////////////////////////////////////////////////
317

318
bool
319
fancy_output_allowed()
×
320
{
321
  if (::isatty(STDERR_FILENO)) {
×
322
    // NO_COLOR is checked as suggested by https://no-color.org/
323
    const char* no_color = std::getenv("NO_COLOR");
×
324
    const char* term = std::getenv("TERM");
×
325

326
    return !(no_color && no_color[0] != '\0') &&
×
327
           !(term && strcmp(term, "dumb") == 0);
×
328
  }
329

330
  return false;
331
}
332

333
void
334
configure_log_levels(const std::string& value, bool fallible = false)
×
335
{
336
  const auto log_level = to_lower(value);
×
337

338
  if (log_level == "debug") {
×
339
    log::set_level(log::level::debug);
×
340
  } else if (log_level == "info") {
×
341
    log::set_level(log::level::info);
×
342
  } else if (log_level == "warning") {
×
343
    log::set_level(log::level::warning);
×
344
  } else if (log_level == "error") {
×
345
    log::set_level(log::level::error);
×
346
  } else {
347
    AR_REQUIRE(fallible, "unhandled log_level value");
×
348
  }
349
}
350

351
void
352
configure_log_colors(const std::string& colors, bool fallible = false)
×
353
{
354
  if (colors == "always") {
×
355
    log::set_colors(true);
×
356
  } else if (colors == "never") {
×
357
    log::set_colors(false);
×
358
  } else if (colors == "auto") {
×
359
    log::set_colors(fancy_output_allowed());
×
360
  } else {
361
    AR_REQUIRE(fallible, "unhandled log_colors value");
×
362
  }
363
}
364

365
progress_type
366
configure_log_progress(const std::string& progress)
×
367
{
368
  if (progress == "never") {
×
369
    return progress_type::none;
370
  } else if (progress == "spin") {
×
371
    return progress_type::spinner;
372
  } else if (progress == "log") {
×
373
    return progress_type::simple;
374
  } else if (progress == "auto") {
×
375
    if (fancy_output_allowed()) {
×
376
      return progress_type::spinner;
377
    } else {
378
      return progress_type::simple;
379
    }
380
  }
381

382
  AR_FAIL("unhandled log_progress value");
×
383
}
384

385
fastq_encoding
386
configure_encoding(const std::string& value,
×
387
                   degenerate_encoding degenerate,
388
                   uracil_encoding uracils)
389
{
390
  if (value == "33") {
×
391
    return fastq_encoding{ quality_encoding::phred_33, degenerate, uracils };
×
392
  } else if (value == "64") {
×
393
    return fastq_encoding{ quality_encoding::phred_64, degenerate, uracils };
×
394
  } else if (value == "solexa") {
×
395
    return fastq_encoding{ quality_encoding::solexa, degenerate, uracils };
×
396
  } else if (value == "sam") {
×
397
    return fastq_encoding{ quality_encoding::sam, degenerate, uracils };
×
398
  }
399

400
  AR_FAIL("unhandled qualitybase value");
×
401
}
402

403
bool
404
parse_output_formats(const argparse::parser& argparser,
×
405
                     output_format& file_format,
406
                     output_format& stdout_format)
407
{
408
  if (argparser.is_set("--gzip")) {
×
409
    file_format = stdout_format = output_format::fastq_gzip;
×
410
    return true;
×
411
  }
412

413
  auto format_s = argparser.value("--out-format");
×
414
  if (!output_files::parse_format(format_s, file_format)) {
×
415
    log::error() << "Invalid output format " + log_escape(format_s);
×
416
    return false;
×
417
  }
418

419
  // Default to writing uncompressed output to STDOUT
420
  if (!argparser.is_set("--stdout-format")) {
×
421
    switch (file_format) {
×
422
      case output_format::fastq:
×
423
      case output_format::fastq_gzip:
×
424
        stdout_format = output_format::fastq;
×
425
        return true;
×
426
      case output_format::sam:
×
427
      case output_format::sam_gzip:
×
428
        stdout_format = output_format::sam;
×
429
        return true;
×
430
      case output_format::bam:
×
431
      case output_format::ubam:
×
432
        stdout_format = output_format::ubam;
×
433
        return true;
×
434
      default:
×
435
        AR_FAIL("invalid output format");
×
436
    }
437
  }
438

439
  format_s = argparser.value("--stdout-format");
×
440
  if (!output_files::parse_format(format_s, stdout_format)) {
×
441
    log::error() << "Invalid output format " + log_escape(format_s);
×
442
    return false;
×
443
  }
444

445
  return true;
446
}
447

448
} // namespace
449

450
////////////////////////////////////////////////////////////////////////////////
451
// Implementations for `userconfig`
452

453
std::string userconfig::start_time = timestamp("%FT%T%z");
454

455
userconfig::userconfig()
×
456
{
457
  argparser.set_name(NAME);
×
458
  argparser.set_version(VERSION);
×
459
  argparser.set_preamble(HELPTEXT);
×
460
  argparser.set_licenses(LICENSES);
×
461
  argparser.set_terminal_width(log::get_terminal_width());
×
462

463
  //////////////////////////////////////////////////////////////////////////////
464
  argparser.add("--threads", "N")
×
465
    .help("Maximum number of threads")
×
466
    .bind_u32(&max_threads)
×
467
    .with_default(2)
×
468
    .with_minimum(1);
×
469

470
  {
×
471
    std::vector<std::string> choices;
×
472
    for (const auto is : simd::supported()) {
×
473
      choices.emplace_back(simd::name(is));
×
474
    }
475

476
    AR_REQUIRE(!choices.empty());
×
477
    argparser.add("--simd", "NAME")
×
478
      .help("SIMD instruction set to use; defaults to the most advanced "
×
479
            "instruction set supported by this computer")
480
      .bind_str(nullptr)
×
481
      .with_choices(choices)
×
482
      .with_default(choices.back());
×
483
  }
484

485
  argparser.add("--benchmark")
×
486
    .help("Carry out benchmarking of AdapterRemoval sub-systems")
×
487
    .conflicts_with("--demultiplex-only")
×
488
    .conflicts_with("--report-only")
×
489
    .conflicts_with("--interleaved")
×
490
    .conflicts_with("--interleaved-input")
×
491
#if !defined(DEBUG)
492
    .hidden()
×
493
#endif
494
    .bind_vec(&benchmarks)
×
495
    .with_min_values(0);
×
496

497
  //////////////////////////////////////////////////////////////////////////////
498
  argparser.add_header("INPUT FILES:");
×
499

500
  argparser.add("--in-file1", "FILE")
×
501
    .help("One or more input files containing mate 1 reads [REQUIRED]")
×
502
    .deprecated_alias("--file1")
×
503
    .bind_vec(&input_files_1)
×
504
    .with_preprocessor(normalize_input_file);
×
505
  argparser.add("--in-file2", "FILE")
×
506
    .help("Input files containing mate 2 reads; if used, then the same number "
×
507
          "of files as --in-file1 must be listed [OPTIONAL]")
508
    .deprecated_alias("--file2")
×
509
    .bind_vec(&input_files_2)
×
510
    .with_preprocessor(normalize_input_file);
×
511
  argparser.add("--head", "N")
×
512
    .help("Process only the first N reads in single-end mode or the first N "
×
513
          "read-pairs in paired-end mode. Accepts suffixes K (thousands), M "
514
          "(millions), and G (billions) [default: all reads]")
515
    .bind_str(nullptr);
×
516

517
  //////////////////////////////////////////////////////////////////////////////
518
  argparser.add_header("OUTPUT FILES:");
×
519

520
  argparser.add("--out-prefix", "PREFIX")
×
521
    .help("Prefix for output files for which the corresponding --out option "
×
522
          "was not set [default: not set]")
523
    .deprecated_alias("--basename")
×
524
    .bind_str(&out_prefix)
×
525
    .with_default(DEV_NULL);
×
526

527
  argparser.add_separator();
×
528
  argparser.add("--out-file1", "FILE")
×
529
    .help("Output file containing trimmed mate 1 reads. Setting this value in "
×
530
          "in demultiplexing mode overrides --out-prefix for this file")
531
    .deprecated_alias("--output1")
×
532
    .bind_str(nullptr)
×
533
    .with_default("{prefix}[.sample].r1.fastq")
×
534
    .with_preprocessor(normalize_output_file);
×
535
  argparser.add("--out-file2", "FILE")
×
536
    .help("Output file containing trimmed mate 2 reads. Setting this value in "
×
537
          "in demultiplexing mode overrides --out-prefix for this file")
538
    .deprecated_alias("--output2")
×
539
    .bind_str(nullptr)
×
540
    .with_default("{prefix}[.sample].r2.fastq")
×
541
    .with_preprocessor(normalize_output_file);
×
542
  argparser.add("--out-merged", "FILE")
×
543
    .help("Output file that, if --merge is set, contains overlapping "
×
544
          "read-pairs that have been merged into a single read (PE mode only). "
545
          "Setting this value in demultiplexing mode overrides --out-prefix "
546
          "for this file")
547
    .deprecated_alias("--outputcollapsed")
×
548
    .bind_str(nullptr)
×
549
    .with_default("{prefix}[.sample].merged.fastq")
×
550
    .with_preprocessor(normalize_output_file);
×
551
  argparser.add("--out-singleton", "FILE")
×
552
    .help("Output file containing paired reads for which the mate "
×
553
          "has been discarded. This file is only created if filtering is "
554
          "enabled. Setting this value in demultiplexing mode overrides "
555
          "--out-prefix for this file")
556
    .deprecated_alias("--singleton")
×
557
    .bind_str(nullptr)
×
558
    .with_default("{prefix}[.sample].singleton.fastq")
×
559
    .with_preprocessor(normalize_output_file);
×
560

561
  argparser.add_separator();
×
562
  argparser.add("--out-unidentified1", "FILE")
×
563
    .help("In demultiplexing mode, contains mate 1 reads that could not be "
×
564
          "assigned to a single sample")
565
    .bind_str(nullptr)
×
566
    .with_default("{prefix}.unidentified.r1.fastq")
×
567
    .with_preprocessor(normalize_output_file);
×
568
  argparser.add("--out-unidentified2", "FILE")
×
569
    .help("In demultiplexing mode, contains mate 2 reads that could not be "
×
570
          "assigned to a single sample")
571
    .bind_str(nullptr)
×
572
    .with_default("{prefix}.unidentified.r2.fastq")
×
573
    .with_preprocessor(normalize_output_file);
×
574
  argparser.add("--out-discarded", "FILE")
×
575
    .help("Output file containing filtered reads. Setting this value in "
×
576
          "demultiplexing mode overrides --out-prefix for this file [default: "
577
          "not saved]")
578
    .deprecated_alias("--discarded")
×
579
    .bind_str(nullptr)
×
580
    .with_preprocessor(normalize_output_file);
×
581

582
  argparser.add_separator();
×
583
  argparser.add("--out-json", "FILE")
×
584
    .help("Output file containing statistics about input files, trimming, "
×
585
          "merging, and more in JSON format")
586
    .bind_str(nullptr)
×
587
    .with_default("{prefix}.json")
×
588
    .with_preprocessor(normalize_output_file);
×
589
  argparser.add("--out-html", "FILE")
×
590
    .help("Output file containing statistics about input files, trimming, "
×
591
          "merging, and more in HTML format")
592
    .bind_str(nullptr)
×
593
    .with_default("{prefix}.html")
×
594
    .with_preprocessor(normalize_output_file);
×
595

596
  //////////////////////////////////////////////////////////////////////////////
597
  argparser.add_header("FASTQ OPTIONS:");
×
598

599
  argparser.add("--quality-format", "N")
×
600
    .help("Format used to encode Phred scores in input")
×
601
    .deprecated_alias("--qualitybase")
×
602
    .bind_str(&quality_input_base)
×
603
    .with_choices({ "33", "64", "solexa", "sam" })
×
604
    .with_default("33");
×
605
  argparser.add("--mate-separator", "CHAR")
×
606
    .help("Character separating the mate number (1 or 2) from the read name in "
×
607
          "FASTQ records. Will be determined automatically if not specified")
608
    .bind_str(&mate_separator_str);
×
609

610
  argparser.add("--interleaved-input")
×
611
    .help("The (single) input file provided contains both the mate 1 and mate "
×
612
          "2 reads, one pair after the other, with one mate 1 reads followed "
613
          "by one mate 2 read. This option is implied by the --interleaved "
614
          "option")
615
    .conflicts_with("--in-file2")
×
616
    .bind_bool(&interleaved_input);
×
617
  argparser.add("--interleaved-output")
×
618
    .help("If set, trimmed paired-end reads are written to a single file "
×
619
          "containing mate 1 and mate 2 reads, one pair after the other. This "
620
          "option is implied by the --interleaved option")
621
    .conflicts_with("--out-file2")
×
622
    .bind_bool(&interleaved_output);
×
623
  argparser.add("--interleaved")
×
624
    .help("This option enables both the --interleaved-input option and the "
×
625
          "--interleaved-output option")
626
    .conflicts_with("--in-file2")
×
627
    .conflicts_with("--out-file2")
×
628
    .bind_bool(&interleaved);
×
629

630
  argparser.add("--mask-degenerate-bases")
×
631
    .help("Mask degenerate/ambiguous bases (B/D/H/K/M/N/R/S/V/W/Y) in the "
×
632
          "input by replacing them with an 'N'; if this option is not used, "
633
          "AdapterRemoval will abort upon encountering degenerate bases");
634
  argparser.add("--convert-uracils")
×
635
    .help("Convert uracils (U) to thymine (T) in input reads; if this option "
×
636
          "is not used, AdapterRemoval will abort upon encountering uracils");
637

638
  //////////////////////////////////////////////////////////////////////////////
639
  argparser.add_header("OUTPUT FORMAT:");
×
640

641
  argparser.add("--gzip")
×
642
    .hidden()
×
643
    .deprecated()
×
644
    .conflicts_with("--out-format")
×
645
    .conflicts_with("--stdout-format");
×
646
  argparser.add("--out-format", "X")
×
647
    .help("Selects the default output format; either 'fastq' for uncompressed "
×
648
          "FASTQ reads, 'fastq.gz' for gzip compressed FASTQ reads, 'sam' for "
649
          "uncompressed SAM records, 'sam.gz' for gzip compressed SAM records, "
650
          "'bam' for BGZF compressed BAM records, and 'ubam' for uncompressed "
651
          "BAM records. Setting an `--out-*` option overrides this option "
652
          "based on the filename used (except .ubam)")
653
    .bind_str(nullptr)
×
654
    .with_choices({ "fastq", "fastq.gz", "sam", "sam.gz", "bam", "ubam" })
×
655
    .with_default("fastq.gz");
×
656
  argparser.add("--stdout-format", "X")
×
657
    .help("Selects the output format for data written to STDOUT; choices are "
×
658
          "the same as for --out-format [default: the same format as "
659
          "--out-format, but uncompressed]")
660
    .bind_str(nullptr)
×
661
    .with_choices({ "fastq", "fastq.gz", "sam", "sam.gz", "bam", "ubam" });
×
662
  argparser.add("--read-group", "RG")
×
663
    .help("Add read-group to SAM/BAM output. Takes zero or more arguments in "
×
664
          "the form 'tag:value' where tag consists of two alphanumerical "
665
          "characters and where value is one or more characters. An argument "
666
          "may also contain multiple, tab-separated tag/value pairs. An ID tag "
667
          "is automatically generated if no ID tag is specified")
668
    .bind_vec(&read_group)
×
669
    .with_min_values(0);
×
670
  argparser.add("--compression-level", "N")
×
671
    .help(
×
672
      "Sets the compression level for compressed output. Valid values are 0 to "
673
      "13: Level 0 is uncompressed but includes gzip headers/checksums, level "
674
      "1 is streamed for SAM/FASTQ output (this may be required in rare cases "
675
      "for compatibility), and levels 2 to 13 are block compressed using the "
676
      "BGZF format")
677
    .deprecated_alias("--gzip-level")
×
678
    .bind_u32(&compression_level)
×
679
    .with_maximum(13)
×
680
    .with_default(5);
×
681

682
  //////////////////////////////////////////////////////////////////////////////
683
  argparser.add_header("PROCESSING:");
×
684

685
  argparser.add("--adapter1", "SEQ")
×
686
    .help("Adapter sequence expected to be found in mate 1 reads. Any 'N' in "
×
687
          "this sequence is treated as a wildcard")
688
    .bind_str(&adapter_1)
×
689
    .with_default("AGATCGGAAGAGCACACGTCTGAACTCCAGTCA");
×
690
  argparser.add("--adapter2", "SEQ")
×
691
    .help("Adapter sequence expected to be found in mate 2 reads. Any 'N' in "
×
692
          "this sequence is treated as a wildcard")
693
    .bind_str(&adapter_2)
×
694
    .with_default("AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGT");
×
695
  argparser.add("--adapter-list", "FILE")
×
696
    .help("Read adapter pairs from the first two columns of a white-space "
×
697
          "separated table. AdapterRemoval will then select the best matching "
698
          "adapter pair for each pair of input reads when trimming. Only the "
699
          "first column is required for single-end trimming")
700
    .conflicts_with("--adapter1")
×
701
    .conflicts_with("--adapter2")
×
702
    .bind_str(&adapter_list);
×
703

704
  argparser.add_separator();
×
705
  argparser.add("--min-adapter-overlap", "N")
×
706
    .help("In single-end mode, reads are only trimmed if the overlap between "
×
707
          "read and the adapter is at least X bases long, not counting "
708
          "ambiguous nucleotides (Ns)")
709
    .deprecated_alias("--minadapteroverlap")
×
710
    .bind_u32(&min_adapter_overlap)
×
711
    .with_default(1)
×
712
    .with_minimum(1);
×
713
  argparser.add("--mismatch-rate", "X")
×
714
    .help("Max error-rate when aligning reads and/or adapters. If > 1, the max "
×
715
          "error-rate is set to 1 / X; if < 0, the defaults are used, "
716
          "otherwise the user-supplied value is used directly [default: 1/6 "
717
          "for trimming; 1/10 when identifying adapters]")
718
    .deprecated_alias("--mm")
×
719
    .bind_double(&mismatch_threshold)
×
720
    .with_default(-1.0);
×
721
  argparser.add("--shift", "N")
×
722
    .help("Consider alignments where up to N nucleotides are missing from the "
×
723
          "5' termini")
724
    .bind_u32(&shift)
×
725
    .with_default(2);
×
726

727
  argparser.add_separator();
×
728
  argparser.add("--merge")
×
729
    .help("When set, paired ended read alignments of --merge-threshold or "
×
730
          "more bases are merged into a single consensus sequence. Merged "
731
          "reads are written to prefix.merged by default. Has no effect "
732
          "in single-end mode")
733
    .deprecated_alias("--collapse");
×
734
  argparser.add("--merge-threshold", "N")
×
735
    .help("Paired reads must overlap at least this many bases to be considered "
×
736
          "overlapping for the purpose of read merging. Overlapping bases "
737
          "where one or both bases are ambiguous (N) are not counted")
738
    .deprecated_alias("--minalignmentlength")
×
739
    .bind_u32(&merge_threshold)
×
740
    .with_default(11);
×
741
  argparser.add("--merge-strategy", "X")
×
742
    .help(
×
743
      "The 'maximum' strategy uses Q=max(Q1,Q2) for matches while the "
744
      "'additive' strategy uses Q=Q1+Q2. Both strategies use Q=abs(Q1-Q2) for "
745
      "mismatches and picks the highest quality base, unless the qualities are "
746
      "the same in which case 'N' is used. Setting this option implies --merge")
747
    .bind_str(nullptr)
×
748
    .with_choices({ "maximum", "additive" })
×
749
    .with_default("maximum");
×
750
  argparser.add("--merge-quality-max", "N")
×
751
    .help("Sets the maximum Phred score for re-calculated quality scores when "
×
752
          "read merging is enabled with the 'additive' merging strategy. The "
753
          "value must be in the range 0 to 93, corresponding to Phred+33 "
754
          "encoded values of '!' to '~'")
755
    .deprecated_alias("--qualitymax")
×
756
    .bind_u32(&merge_quality_max)
×
757
    .with_maximum(PHRED_SCORE_MAX)
×
758
    .with_default(41);
×
759
  argparser.add("--collapse-deterministic")
×
760
    .conflicts_with("--collapse-conservatively")
×
761
    .conflicts_with("--merge-strategy")
×
762
    .deprecated();
×
763
  argparser.add("--collapse-conservatively")
×
764
    .conflicts_with("--collapse-deterministic")
×
765
    .conflicts_with("--merge-strategy")
×
766
    .deprecated();
×
767

768
  argparser.add_separator();
×
769
  argparser.add("--prefix-read1", "X")
×
770
    .help("Adds the specified prefix to read 1 names [default: no prefix]")
×
771
    .bind_str(&prefix_read_1);
×
772
  argparser.add("--prefix-read2", "X")
×
773
    .help("Adds the specified prefix to read 2 names [default: no prefix]")
×
774
    .bind_str(&prefix_read_2);
×
775
  argparser.add("--prefix-merged", "X")
×
776
    .help("Adds the specified prefix to merged read names [default: no prefix]")
×
777
    .bind_str(&prefix_merged);
×
778

779
  //////////////////////////////////////////////////////////////////////////////
780
  argparser.add_header("QUALITY TRIMMING:");
×
781

782
#ifdef PRE_TRIM_5P
783
  argparser.add("--pre-trim5p", "N")
784
    .help("Trim the 5' of reads by a fixed amount after demultiplexing (if "
785
          "enabled) but before trimming adapters and low quality bases. "
786
          "Specify one value to trim mate 1 and mate 2 reads the same amount, "
787
          "or two values separated by a space to trim each mate a different "
788
          "amount [default: no trimming]")
789
    .bind_vec(&pre_trim5p)
790
    .with_max_values(2);
791
#endif
792
  argparser.add("--pre-trim3p", "N")
×
793
    .help("Trim the 3' of reads by a fixed amount after demultiplexing (if "
×
794
          "enabled) but before trimming adapters and low quality bases. "
795
          "Specify one value to trim mate 1 and mate 2 reads the same amount, "
796
          "or two values separated by a space to trim each mate a different "
797
          "amount [default: no trimming]")
798
    .bind_vec(&pre_trim3p)
×
799
    .with_max_values(2);
×
800

801
  argparser.add("--post-trim5p", "N")
×
802
    .help("Trim the 5' by a fixed amount after removing adapters, but before "
×
803
          "carrying out quality based trimming [default: no trimming]")
804
    .deprecated_alias("--trim5p")
×
805
    .bind_vec(&post_trim5p)
×
806
    .with_max_values(2);
×
807
  argparser.add("--post-trim3p", "N")
×
808
    .deprecated_alias("--trim3p")
×
809
    .help("Trim the 3' by a fixed amount after removing adapters, but before "
×
810
          "carrying out quality based trimming [default: no trimming]")
811
    .bind_vec(&post_trim3p)
×
812
    .with_max_values(2);
×
813

814
  argparser.add_separator();
×
815
  argparser.add("--quality-trimming", "method")
×
816
    .help("Strategy for trimming low quality bases: 'mott' for the modified "
×
817
          "Mott's algorithm; 'window' for window based trimming; 'per-base' "
818
          "for a per-base trimming of low quality base; and 'none' for no "
819
          "trimming of low quality bases")
820
    .deprecated_alias("--trim-strategy") // name used during v3 alpha 1
×
821
    .bind_str(nullptr)
×
822
    .with_choices({ "mott", "window", "per-base", "none" })
×
823
    .with_default("mott");
×
824

825
  argparser.add("--trim-mott-quality", "N")
×
826
    .help("The inclusive threshold value used when performing quality based "
×
827
          "trimming using the modified Mott's algorithm. The value must be in "
828
          "the range 0 to 93, corresponding to Phred+33 encoded values of '!' "
829
          "to '~'")
830
    .deprecated_alias("--trim-mott-rate")
×
831
    .conflicts_with("--trim-windows")
×
832
    .conflicts_with("--trim-ns")
×
833
    .conflicts_with("--trim-qualities")
×
834
    .conflicts_with("--trim-min-quality")
×
835
    .bind_double(&trim_mott_rate)
×
836
    .with_minimum(0)
×
837
    .with_maximum(93)
×
838
    .with_default(13);
×
839
  argparser.add("--trim-windows", "X")
×
840
    .help("Specifies the size of the window used for '--quality-trimming "
×
841
          "window': If >= 1, this value will be used as the window size; if "
842
          "the value is < 1, window size is the read length times this value. "
843
          "If the resulting window size is 0 or larger than the read length, "
844
          "the read length is used as the window size")
845
    .deprecated_alias("--trimwindows")
×
846
    .conflicts_with("--trim-mott-quality")
×
847
    .conflicts_with("--trim-qualities")
×
848
    .bind_double(&trim_window_length)
×
849
    .with_minimum(0.0)
×
850
    .with_default(0.1);
×
851
  argparser.add("--trim-min-quality", "N")
×
852
    .help("Inclusive minimum quality used when trimming low-quality bases with "
×
853
          "--quality-trimming options 'window' and 'per-base'. The value must "
854
          "be in the range 0 to 93, corresponding to Phred+33 encoded values "
855
          "of '!' to '~'")
856
    .deprecated_alias("--minquality")
×
857
    .conflicts_with("--trim-mott-quality")
×
858
    .bind_u32(&trim_quality_score)
×
859
    .with_maximum(PHRED_SCORE_MAX)
×
860
    .with_default(2);
×
861
  argparser.add("--trim-ns")
×
862
    .help("If set, trim ambiguous bases (N) at 5'/3' termini when using the "
×
863
          "'window' or the 'per-base' trimming strategy")
864
    .conflicts_with("--trim-mott-quality")
×
865
    .deprecated_alias("--trimns")
×
866
    .bind_bool(&trim_ambiguous_bases);
×
867
  argparser.add("--trim-qualities")
×
868
    .help("If set, trim low-quality bases (< --trim-min-quality) when using "
×
869
          "the 'per-base' trimming strategy")
870
    .deprecated_alias("--trimqualities")
×
871
    .conflicts_with("--trim-mott-quality")
×
872
    .conflicts_with("--trim-windows")
×
873
    .bind_bool(&trim_low_quality_bases);
×
874

875
  argparser.add_separator();
×
876
  argparser.add("--pre-trim-polyx", "X")
×
877
    .help("Enable trimming of poly-X tails prior to read alignment and adapter "
×
878
          "trimming. Zero or more nucleotides (A, C, G, T) may be specified. "
879
          "Zero or more nucleotides may be specified after the option "
880
          "separated by spaces, with zero nucleotides corresponding to all of "
881
          "A, C, G, and T")
882
    .bind_vec(&pre_trim_poly_x_sink)
×
883
    .with_min_values(0);
×
884
  argparser.add("--post-trim-polyx", "X")
×
885
    .help("Enable trimming of poly-X tails after read alignment and adapter "
×
886
          "trimming/merging, but before trimming of low-quality bases. Merged "
887
          "reads are not trimmed by this option (both ends are 5'). Zero or "
888
          "more nucleotides (A, C, G, T) may be specified. Zero or more "
889
          "nucleotides may be specified after the option separated by spaces, "
890
          "with zero nucleotides corresponding to all of A, C, G, and T")
891
    .bind_vec(&post_trim_poly_x_sink)
×
892
    .with_min_values(0);
×
893
  argparser.add("--trim-polyx-threshold", "N")
×
894
    .help("The minimum number of bases in a poly-X tail")
×
895
    .bind_u32(&trim_poly_x_threshold)
×
896
    .with_default(10);
×
897

898
  argparser.add_separator();
×
899
  argparser.add("--preserve5p")
×
900
    .help("If set, bases at the 5p will not be trimmed by when performing "
×
901
          "quality based trimming of reads. Merged reads will not be quality "
902
          "trimmed when this option is enabled [default: 5p bases are trimmed]")
903
    .bind_bool(&preserve5p);
×
904

905
  //////////////////////////////////////////////////////////////////////////////
906
  argparser.add_header("FILTERING:");
×
907

908
  argparser.add("--max-ns", "N")
×
909
    .help("Reads containing more ambiguous bases (N) than this number after "
×
910
          "trimming are discarded [default: no maximum]")
911
    .deprecated_alias("--maxns")
×
912
    .bind_u32(&max_ambiguous_bases)
×
913
    .with_default(std::numeric_limits<uint32_t>::max());
×
914

915
  argparser.add("--min-length", "N")
×
916
    .help("Reads shorter than this length following trimming are discarded")
×
917
    .deprecated_alias("--minlength")
×
918
    .bind_u32(&min_genomic_length)
×
919
    .with_default(15);
×
920
  argparser.add("--max-length", "N")
×
921
    .help("Reads longer than this length following trimming are discarded "
×
922
          "[default: no maximum]")
923
    .deprecated_alias("--maxlength")
×
924
    .bind_u32(&max_genomic_length)
×
925
    .with_default(std::numeric_limits<uint32_t>::max());
×
926

927
  argparser.add("--min-mean-quality", "N")
×
928
    .help("Reads with a mean Phred quality score less than this value "
×
929
          "following trimming are discarded. The value must be in the range 0 "
930
          "to 93, corresponding to Phred+33 encoded values of '!' to '~' "
931
          "[default: no minimum]")
932
    .bind_double(&min_mean_quality)
×
933
    .with_minimum(0.0)
×
934
    .with_maximum(PHRED_SCORE_MAX)
×
935
    .with_default(0.0);
×
936

937
  argparser.add("--min-complexity", "X")
×
938
    .help(
×
939
      "Filter reads with a complexity score less than this value. Complexity "
940
      "is measured as the fraction of positions that differ from the previous "
941
      "position. A suggested value is 0.3 [default: no minimum]")
942
    .bind_double(&min_complexity)
×
943
    .with_minimum(0.0)
×
944
    .with_maximum(1.0)
×
945
    .with_default(0);
×
946

947
  //////////////////////////////////////////////////////////////////////////////
948
  argparser.add_header("DEMULTIPLEXING:");
×
949

950
  argparser.add("--barcode-list", "FILE")
×
951
    .help("List of barcodes or barcode pairs for single or double-indexed "
×
952
          "demultiplexing. Note that both indexes should be specified for "
953
          "both single-end and paired-end trimming, if double-indexed "
954
          "multiplexing was used, in order to ensure that the demultiplexed "
955
          "reads can be trimmed correctly")
956
    .bind_str(&barcode_list);
×
957
  argparser.add("--multiple-barcodes")
×
958
    .help("Allow for more than one barcode (pair) for each sample. If this "
×
959
          "option is not specified, AdapterRemoval will abort if multiple "
960
          "barcodes/barcode pairs identify the same sample");
961
  argparser.add("--mixed-orientation", "X")
×
962
    .help("Process barcodes be sequences in both the barcode1-insert-barcode2 "
×
963
          "(forward) orientation and barcode2-insert-barcode1 (reverse) "
964
          "orientation. Takes an optional argument specifying the orientation "
965
          "of the barcodes in the `--barcode-list`, defaulting to `forward`")
966
    .deprecated_alias("--reversible-barcodes")
×
967
    .depends_on("--barcode-list")
×
968
    .bind_str(nullptr)
×
969
    .with_default("unspecified")
×
970
    .with_implicit_argument("forward")
×
971
    .with_choices({ "unspecified", "forward", "reverse", "explicit" });
×
NEW
972
  argparser.add("--normalize-orientation")
×
NEW
973
    .help("Reverse complement merged reads found to be in the reverse "
×
974
          "orientation, based on barcodes")
NEW
975
    .depends_on("--mixed-orientation")
×
NEW
976
    .depends_on("--merge")
×
NEW
977
    .bind_bool(&normalize_orientation);
×
978

979
  argparser.add_separator();
×
980
  argparser.add("--barcode-mm", "N")
×
981
    .help("Maximum number of mismatches allowed when counting mismatches in "
×
982
          "both the mate 1 and the mate 2 barcode for paired reads")
983
    .bind_u32(&barcode_mm)
×
984
    .with_default(0);
×
985
  argparser.add("--barcode-mm-r1", "N")
×
986
    .help("Maximum number of mismatches allowed for the mate 1 barcode. "
×
987
          "Cannot be higher than the --barcode-mm value [default: same value "
988
          "as --barcode-mm]")
989
    .bind_u32(&barcode_mm_r1)
×
990
    .with_default(0);
×
991
  argparser.add("--barcode-mm-r2", "N")
×
992
    .help("Maximum number of mismatches allowed for the mate 2 barcode. "
×
993
          "Cannot be higher than the --barcode-mm value [default: same value "
994
          "as --barcode-mm]")
995
    .bind_u32(&barcode_mm_r2)
×
996
    .with_default(0);
×
997
  argparser.add("--demultiplex-only")
×
998
    .help("Only carry out demultiplexing using the list of barcodes "
×
999
          "supplied with --barcode-list. No other processing is done")
1000
    .depends_on("--barcode-list")
×
1001
    .conflicts_with("--report-only");
×
1002

1003
  //////////////////////////////////////////////////////////////////////////////
1004
  argparser.add_header("REPORTS:");
×
1005

1006
  argparser.add("--report-only")
×
1007
    .help("Write a report of the input data without performing any processing "
×
1008
          "of the FASTQ reads. Adapter sequence inference is performed for PE "
1009
          "data based on overlapping mate reads. A report including read "
1010
          "processing, but without output, can be generated by setting "
1011
          "--output options to /dev/null")
1012
    .deprecated_alias("--identify-adapters")
×
1013
    .conflicts_with("--barcode-list")
×
1014
    .conflicts_with("--benchmark")
×
1015
    .conflicts_with("--demultiplex-only");
×
1016

1017
  argparser.add("--report-title", "X")
×
1018
    .help("Title used for HTML report")
×
1019
    .bind_str(&report_title)
×
1020
    .with_default(NAME + " " + VERSION);
×
1021
  argparser.add("--report-sample-rate", "X")
×
1022
    .help("Fraction of reads to use when generating base quality/composition "
×
1023
          "curves for trimming reports. Using all data (--report-sample-nth "
1024
          "1.0) results in an 10-30% decrease in throughput")
1025
    .bind_double(&report_sample_rate)
×
1026
    .with_minimum(0.0)
×
1027
    .with_maximum(1.0)
×
1028
    .with_default(0.1);
×
1029
  argparser.add("--report-duplication", "N")
×
1030
    .help("FastQC based duplicate detection, based on the frequency of the "
×
1031
          "first N unique sequences observed. If no value is given, an N of "
1032
          "100k is used, corresponding to FastQC defaults; a value of 0 "
1033
          "disables the analysis. Accepts suffixes K, M, and G")
1034
    .bind_str(nullptr)
×
1035
    .with_implicit_argument("100k");
×
1036

1037
  //////////////////////////////////////////////////////////////////////////////
1038
  argparser.add_header("LOGGING:");
×
1039

1040
  argparser.add("--log-level", "X")
×
1041
    .help("The minimum severity of messages to be written to STDERR")
×
1042
    .bind_str(&log_level)
×
1043
    .with_choices({ "debug", "info", "warning", "error" })
×
1044
    .with_default("info");
×
1045

1046
  argparser.add("--log-colors", "X")
×
1047
    .help("Enable/disable the use of colors when writing log messages. If set "
×
1048
          "to auto, colors will only be enabled if STDERR is a terminal and "
1049
          "the NO_COLORS is environmental variable is not set")
1050
    .bind_str(&log_color)
×
1051
    .with_choices({ "auto", "always", "never" })
×
1052
    .with_default("auto");
×
1053
  argparser.add("--log-progress", "X")
×
1054
    .help("Specify the type of progress reports used. If set to auto, then a "
×
1055
          "spinner will be used if STDERR is a terminal and the NO_COLORS "
1056
          "environmental variable is not set, otherwise logging will be used")
1057
    .bind_str(nullptr)
×
1058
    .with_choices({ "auto", "log", "spin", "never" })
×
1059
    .with_default("auto");
×
1060
}
1061

1062
argparse::parse_result
1063
userconfig::parse_args(const string_vec& argvec)
×
1064
{
1065
  args = argvec;
×
1066
  if (args.size() <= 1) {
×
1067
    argparser.print_help();
×
1068
    return argparse::parse_result::error;
1069
  }
1070

1071
  // ad-hoc arg parsing to make argparse output consistent with rest of run
1072
  configure_log_colors(try_parse_argument(args, "--log-color", "auto"), true);
×
1073
  configure_log_levels(try_parse_argument(args, "--log-level", "info"), true);
×
1074

1075
  const argparse::parse_result result = argparser.parse_args(args);
×
1076
  if (result != argparse::parse_result::ok) {
×
1077
    return result;
1078
  }
1079

1080
  configure_log_colors(log_color);
×
1081
  configure_log_levels(log_level);
×
1082
  log_progress = configure_log_progress(argparser.value("--log-progress"));
×
1083

1084
  {
×
1085
    const auto degenerate = argparser.is_set("--mask-degenerate-bases")
×
1086
                              ? degenerate_encoding::mask
×
1087
                              : degenerate_encoding::reject;
×
1088
    const auto uracils = argparser.is_set("--convert-uracils")
×
1089
                           ? uracil_encoding::convert
×
1090
                           : uracil_encoding::reject;
×
1091

1092
    io_encoding = configure_encoding(quality_input_base, degenerate, uracils);
×
1093
  }
1094

1095
  if (argparser.is_set("--mate-separator")) {
×
1096
    if (mate_separator_str.size() != 1) {
×
1097
      log::error() << "The argument for --mate-separator must be "
×
1098
                      "exactly one character long, not "
×
1099
                   << mate_separator_str.size() << " characters!";
×
1100
      return argparse::parse_result::error;
×
1101
    } else {
1102
      mate_separator = mate_separator_str.at(0);
×
1103
    }
1104
  }
1105

1106
  if (argparser.is_set("--demultiplex-only")) {
×
1107
    run_type = ar_command::demultiplex_only;
×
1108
  } else if (argparser.is_set("--report-only")) {
×
1109
    run_type = ar_command::report_only;
×
1110
  } else if (argparser.is_set("--benchmark")) {
×
1111
    run_type = ar_command::benchmark;
×
1112
  }
1113

1114
  {
×
1115
    const auto strategy = argparser.value("--quality-trimming");
×
1116
    if (strategy == "mott") {
×
1117
      trim = trimming_strategy::mott;
×
1118
      trim_mott_rate = std::pow(10.0, trim_mott_rate / -10.0);
×
1119
    } else if (strategy == "window") {
×
1120
      trim = trimming_strategy::window;
×
1121
    } else if (strategy == "per-base") {
×
1122
      trim = trimming_strategy::per_base;
×
1123

1124
      if (!trim_low_quality_bases && !trim_ambiguous_bases) {
×
1125
        log::error() << "The per-base quality trimming strategy is enabled, "
×
1126
                     << "but neither trimming of low-quality bases (via "
×
1127
                     << "--trim-qualities) nor trimming of Ns (via --trim-ns) "
×
1128
                     << "is enabled.";
×
1129
        return argparse::parse_result::error;
×
1130
      }
1131
    } else if (strategy == "none") {
×
1132
      trim = trimming_strategy::none;
×
1133
    } else {
1134
      AR_FAIL(shell_escape(strategy));
×
1135
    }
1136
  }
1137

1138
  // Check for invalid combinations of settings
1139
  if (input_files_1.empty() && input_files_2.empty()) {
×
1140
    log::error()
×
1141
      << "No input files (--in-file1 / --in-file2) specified.\n"
×
1142
      << "Please specify at least one input file using --in-file1 FILENAME.";
×
1143

1144
    return argparse::parse_result::error;
×
1145
  } else if (!input_files_2.empty() &&
×
1146
             (input_files_1.size() != input_files_2.size())) {
×
1147
    log::error()
×
1148
      << "Different number of files specified for --in-file1 and --in-file2.";
×
1149

1150
    return argparse::parse_result::error;
×
1151
  } else if (!input_files_2.empty()) {
×
1152
    paired_ended_mode = true;
×
1153
  }
1154

1155
  interleaved_input |= interleaved;
×
1156
  interleaved_output |= interleaved;
×
1157

1158
  if (interleaved_input) {
×
1159
    // Enable paired end mode .. other than the FASTQ reader, all other
1160
    // parts of the pipeline simply run in paired-end mode.
1161
    paired_ended_mode = true;
×
1162
  }
1163

1164
  if (paired_ended_mode) {
×
1165
    min_adapter_overlap = 0;
×
1166

1167
    // merge related options implies --merge
1168
    if (argparser.is_set("--collapse-deterministic")) {
×
1169
      merge = merge_strategy::additive;
×
1170
    } else if (argparser.is_set("--collapse-conservatively")) {
×
1171
      merge = merge_strategy::maximum;
×
1172
    } else if (argparser.is_set("--merge") ||
×
1173
               argparser.is_set("--merge-strategy")) {
×
1174
      const auto strategy = argparser.value("--merge-strategy");
×
1175
      if (strategy == "maximum") {
×
1176
        merge = merge_strategy::maximum;
×
1177
      } else if (strategy == "additive") {
×
1178
        merge = merge_strategy::additive;
×
1179
      } else {
1180
        AR_FAIL(strategy);
×
1181
      }
1182
    }
1183
  }
1184

1185
  // (Optionally) read adapters from file and validate
1186
  if (!setup_adapter_sequences()) {
×
1187
    return argparse::parse_result::error;
1188
  }
1189

1190
  // (Optionally) read barcodes from file and validate
1191
  if (!setup_demultiplexing()) {
×
1192
    return argparse::parse_result::error;
1193
  }
1194

1195
  if (argparser.is_set("--read-group")) {
×
1196
    auto merged_tags = join_text(read_group, "\t");
×
1197

1198
    try {
×
1199
      samples.set_read_group(merged_tags);
×
1200
    } catch (const std::invalid_argument& error) {
×
1201
      log::error() << "Invalid argument --read-group "
×
1202
                   << log_escape(merged_tags) << ": " << error.what();
×
1203

1204
      return argparse::parse_result::error;
×
1205
    }
×
1206
  }
1207

1208
  // Set mismatch threshold
1209
  if (mismatch_threshold > 1) {
×
1210
    mismatch_threshold = 1.0 / mismatch_threshold;
×
1211
  } else if (mismatch_threshold < 0) {
×
1212
    if (run_type == ar_command::report_only) {
×
1213
      mismatch_threshold = 1.0 / 10.0;
×
1214
    } else {
1215
      // Defaults for PE / SE trimming (changed in v3)
1216
      mismatch_threshold = 1.0 / 6.0;
×
1217
    }
1218
  }
1219

1220
  {
×
1221
    bool found = false;
×
1222
    const auto simd_choice = argparser.value("--simd");
×
1223
    for (const auto is : simd::supported()) {
×
1224
      if (simd_choice == simd::name(is)) {
×
1225
        simd = is;
×
1226
        found = true;
×
1227
        break;
×
1228
      }
1229
    }
1230

1231
    AR_REQUIRE(found);
×
1232
  }
1233

1234
  using fixed_trimming =
×
1235
    std::tuple<const char*, const string_vec&, std::pair<unsigned, unsigned>&>;
1236

1237
  const std::vector<fixed_trimming> fixed_trimming_options = {
×
1238
#ifdef PRE_TRIM_5P
1239
    { "--pre-trim5p", pre_trim5p, pre_trim_fixed_5p },
1240
#endif
1241
    { "--pre-trim3p", pre_trim3p, pre_trim_fixed_3p },
×
1242
    { "--post-trim5p", post_trim5p, post_trim_fixed_5p },
×
1243
    { "--post-trim3p", post_trim3p, post_trim_fixed_3p },
×
1244
  };
1245

1246
  for (const auto& it : fixed_trimming_options) {
×
1247
    try {
×
1248
      if (argparser.is_set(std::get<0>(it))) {
×
1249
        std::get<2>(it) = parse_trim_argument(std::get<1>(it));
×
1250
      }
1251
    } catch (const std::invalid_argument& error) {
×
1252
      log::error() << "Could not parse " << std::get<0>(it)
×
1253
                   << " argument(s): " << error.what();
×
1254

1255
      return argparse::parse_result::error;
×
1256
    }
×
1257
  }
1258

1259
  if (!parse_output_formats(argparser, out_file_format, out_stdout_format)) {
×
1260
    return argparse::parse_result::error;
1261
  }
1262

1263
  // An empty prefix or directory would results in the creation of dot-files
1264
  if (out_prefix.empty()) {
×
1265
    log::error() << "--out-prefix must be a non-empty value.";
×
1266

1267
    return argparse::parse_result::error;
×
1268
  } else if (out_prefix.back() == '/') {
×
1269
    log::error() << "--out-prefix must not be a directory: "
×
1270
                 << shell_escape(out_prefix);
×
1271

1272
    return argparse::parse_result::error;
×
1273
  } else if (out_prefix == DEV_NULL && run_type != ar_command::benchmark) {
×
1274
    // Relevant output options depend on input files and other settings
1275
    const std::vector<std::pair<std::string, bool>> output_keys = {
×
1276
      { "--out-file1",
1277
        is_adapter_trimming_enabled() || is_demultiplexing_enabled() },
×
1278
      { "--out-file2",
1279
        is_adapter_trimming_enabled() || is_demultiplexing_enabled() },
×
1280
      { "--out-singleton", is_any_filtering_enabled() },
×
1281
      { "--out-merged", is_read_merging_enabled() },
×
1282
      { "--out-discarded", is_any_filtering_enabled() },
×
1283
      { "--out-unidentified1", is_demultiplexing_enabled() },
×
1284
      { "--out-unidentified2", is_demultiplexing_enabled() },
×
1285
      { "--out-json", true },
1286
      { "--out-html", true },
1287
      { "--out-prefix", true },
1288
    };
1289

1290
    string_vec required_keys;
×
1291
    for (const auto& it : output_keys) {
×
1292
      if (it.second) {
×
1293
        required_keys.push_back(it.first);
×
1294
      }
1295
    }
1296

1297
    const auto user_keys = user_supplied_keys(argparser, required_keys);
×
1298
    if (user_keys.empty()) {
×
1299
      auto error = log::error();
×
1300
      error << "No output would be generated; at least one of the options "
×
1301
            << join_text(required_keys, ", ", ", or ")
×
1302
            << " must be used. The --out-prefix option automatically enables "
1303
               "all relevant --out options.";
×
1304

1305
      return argparse::parse_result::error;
×
1306
    }
1307
  }
1308

1309
  {
×
1310
    const std::string key = "--pre-trim-polyx";
×
1311
    if (argparser.is_set(key) &&
×
1312
        !parse_poly_x_option(key, pre_trim_poly_x_sink, pre_trim_poly_x)) {
×
1313
      return argparse::parse_result::error;
×
1314
    }
1315
  }
1316

1317
  {
×
1318
    const std::string key = "--post-trim-polyx";
×
1319
    if (argparser.is_set(key) &&
×
1320
        !parse_poly_x_option(key, post_trim_poly_x_sink, post_trim_poly_x)) {
×
1321
      return argparse::parse_result::error;
×
1322
    }
1323
  }
1324

1325
  if (!min_genomic_length) {
×
1326
    log::warn() << "--min-length is set to 0. This may produce FASTQ files "
×
1327
                   "that are incompatible with some tools!";
×
1328
  }
1329

1330
  // Default to all reads, but don't print value with --help
1331
  head = std::numeric_limits<uint64_t>::max();
×
1332
  if (!parse_counts(argparser, "--head", head)) {
×
1333
    return argparse::parse_result::error;
1334
  }
1335

1336
  if (!parse_counts(argparser, "--report-duplication", report_duplication)) {
×
1337
    return argparse::parse_result::error;
1338
  }
1339

1340
  return argparse::parse_result::ok;
1341
}
1342

1343
bool
1344
userconfig::is_good_alignment(const alignment_info& alignment) const
×
1345
{
1346
  if (!alignment.length || alignment.score() <= 0) {
×
1347
    return false;
×
1348
  }
1349

1350
  // Only pairs of called bases are considered part of the alignment
1351
  const size_t n_aligned = alignment.length - alignment.n_ambiguous;
×
1352
  if (n_aligned < min_adapter_overlap && !paired_ended_mode) {
×
1353
    return false;
1354
  }
1355

1356
  auto mm_threshold = static_cast<size_t>(mismatch_threshold * n_aligned);
×
1357
  if (n_aligned < 6) {
×
1358
    mm_threshold = 0;
×
1359
  } else if (n_aligned < 10) {
×
1360
    // Allow at most 1 mismatch, possibly set to 0 by the user
1361
    mm_threshold = std::min<size_t>(1, mm_threshold);
×
1362
  }
1363

1364
  return alignment.n_mismatches <= mm_threshold;
×
1365
}
1366

1367
bool
1368
userconfig::can_merge_alignment(const alignment_info& alignment) const
×
1369
{
1370
  if (alignment.length < alignment.n_ambiguous) {
×
1371
    throw std::invalid_argument("#ambiguous bases > read length");
×
1372
  }
1373

1374
  return alignment.length - alignment.n_ambiguous >= merge_threshold;
×
1375
}
1376

1377
output_format
1378
userconfig::infer_output_format(const std::string& filename) const
×
1379
{
1380
  if (filename == DEV_STDOUT) {
×
1381
    return out_stdout_format;
×
1382
  }
1383

1384
  output_format result = out_file_format;
×
1385
  // Parse failures are ignored here; default to --out-format
1386
  output_files::parse_extension(filename, result);
×
1387

1388
  return result;
×
1389
}
1390

1391
output_files
1392
userconfig::get_output_filenames() const
×
1393
{
1394
  output_files files;
×
1395

1396
  files.settings_json = new_output_file("--out-json", {}, {}, ".json").name;
×
1397
  files.settings_html = new_output_file("--out-html", {}, {}, ".html").name;
×
1398

1399
  auto ext = output_files::file_extension(out_file_format);
×
1400
  std::string_view out1 = interleaved_output ? "" : ".r1";
×
1401
  std::string_view out2 = interleaved_output ? "" : ".r2";
×
1402

1403
  if (is_demultiplexing_enabled()) {
×
1404
    files.unidentified_1 = new_output_file("--out-unidentified1",
×
1405
                                           {},
1406
                                           { ".unidentified", out1 },
1407
                                           ext);
×
1408

1409
    if (paired_ended_mode) {
×
1410
      if (interleaved_output) {
×
1411
        files.unidentified_2 = files.unidentified_1;
×
1412
      } else {
1413
        files.unidentified_2 = new_output_file("--out-unidentified2",
×
1414
                                               {},
1415
                                               { ".unidentified", out2 },
1416
                                               ext);
×
1417
      }
1418
    }
1419
  }
1420

1421
  for (const auto& sample : samples) {
×
1422
    const auto& name = sample.name();
×
1423
    sample_output_files map;
×
1424

1425
    const auto mate_1 = new_output_file("--out-file1", name, { out1 }, ext);
×
1426
    map.set_file(read_file::mate_1, mate_1);
×
1427

1428
    if (paired_ended_mode) {
×
1429
      if (interleaved_output) {
×
1430
        map.set_file(read_file::mate_2, mate_1);
×
1431
      } else {
1432
        map.set_file(read_file::mate_2,
×
1433
                     new_output_file("--out-file2", name, { out2 }, ext));
×
1434
      }
1435
    }
1436

1437
    if (run_type == ar_command::trim_adapters) {
×
1438
      if (is_any_filtering_enabled()) {
×
1439
        map.set_file(
×
1440
          read_file::discarded,
1441
          new_output_file("--out-discarded", name, { ".discarded" }, ext));
×
1442
      }
1443

1444
      if (paired_ended_mode) {
×
1445
        if (is_any_filtering_enabled()) {
×
1446
          map.set_file(
×
1447
            read_file::singleton,
1448
            new_output_file("--out-singleton", name, { ".singleton" }, ext));
×
1449
        }
1450

1451
        if (is_read_merging_enabled()) {
×
1452
          map.set_file(
×
1453
            read_file::merged,
1454
            new_output_file("--out-merged", name, { ".merged" }, ext));
×
1455
        }
1456
      }
1457
    }
1458

1459
    files.add_sample(std::move(map));
×
1460
  }
1461

1462
  return files;
×
1463
}
×
1464

1465
output_file
1466
userconfig::new_output_file(const std::string& key,
×
1467
                            std::string_view sample,
1468
                            std::vector<std::string_view> keys,
1469
                            std::string_view ext) const
1470
{
1471
  AR_REQUIRE(!ext.empty());
×
1472
  const auto default_is_fastq = out_file_format == output_format::fastq ||
×
1473
                                out_file_format == output_format::fastq_gzip;
1474

1475
  std::string out;
×
1476
  if (argparser.is_set(key)) {
×
1477
    out = argparser.value(key);
×
1478

1479
    // global files, e.g. reports and unidentified reads
1480
    if (sample.empty()) {
×
1481
      return { out, infer_output_format(out) };
×
1482
    }
1483
  } else if (default_is_fastq && key == "--out-discarded") {
×
1484
    // Discarded reads are dropped by default for non-archival formats
1485
    out = DEV_NULL;
×
1486
  } else {
1487
    out = out_prefix;
×
1488
  }
1489

1490
  if (out == DEV_NULL) {
×
1491
    return { out, output_format::fastq };
×
1492
  }
1493

1494
  if (!(default_is_fastq || keys.empty())) {
×
1495
    // SAM/BAM files are combined by default
1496
    keys.pop_back();
×
1497
  }
1498

1499
  if (!sample.empty()) {
×
1500
    keys.insert(keys.begin(), sample);
×
1501
  }
1502

1503
  keys.emplace_back(ext);
×
1504

1505
  for (const auto& value : keys) {
×
1506
    if (!value.empty() && value.front() != '.') {
×
1507
      out.push_back('.');
×
1508
    }
1509

1510
    out.append(value);
×
1511
  }
1512

1513
  return output_file{ out, infer_output_format(out) };
×
1514
}
1515

1516
bool
1517
check_and_set_barcode_mm(const argparse::parser& argparser,
×
1518
                         const std::string& key,
1519
                         uint32_t barcode_mm,
1520
                         uint32_t& dst)
1521
{
1522
  if (!argparser.is_set(key)) {
×
1523
    dst = barcode_mm;
×
1524
  } else if (dst > barcode_mm) {
×
1525
    log::error()
×
1526
      << "The maximum number of errors for " << key
×
1527
      << " is set \n"
1528
         "to a higher value than the total number of mismatches allowed\n"
1529
         "for barcodes (--barcode-mm). Please correct these settings.";
×
1530
    return false;
×
1531
  }
1532

1533
  return true;
1534
}
1535

1536
bool
1537
userconfig::is_adapter_trimming_enabled() const
×
1538
{
1539
  return run_type == ar_command::trim_adapters;
×
1540
}
1541

1542
bool
1543
userconfig::is_demultiplexing_enabled() const
×
1544
{
1545
  return !barcode_list.empty();
×
1546
}
1547

1548
bool
1549
userconfig::is_read_merging_enabled() const
×
1550
{
1551
  return is_adapter_trimming_enabled() && merge != merge_strategy::none;
×
1552
}
1553

1554
bool
1555
userconfig::is_any_quality_trimming_enabled() const
×
1556
{
1557
  return is_adapter_trimming_enabled() &&
×
1558
         (is_low_quality_trimming_enabled() ||
×
1559
          is_terminal_base_pre_trimming_enabled() ||
×
1560
          is_terminal_base_post_trimming_enabled() ||
×
1561
          is_poly_x_tail_pre_trimming_enabled() ||
×
1562
          is_poly_x_tail_post_trimming_enabled());
×
1563
}
1564

1565
bool
1566
userconfig::is_low_quality_trimming_enabled() const
×
1567
{
1568
  return trim != trimming_strategy::none;
×
1569
}
1570

1571
bool
1572
userconfig::is_terminal_base_pre_trimming_enabled() const
×
1573
{
1574
  return
×
1575
#ifdef PRE_TRIM_5P
1576
    pre_trim_fixed_5p.first || pre_trim_fixed_5p.second ||
1577
#endif
1578
    pre_trim_fixed_3p.first || pre_trim_fixed_3p.second;
×
1579
}
1580

1581
bool
1582
userconfig::is_terminal_base_post_trimming_enabled() const
×
1583
{
1584
  return post_trim_fixed_5p.first || post_trim_fixed_5p.second ||
×
1585
         post_trim_fixed_3p.first || post_trim_fixed_3p.second;
×
1586
}
1587

1588
bool
1589
userconfig::is_poly_x_tail_pre_trimming_enabled() const
×
1590
{
1591
  return !pre_trim_poly_x.empty();
×
1592
}
1593

1594
bool
1595
userconfig::is_poly_x_tail_post_trimming_enabled() const
×
1596
{
1597
  return !post_trim_poly_x.empty();
×
1598
}
1599

1600
bool
1601
userconfig::is_any_filtering_enabled() const
×
1602
{
1603
  return is_adapter_trimming_enabled() &&
×
1604
         (is_short_read_filtering_enabled() ||
×
1605
          is_long_read_filtering_enabled() ||
×
1606
          is_ambiguous_base_filtering_enabled() ||
×
1607
          is_mean_quality_filtering_enabled() ||
×
1608
          is_low_complexity_filtering_enabled());
×
1609
}
1610

1611
bool
1612
userconfig::is_short_read_filtering_enabled() const
×
1613
{
1614
  return min_genomic_length > 0;
×
1615
}
1616

1617
bool
1618
userconfig::is_long_read_filtering_enabled() const
×
1619
{
1620
  return max_genomic_length !=
×
1621
         std::numeric_limits<decltype(max_genomic_length)>::max();
×
1622
}
1623

1624
bool
1625
userconfig::is_ambiguous_base_filtering_enabled() const
×
1626
{
1627
  return max_ambiguous_bases !=
×
1628
         std::numeric_limits<decltype(max_ambiguous_bases)>::max();
×
1629
}
1630

1631
bool
1632
userconfig::is_mean_quality_filtering_enabled() const
×
1633
{
1634
  return min_mean_quality > 0;
×
1635
}
1636

1637
bool
1638
userconfig::is_low_complexity_filtering_enabled() const
×
1639
{
1640
  return min_complexity > 0;
×
1641
}
1642

1643
bool
1644
userconfig::setup_adapter_sequences()
×
1645
{
1646
  adapter_set adapters;
×
1647
  if (argparser.is_set("--adapter-list")) {
×
1648
    try {
×
1649
      adapters.load(adapter_list, paired_ended_mode);
×
1650
    } catch (const std::exception& error) {
×
1651
      log::error() << "Error reading adapters from " << log_escape(adapter_list)
×
1652
                   << ": " << error.what();
×
1653
      return false;
×
1654
    }
×
1655

1656
    log::info() << "Read " << adapters.size()
×
1657
                << " adapters / adapter pairs from '" << adapter_list << "'";
×
1658
  } else {
1659
    try {
×
1660
      adapters.add(dna_sequence{ adapter_1 }, dna_sequence{ adapter_2 });
×
1661
    } catch (const fastq_error& error) {
×
1662
      log::error() << "Error parsing adapter sequence(s):\n"
×
1663
                   << "   " << error.what();
×
1664

1665
      return false;
×
1666
    }
×
1667
  }
1668

1669
  samples.set_adapters(std::move(adapters));
×
1670

1671
  return true;
×
1672
}
1673

1674
bool
1675
userconfig::setup_demultiplexing()
×
1676
{
1677
  if (!argparser.is_set("--barcode-mm")) {
×
1678
    barcode_mm = barcode_mm_r1 + barcode_mm_r2;
×
1679
  }
1680

1681
  if (!check_and_set_barcode_mm(argparser,
×
1682
                                "--barcode-mm-r1",
1683
                                barcode_mm,
1684
                                barcode_mm_r1)) {
×
1685
    return false;
1686
  }
1687

1688
  if (!check_and_set_barcode_mm(argparser,
×
1689
                                "--barcode-mm-r2",
1690
                                barcode_mm,
1691
                                barcode_mm_r2)) {
×
1692
    return false;
1693
  }
1694

1695
  if (argparser.is_set("--barcode-list")) {
×
1696
    const auto orientation =
×
1697
      parse_table_orientation(argparser.value("--mixed-orientation"));
×
1698

1699
    barcode_config config;
×
1700
    config.paired_end_mode(paired_ended_mode)
×
1701
      .allow_multiple_barcodes(argparser.is_set("--multiple-barcodes"))
×
1702
      .orientation(orientation);
×
1703

1704
    try {
×
1705
      samples.load(barcode_list, config);
×
1706
    } catch (const std::exception& error) {
×
1707
      log::error() << "Error reading barcodes from " << log_escape(barcode_list)
×
1708
                   << ": " << error.what();
×
1709
      return false;
×
1710
    }
×
1711

1712
    log::info() << "Read " << samples.size() << " sets of barcodes from "
×
1713
                << shell_escape(barcode_list);
×
1714
  }
1715

1716
  const auto& output_files = get_output_filenames();
×
1717

1718
  return check_input_files(input_files_1, input_files_2) &&
×
1719
         check_output_files("--in-file1", input_files_1, output_files) &&
×
1720
         check_output_files("--in-file2", input_files_2, output_files);
×
1721
}
1722

1723
} // namespace adapterremoval
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc