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

MikkelSchubert / adapterremoval / #106

28 Apr 2025 11:42AM UTC coverage: 66.997% (+0.07%) from 66.927%
#106

push

travis-ci

web-flow
gather phred<->p code and fix reported mott value (#132)

42 of 47 new or added lines in 6 files covered. (89.36%)

8 existing lines in 1 file now uncovered.

9732 of 14526 relevant lines covered (67.0%)

3044.2 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 <cstdlib>         // for getenv
22
#include <cstring>         // for size_t, strerror, strcmp
23
#include <filesystem>      // for weakly_canonical
24
#include <limits>          // for numeric_limits
25
#include <stdexcept>       // for invalid_argument
26
#include <string>          // for string, basic_string, operator==, operator+
27
#include <string_view>     // for string_view
28
#include <tuple>           // for get, tuple
29
#include <unistd.h>        // for access, isatty, R_OK, STDERR_FILENO
30

31
namespace adapterremoval {
32

33
namespace {
34

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

54
////////////////////////////////////////////////////////////////////////////////
55
// Helper functions
56

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

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

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

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

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

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

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

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

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

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

119
  return true;
120
}
121

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

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

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

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

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

157
    sink_without_unit.pop_back();
×
158
  }
159

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

170
  return true;
×
171
}
172

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

186
  return true;
×
187
}
188

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

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

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

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

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

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

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

255
  return !any_errors;
×
256
}
257

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

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

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

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

280
  return true;
×
281
}
282

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

298
  return fallback;
×
299
}
300

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

312
  return result;
×
313
}
×
314

315
////////////////////////////////////////////////////////////////////////////////
316

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

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

329
  return false;
330
}
331

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

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

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

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

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

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

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

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

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

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

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

444
  return true;
445
}
446

447
} // namespace
448

449
////////////////////////////////////////////////////////////////////////////////
450
// Implementations for `userconfig`
451

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1113
  {
×
1114
    const auto strategy = argparser.value("--quality-trimming");
×
1115
    if (strategy == "mott") {
×
1116
      trim = trimming_strategy::mott;
×
NEW
1117
      trim_mott_rate = fastq_encoding::phred_to_p(trim_mott_rate);
×
1118
    } else if (strategy == "window") {
×
1119
      trim = trimming_strategy::window;
×
1120
    } else if (strategy == "per-base") {
×
1121
      trim = trimming_strategy::per_base;
×
1122

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1230
    AR_REQUIRE(found);
×
1231
  }
1232

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1387
  return result;
×
1388
}
1389

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

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

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

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

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

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

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

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

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

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

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

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

1461
  return files;
×
1462
}
×
1463

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

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

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

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

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

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

1502
  keys.emplace_back(ext);
×
1503

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

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

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

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

1532
  return true;
1533
}
1534

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1664
      return false;
×
1665
    }
×
1666
  }
1667

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

1670
  return true;
×
1671
}
1672

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

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

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

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

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

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

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

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

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

1722
} // 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