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

MikkelSchubert / adapterremoval / #46

27 Nov 2024 03:10PM UTC coverage: 27.245% (+1.0%) from 26.244%
#46

push

travis-ci

MikkelSchubert
fix convenience executable make target

2609 of 9576 relevant lines covered (27.25%)

4268.73 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 <tuple>           // for get, tuple
44
#include <unistd.h>        // for access, isatty, R_OK, STDERR_FILENO
45

46
namespace adapterremoval {
47

48
namespace {
49

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

69
////////////////////////////////////////////////////////////////////////////////
70
// Helper functions
71

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

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

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

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

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

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

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

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

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

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

134
  return true;
135
}
136

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

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

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

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

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

171
    sink_without_unit.pop_back();
×
172
  }
173

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

184
  return true;
×
185
}
186

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

200
  return true;
×
201
}
202

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

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

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

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

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

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

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

269
  return !any_errors;
×
270
}
271

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

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

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

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

294
  return true;
×
295
}
296

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

312
  return fallback;
×
313
}
314

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

326
  return result;
×
327
}
×
328

329
////////////////////////////////////////////////////////////////////////////////
330

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

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

343
  return false;
344
}
345

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

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

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

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

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

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

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

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

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

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

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

458
  return true;
459
}
460

461
} // namespace
462

463
////////////////////////////////////////////////////////////////////////////////
464
// Implementations for `userconfig`
465

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

654
  argparser.add("--gzip")
×
655
    .hidden()
×
656
    .deprecated()
×
657
    .conflicts_with("--out-format")
×
658
    .conflicts_with("--stdout-format");
×
659
  argparser.add("--out-format", "X")
×
660
    .help("Selects the default output format; either 'fastq' for uncompressed "
×
661
          "FASTQ reads, 'fastq.gz' for gzip compressed FASTQ reads, 'sam' for "
662
          "uncompressed SAM records, 'sam.gz' for gzip compressed SAM records, "
663
          "'bam' for BGZF compressed BAM records, and 'ubam' for uncompressed "
664
          "BAM records. Setting an `--out-*` option overrides this option "
665
          "based on the filename used (except .ubam)")
666
    .bind_str(nullptr)
×
667
    .with_choices({ "fastq", "fastq.gz", "sam", "sam.gz", "bam", "ubam" })
×
668
    .with_default("fastq.gz");
×
669
  argparser.add("--stdout-format", "X")
×
670
    .help("Selects the output format for data written to STDOUT; choices are "
×
671
          "the same as for --out-format [default: the same format as "
672
          "--out-format, but uncompressed]")
673
    .bind_str(nullptr)
×
674
    .with_choices({ "fastq", "fastq.gz", "sam", "sam.gz", "bam", "ubam" });
×
675
  argparser.add("--read-group", "RG")
×
676
    .help("Add read-group (RG) information to SAM/BAM output. The value is "
×
677
          "expected to be a valid set of read-group tags separated by tabs, "
678
          "for example \"ID:DS-1\\tSM:TK-421\\tPL:ILLUMINA\". If the ID tag is "
679
          "not provided, the default ID \"1\" will be used")
680
    .bind_str(nullptr);
×
681
  argparser.add("--compression-level", "N")
×
682
    .help(
×
683
      "Sets the compression level for compressed output. Valid values are 0 to "
684
      "13: Level 0 is uncompressed but includes gzip headers/checksums, level "
685
      "1 is streamed for SAM/FASTQ output (this may be required in rare cases "
686
      "for compatibility), and levels 2 to 13 are block compressed using the "
687
      "BGZF format")
688
    .deprecated_alias("--gzip-level")
×
689
    .bind_u32(&compression_level)
×
690
    .with_maximum(13)
×
691
    .with_default(5);
×
692

693
  //////////////////////////////////////////////////////////////////////////////
694
  argparser.add_header("PROCESSING:");
×
695

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

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

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

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

788
  //////////////////////////////////////////////////////////////////////////////
789
  argparser.add_header("QUALITY TRIMMING:");
×
790

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

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

823
  argparser.add_separator();
×
824
  argparser.add("--quality-trimming", "method")
×
825
    .help("Strategy for trimming low quality bases: 'mott' for the modified "
×
826
          "Mott's algorithm; 'window' for window based trimming; 'per-base' "
827
          "for a per-base trimming of low quality base; and 'none' for no "
828
          "trimming of low quality bases")
829
    .bind_str(nullptr)
×
830
    .with_choices({ "mott", "window", "per-base", "none" })
×
831
    .with_default("mott");
×
832

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

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

905
  argparser.add_separator();
×
906
  argparser.add("--preserve5p")
×
907
    .help("If set, bases at the 5p will not be trimmed by when performing "
×
908
          "quality based trimming of reads. Merged reads will not be quality "
909
          "trimmed when this option is enabled [default: 5p bases are trimmed]")
910
    .bind_bool(&preserve5p);
×
911

912
  //////////////////////////////////////////////////////////////////////////////
913
  argparser.add_header("FILTERING:");
×
914

915
  argparser.add("--max-ns", "N")
×
916
    .help("Reads containing more ambiguous bases (N) than this number after "
×
917
          "trimming are discarded [default: no maximum]")
918
    .deprecated_alias("--maxns")
×
919
    .bind_u32(&max_ambiguous_bases)
×
920
    .with_default(std::numeric_limits<uint32_t>::max());
×
921

922
  argparser.add("--min-length", "N")
×
923
    .help("Reads shorter than this length following trimming are discarded")
×
924
    .deprecated_alias("--minlength")
×
925
    .bind_u32(&min_genomic_length)
×
926
    .with_default(15);
×
927
  argparser.add("--max-length", "N")
×
928
    .help("Reads longer than this length following trimming are discarded "
×
929
          "[default: no maximum]")
930
    .deprecated_alias("--maxlength")
×
931
    .bind_u32(&max_genomic_length)
×
932
    .with_default(std::numeric_limits<uint32_t>::max());
×
933

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

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

954
  //////////////////////////////////////////////////////////////////////////////
955
  argparser.add_header("DEMULTIPLEXING:");
×
956

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

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

998
  //////////////////////////////////////////////////////////////////////////////
999
  argparser.add_header("REPORTS:");
×
1000

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

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

1031
  //////////////////////////////////////////////////////////////////////////////
1032
  argparser.add_header("LOGGING:");
×
1033

1034
  argparser.add("--log-level", "X")
×
1035
    .help("The minimum severity of messages to be written to STDERR")
×
1036
    .bind_str(&log_level)
×
1037
    .with_choices({ "debug", "info", "warning", "error" })
×
1038
    .with_default("info");
×
1039

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

1056
argparse::parse_result
1057
userconfig::parse_args(const string_vec& argvec)
×
1058
{
1059
  args = argvec;
×
1060
  if (args.size() <= 1) {
×
1061
    argparser.print_help();
×
1062
    return argparse::parse_result::error;
1063
  }
1064

1065
  // ad-hoc arg parsing to make argparse output consistent with rest of run
1066
  configure_log_colors(try_parse_argument(args, "--log-color", "auto"), true);
×
1067
  configure_log_levels(try_parse_argument(args, "--log-level", "info"), true);
×
1068

1069
  const argparse::parse_result result = argparser.parse_args(args);
×
1070
  if (result != argparse::parse_result::ok) {
×
1071
    return result;
1072
  }
1073

1074
  configure_log_colors(log_color);
×
1075
  configure_log_levels(log_level);
×
1076
  log_progress = configure_log_progress(argparser.value("--log-progress"));
×
1077

1078
  {
×
1079
    const auto degenerate = argparser.is_set("--mask-degenerate-bases")
×
1080
                              ? degenerate_encoding::mask
×
1081
                              : degenerate_encoding::reject;
×
1082
    const auto uracils = argparser.is_set("--convert-uracils")
×
1083
                           ? uracil_encoding::convert
×
1084
                           : uracil_encoding::reject;
×
1085

1086
    io_encoding = configure_encoding(quality_input_base, degenerate, uracils);
×
1087
  }
1088

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

1100
  if (argparser.is_set("--demultiplex-only")) {
×
1101
    run_type = ar_command::demultiplex_only;
×
1102
  } else if (argparser.is_set("--report-only")) {
×
1103
    run_type = ar_command::report_only;
×
1104
  } else if (argparser.is_set("--benchmark")) {
×
1105
    run_type = ar_command::benchmark;
×
1106
  }
1107

1108
  {
×
1109
    const auto strategy = argparser.value("--quality-trimming");
×
1110
    if (strategy == "mott") {
×
1111
      trim = trimming_strategy::mott;
×
1112

1113
      if (trim_mott_rate > 1) {
×
1114
        trim_mott_rate = std::pow(10.0, trim_mott_rate / -10.0);
×
1115
      }
1116
    } else if (strategy == "window") {
×
1117
      trim = trimming_strategy::window;
×
1118
    } else if (strategy == "per-base") {
×
1119
      trim = trimming_strategy::per_base;
×
1120

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

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

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

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

1152
  interleaved_input |= interleaved;
×
1153
  interleaved_output |= interleaved;
×
1154

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

1161
  if (paired_ended_mode) {
×
1162
    min_adapter_overlap = 0;
×
1163

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

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

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

1192
  try {
×
1193
    samples.set_read_group(argparser.value("--read-group"));
×
1194
  } catch (const std::invalid_argument& error) {
×
1195
    log::error() << "Invalid argument --read-group "
×
1196
                 << log_escape(argparser.value("--read-group")) << ": "
×
1197
                 << error.what();
×
1198

1199
    return argparse::parse_result::error;
×
1200
  }
×
1201

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

1214
  {
×
1215
    bool found = false;
×
1216
    const auto simd_choice = argparser.value("--simd");
×
1217
    for (const auto is : simd::supported()) {
×
1218
      if (simd_choice == simd::name(is)) {
×
1219
        simd = is;
×
1220
        found = true;
×
1221
        break;
×
1222
      }
1223
    }
1224

1225
    AR_REQUIRE(found);
×
1226
  }
1227

1228
  using fixed_trimming =
×
1229
    std::tuple<const char*, const string_vec&, std::pair<unsigned, unsigned>&>;
1230

1231
  const std::vector<fixed_trimming> fixed_trimming_options = {
×
1232
#ifdef PRE_TRIM_5P
1233
    { "--pre-trim5p", pre_trim5p, pre_trim_fixed_5p },
1234
#endif
1235
    { "--pre-trim3p", pre_trim3p, pre_trim_fixed_3p },
×
1236
    { "--post-trim5p", post_trim5p, post_trim_fixed_5p },
×
1237
    { "--post-trim3p", post_trim3p, post_trim_fixed_3p },
×
1238
  };
1239

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

1249
      return argparse::parse_result::error;
×
1250
    }
×
1251
  }
1252

1253
  if (!parse_output_formats(argparser, out_file_format, out_stdout_format)) {
×
1254
    return argparse::parse_result::error;
1255
  }
1256

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

1261
    return argparse::parse_result::error;
×
1262
  } else if (out_prefix.back() == '/') {
×
1263
    log::error() << "--out-prefix must not be a directory: "
×
1264
                 << shell_escape(out_prefix);
×
1265

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

1284
    string_vec required_keys;
×
1285
    for (const auto& it : output_keys) {
×
1286
      if (it.second) {
×
1287
        required_keys.push_back(it.first);
×
1288
      }
1289
    }
1290

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

1299
      return argparse::parse_result::error;
×
1300
    }
1301
  }
1302

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

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

1319
  if (!min_genomic_length) {
×
1320
    log::warn() << "--min-length is set to 0. This may produce FASTQ files "
×
1321
                   "that are incompatible with some tools!";
×
1322
  }
1323

1324
  if (!parse_head(argparser.value("--head"), head)) {
×
1325
    return argparse::parse_result::error;
×
1326
  }
1327

1328
  return argparse::parse_result::ok;
1329
}
1330

1331
bool
1332
userconfig::is_good_alignment(const alignment_info& alignment) const
×
1333
{
1334
  if (!alignment.length || alignment.score() <= 0) {
×
1335
    return false;
×
1336
  }
1337

1338
  // Only pairs of called bases are considered part of the alignment
1339
  const size_t n_aligned = alignment.length - alignment.n_ambiguous;
×
1340
  if (n_aligned < min_adapter_overlap && !paired_ended_mode) {
×
1341
    return false;
1342
  }
1343

1344
  auto mm_threshold = static_cast<size_t>(mismatch_threshold * n_aligned);
×
1345
  if (n_aligned < 6) {
×
1346
    mm_threshold = 0;
×
1347
  } else if (n_aligned < 10) {
×
1348
    // Allow at most 1 mismatch, possibly set to 0 by the user
1349
    mm_threshold = std::min<size_t>(1, mm_threshold);
×
1350
  }
1351

1352
  return alignment.n_mismatches <= mm_threshold;
×
1353
}
1354

1355
bool
1356
userconfig::can_merge_alignment(const alignment_info& alignment) const
×
1357
{
1358
  if (alignment.length < alignment.n_ambiguous) {
×
1359
    throw std::invalid_argument("#ambiguous bases > read length");
×
1360
  }
1361

1362
  return alignment.length - alignment.n_ambiguous >= merge_threshold;
×
1363
}
1364

1365
output_format
1366
userconfig::infer_output_format(const std::string& filename) const
×
1367
{
1368
  if (filename == "/dev/stdout") {
×
1369
    return out_stdout_format;
×
1370
  }
1371

1372
  output_format result = out_file_format;
×
1373
  // Parse failures are ignored here; default to --out-format
1374
  output_files::parse_extension(filename, result);
×
1375

1376
  return result;
×
1377
}
1378

1379
output_files
1380
userconfig::get_output_filenames() const
×
1381
{
1382
  output_files files;
×
1383

1384
  files.settings_json = new_output_file("--out-json", { ".json" }).name;
×
1385
  files.settings_html = new_output_file("--out-html", { ".html" }).name;
×
1386

1387
  const std::string ext{ output_files::file_extension(out_file_format) };
×
1388
  const std::string out1 = (interleaved_output ? "" : ".r1") + ext;
×
1389
  const std::string out2 = (interleaved_output ? "" : ".r2") + ext;
×
1390

1391
  if (is_demultiplexing_enabled()) {
×
1392
    files.unidentified_1 =
×
1393
      new_output_file("--out-unidentified1", { ".unidentified", out1 });
×
1394

1395
    if (paired_ended_mode) {
×
1396
      if (interleaved_output) {
×
1397
        files.unidentified_2 = files.unidentified_1;
×
1398
      } else {
1399
        files.unidentified_2 =
×
1400
          new_output_file("--out-unidentified2", { ".unidentified", out2 });
×
1401
      }
1402
    }
1403
  }
1404

1405
  for (const auto& sample : samples) {
×
1406
    const auto& name = sample.name();
×
1407
    sample_output_files map;
×
1408

1409
    const auto mate_1 = new_output_file("--out-file1", { name, out1 });
×
1410
    map.set_file(read_type::mate_1, mate_1);
×
1411

1412
    if (paired_ended_mode) {
×
1413
      if (interleaved_output) {
×
1414
        map.set_file(read_type::mate_2, mate_1);
×
1415
      } else {
1416
        map.set_file(read_type::mate_2,
×
1417
                     new_output_file("--out-file2", { name, out2 }));
×
1418
      }
1419
    }
1420

1421
    if (run_type == ar_command::trim_adapters) {
×
1422
      if (is_any_filtering_enabled()) {
×
1423
        map.set_file(
×
1424
          read_type::discarded,
1425
          new_output_file("--out-discarded", { name, ".discarded", ext }));
×
1426
      }
1427

1428
      if (paired_ended_mode) {
×
1429
        if (is_any_filtering_enabled()) {
×
1430
          map.set_file(
×
1431
            read_type::singleton,
1432
            new_output_file("--out-singleton", { name, ".singleton", ext }));
×
1433
        }
1434

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

1443
    files.add_sample(std::move(map));
×
1444
  }
1445

1446
  return files;
×
1447
}
1448

1449
output_file
1450
userconfig::new_output_file(const std::string& key,
×
1451
                            const string_vec& values) const
1452
{
1453
  std::string out;
×
1454
  if (argparser.is_set(key)) {
×
1455
    if (!is_demultiplexing_enabled()) {
×
1456
      const auto filename = argparser.value(key);
×
1457

1458
      return { filename, infer_output_format(filename) };
×
1459
    }
1460

1461
    out = argparser.value(key);
×
1462
  } else if (out_prefix == DEV_NULL || key == "--out-discarded") {
×
1463
    return { DEV_NULL, output_format::fastq };
×
1464
  } else {
1465
    out = out_prefix;
×
1466
  }
1467

1468
  for (const auto& value : values) {
×
1469
    if (!value.empty() && value.front() != '.') {
×
1470
      out.push_back('.');
×
1471
    }
1472

1473
    out.append(value);
×
1474
  }
1475

1476
  return output_file{ out, infer_output_format(out) };
×
1477
}
1478

1479
bool
1480
check_and_set_barcode_mm(const argparse::parser& argparser,
×
1481
                         const std::string& key,
1482
                         uint32_t barcode_mm,
1483
                         uint32_t& dst)
1484
{
1485
  if (!argparser.is_set(key)) {
×
1486
    dst = barcode_mm;
×
1487
  } else if (dst > barcode_mm) {
×
1488
    log::error()
×
1489
      << "The maximum number of errors for " << key
×
1490
      << " is set \n"
1491
         "to a higher value than the total number of mismatches allowed\n"
1492
         "for barcodes (--barcode-mm). Please correct these settings.";
×
1493
    return false;
×
1494
  }
1495

1496
  return true;
1497
}
1498

1499
bool
1500
userconfig::is_adapter_trimming_enabled() const
×
1501
{
1502
  return run_type == ar_command::trim_adapters;
×
1503
}
1504

1505
bool
1506
userconfig::is_demultiplexing_enabled() const
×
1507
{
1508
  return !barcode_list.empty();
×
1509
}
1510

1511
bool
1512
userconfig::is_read_merging_enabled() const
×
1513
{
1514
  return is_adapter_trimming_enabled() && merge != merge_strategy::none;
×
1515
}
1516

1517
bool
1518
userconfig::is_any_quality_trimming_enabled() const
×
1519
{
1520
  return is_adapter_trimming_enabled() &&
×
1521
         (is_low_quality_trimming_enabled() ||
×
1522
          is_terminal_base_pre_trimming_enabled() ||
×
1523
          is_terminal_base_post_trimming_enabled() ||
×
1524
          is_poly_x_tail_pre_trimming_enabled() ||
×
1525
          is_poly_x_tail_post_trimming_enabled());
×
1526
}
1527

1528
bool
1529
userconfig::is_low_quality_trimming_enabled() const
×
1530
{
1531
  return trim != trimming_strategy::none;
×
1532
}
1533

1534
bool
1535
userconfig::is_terminal_base_pre_trimming_enabled() const
×
1536
{
1537
  return
×
1538
#ifdef PRE_TRIM_5P
1539
    pre_trim_fixed_5p.first || pre_trim_fixed_5p.second ||
1540
#endif
1541
    pre_trim_fixed_3p.first || pre_trim_fixed_3p.second;
×
1542
}
1543

1544
bool
1545
userconfig::is_terminal_base_post_trimming_enabled() const
×
1546
{
1547
  return post_trim_fixed_5p.first || post_trim_fixed_5p.second ||
×
1548
         post_trim_fixed_3p.first || post_trim_fixed_3p.second;
×
1549
}
1550

1551
bool
1552
userconfig::is_poly_x_tail_pre_trimming_enabled() const
×
1553
{
1554
  return !pre_trim_poly_x.empty();
×
1555
}
1556

1557
bool
1558
userconfig::is_poly_x_tail_post_trimming_enabled() const
×
1559
{
1560
  return !post_trim_poly_x.empty();
×
1561
}
1562

1563
bool
1564
userconfig::is_any_filtering_enabled() const
×
1565
{
1566
  return is_adapter_trimming_enabled() &&
×
1567
         (is_short_read_filtering_enabled() ||
×
1568
          is_long_read_filtering_enabled() ||
×
1569
          is_ambiguous_base_filtering_enabled() ||
×
1570
          is_mean_quality_filtering_enabled() ||
×
1571
          is_low_complexity_filtering_enabled());
×
1572
}
1573

1574
bool
1575
userconfig::is_short_read_filtering_enabled() const
×
1576
{
1577
  return min_genomic_length > 0;
×
1578
}
1579

1580
bool
1581
userconfig::is_long_read_filtering_enabled() const
×
1582
{
1583
  return max_genomic_length !=
×
1584
         std::numeric_limits<decltype(max_genomic_length)>::max();
×
1585
}
1586

1587
bool
1588
userconfig::is_ambiguous_base_filtering_enabled() const
×
1589
{
1590
  return max_ambiguous_bases !=
×
1591
         std::numeric_limits<decltype(max_ambiguous_bases)>::max();
×
1592
}
1593

1594
bool
1595
userconfig::is_mean_quality_filtering_enabled() const
×
1596
{
1597
  return min_mean_quality > 0;
×
1598
}
1599

1600
bool
1601
userconfig::is_low_complexity_filtering_enabled() const
×
1602
{
1603
  return min_complexity > 0;
×
1604
}
1605

1606
bool
1607
userconfig::setup_adapter_sequences()
×
1608
{
1609
  adapter_set adapters;
×
1610
  if (argparser.is_set("--adapter-list")) {
×
1611
    try {
×
1612
      adapters.load(adapter_list, paired_ended_mode);
×
1613
    } catch (const std::exception& error) {
×
1614
      log::error() << "Error reading adapters from " << log_escape(adapter_list)
×
1615
                   << ": " << error.what();
×
1616
      return false;
×
1617
    }
×
1618

1619
    if (adapters.size()) {
×
1620
      log::info() << "Read " << adapters.size()
×
1621
                  << " adapters / adapter pairs from '" << adapter_list << "'";
×
1622
    } else {
1623
      log::error() << "No adapter sequences found in table!";
×
1624
      return false;
×
1625
    }
1626
  } else {
1627
    try {
×
1628
      adapters.add(adapter_1, adapter_2);
×
1629
    } catch (const fastq_error& error) {
×
1630
      log::error() << "Error parsing adapter sequence(s):\n"
×
1631
                   << "   " << error.what();
×
1632

1633
      return false;
×
1634
    }
×
1635
  }
1636

1637
  samples.set_adapters(std::move(adapters));
×
1638

1639
  return true;
×
1640
}
1641

1642
bool
1643
userconfig::setup_demultiplexing()
×
1644
{
1645
  if (!argparser.is_set("--barcode-mm")) {
×
1646
    barcode_mm = barcode_mm_r1 + barcode_mm_r2;
×
1647
  }
1648

1649
  if (!check_and_set_barcode_mm(
×
1650
        argparser, "--barcode-mm-r1", barcode_mm, barcode_mm_r1)) {
×
1651
    return false;
1652
  }
1653

1654
  if (!check_and_set_barcode_mm(
×
1655
        argparser, "--barcode-mm-r2", barcode_mm, barcode_mm_r2)) {
×
1656
    return false;
1657
  }
1658

1659
  if (argparser.is_set("--barcode-list")) {
×
1660
    const auto config =
×
1661
      barcode_config()
×
1662
        .paired_end_mode(paired_ended_mode)
×
1663
        .allow_multiple_barcodes(argparser.is_set("--multiple-barcodes"))
×
1664
        .unidirectional_barcodes(!argparser.is_set("--reversible-barcodes"));
×
1665

1666
    try {
×
1667
      samples.load(barcode_list, config);
×
1668
    } catch (const std::exception& error) {
×
1669
      log::error() << "Error reading barcodes from " << log_escape(barcode_list)
×
1670
                   << ": " << error.what();
×
1671
      return false;
×
1672
    }
×
1673

1674
    log::info() << "Read " << samples.size() << " sets of barcodes from "
×
1675
                << shell_escape(barcode_list);
×
1676
  }
1677

1678
  const auto& output_files = get_output_filenames();
×
1679

1680
  return check_input_files(input_files_1, input_files_2) &&
×
1681
         check_output_files("--in-file1", input_files_1, output_files) &&
×
1682
         check_output_files("--in-file2", input_files_2, output_files);
×
1683
}
1684

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

© 2025 Coveralls, Inc