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

MikkelSchubert / adapterremoval / #73

22 Mar 2025 10:19PM UTC coverage: 27.088% (-0.002%) from 27.09%
#73

push

travis-ci

web-flow
updates to formating and licensing headers (#95)

* use SPDX headers for licenses

This reduces verbosity and works around an issue with clang-format where
some formatting would not be applied due to the \***\ headers.

* set AllowAllArgumentsOnNextLine and InsertBraces

This results in more consistent formatting using clang-format

18 of 61 new or added lines in 12 files covered. (29.51%)

343 existing lines in 3 files now uncovered.

2601 of 9602 relevant lines covered (27.09%)

4259.01 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, ...
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 "simd.hpp"        // for size_t, name, supported, instruction_set
17
#include "strutils.hpp"    // for shell_escape, str_to_u32
18
#include <algorithm>       // for find, max, min
19
#include <cerrno>          // for errno
20
#include <cmath>           // for pow
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_head(const std::string& sink, uint64_t& out)
×
124
{
125
  if (sink.empty()) {
×
126
    // Default to all reads
127
    out = std::numeric_limits<uint64_t>::max();
×
128
    return true;
×
129
  }
130

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

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

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

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

156
    sink_without_unit.pop_back();
×
157
  }
158

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

169
  return true;
×
170
}
171

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

185
  return true;
×
186
}
187

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

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

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

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

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

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

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

254
  return !any_errors;
×
255
}
256

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

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

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

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

279
  return true;
×
280
}
281

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

297
  return fallback;
×
298
}
299

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

311
  return result;
×
312
}
×
313

314
////////////////////////////////////////////////////////////////////////////////
315

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

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

328
  return false;
329
}
330

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

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

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

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

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

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

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

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

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

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

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

443
  return true;
444
}
445

446
} // namespace
447

448
////////////////////////////////////////////////////////////////////////////////
449
// Implementations for `userconfig`
450

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

948
  argparser.add("--barcode-list", "FILE")
×
949
    .help("List of barcodes or barcode pairs for single or double-indexed "
×
950
          "demultiplexing. Note that both indexes should be specified for "
951
          "both single-end and paired-end trimming, if double-indexed "
952
          "multiplexing was used, in order to ensure that the demultiplexed "
953
          "reads can be trimmed correctly")
954
    .bind_str(&barcode_list);
×
955
  argparser.add("--multiple-barcodes")
×
956
    .help("Allow for more than one barcode (pair) for each sample. If this "
×
957
          "option is not specified, AdapterRemoval will abort if "
958
          "barcodes/barcode pairs do not to unique samples");
959
  argparser.add("--reversible-barcodes")
×
960
    .help("If set, it is assumed that barcodes can be sequences in both the "
×
961
          "barcode1-insert-barcode2 orientation and barcode2'-insert-barcode1' "
962
          "orientation, where ' indicates reverse complementation. This option "
963
          "requires two barcodes per sample (double-indexing)");
964

965
  argparser.add_separator();
×
966
  argparser.add("--barcode-mm", "N")
×
967
    .help("Maximum number of mismatches allowed when counting mismatches in "
×
968
          "both the mate 1 and the mate 2 barcode for paired reads")
969
    .bind_u32(&barcode_mm)
×
970
    .with_default(0);
×
971
  argparser.add("--barcode-mm-r1", "N")
×
972
    .help("Maximum number of mismatches allowed for the mate 1 barcode. "
×
973
          "Cannot be higher than the --barcode-mm value [default: same value "
974
          "as --barcode-mm]")
975
    .bind_u32(&barcode_mm_r1)
×
976
    .with_default(0);
×
977
  argparser.add("--barcode-mm-r2", "N")
×
978
    .help("Maximum number of mismatches allowed for the mate 2 barcode. "
×
979
          "Cannot be higher than the --barcode-mm value [default: same value "
980
          "as --barcode-mm]")
981
    .bind_u32(&barcode_mm_r2)
×
982
    .with_default(0);
×
983
  argparser.add("--demultiplex-only")
×
984
    .help("Only carry out demultiplexing using the list of barcodes "
×
985
          "supplied with --barcode-list. No other processing is done")
986
    .depends_on("--barcode-list")
×
987
    .conflicts_with("--report-only");
×
988

989
  //////////////////////////////////////////////////////////////////////////////
990
  argparser.add_header("REPORTS:");
×
991

992
  argparser.add("--report-only")
×
993
    .help("Write a report of the input data without performing any processing "
×
994
          "of the FASTQ reads. Adapter sequence inference is performed for PE "
995
          "data based on overlapping mate reads. A report including read "
996
          "processing, but without output, can be generated by setting "
997
          "--output options to /dev/null")
998
    .deprecated_alias("--identify-adapters")
×
999
    .conflicts_with("--barcode-list")
×
1000
    .conflicts_with("--benchmark")
×
1001
    .conflicts_with("--demultiplex-only");
×
1002

1003
  argparser.add("--report-title", "X")
×
1004
    .help("Title used for HTML report")
×
1005
    .bind_str(&report_title)
×
1006
    .with_default(NAME + " " + VERSION);
×
1007
  argparser.add("--report-sample-rate", "X")
×
1008
    .help("Fraction of reads to use when generating base quality/composition "
×
1009
          "curves for trimming reports. Using all data (--report-sample-nth "
1010
          "1.0) results in an 10-30% decrease in throughput")
1011
    .bind_double(&report_sample_rate)
×
1012
    .with_minimum(0.0)
×
1013
    .with_maximum(1.0)
×
1014
    .with_default(0.1);
×
1015
  argparser.add("--report-duplication", "N")
×
1016
    .help("FastQC based duplicate detection, based on the frequency of the "
×
1017
          "first N unique sequences observed. A value of 100,000 corresponds "
1018
          "to FastQC defaults; a value of 0 disables the analysis")
1019
    .bind_u32(&report_duplication)
×
1020
    .with_default(0);
×
1021

1022
  //////////////////////////////////////////////////////////////////////////////
1023
  argparser.add_header("LOGGING:");
×
1024

1025
  argparser.add("--log-level", "X")
×
1026
    .help("The minimum severity of messages to be written to STDERR")
×
1027
    .bind_str(&log_level)
×
1028
    .with_choices({ "debug", "info", "warning", "error" })
×
1029
    .with_default("info");
×
1030

1031
  argparser.add("--log-colors", "X")
×
1032
    .help("Enable/disable the use of colors when writing log messages. If set "
×
1033
          "to auto, colors will only be enabled if STDERR is a terminal and "
1034
          "the NO_COLORS is environmental variable is not set")
1035
    .bind_str(&log_color)
×
1036
    .with_choices({ "auto", "always", "never" })
×
1037
    .with_default("auto");
×
1038
  argparser.add("--log-progress", "X")
×
1039
    .help("Specify the type of progress reports used. If set to auto, then a "
×
1040
          "spinner will be used if STDERR is a terminal and the NO_COLORS "
1041
          "environmental variable is not set, otherwise logging will be used")
1042
    .bind_str(nullptr)
×
1043
    .with_choices({ "auto", "log", "spin", "never" })
×
1044
    .with_default("auto");
×
1045
}
1046

1047
argparse::parse_result
1048
userconfig::parse_args(const string_vec& argvec)
×
1049
{
1050
  args = argvec;
×
1051
  if (args.size() <= 1) {
×
1052
    argparser.print_help();
×
1053
    return argparse::parse_result::error;
1054
  }
1055

1056
  // ad-hoc arg parsing to make argparse output consistent with rest of run
1057
  configure_log_colors(try_parse_argument(args, "--log-color", "auto"), true);
×
1058
  configure_log_levels(try_parse_argument(args, "--log-level", "info"), true);
×
1059

1060
  const argparse::parse_result result = argparser.parse_args(args);
×
1061
  if (result != argparse::parse_result::ok) {
×
1062
    return result;
1063
  }
1064

1065
  configure_log_colors(log_color);
×
1066
  configure_log_levels(log_level);
×
1067
  log_progress = configure_log_progress(argparser.value("--log-progress"));
×
1068

1069
  {
×
1070
    const auto degenerate = argparser.is_set("--mask-degenerate-bases")
×
1071
                              ? degenerate_encoding::mask
×
1072
                              : degenerate_encoding::reject;
×
1073
    const auto uracils = argparser.is_set("--convert-uracils")
×
1074
                           ? uracil_encoding::convert
×
1075
                           : uracil_encoding::reject;
×
1076

1077
    io_encoding = configure_encoding(quality_input_base, degenerate, uracils);
×
1078
  }
1079

1080
  if (argparser.is_set("--mate-separator")) {
×
1081
    if (mate_separator_str.size() != 1) {
×
1082
      log::error() << "The argument for --mate-separator must be "
×
1083
                      "exactly one character long, not "
×
1084
                   << mate_separator_str.size() << " characters!";
×
1085
      return argparse::parse_result::error;
×
1086
    } else {
1087
      mate_separator = mate_separator_str.at(0);
×
1088
    }
1089
  }
1090

1091
  if (argparser.is_set("--demultiplex-only")) {
×
1092
    run_type = ar_command::demultiplex_only;
×
1093
  } else if (argparser.is_set("--report-only")) {
×
1094
    run_type = ar_command::report_only;
×
1095
  } else if (argparser.is_set("--benchmark")) {
×
1096
    run_type = ar_command::benchmark;
×
1097
  }
1098

1099
  {
×
1100
    const auto strategy = argparser.value("--quality-trimming");
×
1101
    if (strategy == "mott") {
×
1102
      trim = trimming_strategy::mott;
×
1103
      trim_mott_rate = std::pow(10.0, trim_mott_rate / -10.0);
×
1104
    } else if (strategy == "window") {
×
1105
      trim = trimming_strategy::window;
×
1106
    } else if (strategy == "per-base") {
×
1107
      trim = trimming_strategy::per_base;
×
1108

1109
      if (!trim_low_quality_bases && !trim_ambiguous_bases) {
×
1110
        log::error() << "The per-base quality trimming strategy is enabled, "
×
1111
                     << "but neither trimming of low-quality bases (via "
×
1112
                     << "--trim-qualities) nor trimming of Ns (via --trim-ns) "
×
1113
                     << "is enabled.";
×
1114
        return argparse::parse_result::error;
×
1115
      }
1116
    } else if (strategy == "none") {
×
1117
      trim = trimming_strategy::none;
×
1118
    } else {
1119
      AR_FAIL(shell_escape(strategy));
×
1120
    }
1121
  }
1122

1123
  // Check for invalid combinations of settings
1124
  if (input_files_1.empty() && input_files_2.empty()) {
×
1125
    log::error()
×
1126
      << "No input files (--in-file1 / --in-file2) specified.\n"
×
1127
      << "Please specify at least one input file using --in-file1 FILENAME.";
×
1128

1129
    return argparse::parse_result::error;
×
1130
  } else if (!input_files_2.empty() &&
×
1131
             (input_files_1.size() != input_files_2.size())) {
×
1132
    log::error()
×
1133
      << "Different number of files specified for --in-file1 and --in-file2.";
×
1134

1135
    return argparse::parse_result::error;
×
1136
  } else if (!input_files_2.empty()) {
×
1137
    paired_ended_mode = true;
×
1138
  }
1139

1140
  interleaved_input |= interleaved;
×
1141
  interleaved_output |= interleaved;
×
1142

1143
  if (interleaved_input) {
×
1144
    // Enable paired end mode .. other than the FASTQ reader, all other
1145
    // parts of the pipeline simply run in paired-end mode.
1146
    paired_ended_mode = true;
×
1147
  }
1148

1149
  if (paired_ended_mode) {
×
1150
    min_adapter_overlap = 0;
×
1151

1152
    // merge related options implies --merge
1153
    if (argparser.is_set("--collapse-deterministic")) {
×
1154
      merge = merge_strategy::additive;
×
1155
    } else if (argparser.is_set("--collapse-conservatively")) {
×
1156
      merge = merge_strategy::maximum;
×
1157
    } else if (argparser.is_set("--merge") ||
×
1158
               argparser.is_set("--merge-strategy")) {
×
1159
      const auto strategy = argparser.value("--merge-strategy");
×
1160
      if (strategy == "maximum") {
×
1161
        merge = merge_strategy::maximum;
×
1162
      } else if (strategy == "additive") {
×
1163
        merge = merge_strategy::additive;
×
1164
      } else {
1165
        AR_FAIL(strategy);
×
1166
      }
1167
    }
1168
  }
1169

1170
  // (Optionally) read adapters from file and validate
1171
  if (!setup_adapter_sequences()) {
×
1172
    return argparse::parse_result::error;
1173
  }
1174

1175
  // (Optionally) read barcodes from file and validate
1176
  if (!setup_demultiplexing()) {
×
1177
    return argparse::parse_result::error;
1178
  }
1179

1180
  if (argparser.is_set("--read-group")) {
×
1181
    auto merged_tags = join_text(read_group, "\t");
×
1182

1183
    try {
×
1184
      samples.set_read_group(merged_tags);
×
1185
    } catch (const std::invalid_argument& error) {
×
1186
      log::error() << "Invalid argument --read-group "
×
1187
                   << log_escape(merged_tags) << ": " << error.what();
×
1188

1189
      return argparse::parse_result::error;
×
1190
    }
×
1191
  }
1192

1193
  // Set mismatch threshold
1194
  if (mismatch_threshold > 1) {
×
1195
    mismatch_threshold = 1.0 / mismatch_threshold;
×
1196
  } else if (mismatch_threshold < 0) {
×
1197
    if (run_type == ar_command::report_only) {
×
1198
      mismatch_threshold = 1.0 / 10.0;
×
1199
    } else {
1200
      // Defaults for PE / SE trimming (changed in v3)
1201
      mismatch_threshold = 1.0 / 6.0;
×
1202
    }
1203
  }
1204

1205
  {
×
1206
    bool found = false;
×
1207
    const auto simd_choice = argparser.value("--simd");
×
1208
    for (const auto is : simd::supported()) {
×
1209
      if (simd_choice == simd::name(is)) {
×
1210
        simd = is;
×
1211
        found = true;
×
1212
        break;
×
1213
      }
1214
    }
1215

1216
    AR_REQUIRE(found);
×
1217
  }
1218

1219
  using fixed_trimming =
×
1220
    std::tuple<const char*, const string_vec&, std::pair<unsigned, unsigned>&>;
1221

1222
  const std::vector<fixed_trimming> fixed_trimming_options = {
×
1223
#ifdef PRE_TRIM_5P
1224
    { "--pre-trim5p", pre_trim5p, pre_trim_fixed_5p },
1225
#endif
1226
    { "--pre-trim3p", pre_trim3p, pre_trim_fixed_3p },
×
1227
    { "--post-trim5p", post_trim5p, post_trim_fixed_5p },
×
1228
    { "--post-trim3p", post_trim3p, post_trim_fixed_3p },
×
1229
  };
1230

1231
  for (const auto& it : fixed_trimming_options) {
×
1232
    try {
×
1233
      if (argparser.is_set(std::get<0>(it))) {
×
1234
        std::get<2>(it) = parse_trim_argument(std::get<1>(it));
×
1235
      }
1236
    } catch (const std::invalid_argument& error) {
×
1237
      log::error() << "Could not parse " << std::get<0>(it)
×
1238
                   << " argument(s): " << error.what();
×
1239

1240
      return argparse::parse_result::error;
×
1241
    }
×
1242
  }
1243

1244
  if (!parse_output_formats(argparser, out_file_format, out_stdout_format)) {
×
1245
    return argparse::parse_result::error;
1246
  }
1247

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

1252
    return argparse::parse_result::error;
×
1253
  } else if (out_prefix.back() == '/') {
×
1254
    log::error() << "--out-prefix must not be a directory: "
×
1255
                 << shell_escape(out_prefix);
×
1256

1257
    return argparse::parse_result::error;
×
1258
  } else if (out_prefix == DEV_NULL && run_type != ar_command::benchmark) {
×
1259
    // Relevant output options depend on input files and other settings
1260
    const std::vector<std::pair<std::string, bool>> output_keys = {
×
1261
      { "--out-file1",
1262
        is_adapter_trimming_enabled() || is_demultiplexing_enabled() },
×
1263
      { "--out-file2",
1264
        is_adapter_trimming_enabled() || is_demultiplexing_enabled() },
×
1265
      { "--out-singleton", is_any_filtering_enabled() },
×
1266
      { "--out-merged", is_read_merging_enabled() },
×
1267
      { "--out-discarded", is_any_filtering_enabled() },
×
1268
      { "--out-unidentified1", is_demultiplexing_enabled() },
×
1269
      { "--out-unidentified2", is_demultiplexing_enabled() },
×
1270
      { "--out-json", true },
1271
      { "--out-html", true },
1272
      { "--out-prefix", true },
1273
    };
1274

1275
    string_vec required_keys;
×
1276
    for (const auto& it : output_keys) {
×
1277
      if (it.second) {
×
1278
        required_keys.push_back(it.first);
×
1279
      }
1280
    }
1281

1282
    const auto user_keys = user_supplied_keys(argparser, required_keys);
×
1283
    if (user_keys.empty()) {
×
1284
      auto error = log::error();
×
1285
      error << "No output would be generated; at least one of the options "
×
1286
            << join_text(required_keys, ", ", ", or ")
×
1287
            << " must be used. The --out-prefix option automatically enables "
1288
               "all relevant --out options.";
×
1289

1290
      return argparse::parse_result::error;
×
1291
    }
1292
  }
1293

1294
  {
×
1295
    const std::string key = "--pre-trim-polyx";
×
1296
    if (argparser.is_set(key) &&
×
1297
        !parse_poly_x_option(key, pre_trim_poly_x_sink, pre_trim_poly_x)) {
×
1298
      return argparse::parse_result::error;
×
1299
    }
1300
  }
1301

1302
  {
×
1303
    const std::string key = "--post-trim-polyx";
×
1304
    if (argparser.is_set(key) &&
×
1305
        !parse_poly_x_option(key, post_trim_poly_x_sink, post_trim_poly_x)) {
×
1306
      return argparse::parse_result::error;
×
1307
    }
1308
  }
1309

1310
  if (!min_genomic_length) {
×
1311
    log::warn() << "--min-length is set to 0. This may produce FASTQ files "
×
1312
                   "that are incompatible with some tools!";
×
1313
  }
1314

1315
  if (!parse_head(argparser.value("--head"), head)) {
×
1316
    return argparse::parse_result::error;
×
1317
  }
1318

1319
  return argparse::parse_result::ok;
1320
}
1321

1322
bool
1323
userconfig::is_good_alignment(const alignment_info& alignment) const
×
1324
{
1325
  if (!alignment.length || alignment.score() <= 0) {
×
1326
    return false;
×
1327
  }
1328

1329
  // Only pairs of called bases are considered part of the alignment
1330
  const size_t n_aligned = alignment.length - alignment.n_ambiguous;
×
1331
  if (n_aligned < min_adapter_overlap && !paired_ended_mode) {
×
1332
    return false;
1333
  }
1334

1335
  auto mm_threshold = static_cast<size_t>(mismatch_threshold * n_aligned);
×
1336
  if (n_aligned < 6) {
×
1337
    mm_threshold = 0;
×
1338
  } else if (n_aligned < 10) {
×
1339
    // Allow at most 1 mismatch, possibly set to 0 by the user
1340
    mm_threshold = std::min<size_t>(1, mm_threshold);
×
1341
  }
1342

1343
  return alignment.n_mismatches <= mm_threshold;
×
1344
}
1345

1346
bool
1347
userconfig::can_merge_alignment(const alignment_info& alignment) const
×
1348
{
1349
  if (alignment.length < alignment.n_ambiguous) {
×
1350
    throw std::invalid_argument("#ambiguous bases > read length");
×
1351
  }
1352

1353
  return alignment.length - alignment.n_ambiguous >= merge_threshold;
×
1354
}
1355

1356
output_format
1357
userconfig::infer_output_format(const std::string& filename) const
×
1358
{
1359
  if (filename == "/dev/stdout") {
×
1360
    return out_stdout_format;
×
1361
  }
1362

1363
  output_format result = out_file_format;
×
1364
  // Parse failures are ignored here; default to --out-format
1365
  output_files::parse_extension(filename, result);
×
1366

1367
  return result;
×
1368
}
1369

1370
output_files
1371
userconfig::get_output_filenames() const
×
1372
{
1373
  output_files files;
×
1374

1375
  files.settings_json = new_output_file("--out-json", {}, {}, ".json").name;
×
1376
  files.settings_html = new_output_file("--out-html", {}, {}, ".html").name;
×
1377

1378
  auto ext = output_files::file_extension(out_file_format);
×
1379
  std::string_view out1 = interleaved_output ? "" : ".r1";
×
1380
  std::string_view out2 = interleaved_output ? "" : ".r2";
×
1381

1382
  if (is_demultiplexing_enabled()) {
×
NEW
1383
    files.unidentified_1 = new_output_file("--out-unidentified1",
×
1384
                                           {},
1385
                                           { ".unidentified", out1 },
NEW
1386
                                           ext);
×
1387

1388
    if (paired_ended_mode) {
×
1389
      if (interleaved_output) {
×
1390
        files.unidentified_2 = files.unidentified_1;
×
1391
      } else {
NEW
1392
        files.unidentified_2 = new_output_file("--out-unidentified2",
×
1393
                                               {},
1394
                                               { ".unidentified", out2 },
NEW
1395
                                               ext);
×
1396
      }
1397
    }
1398
  }
1399

1400
  for (const auto& sample : samples) {
×
1401
    const auto& name = sample.name();
×
1402
    sample_output_files map;
×
1403

1404
    const auto mate_1 = new_output_file("--out-file1", name, { out1 }, ext);
×
1405
    map.set_file(read_type::mate_1, mate_1);
×
1406

1407
    if (paired_ended_mode) {
×
1408
      if (interleaved_output) {
×
1409
        map.set_file(read_type::mate_2, mate_1);
×
1410
      } else {
1411
        map.set_file(read_type::mate_2,
×
1412
                     new_output_file("--out-file2", name, { out2 }, ext));
×
1413
      }
1414
    }
1415

1416
    if (run_type == ar_command::trim_adapters) {
×
1417
      if (is_any_filtering_enabled()) {
×
1418
        map.set_file(
×
1419
          read_type::discarded,
1420
          new_output_file("--out-discarded", name, { ".discarded" }, ext));
×
1421
      }
1422

1423
      if (paired_ended_mode) {
×
1424
        if (is_any_filtering_enabled()) {
×
1425
          map.set_file(
×
1426
            read_type::singleton,
1427
            new_output_file("--out-singleton", name, { ".singleton" }, ext));
×
1428
        }
1429

1430
        if (is_read_merging_enabled()) {
×
1431
          map.set_file(
×
1432
            read_type::merged,
1433
            new_output_file("--out-merged", name, { ".merged" }, ext));
×
1434
        }
1435
      }
1436
    }
1437

1438
    files.add_sample(std::move(map));
×
1439
  }
1440

1441
  return files;
×
1442
}
×
1443

1444
output_file
1445
userconfig::new_output_file(const std::string& key,
×
1446
                            std::string_view sample,
1447
                            std::vector<std::string_view> keys,
1448
                            std::string_view ext) const
1449
{
1450
  AR_REQUIRE(!ext.empty());
×
1451
  const auto default_is_fastq = out_file_format == output_format::fastq ||
×
1452
                                out_file_format == output_format::fastq_gzip;
1453

1454
  std::string out;
×
1455
  if (argparser.is_set(key)) {
×
1456
    out = argparser.value(key);
×
1457

1458
    // global files, e.g. reports and unidentified reads
1459
    if (sample.empty()) {
×
1460
      return { out, infer_output_format(out) };
×
1461
    }
1462
  } else if (default_is_fastq && key == "--out-discarded") {
×
1463
    // Discarded reads are dropped by default for non-archival formats
1464
    out = DEV_NULL;
×
1465
  } else {
1466
    out = out_prefix;
×
1467
  }
1468

1469
  if (out == DEV_NULL) {
×
1470
    return { out, output_format::fastq };
×
1471
  }
1472

1473
  if (!(default_is_fastq || keys.empty())) {
×
1474
    // SAM/BAM files are combined by default
1475
    keys.pop_back();
×
1476
  }
1477

1478
  if (!sample.empty()) {
×
1479
    keys.insert(keys.begin(), sample);
×
1480
  }
1481

1482
  keys.emplace_back(ext);
×
1483

1484
  for (const auto& value : keys) {
×
1485
    if (!value.empty() && value.front() != '.') {
×
1486
      out.push_back('.');
×
1487
    }
1488

1489
    out.append(value);
×
1490
  }
1491

1492
  return output_file{ out, infer_output_format(out) };
×
1493
}
1494

1495
bool
1496
check_and_set_barcode_mm(const argparse::parser& argparser,
×
1497
                         const std::string& key,
1498
                         uint32_t barcode_mm,
1499
                         uint32_t& dst)
1500
{
1501
  if (!argparser.is_set(key)) {
×
1502
    dst = barcode_mm;
×
1503
  } else if (dst > barcode_mm) {
×
1504
    log::error()
×
1505
      << "The maximum number of errors for " << key
×
1506
      << " is set \n"
1507
         "to a higher value than the total number of mismatches allowed\n"
1508
         "for barcodes (--barcode-mm). Please correct these settings.";
×
1509
    return false;
×
1510
  }
1511

1512
  return true;
1513
}
1514

1515
bool
1516
userconfig::is_adapter_trimming_enabled() const
×
1517
{
1518
  return run_type == ar_command::trim_adapters;
×
1519
}
1520

1521
bool
1522
userconfig::is_demultiplexing_enabled() const
×
1523
{
1524
  return !barcode_list.empty();
×
1525
}
1526

1527
bool
1528
userconfig::is_read_merging_enabled() const
×
1529
{
1530
  return is_adapter_trimming_enabled() && merge != merge_strategy::none;
×
1531
}
1532

1533
bool
1534
userconfig::is_any_quality_trimming_enabled() const
×
1535
{
1536
  return is_adapter_trimming_enabled() &&
×
1537
         (is_low_quality_trimming_enabled() ||
×
1538
          is_terminal_base_pre_trimming_enabled() ||
×
1539
          is_terminal_base_post_trimming_enabled() ||
×
1540
          is_poly_x_tail_pre_trimming_enabled() ||
×
1541
          is_poly_x_tail_post_trimming_enabled());
×
1542
}
1543

1544
bool
1545
userconfig::is_low_quality_trimming_enabled() const
×
1546
{
1547
  return trim != trimming_strategy::none;
×
1548
}
1549

1550
bool
1551
userconfig::is_terminal_base_pre_trimming_enabled() const
×
1552
{
1553
  return
×
1554
#ifdef PRE_TRIM_5P
1555
    pre_trim_fixed_5p.first || pre_trim_fixed_5p.second ||
1556
#endif
1557
    pre_trim_fixed_3p.first || pre_trim_fixed_3p.second;
×
1558
}
1559

1560
bool
1561
userconfig::is_terminal_base_post_trimming_enabled() const
×
1562
{
1563
  return post_trim_fixed_5p.first || post_trim_fixed_5p.second ||
×
1564
         post_trim_fixed_3p.first || post_trim_fixed_3p.second;
×
1565
}
1566

1567
bool
1568
userconfig::is_poly_x_tail_pre_trimming_enabled() const
×
1569
{
1570
  return !pre_trim_poly_x.empty();
×
1571
}
1572

1573
bool
1574
userconfig::is_poly_x_tail_post_trimming_enabled() const
×
1575
{
1576
  return !post_trim_poly_x.empty();
×
1577
}
1578

1579
bool
1580
userconfig::is_any_filtering_enabled() const
×
1581
{
1582
  return is_adapter_trimming_enabled() &&
×
1583
         (is_short_read_filtering_enabled() ||
×
1584
          is_long_read_filtering_enabled() ||
×
1585
          is_ambiguous_base_filtering_enabled() ||
×
1586
          is_mean_quality_filtering_enabled() ||
×
1587
          is_low_complexity_filtering_enabled());
×
1588
}
1589

1590
bool
1591
userconfig::is_short_read_filtering_enabled() const
×
1592
{
1593
  return min_genomic_length > 0;
×
1594
}
1595

1596
bool
1597
userconfig::is_long_read_filtering_enabled() const
×
1598
{
1599
  return max_genomic_length !=
×
1600
         std::numeric_limits<decltype(max_genomic_length)>::max();
×
1601
}
1602

1603
bool
1604
userconfig::is_ambiguous_base_filtering_enabled() const
×
1605
{
1606
  return max_ambiguous_bases !=
×
1607
         std::numeric_limits<decltype(max_ambiguous_bases)>::max();
×
1608
}
1609

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

1616
bool
1617
userconfig::is_low_complexity_filtering_enabled() const
×
1618
{
1619
  return min_complexity > 0;
×
1620
}
1621

1622
bool
1623
userconfig::setup_adapter_sequences()
×
1624
{
1625
  adapter_set adapters;
×
1626
  if (argparser.is_set("--adapter-list")) {
×
1627
    try {
×
1628
      adapters.load(adapter_list, paired_ended_mode);
×
1629
    } catch (const std::exception& error) {
×
1630
      log::error() << "Error reading adapters from " << log_escape(adapter_list)
×
1631
                   << ": " << error.what();
×
1632
      return false;
×
1633
    }
×
1634

1635
    if (adapters.size()) {
×
1636
      log::info() << "Read " << adapters.size()
×
1637
                  << " adapters / adapter pairs from '" << adapter_list << "'";
×
1638
    } else {
1639
      log::error() << "No adapter sequences found in table!";
×
1640
      return false;
×
1641
    }
1642
  } else {
1643
    try {
×
1644
      adapters.add(adapter_1, adapter_2);
×
1645
    } catch (const fastq_error& error) {
×
1646
      log::error() << "Error parsing adapter sequence(s):\n"
×
1647
                   << "   " << error.what();
×
1648

1649
      return false;
×
1650
    }
×
1651
  }
1652

1653
  samples.set_adapters(std::move(adapters));
×
1654

1655
  return true;
×
1656
}
1657

1658
bool
1659
userconfig::setup_demultiplexing()
×
1660
{
1661
  if (!argparser.is_set("--barcode-mm")) {
×
1662
    barcode_mm = barcode_mm_r1 + barcode_mm_r2;
×
1663
  }
1664

NEW
1665
  if (!check_and_set_barcode_mm(argparser,
×
1666
                                "--barcode-mm-r1",
1667
                                barcode_mm,
NEW
1668
                                barcode_mm_r1)) {
×
1669
    return false;
1670
  }
1671

NEW
1672
  if (!check_and_set_barcode_mm(argparser,
×
1673
                                "--barcode-mm-r2",
1674
                                barcode_mm,
NEW
1675
                                barcode_mm_r2)) {
×
1676
    return false;
1677
  }
1678

1679
  if (argparser.is_set("--barcode-list")) {
×
1680
    const auto config =
×
1681
      barcode_config()
×
1682
        .paired_end_mode(paired_ended_mode)
×
1683
        .allow_multiple_barcodes(argparser.is_set("--multiple-barcodes"))
×
1684
        .unidirectional_barcodes(!argparser.is_set("--reversible-barcodes"));
×
1685

1686
    try {
×
1687
      samples.load(barcode_list, config);
×
1688
    } catch (const std::exception& error) {
×
1689
      log::error() << "Error reading barcodes from " << log_escape(barcode_list)
×
1690
                   << ": " << error.what();
×
1691
      return false;
×
1692
    }
×
1693

1694
    log::info() << "Read " << samples.size() << " sets of barcodes from "
×
1695
                << shell_escape(barcode_list);
×
1696
  }
1697

1698
  const auto& output_files = get_output_filenames();
×
1699

1700
  return check_input_files(input_files_1, input_files_2) &&
×
1701
         check_output_files("--in-file1", input_files_1, output_files) &&
×
1702
         check_output_files("--in-file2", input_files_2, output_files);
×
1703
}
1704

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

© 2026 Coveralls, Inc