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

MikkelSchubert / adapterremoval / #70

20 Mar 2025 11:40AM UTC coverage: 27.092%. Remained the same
#70

push

travis-ci

web-flow
fix manually disabled files when demultiplexing (#92)

0 of 6 new or added lines in 1 file covered. (0.0%)

1 existing line in 1 file now uncovered.

2597 of 9586 relevant lines covered (27.09%)

4264.39 hits per line

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

0.0
/src/userconfig.cpp
1
/*************************************************************************\
2
 * AdapterRemoval - cleaning next-generation sequencing reads            *
3
 *                                                                       *
4
 * Copyright (C) 2011 by Stinus Lindgreen - stinus@binf.ku.dk            *
5
 * Copyright (C) 2014 by Mikkel Schubert - mikkelsch@gmail.com           *
6
 *                                                                       *
7
 * This program is free software: you can redistribute it and/or modify  *
8
 * it under the terms of the GNU General Public License as published by  *
9
 * the Free Software Foundation, either version 3 of the License, or     *
10
 * (at your option) any later version.                                   *
11
 *                                                                       *
12
 * This program is distributed in the hope that it will be useful,       *
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
15
 * GNU General Public License for more details.                          *
16
 *                                                                       *
17
 * You should have received a copy of the GNU General Public License     *
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. *
19
\*************************************************************************/
20
#include "userconfig.hpp"  // declarations
21
#include "alignment.hpp"   // for alignment_info
22
#include "commontypes.hpp" // for string_vec, ...
23
#include "debug.hpp"       // for AR_REQUIRE, AR_FAIL
24
#include "errors.hpp"      // for fastq_error
25
#include "fastq.hpp"       // for ACGT, ACGT::indices, ACGT::values
26
#include "fastq_enc.hpp"   // for PHRED_SCORE_MAX
27
#include "licenses.hpp"    // for LICENSES
28
#include "logging.hpp"     // for log_stream, error, set_level, set_colors, info
29
#include "main.hpp"        // for HELPTEXT, NAME, VERSION
30
#include "output.hpp"      // for DEV_NULL, output_files, output_file
31
#include "progress.hpp"    // for progress_type, progress_type::simple, progr...
32
#include "simd.hpp"        // for size_t, name, supported, instruction_set
33
#include "strutils.hpp"    // for shell_escape, str_to_u32
34
#include <algorithm>       // for find, max, min
35
#include <cerrno>          // for errno
36
#include <cmath>           // for pow
37
#include <cstdlib>         // for getenv
38
#include <cstring>         // for size_t, strerror, strcmp
39
#include <filesystem>      // for weakly_canonical
40
#include <limits>          // for numeric_limits
41
#include <stdexcept>       // for invalid_argument
42
#include <string>          // for string, basic_string, operator==, operator+
43
#include <string_view>     // for string_view
44
#include <tuple>           // for get, tuple
45
#include <unistd.h>        // for access, isatty, R_OK, STDERR_FILENO
46

47
namespace adapterremoval {
48

49
namespace {
50

51
const char* HELPTEXT =
52
  "This program searches for and removes remnant adapter sequences, poly-X "
53
  "tails and low-quality base from FASTQ reads. For detailed explanation of "
54
  "the parameters, please refer to the man page. For comments, suggestions "
55
  "and feedback please use\n"
56
  "\n"
57
  "  https://github.com/MikkelSchubert/adapterremoval/issues/new\n"
58
  "\n"
59
  "If you use the program, please cite the paper\n"
60
  "\n"
61
  "  Schubert, Lindgreen, and Orlando (2016). AdapterRemoval v2: rapid\n"
62
  "  adapter trimming, identification, and read merging. BMC Research\n"
63
  "  Notes, 12;9(1):88. https://doi.org/10.1186/s13104-016-1900-2\n"
64
  "\n"
65
  "Use the filename '-' to read from STDIN or to write to STDOUT. If the same "
66
  "filenames are used for two or more of the --out-* options (excluding "
67
  "--out-json and --out-html), then the combined output is written to that "
68
  "file in interleaved mode.\n";
69

70
////////////////////////////////////////////////////////////////////////////////
71
// Helper functions
72

73
std::pair<unsigned, unsigned>
74
parse_trim_argument(const string_vec& values)
×
75
{
76
  unsigned mate_1 = 0;
×
77
  unsigned mate_2 = 0;
×
78

79
  switch (values.size()) {
×
80
    case 1:
×
81
      mate_1 = str_to_u32(values.front());
×
82
      mate_2 = mate_1;
×
83
      break;
×
84

85
    case 2:
×
86
      mate_1 = str_to_u32(values.front());
×
87
      mate_2 = str_to_u32(values.back());
×
88
      break;
×
89

90
    default:
×
91
      throw std::invalid_argument("please specify exactly one or two values");
×
92
  }
93

94
  return { mate_1, mate_2 };
×
95
}
96

97
bool
98
parse_poly_x_option(const std::string& key,
×
99
                    const string_vec& values,
100
                    std::string& out)
101
{
102
  out.clear();
×
103
  if (values.empty()) {
×
104
    out = "ACGT";
×
105
    return true;
106
  }
107

108
  std::array<bool, ACGT::indices> enabled = {};
×
109
  for (const auto& value : values) {
×
110
    for (const auto nuc : to_upper(value)) {
×
111
      switch (nuc) {
×
112
        case 'A':
×
113
        case 'C':
×
114
        case 'G':
×
115
        case 'T':
×
116
          enabled.at(ACGT::to_index(nuc)) = true;
×
117
          break;
×
118

119
        default:
×
120
          log::error() << "Option " << key << " called with invalid value "
×
121
                       << shell_escape(value) << ". Only A, C, G, and T are "
×
122
                       << "permitted!";
×
123

124
          return false;
×
125
      }
126
    }
127
  }
128

129
  for (const auto nuc : ACGT::values) {
×
130
    if (enabled.at(ACGT::to_index(nuc))) {
×
131
      out.push_back(nuc);
×
132
    }
133
  }
134

135
  return true;
136
}
137

138
bool
139
parse_head(const std::string& sink, uint64_t& out)
×
140
{
141
  if (sink.empty()) {
×
142
    // Default to all reads
143
    out = std::numeric_limits<uint64_t>::max();
×
144
    return true;
×
145
  }
146

147
  uint64_t unit = 1;
×
148
  std::string sink_without_unit = sink;
×
149
  if (sink.back() < '0' || sink.back() > '9') {
×
150
    switch (sink.back()) {
×
151
      case 'k':
152
      case 'K':
153
        unit = 1000;
154
        break;
155

156
      case 'm':
×
157
      case 'M':
×
158
        unit = 1000'000;
×
159
        break;
×
160

161
      case 'g':
×
162
      case 'G':
×
163
        unit = 1000'000'000;
×
164
        break;
×
165

166
      default:
×
167
        log::error() << "Invalid unit in command-line option --sink "
×
168
                     << shell_escape(sink);
×
169
        return false;
×
170
    }
171

172
    sink_without_unit.pop_back();
×
173
  }
174

175
  try {
×
176
    // This should not be able to overflow as log2(2^32 * 1e9) ~= 62,
177
    // but will need to be changed if we want to allow large raw numbers
178
    out = static_cast<uint64_t>(str_to_u32(sink_without_unit)) * unit;
×
179
  } catch (const std::invalid_argument&) {
×
180
    log::error() << "Invalid value in command-line option --sink "
×
181
                 << shell_escape(sink);
×
182
    return false;
×
183
  }
×
184

185
  return true;
×
186
}
187

188
bool
189
check_no_clobber(const std::string& label,
×
190
                 const string_vec& in_files,
191
                 const output_file& out_file)
192
{
193
  for (const auto& in_file : in_files) {
×
194
    if (in_file == out_file.name && in_file != DEV_NULL) {
×
195
      log::error() << "Input file would be overwritten: " << label << " "
×
196
                   << in_file;
×
197
      return false;
×
198
    }
199
  }
200

201
  return true;
×
202
}
203

204
/** Replace the STDIN pseudo-filename with the device path */
205
void
206
normalize_input_file(std::string& filename)
×
207
{
208
  if (filename == "-") {
×
209
    filename = "/dev/stdin";
×
210
  }
211
}
212

213
/** Replace the STDIN pseudo-filename with the device path */
214
void
215
normalize_output_file(std::string& filename)
×
216
{
217
  if (filename == "-") {
×
218
    filename = "/dev/stdout";
×
219
  }
220
}
221

222
void
223
append_normalized_input_files(string_pair_vec& out, const string_vec& filenames)
×
224
{
225
  for (const auto& filename : filenames) {
×
226
    try {
×
227
      out.emplace_back(std::filesystem::weakly_canonical(filename), filename);
×
228
    } catch (const std::filesystem::filesystem_error&) {
×
229
      // Permission errors are handled by the explicit access checks below
230
      out.emplace_back(filename, filename);
×
231
    }
×
232
  }
233
}
234

235
bool
236
check_input_files(const string_vec& filenames_1, const string_vec& filenames_2)
×
237
{
238
  string_pair_vec filenames;
×
239
  append_normalized_input_files(filenames, filenames_1);
×
240
  append_normalized_input_files(filenames, filenames_2);
×
241
  std::sort(filenames.begin(), filenames.end());
×
242

243
  bool any_errors = false;
244
  for (size_t i = 1; i < filenames.size(); ++i) {
×
245
    const auto& it_0 = filenames.at(i - 1);
×
246
    const auto& it_1 = filenames.at(i);
×
247

248
    if (it_0.second == it_1.second) {
×
249
      log::error() << "Input file " << log_escape(it_0.second)
×
250
                   << " has been specified multiple times using --in-file1 "
251
                      "and/or --in-file2";
×
252
      any_errors = true;
×
253
    } else if (it_0.first == it_1.first) {
×
254
      log::error() << "The path of input file " << log_escape(it_0.second)
×
255
                   << " and the path of input " << "file "
×
256
                   << log_escape(it_1.second) << " both point to the file "
×
257
                   << log_escape(it_0.first);
×
258
      any_errors = true;
×
259
    }
260
  }
261

262
  for (const auto& it : filenames) {
×
263
    if (access(it.second.c_str(), R_OK)) {
×
264
      log::error() << "Cannot access input file " << log_escape(it.second)
×
265
                   << ": " << std::strerror(errno);
×
266
      any_errors = true;
×
267
    }
268
  }
269

270
  return !any_errors;
×
271
}
272

273
bool
274
check_output_files(const std::string& label,
×
275
                   const string_vec& filenames,
276
                   const output_files& output_files)
277
{
278

279
  if (!check_no_clobber(label, filenames, output_files.unidentified_1)) {
×
280
    return false;
281
  }
282

283
  if (!check_no_clobber(label, filenames, output_files.unidentified_2)) {
×
284
    return false;
285
  }
286

287
  for (const auto& sample : output_files.samples()) {
×
288
    for (size_t i = 0; i < sample.size(); ++i) {
×
289
      if (!check_no_clobber(label, filenames, sample.file(i))) {
×
290
        return false;
×
291
      }
292
    }
293
  }
294

295
  return true;
×
296
}
297

298
/**
299
 * Tries to parse a simple command-line argument while ignoring the validity
300
 * of the overall command-line. This is only intended to make pre-configured
301
 * logging output consistent with post-configured output if possible.
302
 */
303
std::string
304
try_parse_argument(const string_vec& args,
×
305
                   const std::string& key,
306
                   const std::string& fallback)
307
{
308
  auto it = std::find(args.begin(), args.end(), key);
×
309
  if (it != args.end() && (it + 1) != args.end()) {
×
310
    return *(it + 1);
×
311
  }
312

313
  return fallback;
×
314
}
315

316
/** Returns vector of keys for output files that have been set by the user. */
317
string_vec
318
user_supplied_keys(const argparse::parser& argparser, const string_vec& keys)
×
319
{
320
  string_vec result;
×
321
  for (const auto& key : keys) {
×
322
    if (argparser.is_set(key)) {
×
323
      result.push_back(key);
×
324
    }
325
  }
326

327
  return result;
×
328
}
×
329

330
////////////////////////////////////////////////////////////////////////////////
331

332
bool
333
fancy_output_allowed()
×
334
{
335
  if (::isatty(STDERR_FILENO)) {
×
336
    // NO_COLOR is checked as suggested by https://no-color.org/
337
    const char* no_color = std::getenv("NO_COLOR");
×
338
    const char* term = std::getenv("TERM");
×
339

340
    return !(no_color && no_color[0] != '\0') &&
×
341
           !(term && strcmp(term, "dumb") == 0);
×
342
  }
343

344
  return false;
345
}
346

347
void
348
configure_log_levels(const std::string& value, bool fallible = false)
×
349
{
350
  const auto log_level = to_lower(value);
×
351

352
  if (log_level == "debug") {
×
353
    log::set_level(log::level::debug);
×
354
  } else if (log_level == "info") {
×
355
    log::set_level(log::level::info);
×
356
  } else if (log_level == "warning") {
×
357
    log::set_level(log::level::warning);
×
358
  } else if (log_level == "error") {
×
359
    log::set_level(log::level::error);
×
360
  } else {
361
    AR_REQUIRE(fallible, "unhandled log_level value");
×
362
  }
363
}
364

365
void
366
configure_log_colors(const std::string& colors, bool fallible = false)
×
367
{
368
  if (colors == "always") {
×
369
    log::set_colors(true);
×
370
  } else if (colors == "never") {
×
371
    log::set_colors(false);
×
372
  } else if (colors == "auto") {
×
373
    log::set_colors(fancy_output_allowed());
×
374
  } else {
375
    AR_REQUIRE(fallible, "unhandled log_colors value");
×
376
  }
377
}
378

379
progress_type
380
configure_log_progress(const std::string& progress)
×
381
{
382
  if (progress == "never") {
×
383
    return progress_type::none;
384
  } else if (progress == "spin") {
×
385
    return progress_type::spinner;
386
  } else if (progress == "log") {
×
387
    return progress_type::simple;
388
  } else if (progress == "auto") {
×
389
    if (fancy_output_allowed()) {
×
390
      return progress_type::spinner;
391
    } else {
392
      return progress_type::simple;
×
393
    }
394
  }
395

396
  AR_FAIL("unhandled log_progress value");
×
397
}
398

399
fastq_encoding
400
configure_encoding(const std::string& value,
×
401
                   degenerate_encoding degenerate,
402
                   uracil_encoding uracils)
403
{
404
  if (value == "33") {
×
405
    return fastq_encoding{ quality_encoding::phred_33, degenerate, uracils };
×
406
  } else if (value == "64") {
×
407
    return fastq_encoding{ quality_encoding::phred_64, degenerate, uracils };
×
408
  } else if (value == "solexa") {
×
409
    return fastq_encoding{ quality_encoding::solexa, degenerate, uracils };
×
410
  } else if (value == "sam") {
×
411
    return fastq_encoding{ quality_encoding::sam, degenerate, uracils };
×
412
  }
413

414
  AR_FAIL("unhandled qualitybase value");
×
415
}
416

417
bool
418
parse_output_formats(const argparse::parser& argparser,
×
419
                     output_format& file_format,
420
                     output_format& stdout_format)
421
{
422
  if (argparser.is_set("--gzip")) {
×
423
    file_format = stdout_format = output_format::fastq_gzip;
×
424
    return true;
×
425
  }
426

427
  auto format_s = argparser.value("--out-format");
×
428
  if (!output_files::parse_format(format_s, file_format)) {
×
429
    log::error() << "Invalid output format " + log_escape(format_s);
×
430
    return false;
×
431
  }
432

433
  // Default to writing uncompressed output to STDOUT
434
  if (!argparser.is_set("--stdout-format")) {
×
435
    switch (file_format) {
×
436
      case output_format::fastq:
×
437
      case output_format::fastq_gzip:
×
438
        stdout_format = output_format::fastq;
×
439
        return true;
×
440
      case output_format::sam:
×
441
      case output_format::sam_gzip:
×
442
        stdout_format = output_format::sam;
×
443
        return true;
×
444
      case output_format::bam:
×
445
      case output_format::ubam:
×
446
        stdout_format = output_format::ubam;
×
447
        return true;
×
448
      default:
×
449
        AR_FAIL("invalid output format");
×
450
    }
451
  }
452

453
  format_s = argparser.value("--stdout-format");
×
454
  if (!output_files::parse_format(format_s, stdout_format)) {
×
455
    log::error() << "Invalid output format " + log_escape(format_s);
×
456
    return false;
×
457
  }
458

459
  return true;
460
}
461

462
} // namespace
463

464
////////////////////////////////////////////////////////////////////////////////
465
// Implementations for `userconfig`
466

467
std::string userconfig::start_time = timestamp("%FT%T%z");
468

469
userconfig::userconfig()
×
470
{
471
  argparser.set_name(NAME);
×
472
  argparser.set_version(VERSION);
×
473
  argparser.set_preamble(HELPTEXT);
×
474
  argparser.set_licenses(LICENSES);
×
475
  argparser.set_terminal_width(log::get_terminal_width());
×
476

477
  //////////////////////////////////////////////////////////////////////////////
478
  argparser.add("--threads", "N")
×
479
    .help("Maximum number of threads")
×
480
    .bind_u32(&max_threads)
×
481
    .with_default(2)
×
482
    .with_minimum(1);
×
483

484
  {
×
485
    std::vector<std::string> choices;
×
486
    for (const auto is : simd::supported()) {
×
487
      choices.emplace_back(simd::name(is));
×
488
    }
489

490
    AR_REQUIRE(!choices.empty());
×
491
    argparser.add("--simd", "NAME")
×
492
      .help("SIMD instruction set to use; defaults to the most advanced "
×
493
            "instruction set supported by this computer")
494
      .bind_str(nullptr)
×
495
      .with_choices(choices)
×
496
      .with_default(choices.back());
×
497
  }
498

499
  argparser.add("--benchmark")
×
500
    .help("Carry out benchmarking of AdapterRemoval sub-systems")
×
501
    .conflicts_with("--demultiplex-only")
×
502
    .conflicts_with("--report-only")
×
503
    .conflicts_with("--interleaved")
×
504
    .conflicts_with("--interleaved-input")
×
505
#if !defined(DEBUG)
506
    .hidden()
×
507
#endif
508
    .bind_vec(&benchmarks)
×
509
    .with_min_values(0);
×
510

511
  //////////////////////////////////////////////////////////////////////////////
512
  argparser.add_header("INPUT FILES:");
×
513

514
  argparser.add("--in-file1", "FILE")
×
515
    .help("One or more input files containing mate 1 reads [REQUIRED]")
×
516
    .deprecated_alias("--file1")
×
517
    .bind_vec(&input_files_1)
×
518
    .with_preprocessor(normalize_input_file);
×
519
  argparser.add("--in-file2", "FILE")
×
520
    .help("Input files containing mate 2 reads; if used, then the same number "
×
521
          "of files as --in-file1 must be listed [OPTIONAL]")
522
    .deprecated_alias("--file2")
×
523
    .bind_vec(&input_files_2)
×
524
    .with_preprocessor(normalize_input_file);
×
525
  argparser.add("--head", "N")
×
526
    .help("Process only the first N reads in single-end mode or the first N "
×
527
          "read-pairs in paired-end mode. Accepts suffixes K (thousands), M "
528
          "(millions), and G (billions) [default: all reads]")
529
    .bind_str(nullptr);
×
530

531
  //////////////////////////////////////////////////////////////////////////////
532
  argparser.add_header("OUTPUT FILES:");
×
533

534
  argparser.add("--out-prefix", "PREFIX")
×
535
    .help("Prefix for output files for which the corresponding --out option "
×
536
          "was not set [default: not set]")
537
    .deprecated_alias("--basename")
×
538
    .bind_str(&out_prefix)
×
539
    .with_default("/dev/null");
×
540

541
  argparser.add_separator();
×
542
  argparser.add("--out-file1", "FILE")
×
543
    .help("Output file containing trimmed mate 1 reads. Setting this value in "
×
544
          "in demultiplexing mode overrides --out-prefix for this file")
545
    .deprecated_alias("--output1")
×
546
    .bind_str(nullptr)
×
547
    .with_default("{prefix}[.sample].r1.fastq")
×
548
    .with_preprocessor(normalize_output_file);
×
549
  argparser.add("--out-file2", "FILE")
×
550
    .help("Output file containing trimmed mate 2 reads. Setting this value in "
×
551
          "in demultiplexing mode overrides --out-prefix for this file")
552
    .deprecated_alias("--output2")
×
553
    .bind_str(nullptr)
×
554
    .with_default("{prefix}[.sample].r2.fastq")
×
555
    .with_preprocessor(normalize_output_file);
×
556
  argparser.add("--out-merged", "FILE")
×
557
    .help("Output file that, if --merge is set, contains overlapping "
×
558
          "read-pairs that have been merged into a single read (PE mode only). "
559
          "Setting this value in demultiplexing mode overrides --out-prefix "
560
          "for this file")
561
    .deprecated_alias("--outputcollapsed")
×
562
    .bind_str(nullptr)
×
563
    .with_default("{prefix}[.sample].merged.fastq")
×
564
    .with_preprocessor(normalize_output_file);
×
565
  argparser.add("--out-singleton", "FILE")
×
566
    .help("Output file containing paired reads for which the mate "
×
567
          "has been discarded. This file is only created if filtering is "
568
          "enabled. Setting this value in demultiplexing mode overrides "
569
          "--out-prefix for this file")
570
    .deprecated_alias("--singleton")
×
571
    .bind_str(nullptr)
×
572
    .with_default("{prefix}[.sample].singleton.fastq")
×
573
    .with_preprocessor(normalize_output_file);
×
574

575
  argparser.add_separator();
×
576
  argparser.add("--out-unidentified1", "FILE")
×
577
    .help("In demultiplexing mode, contains mate 1 reads that could not be "
×
578
          "assigned to a single sample")
579
    .bind_str(nullptr)
×
580
    .with_default("{prefix}.unidentified.r1.fastq")
×
581
    .with_preprocessor(normalize_output_file);
×
582
  argparser.add("--out-unidentified2", "FILE")
×
583
    .help("In demultiplexing mode, contains mate 2 reads that could not be "
×
584
          "assigned to a single sample")
585
    .bind_str(nullptr)
×
586
    .with_default("{prefix}.unidentified.r2.fastq")
×
587
    .with_preprocessor(normalize_output_file);
×
588
  argparser.add("--out-discarded", "FILE")
×
589
    .help("Output file containing filtered reads. Setting this value in "
×
590
          "demultiplexing mode overrides --out-prefix for this file [default: "
591
          "not saved]")
592
    .deprecated_alias("--discarded")
×
593
    .bind_str(nullptr)
×
594
    .with_preprocessor(normalize_output_file);
×
595

596
  argparser.add_separator();
×
597
  argparser.add("--out-json", "FILE")
×
598
    .help("Output file containing statistics about input files, trimming, "
×
599
          "merging, and more in JSON format")
600
    .bind_str(nullptr)
×
601
    .with_default("{prefix}.json")
×
602
    .with_preprocessor(normalize_output_file);
×
603
  argparser.add("--out-html", "FILE")
×
604
    .help("Output file containing statistics about input files, trimming, "
×
605
          "merging, and more in HTML format")
606
    .bind_str(nullptr)
×
607
    .with_default("{prefix}.html")
×
608
    .with_preprocessor(normalize_output_file);
×
609

610
  //////////////////////////////////////////////////////////////////////////////
611
  argparser.add_header("FASTQ OPTIONS:");
×
612

613
  argparser.add("--quality-format", "N")
×
614
    .help("Format used to encode Phred scores in input")
×
615
    .deprecated_alias("--qualitybase")
×
616
    .bind_str(&quality_input_base)
×
617
    .with_choices({ "33", "64", "solexa", "sam" })
×
618
    .with_default("33");
×
619
  argparser.add("--mate-separator", "CHAR")
×
620
    .help("Character separating the mate number (1 or 2) from the read name in "
×
621
          "FASTQ records. Will be determined automatically if not specified")
622
    .bind_str(&mate_separator_str);
×
623

624
  argparser.add("--interleaved-input")
×
625
    .help("The (single) input file provided contains both the mate 1 and mate "
×
626
          "2 reads, one pair after the other, with one mate 1 reads followed "
627
          "by one mate 2 read. This option is implied by the --interleaved "
628
          "option")
629
    .conflicts_with("--in-file2")
×
630
    .bind_bool(&interleaved_input);
×
631
  argparser.add("--interleaved-output")
×
632
    .help("If set, trimmed paired-end reads are written to a single file "
×
633
          "containing mate 1 and mate 2 reads, one pair after the other. This "
634
          "option is implied by the --interleaved option")
635
    .conflicts_with("--out-file2")
×
636
    .bind_bool(&interleaved_output);
×
637
  argparser.add("--interleaved")
×
638
    .help("This option enables both the --interleaved-input option and the "
×
639
          "--interleaved-output option")
640
    .conflicts_with("--in-file2")
×
641
    .conflicts_with("--out-file2")
×
642
    .bind_bool(&interleaved);
×
643

644
  argparser.add("--mask-degenerate-bases")
×
645
    .help("Mask degenerate/ambiguous bases (B/D/H/K/M/N/R/S/V/W/Y) in the "
×
646
          "input by replacing them with an 'N'; if this option is not used, "
647
          "AdapterRemoval will abort upon encountering degenerate bases");
648
  argparser.add("--convert-uracils")
×
649
    .help("Convert uracils (U) to thymine (T) in input reads; if this option "
×
650
          "is not used, AdapterRemoval will abort upon encountering uracils");
651

652
  //////////////////////////////////////////////////////////////////////////////
653
  argparser.add_header("OUTPUT FORMAT:");
×
654

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

696
  //////////////////////////////////////////////////////////////////////////////
697
  argparser.add_header("PROCESSING:");
×
698

699
  argparser.add("--adapter1", "SEQ")
×
700
    .help("Adapter sequence expected to be found in mate 1 reads. Any 'N' in "
×
701
          "this sequence is treated as a wildcard")
702
    .bind_str(&adapter_1)
×
703
    .with_default("AGATCGGAAGAGCACACGTCTGAACTCCAGTCA");
×
704
  argparser.add("--adapter2", "SEQ")
×
705
    .help("Adapter sequence expected to be found in mate 2 reads. Any 'N' in "
×
706
          "this sequence is treated as a wildcard")
707
    .bind_str(&adapter_2)
×
708
    .with_default("AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGT");
×
709
  argparser.add("--adapter-list", "FILE")
×
710
    .help("Read adapter pairs from the first two columns of a white-space "
×
711
          "separated table. AdapterRemoval will then select the best matching "
712
          "adapter pair for each pair of input reads when trimming. Only the "
713
          "first column is required for single-end trimming")
714
    .conflicts_with("--adapter1")
×
715
    .conflicts_with("--adapter2")
×
716
    .bind_str(&adapter_list);
×
717

718
  argparser.add_separator();
×
719
  argparser.add("--min-adapter-overlap", "N")
×
720
    .help("In single-end mode, reads are only trimmed if the overlap between "
×
721
          "read and the adapter is at least X bases long, not counting "
722
          "ambiguous nucleotides (Ns)")
723
    .deprecated_alias("--minadapteroverlap")
×
724
    .bind_u32(&min_adapter_overlap)
×
725
    .with_default(1)
×
726
    .with_minimum(1);
×
727
  argparser.add("--mismatch-rate", "X")
×
728
    .help("Max error-rate when aligning reads and/or adapters. If > 1, the max "
×
729
          "error-rate is set to 1 / X; if < 0, the defaults are used, "
730
          "otherwise the user-supplied value is used directly [default: 1/6 "
731
          "for trimming; 1/10 when identifying adapters]")
732
    .deprecated_alias("--mm")
×
733
    .bind_double(&mismatch_threshold)
×
734
    .with_default(-1.0);
×
735
  argparser.add("--shift", "N")
×
736
    .help("Consider alignments where up to N nucleotides are missing from the "
×
737
          "5' termini")
738
    .bind_u32(&shift)
×
739
    .with_default(2);
×
740

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

782
  argparser.add_separator();
×
783
  argparser.add("--prefix-read1", "X")
×
784
    .help("Adds the specified prefix to read 1 names [default: no prefix]")
×
785
    .bind_str(&prefix_read_1);
×
786
  argparser.add("--prefix-read2", "X")
×
787
    .help("Adds the specified prefix to read 2 names [default: no prefix]")
×
788
    .bind_str(&prefix_read_2);
×
789
  argparser.add("--prefix-merged", "X")
×
790
    .help("Adds the specified prefix to merged read names [default: no prefix]")
×
791
    .bind_str(&prefix_merged);
×
792

793
  //////////////////////////////////////////////////////////////////////////////
794
  argparser.add_header("QUALITY TRIMMING:");
×
795

796
#ifdef PRE_TRIM_5P
797
  argparser.add("--pre-trim5p", "N")
798
    .help("Trim the 5' of reads by a fixed amount after demultiplexing (if "
799
          "enabled) but before trimming adapters and low quality bases. "
800
          "Specify one value to trim mate 1 and mate 2 reads the same amount, "
801
          "or two values separated by a space to trim each mate a different "
802
          "amount [default: no trimming]")
803
    .bind_vec(&pre_trim5p)
804
    .with_max_values(2);
805
#endif
806
  argparser.add("--pre-trim3p", "N")
×
807
    .help("Trim the 3' of reads by a fixed amount after demultiplexing (if "
×
808
          "enabled) but before trimming adapters and low quality bases. "
809
          "Specify one value to trim mate 1 and mate 2 reads the same amount, "
810
          "or two values separated by a space to trim each mate a different "
811
          "amount [default: no trimming]")
812
    .bind_vec(&pre_trim3p)
×
813
    .with_max_values(2);
×
814

815
  argparser.add("--post-trim5p", "N")
×
816
    .help("Trim the 5' by a fixed amount after removing adapters, but before "
×
817
          "carrying out quality based trimming [default: no trimming]")
818
    .deprecated_alias("--trim5p")
×
819
    .bind_vec(&post_trim5p)
×
820
    .with_max_values(2);
×
821
  argparser.add("--post-trim3p", "N")
×
822
    .deprecated_alias("--trim3p")
×
823
    .help("Trim the 3' by a fixed amount after removing adapters, but before "
×
824
          "carrying out quality based trimming [default: no trimming]")
825
    .bind_vec(&post_trim3p)
×
826
    .with_max_values(2);
×
827

828
  argparser.add_separator();
×
829
  argparser.add("--quality-trimming", "method")
×
830
    .help("Strategy for trimming low quality bases: 'mott' for the modified "
×
831
          "Mott's algorithm; 'window' for window based trimming; 'per-base' "
832
          "for a per-base trimming of low quality base; and 'none' for no "
833
          "trimming of low quality bases")
834
    .deprecated_alias("--trim-strategy") // name used during v3 alpha 1
×
835
    .bind_str(nullptr)
×
836
    .with_choices({ "mott", "window", "per-base", "none" })
×
837
    .with_default("mott");
×
838

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

889
  argparser.add_separator();
×
890
  argparser.add("--pre-trim-polyx", "X")
×
891
    .help("Enable trimming of poly-X tails prior to read alignment and adapter "
×
892
          "trimming. Zero or more nucleotides (A, C, G, T) may be specified. "
893
          "Zero or more nucleotides may be specified after the option "
894
          "separated by spaces, with zero nucleotides corresponding to all of "
895
          "A, C, G, and T")
896
    .bind_vec(&pre_trim_poly_x_sink)
×
897
    .with_min_values(0);
×
898
  argparser.add("--post-trim-polyx", "X")
×
899
    .help("Enable trimming of poly-X tails after read alignment and adapter "
×
900
          "trimming/merging, but before trimming of low-quality bases. Merged "
901
          "reads are not trimmed by this option (both ends are 5'). Zero or "
902
          "more nucleotides (A, C, G, T) may be specified. Zero or more "
903
          "nucleotides may be specified after the option separated by spaces, "
904
          "with zero nucleotides corresponding to all of A, C, G, and T")
905
    .bind_vec(&post_trim_poly_x_sink)
×
906
    .with_min_values(0);
×
907
  argparser.add("--trim-polyx-threshold", "N")
×
908
    .help("The minimum number of bases in a poly-X tail")
×
909
    .bind_u32(&trim_poly_x_threshold)
×
910
    .with_default(10);
×
911

912
  argparser.add_separator();
×
913
  argparser.add("--preserve5p")
×
914
    .help("If set, bases at the 5p will not be trimmed by when performing "
×
915
          "quality based trimming of reads. Merged reads will not be quality "
916
          "trimmed when this option is enabled [default: 5p bases are trimmed]")
917
    .bind_bool(&preserve5p);
×
918

919
  //////////////////////////////////////////////////////////////////////////////
920
  argparser.add_header("FILTERING:");
×
921

922
  argparser.add("--max-ns", "N")
×
923
    .help("Reads containing more ambiguous bases (N) than this number after "
×
924
          "trimming are discarded [default: no maximum]")
925
    .deprecated_alias("--maxns")
×
926
    .bind_u32(&max_ambiguous_bases)
×
927
    .with_default(std::numeric_limits<uint32_t>::max());
×
928

929
  argparser.add("--min-length", "N")
×
930
    .help("Reads shorter than this length following trimming are discarded")
×
931
    .deprecated_alias("--minlength")
×
932
    .bind_u32(&min_genomic_length)
×
933
    .with_default(15);
×
934
  argparser.add("--max-length", "N")
×
935
    .help("Reads longer than this length following trimming are discarded "
×
936
          "[default: no maximum]")
937
    .deprecated_alias("--maxlength")
×
938
    .bind_u32(&max_genomic_length)
×
939
    .with_default(std::numeric_limits<uint32_t>::max());
×
940

941
  argparser.add("--min-mean-quality", "N")
×
942
    .help("Reads with a mean Phred quality score less than this value "
×
943
          "following trimming are discarded. The value must be in the range 0 "
944
          "to 93, corresponding to Phred+33 encoded values of '!' to '~' "
945
          "[default: no minimum]")
946
    .bind_double(&min_mean_quality)
×
947
    .with_minimum(0.0)
×
948
    .with_maximum(PHRED_SCORE_MAX)
×
949
    .with_default(0.0);
×
950

951
  argparser.add("--min-complexity", "X")
×
952
    .help(
×
953
      "Filter reads with a complexity score less than this value. Complexity "
954
      "is measured as the fraction of positions that differ from the previous "
955
      "position. A suggested value is 0.3 [default: no minimum]")
956
    .bind_double(&min_complexity)
×
957
    .with_minimum(0.0)
×
958
    .with_maximum(1.0)
×
959
    .with_default(0);
×
960

961
  //////////////////////////////////////////////////////////////////////////////
962
  argparser.add_header("DEMULTIPLEXING:");
×
963

964
  argparser.add("--barcode-list", "FILE")
×
965
    .help("List of barcodes or barcode pairs for single or double-indexed "
×
966
          "demultiplexing. Note that both indexes should be specified for "
967
          "both single-end and paired-end trimming, if double-indexed "
968
          "multiplexing was used, in order to ensure that the demultiplexed "
969
          "reads can be trimmed correctly")
970
    .bind_str(&barcode_list);
×
971
  argparser.add("--multiple-barcodes")
×
972
    .help("Allow for more than one barcode (pair) for each sample. If this "
×
973
          "option is not specified, AdapterRemoval will abort if "
974
          "barcodes/barcode pairs do not to unique samples");
975
  argparser.add("--reversible-barcodes")
×
976
    .help("If set, it is assumed that barcodes can be sequences in both the "
×
977
          "barcode1-insert-barcode2 orientation and barcode2'-insert-barcode1' "
978
          "orientation, where ' indicates reverse complementation. This option "
979
          "requires two barcodes per sample (double-indexing)");
980

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

1005
  //////////////////////////////////////////////////////////////////////////////
1006
  argparser.add_header("REPORTS:");
×
1007

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1232
    AR_REQUIRE(found);
×
1233
  }
1234

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1331
  if (!parse_head(argparser.value("--head"), head)) {
×
1332
    return argparse::parse_result::error;
×
1333
  }
1334

1335
  return argparse::parse_result::ok;
1336
}
1337

1338
bool
1339
userconfig::is_good_alignment(const alignment_info& alignment) const
×
1340
{
1341
  if (!alignment.length || alignment.score() <= 0) {
×
1342
    return false;
×
1343
  }
1344

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

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

1359
  return alignment.n_mismatches <= mm_threshold;
×
1360
}
1361

1362
bool
1363
userconfig::can_merge_alignment(const alignment_info& alignment) const
×
1364
{
1365
  if (alignment.length < alignment.n_ambiguous) {
×
1366
    throw std::invalid_argument("#ambiguous bases > read length");
×
1367
  }
1368

1369
  return alignment.length - alignment.n_ambiguous >= merge_threshold;
×
1370
}
1371

1372
output_format
1373
userconfig::infer_output_format(const std::string& filename) const
×
1374
{
1375
  if (filename == "/dev/stdout") {
×
1376
    return out_stdout_format;
×
1377
  }
1378

1379
  output_format result = out_file_format;
×
1380
  // Parse failures are ignored here; default to --out-format
1381
  output_files::parse_extension(filename, result);
×
1382

1383
  return result;
×
1384
}
1385

1386
output_files
1387
userconfig::get_output_filenames() const
×
1388
{
1389
  output_files files;
×
1390

1391
  files.settings_json = new_output_file("--out-json", {}, {}, ".json").name;
×
1392
  files.settings_html = new_output_file("--out-html", {}, {}, ".html").name;
×
1393

1394
  auto ext = output_files::file_extension(out_file_format);
×
1395
  std::string_view out1 = interleaved_output ? "" : ".r1";
×
1396
  std::string_view out2 = interleaved_output ? "" : ".r2";
×
1397

1398
  if (is_demultiplexing_enabled()) {
×
1399
    files.unidentified_1 = new_output_file(
×
1400
      "--out-unidentified1", {}, { ".unidentified", out1 }, ext);
×
1401

1402
    if (paired_ended_mode) {
×
1403
      if (interleaved_output) {
×
1404
        files.unidentified_2 = files.unidentified_1;
×
1405
      } else {
1406
        files.unidentified_2 = new_output_file(
×
1407
          "--out-unidentified2", {}, { ".unidentified", out2 }, ext);
×
1408
      }
1409
    }
1410
  }
1411

1412
  for (const auto& sample : samples) {
×
1413
    const auto& name = sample.name();
×
1414
    sample_output_files map;
×
1415

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

1419
    if (paired_ended_mode) {
×
1420
      if (interleaved_output) {
×
1421
        map.set_file(read_type::mate_2, mate_1);
×
1422
      } else {
1423
        map.set_file(read_type::mate_2,
×
1424
                     new_output_file("--out-file2", name, { out2 }, ext));
×
1425
      }
1426
    }
1427

1428
    if (run_type == ar_command::trim_adapters) {
×
1429
      if (is_any_filtering_enabled()) {
×
1430
        map.set_file(
×
1431
          read_type::discarded,
1432
          new_output_file("--out-discarded", name, { ".discarded" }, ext));
×
1433
      }
1434

1435
      if (paired_ended_mode) {
×
1436
        if (is_any_filtering_enabled()) {
×
1437
          map.set_file(
×
1438
            read_type::singleton,
1439
            new_output_file("--out-singleton", name, { ".singleton" }, ext));
×
1440
        }
1441

1442
        if (is_read_merging_enabled()) {
×
1443
          map.set_file(
×
1444
            read_type::merged,
1445
            new_output_file("--out-merged", name, { ".merged" }, ext));
×
1446
        }
1447
      }
1448
    }
1449

1450
    files.add_sample(std::move(map));
×
1451
  }
1452

1453
  return files;
×
1454
}
×
1455

1456
output_file
1457
userconfig::new_output_file(const std::string& key,
×
1458
                            std::string_view sample,
1459
                            std::vector<std::string_view> keys,
1460
                            std::string_view ext) const
1461
{
1462
  AR_REQUIRE(!ext.empty());
×
1463
  const auto default_is_fastq = out_file_format == output_format::fastq ||
×
1464
                                out_file_format == output_format::fastq_gzip;
1465

1466
  std::string out;
×
1467
  if (argparser.is_set(key)) {
×
NEW
1468
    out = argparser.value(key);
×
1469

1470
    // global files, e.g. reports and unidentified reads
1471
    if (sample.empty()) {
×
NEW
1472
      return { out, infer_output_format(out) };
×
1473
    }
NEW
1474
  } else if (default_is_fastq && key == "--out-discarded") {
×
1475
    // Discarded reads are dropped by default for non-archival formats
NEW
1476
    out = DEV_NULL;
×
1477
  } else {
1478
    out = out_prefix;
×
1479
  }
1480

NEW
1481
  if (out == DEV_NULL) {
×
NEW
1482
    return { out, output_format::fastq };
×
1483
  }
1484

UNCOV
1485
  if (!(default_is_fastq || keys.empty())) {
×
1486
    // SAM/BAM files are combined by default
1487
    keys.pop_back();
×
1488
  }
1489

1490
  if (!sample.empty()) {
×
1491
    keys.insert(keys.begin(), sample);
×
1492
  }
1493

1494
  keys.emplace_back(ext);
×
1495

1496
  for (const auto& value : keys) {
×
1497
    if (!value.empty() && value.front() != '.') {
×
1498
      out.push_back('.');
×
1499
    }
1500

1501
    out.append(value);
×
1502
  }
1503

1504
  return output_file{ out, infer_output_format(out) };
×
1505
}
1506

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

1524
  return true;
1525
}
1526

1527
bool
1528
userconfig::is_adapter_trimming_enabled() const
×
1529
{
1530
  return run_type == ar_command::trim_adapters;
×
1531
}
1532

1533
bool
1534
userconfig::is_demultiplexing_enabled() const
×
1535
{
1536
  return !barcode_list.empty();
×
1537
}
1538

1539
bool
1540
userconfig::is_read_merging_enabled() const
×
1541
{
1542
  return is_adapter_trimming_enabled() && merge != merge_strategy::none;
×
1543
}
1544

1545
bool
1546
userconfig::is_any_quality_trimming_enabled() const
×
1547
{
1548
  return is_adapter_trimming_enabled() &&
×
1549
         (is_low_quality_trimming_enabled() ||
×
1550
          is_terminal_base_pre_trimming_enabled() ||
×
1551
          is_terminal_base_post_trimming_enabled() ||
×
1552
          is_poly_x_tail_pre_trimming_enabled() ||
×
1553
          is_poly_x_tail_post_trimming_enabled());
×
1554
}
1555

1556
bool
1557
userconfig::is_low_quality_trimming_enabled() const
×
1558
{
1559
  return trim != trimming_strategy::none;
×
1560
}
1561

1562
bool
1563
userconfig::is_terminal_base_pre_trimming_enabled() const
×
1564
{
1565
  return
×
1566
#ifdef PRE_TRIM_5P
1567
    pre_trim_fixed_5p.first || pre_trim_fixed_5p.second ||
1568
#endif
1569
    pre_trim_fixed_3p.first || pre_trim_fixed_3p.second;
×
1570
}
1571

1572
bool
1573
userconfig::is_terminal_base_post_trimming_enabled() const
×
1574
{
1575
  return post_trim_fixed_5p.first || post_trim_fixed_5p.second ||
×
1576
         post_trim_fixed_3p.first || post_trim_fixed_3p.second;
×
1577
}
1578

1579
bool
1580
userconfig::is_poly_x_tail_pre_trimming_enabled() const
×
1581
{
1582
  return !pre_trim_poly_x.empty();
×
1583
}
1584

1585
bool
1586
userconfig::is_poly_x_tail_post_trimming_enabled() const
×
1587
{
1588
  return !post_trim_poly_x.empty();
×
1589
}
1590

1591
bool
1592
userconfig::is_any_filtering_enabled() const
×
1593
{
1594
  return is_adapter_trimming_enabled() &&
×
1595
         (is_short_read_filtering_enabled() ||
×
1596
          is_long_read_filtering_enabled() ||
×
1597
          is_ambiguous_base_filtering_enabled() ||
×
1598
          is_mean_quality_filtering_enabled() ||
×
1599
          is_low_complexity_filtering_enabled());
×
1600
}
1601

1602
bool
1603
userconfig::is_short_read_filtering_enabled() const
×
1604
{
1605
  return min_genomic_length > 0;
×
1606
}
1607

1608
bool
1609
userconfig::is_long_read_filtering_enabled() const
×
1610
{
1611
  return max_genomic_length !=
×
1612
         std::numeric_limits<decltype(max_genomic_length)>::max();
×
1613
}
1614

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

1622
bool
1623
userconfig::is_mean_quality_filtering_enabled() const
×
1624
{
1625
  return min_mean_quality > 0;
×
1626
}
1627

1628
bool
1629
userconfig::is_low_complexity_filtering_enabled() const
×
1630
{
1631
  return min_complexity > 0;
×
1632
}
1633

1634
bool
1635
userconfig::setup_adapter_sequences()
×
1636
{
1637
  adapter_set adapters;
×
1638
  if (argparser.is_set("--adapter-list")) {
×
1639
    try {
×
1640
      adapters.load(adapter_list, paired_ended_mode);
×
1641
    } catch (const std::exception& error) {
×
1642
      log::error() << "Error reading adapters from " << log_escape(adapter_list)
×
1643
                   << ": " << error.what();
×
1644
      return false;
×
1645
    }
×
1646

1647
    if (adapters.size()) {
×
1648
      log::info() << "Read " << adapters.size()
×
1649
                  << " adapters / adapter pairs from '" << adapter_list << "'";
×
1650
    } else {
1651
      log::error() << "No adapter sequences found in table!";
×
1652
      return false;
×
1653
    }
1654
  } else {
1655
    try {
×
1656
      adapters.add(adapter_1, adapter_2);
×
1657
    } catch (const fastq_error& error) {
×
1658
      log::error() << "Error parsing adapter sequence(s):\n"
×
1659
                   << "   " << error.what();
×
1660

1661
      return false;
×
1662
    }
×
1663
  }
1664

1665
  samples.set_adapters(std::move(adapters));
×
1666

1667
  return true;
×
1668
}
1669

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

1677
  if (!check_and_set_barcode_mm(
×
1678
        argparser, "--barcode-mm-r1", barcode_mm, barcode_mm_r1)) {
×
1679
    return false;
1680
  }
1681

1682
  if (!check_and_set_barcode_mm(
×
1683
        argparser, "--barcode-mm-r2", barcode_mm, barcode_mm_r2)) {
×
1684
    return false;
1685
  }
1686

1687
  if (argparser.is_set("--barcode-list")) {
×
1688
    const auto config =
×
1689
      barcode_config()
×
1690
        .paired_end_mode(paired_ended_mode)
×
1691
        .allow_multiple_barcodes(argparser.is_set("--multiple-barcodes"))
×
1692
        .unidirectional_barcodes(!argparser.is_set("--reversible-barcodes"));
×
1693

1694
    try {
×
1695
      samples.load(barcode_list, config);
×
1696
    } catch (const std::exception& error) {
×
1697
      log::error() << "Error reading barcodes from " << log_escape(barcode_list)
×
1698
                   << ": " << error.what();
×
1699
      return false;
×
1700
    }
×
1701

1702
    log::info() << "Read " << samples.size() << " sets of barcodes from "
×
1703
                << shell_escape(barcode_list);
×
1704
  }
1705

1706
  const auto& output_files = get_output_filenames();
×
1707

1708
  return check_input_files(input_files_1, input_files_2) &&
×
1709
         check_output_files("--in-file1", input_files_1, output_files) &&
×
1710
         check_output_files("--in-file2", input_files_2, output_files);
×
1711
}
1712

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