o
    Dfi                     @   sn  d Z ddlZddlZddlZddlZddlZddlmZmZm	Z	m
Z
mZmZmZ ddlmZmZmZ ddlZddlmZ ddlmZmZmZ ddlmZ ddlmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, dd	l-m.Z.m/Z/m0Z0 dd
l1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z;m<Z<m=Z=m>Z> ddl?m@Z@mAZA eB ZCG dd deZDG dd deEZFdefddZGdeHdeeIeIf fddZJdeHdeeeI df fddZKde>de	eH de	eH de6fddZLdd  ZMd!d" ZNdeeHeOf fd#d$ZPdeOfd%d&ZQd'e	eH d(eOd)eOdeeHeeH f fd*d+ZRd(eOddfd,d-ZSde2fd.d/ZTdee
e e
e f fd0d1ZUd2e2d3e
eI d4e
eI d(eOfd5d6ZVd(eOd7eOd8eeH d9eId:eOd;eOd<eOfd=d>ZWdee fd?d@ZXdAdB ZYdCdD ZZej[j\fde0fdEdFZ]d2e2dGe5dHe6dIe<dJeIdKeIde>de7fdLdMZ^dNdO Z_dPdQ Z`dJeIdeeI fdRdSZadTdU ZbecdVkredeZ  dS dS )Wa  
cutadapt version {version}

Copyright (C) 2010-2021 Marcel Martin <marcel.martin@scilifelab.se>

cutadapt removes adapter sequences from high-throughput sequencing reads.

Usage:
    cutadapt -a ADAPTER [options] [-o output.fastq] input.fastq

For paired-end reads:
    cutadapt -a ADAPT1 -A ADAPT2 [options] -o out1.fastq -p out2.fastq in1.fastq in2.fastq

Replace "ADAPTER" with the actual sequence of your 3' adapter. IUPAC wildcard
characters are supported. All reads from input.fastq will be written to
output.fastq with the adapter sequence removed. Adapter matching is
error-tolerant. Multiple adapter sequences can be given (use further -a
options), but only the best-matching adapter will be removed.

Input may also be in FASTA format. Compressed input and output is supported and
auto-detected from the file name (.gz, .xz, .bz2). Use the file name '-' for
standard input/output. Without the -o option, output is sent to standard output.

Citation:

Marcel Martin. Cutadapt removes adapter sequences from high-throughput
sequencing reads. EMBnet.Journal, 17(1):10-12, May 2011.
http://dx.doi.org/10.14806/ej.17.1.200

Run "cutadapt --help" to see all command-line options.
See https://cutadapt.readthedocs.io/ for full documentation.
    N)TupleOptionalSequenceListAnyIteratorUnion)ArgumentParserSUPPRESSHelpFormatter)__version__)warn_duplicate_adaptersAdapterInvalidCharacter)AdapterParser)SingleEndModifierLengthTagModifierSuffixRemoverPrefixSuffixAdder
ZeroCapperQualityTrimmerUnconditionalCutterNEndTrimmerAdapterCutterPairedAdapterCutterErrorPairedAdapterCutterNextseqQualityTrimmer	ShortenerReverseComplementerPairedEndRenamerRenamerInvalidTemplate)full_reportminimal_report
Statistics)PipelineSingleEndPipelinePairedEndPipeline
InputPathsOutputFilesPipelineRunnerSerialPipelineRunnerParallelPipelineRunner)available_cpu_countProgressDummyProgress
FileOpener)setup_loggingREPORTc                       s8   e Zd ZdZG dd deZ fddZdd Z  ZS )CutadaptArgumentParserz
    This ArgumentParser customizes two things:
    - The usage message is not prefixed with 'usage:'
    - A brief message is shown on errors, not full usage
    c                       s&   e Zd Z fddZdddZ  ZS )z/CutadaptArgumentParser.CustomUsageHelpFormatterc                    sJ   zdd l }td| j|d< W n	 ty   Y nw t j|i | d S )Nr   h   width)shutilminget_terminal_sizecolumnsImportErrorsuper__init__)selfargskwargsr6   	__class__ Z/var/www/html/software/conda/envs/catlas/lib/python3.10/site-packages/cutadapt/__main__.pyr<   Z   s   z8CutadaptArgumentParser.CustomUsageHelpFormatter.__init__Nc                 C   s*   |t ur|||df}| | j| d S d S )N )r
   	_add_item_format_usage)r=   usageactionsgroupsprefixr>   rB   rB   rC   	add_usageb   s   z9CutadaptArgumentParser.CustomUsageHelpFormatter.add_usageN)__name__
__module____qualname__r<   rK   __classcell__rB   rB   r@   rC   CustomUsageHelpFormatterY   s    rQ   c                    s4   | j |d< |d dt|d< t j|i | d S )Nformatter_classrG   z	{version})rQ   replacer   r;   r<   )r=   r>   r?   r@   rB   rC   r<   g   s   
zCutadaptArgumentParser.__init__c                 C   s8   t dtjd t dtjd | ddj| j|d dS )z
        If you override this in a subclass, it should not return -- it
        should either exit or raise an exception.
        z2Run "cutadapt --help" to see command-line options.filez<See https://cutadapt.readthedocs.io/ for full documentation.   z
{prog}: error: {message}
)progmessageN)printsysstderrexitformatrW   )r=   rX   rB   rB   rC   errorl   s   zCutadaptArgumentParser.error)	rM   rN   rO   __doc__r   rQ   r<   r^   rP   rB   rB   r@   rC   r3   S   s
    r3   c                   @   s   e Zd ZdS )CommandLineErrorN)rM   rN   rO   rB   rB   rB   rC   r`   v   s    r`   returnc               
   C   sR  t tdd} | d}|jddddd |jd	d
dtd |jddddd |jdddtd |jddtddd |jdtdtd |jdtdtd |jdtdtd |jdd d!d"td# | jd$d%d&}|jd'd(d)d* d+g d,d-d.d/ |jd0d1d2d* d+g d,d-d3d/ |jd4d5d6d* d+g d,d-d7d/ |jd8d9d:td;d<d=d> |jd?d"d@d!dAdB |jdCdDtdEddFd> |jdGdHtdIdJdKd> |jdLdddMd |jdNdOd"d!dPdQdR |jdSdTdUdVdW |jdXdYdZddd[d# |jd\d]d^d_td` |jdad]d^dbtd` | dc}|jddded+g tdfdgdh |jditd djdkdl |jdmdnd dodpdq |jdrtdsdtdudl |jdvdwtd dfdxdl |jdydddzd |jd{d|d}d~ |jdd+g dd |jddddd |jddddd |jdddd~ |jdddddd | jddd&}|jddd dddq |jddd dddq |jdtd dEddl |jddtd dddl |jdddddd |jdddddd |jddddd | d}|jddddd |jddd ddW |jddddd~ |jddddd |jdd^dddd |jdddd~ |jddddd~ |jdddd~ |jdddd~ |jdddd~ |jdd dddq | jddd&}|jddd* dd+g d,ddʍ |jddd* dd+g d,ddʍ |jddd* dd+g d,ddʍ |jddd+g tdfddԍ |jddddd~ |jdddd |jddd dddލ |jddddd |jdddd~ |jddd dd |jddd dd | jddtd | S )NF)rG   add_helpOptionsz-hz--helphelpzShow this help message and exit)actionrd   z	--versionversionzShow version number and exit)re   rd   rf   z--debugcountr   z4Print debug log. Use twice to also print DP matrices)re   defaultrd   z	--profile
store_truez-jz--cores   zFNumber of CPU cores to use. Use 0 to auto-detect. Default: %(default)s)typerh   rd   z--gc-content2   z--buffer-sizei 	= z--compression-level   z
--no-indexindexTstore_false)destrh   re   rd   zFinding adaptersaC  Parameters -a, -g, -b specify adapters to be removed from each read (or from the first read in a pair if data is paired). If specified multiple times, only the best matching adapter is trimmed (but see the --times option). When the special notation 'file:FILE' is used, adapter sequences are read from the given FASTA file.)descriptionz-az	--adapterc                 S      d| fS NbackrB   xrB   rB   rC   <lambda>       z%get_argument_parser.<locals>.<lambda>appendZADAPTERadapterszSequence of an adapter ligated to the 3' end (paired data: of the first read). The adapter and subsequent bases are trimmed. If a '$' character is appended ('anchoring'), the adapter is only found if it is a suffix of the read.)rk   re   rh   metavarrp   rd   z-gz--frontc                 S   rr   NZfrontrB   ru   rB   rB   rC   rw      rx   a  Sequence of an adapter ligated to the 5' end (paired data: of the first read). The adapter and any preceding bases are trimmed. Partial matches at the 5' end are allowed. If a '^' character is prepended ('anchoring'), the adapter is only found if it is a prefix of the read.z-bz
--anywherec                 S   rr   NZanywhererB   ru   rB   rB   rC   rw      rx   a  Sequence of an adapter that may be ligated to the 5' or 3' end (paired data: of the first read). Both types of matches as described under -a and -g are allowed. If the first base of the read is part of the match, the behavior is as with -g, otherwise as with -a. This option is mostly for rescuing failed library preparations - do not use if you know which end your adapter was ligated to!z-ez--error-ratez--errorsEg?zMaximum allowed error rate (if 0 <= E < 1), or absolute number of errors for full-length adapter match (if E is an integer >= 1). Error rate = no. of errors divided by length of matching region. Default: %(default)s (10%%))rk   r{   rh   rd   z--no-indelsindelszNAllow only mismatches in alignments. Default: allow both mismatches and indels)re   rp   rh   rd   z-nz--timesZCOUNTz@Remove up to COUNT adapters from each read. Default: %(default)sz-Oz	--overlapZ	MINLENGTH   zcRequire MINLENGTH overlap between read and adapter for an adapter to be found. Default: %(default)sz--match-read-wildcardsz8Interpret IUPAC wildcards in reads. Default: %(default)sz-Nz--no-match-adapter-wildcardsmatch_adapter_wildcardsz-Do not interpret IUPAC wildcards in adapters.)re   rh   rp   rd   z--action)trimretainmaskZ	lowercasenoner   zWhat to do if a match was found. trim: trim adapter and up- or downstream sequence; retain: trim, but retain adapter; mask: replace with 'N' characters; lowercase: convert to lowercase; none: leave unchanged. Default: %(default)s)choicesrh   rd   z--rcz	--revcompreverse_complementzCheck both the read and its reverse complement for adapter matches. If match is on reverse-complemented version, output that one. Default: check only readz	--no-trimre   store_constr   )rp   re   constrd   z--mask-adapterr   zAdditional read modificationsz-uz--cutZLENGTHa   Remove bases from each read (first read only if paired). If LENGTH is positive, remove bases from the beginning. If LENGTH is negative, remove bases from the end. Can be used twice if LENGTHs have different signs. This is applied *before* adapter trimming.)re   rh   rk   r{   rd   z--nextseq-trimz3'CUTOFFzhNextSeq-specific quality trimming (each read). Trims also dark cycles appearing as high-quality G bases.)rk   rh   r{   rd   z-qz--quality-cutoffz[5'CUTOFF,]3'CUTOFFa!  Trim low-quality bases from 5' and/or 3' ends of each read before adapter removal. Applied to both reads if data is paired. If one value is given, only the 3' end is trimmed. If two comma-separated cutoffs are given, the 5' end is trimmed with the first cutoff, the 3' end with the second.)rh   r{   rd   z--quality-base!   NzAssume that quality values in FASTQ are encoded as ascii(quality + N). This needs to be set to 64 for some old Illumina FASTQ files. Default: %(default)sz--lengthz-lzShorten reads to LENGTH. Positive values remove bases at the end while negative ones remove bases at the beginning. This and the following modifications are applied after adapter trimming.z--trim-nzTrim N's on ends of reads.z--length-tagZTAGzSearch for TAG followed by a decimal number in the description field of the read. Replace the decimal number with the correct length of the trimmed read. For example, use --length-tag 'length=' to correct fields like 'length=123'.)r{   rd   z--strip-suffixzKRemove this suffix from read names if present. Can be given multiple times.z-xz--prefixrD   zUAdd this prefix to read names. Use {name} to insert the name of the matching adapter.)rh   rd   z-yz--suffixz6Add this suffix to read names; can also include {name}z--renameTEMPLATEzfRename reads using TEMPLATE containing variables such as {id}, {adapter_name} etc. (see documentation)z
--zero-capz-zz'Change negative quality values to zero.zFiltering of processed readsz|Filters are applied after above read modifications. Paired-end reads are always discarded pairwise (see also --pair-filter).z-mz--minimum-lengthz
LEN[:LEN2]z*Discard reads shorter than LEN. Default: 0z-Mz--maximum-lengthz0Discard reads longer than LEN. Default: no limitz--max-nzDiscard reads with more than COUNT 'N' bases. If COUNT is a number between 0 and 1, it is interpreted as a fraction of the read length.z--max-expected-errorsz--max-eeZERRORSz\Discard reads whose expected number of errors (computed from quality values) exceeds ERRORS.z--discard-trimmedz	--discardzhDiscard reads that contain an adapter. Use also -O to avoid discarding too many randomly matching reads.z--discard-untrimmedz--trimmed-onlyz-Discard reads that do not contain an adapter.z--discard-casavazBDiscard reads that did not pass CASAVA filtering (header has :Y:).Outputz--quietzPrint only error messages.)rh   re   rd   z--report)fullminimalzAWhich type of report to print: 'full' or 'minimal'. Default: fullz-oz--outputFILEzWrite trimmed reads to FILE. FASTQ or FASTA format is chosen depending on input. Summary report is sent to standard output. Use '{name}' for demultiplexing (see docs). Default: write to standard outputz--fastaz4Output FASTA to standard output even on FASTQ input.z-Zcompression_levelzNUse compression level 1 for gzipped output files (faster, but uses more space))re   r   rp   rd   z--info-filezoWrite information about each read and its adapter matches into FILE. See the documentation for the file format.z-rz--rest-filez]When the adapter matches in the middle of a read, write the rest (after the adapter) to FILE.z--wildcard-filezyWhen the adapter has N wildcard bases, write adapter bases matching wildcard positions to FILE. (Inaccurate with indels.)z--too-short-outputzdWrite reads that are too short (according to length specified by -m) to FILE. Default: discard readsz--too-long-outputzcWrite reads that are too long (according to length specified by -M) to FILE. Default: discard readsz--untrimmed-outputzbWrite reads that do not contain any adapter to FILE. Default: output to same file as trimmed readszPaired-end optionszrThe -A/-G/-B/-U options work like their -a/-b/-g/-u counterparts, but are applied to the second read in each pair.z-Ac                 S   rr   rs   rB   ru   rB   rB   rC   rw   <  rx   	adapters2z43' adapter to be removed from second read in a pair.)rk   rp   re   rh   r{   rd   z-Gc                 S   rr   r|   rB   ru   rB   rB   rC   rw   ?  rx   z45' adapter to be removed from second read in a pair.z-Bc                 S   rr   r}   rB   ru   rB   rB   rC   rw   B  rx   z65'/3 adapter to be removed from second read in a pair.z-Ucut2z/Remove LENGTH bases from second read in a pair.)rp   re   rh   rk   r{   rd   z-pz--paired-outputz$Write second read in a pair to FILE.z--pair-adapterszcTreat adapters given with -a/-A etc. as pairs. Either both or none are removed from each read pair.z--pair-filterz(any|both|first))anyZbothfirstzWhich of the reads in a paired-end read have to match the filtering criterion in order for the pair to be filtered. Default: any)r{   rh   r   rd   z--interleavedz/Read and/or write interleaved paired-end reads.z--untrimmed-paired-outputzWrite second read in a pair to this FILE when no adapter was found. Use with --untrimmed-output. Default: output to same file as trimmed readsz--too-short-paired-outputz>Write second read in a pair to this file if pair is too short.)r{   rh   rd   z--too-long-paired-outputz=Write second read in a pair to this file if pair is too long.inputs*)nargsrd   )r3   r_   add_argument_groupadd_argumentr   r
   intfloat)parsergrouprB   rB   rC   get_argument_parserz   s  






	



















r   sc              
   C   s~   zdd |  dD }W n ty } ztd|d}~ww t|dkr-d|d g}n
t|dkr7td	|d |d fS )
zParse a string INT[,INT] into a pair of integers

    >>> parse_cutoffs("5")
    (0, 5)
    >>> parse_cutoffs("6,7")
    (6, 7)
    c                 S   s   g | ]}t |qS rB   r   ).0valuerB   rB   rC   
<listcomp>n      z!parse_cutoffs.<locals>.<listcomp>,z'Quality cutoff value not recognized: {}Nrj   r   rV   zJExpected one value or two values separated by comma for the quality cutoff)split
ValueErrorr`   r]   len)r   cutoffserB   rB   rC   parse_cutoffse  s   r   .c              
   C   s   |  d}t|dvrtdztdd |D }W n ty- } ztd|d}~ww t|dkrG|d	 du rG|d
 du rGtd| t|S )zParse [INT][:[INT]] into a pair of integers. If a value is omitted, use None

    >>> parse_lengths('25')
    (25,)
    >>> parse_lengths('17:25')
    (17, 25)
    >>> parse_lengths('25:')
    (25, None)
    >>> parse_lengths(':25')
    (None, 25)
    :)rj   rV   z!Only at most one colon is allowedc                 s   s$    | ]}|d krt |ndV  qdS )rD   Nr   )r   frB   rB   rC   	<genexpr>  s   " z parse_lengths.<locals>.<genexpr>zValue not recognized: {}NrV   r   rj   z8Cannot parse {!r}: At least one length needs to be given)r   r   r`   tupler   r]   )r   fieldsvaluesr   rB   rB   rC   parse_lengths{  s   
$r   file_openeradapter_namesadapter_names2c                 C   s  | | jd}| | jd}| | jd}d }}	| jdur)|| j| jd\}}	d }
}| jdur=|| j	| j
d\}
}t| jt| j t| jdu dkrTtdt| }|ra| jratd|dkrxd }}d }}t|| |\}}}}nT|dkrd| jv rd	| jv sJ d| jv rd	| jv sJ d }}d }}t||| |\}}}}n$d }}d }}|| j| jd\}}|| j| jd\}}|du r|}tdi d
|d|d|d|d|	d|
d|d|d|d|d|d|d|d|d|d| jS )z
    Return an OutputFiles instance. If demultiplex is True, the untrimmed, untrimmed2, out and out2
    attributes are not opened files, but paths (out and out2 with the '{name}' template).
    wbNrj   zsOnly one of the --discard-trimmed, --discard-untrimmed and --untrimmed-output options can be used at the same time.z1Do not use --discard-trimmed when demultiplexing.normalcombinatorial{name1}{name2}restinfowildcard	too_short
too_short2too_long	too_long2	untrimmed
untrimmed2outout2demultiplex_outdemultiplex_out2combinatorial_outcombinatorial_out2Zforce_fastarB   )Zxopen_or_none	rest_file	info_filewildcard_fileminimum_lengthZ
xopen_pairtoo_short_outputtoo_short_paired_outputmaximum_lengthtoo_long_outputtoo_long_paired_outputr   discard_trimmeddiscard_untrimmeduntrimmed_outputr`   determine_demultiplex_modeopen_demultiplex_outoutputpaired_outputopen_combinatorial_outuntrimmed_paired_outputr)   Zfasta)r>   default_outfiler   r   r   r   r   r   r   r   r   r   Zdemultiplex_moder   r   r   r   r   r   r   r   rB   rB   rC   open_output_files  s   





	
r   c                 C   s   t  }t  }|jrg }ndg}|dd |D 7 }|dd | D 7 }tt| || D ]>\}}|d ur5|nd}	|d ur=|nd}
|jd|	d|
}|jd|	d|
}||d|||f< ||d|||f< q+|j	sp|j
rttd	d  }}||||fS )
NNNc                 S   s   g | ]}d |fqS rL   rB   )r   name2rB   rB   rC   r     r   z*open_combinatorial_out.<locals>.<listcomp>c                 S   s   g | ]}|d fqS rL   rB   )r   name1rB   rB   rC   r     r   unknownr   r   r   zCombinatorial demultiplexing (with {name1} and {name2}) cannot be combined with --untrimmed-output or --untrimmed-paired-output)dictr   list	itertoolsproductr   rS   r   xopenr   r   r`   )r   r   r>   r   r   r   extrar   r   Zfname1Zfname2path1path2r   r   rB   rB   rC   r     s(   r   c                 C   s   t  }|jd urt  nd }| D ]%}|jd|}||d||< |jd ur4|jd|}||d||< q|jdd}|jrB|j}|jrHd }	n||d}	|jd urm|jdd}
|jr`|j}
|jrfd }n	||
d}nd }|||	|fS )N{name}r   r   )r   r   r   rS   r   r   r   r   )r   r>   r   r   r   namer   r   Zuntrimmed_pathr   Zuntrimmed2_pathr   rB   rB   rC   r     s0   

r   c                 C   s   | j duo	d| j v }| jdur|d| jv krtd| j duo7| jduo7d| j v o7d| j v o7d| jv o7d| jv }|r@|r@td|rDdS |rHdS d	S )
z0Return one of "normal", "combinatorial" or FalseNr   z_When demultiplexing paired-end data, "{name}" must appear in both output file names (-o and -p)r   r   z2You cannot combine {name} with {name1} and {name2}r   r   F)r   r   r`   )r>   ZdemultiplexZdemultiplex_combinatorialrB   rB   rC   r     s*   
r   c                 C   s4   t | jp| jp| jp| jp| jp| jp| jp| jS )z>
    Determine whether we should work in paired-end mode.
    )	boolr   interleavedr   r   pair_filterr   r   r   r>   rB   rB   rC   determine_paired,  s    r   r   pairedr   c                 C   s   t | dkr
tdt | dkr'tdt | d ddd | D  d	 | d }|rA|sAt | d
kr9td| d
 }||fS t | dkrKtdd}||fS )z>
    Return tuple (input_filename, input_paired_filename)
    r   zIYou did not provide any input file names. Please give me something to do!rV   zFYou provided {} input file names, but either one or two are expected. zThe file names were:
 - z
 - c                 s   s    | ]}d  |V  qdS )z'{}'N)r]   )r   prB   rB   rC   r   J  s    z$setup_input_files.<locals>.<genexpr>zE
Hint: If your path contains spaces, you need to enclose it in quotesrj   zYou used an option that enabled paired-end mode (such as -p, -A, -G, -B, -U), but then you also need to provide two input files (you provided one) or use --interleaved.zIt appears you want to trim paired-end data because you provided two input files, but then you also need to provide two output files (with -o and -p) or use the --interleaved option.N)r   r`   r]   join)r   r   r   input_filenameinput_paired_filenamerB   rB   rC   setup_input_files<  s<   	r   c                 C   s   |s| j r	td| jrtd|rM| jsM| jstd| js#td| j| j df| j| jdf| j	| j
dffD ]\}}}t|t|krLtdj|d	q7| jd
k rVtdd| j  krddksitd td| jru| jd
krwtdd S d S )NzQOption --untrimmed-paired-output can only be used when trimming paired-end reads.zFOption --pair-adapters can only be used when trimming paired-end readszWhen a paired-end trimming option such as -A/-G/-B/-U, is used, a second output file needs to be specified via -p (--paired-output).zDWhen you use -p or --paired-output, you must also use the -o option.r   z	too-shortztoo-longzvWhen trimming paired-end data, you must use either none or both of the --{name}-output/--{name}-paired-output options.r   rj   zThe overlap must be at least 1.r   d   z8GC content must be given as percentage between 0 and 100z+--pair-adapters cannot be used with --times)r   r`   pair_adaptersr   r   r   r   r   r   r   r   r   r]   overlap
gc_contenttimes)r>   r   r   Z
paired_outargnamerB   rB   rC   check_argumentsa  s<   

r   c                 C   s  | j dkrd| _ |r| jdu rdn| j}t||}nt|}t|tr3|r'|s3| js0| js0| jr3d|_t	|| j
| j| |rA|jn|j}| jdurR|t| j| j | jdurit| j}|t|d |d | j t||||| j| j | j| j| j | j
 t| D ]}	||	 q| jr| js| jrtdz|r|t| j n|t | j W n t!y }
 zt|
d}
~
ww dD ]1}t"| |}|durt#|}|st$|d	krtd
|rt$|dkr|d |d f}t%||| q| j&|_&| j'|_'| j(|_(| j)|_)| j|_|S )z
    Setup a processing pipeline from parsed command-line arguments.

    If there are any problems parsing the arguments, a CommandLineError is raised.

    Return an instance of Pipeline (SingleEndPipeline or PairedEndPipeline)
    r   Nr   Tr   rj   zFOption --rename cannot be combined with --prefix (-x) or --suffix (-y))r   r   rV   z8Two minimum or maximum lengths given for single-end data)*re   r   r'   r&   
isinstancer   r   r   Zoverride_untrimmed_pair_filteradd_unconditional_cutterscutr   Zadd_bothaddZnextseq_trimr   quality_baseZquality_cutoffr   r   add_adapter_cutterr   r   r   renamern   )modifiers_applying_to_both_ends_if_pairedrJ   suffixr`   add_paired_modifierr   r    r!   getattrr   r   setattrZmax_nZmax_expected_errorsZdiscard_casavar   )r>   r   r   rz   r   Zpair_filter_modepipelineZpipeline_addr   modifierr   attrparamlengthsrB   rB   rC   pipeline_from_parsed_args  s   





r  c              
   C   s   t | j| j| j| j| jd}z|| j}|| j}W n t	t
tfy/ } zt|d }~ww t| t| | jdkrH|| D ]}|  qA||fS )N)Z
max_errorsZmin_overlapZread_wildcardsZadapter_wildcardsr   rj   )r   Z
error_rater   Zmatch_read_wildcardsr   r   Zparse_multirz   r   FileNotFoundErrorr   r   r`   r   debugZenable_debug)r>   Zadapter_parserrz   r   r   adapterrB   rB   rC   adapters_from_args  s(   

r  r  cut1r   c                 C   s   t ||gD ]c\}}|sqt|dkrtdt|dkr+|d |d  dkr+td|D ];}|dkr4q-|dkrY|rJt| tsAJ | t|d  q-t| tsQJ | t| q-t| ts`J | d t| q-qd S )NrV   z0You cannot remove bases from more than two ends.r   rj   z0You cannot remove bases from the same end twice.)	enumerater   r`   r   r'   r  r   r&   )r  r  r   r   iZcut_argcrB   rB   rC   r    s(    r  r   re   r   r   add_rc_suffixallow_indexc
              
   C   s
  |r,|rt dzt|||}
W n ty$ } zt dt| d }~ww | |
 d S d\}}z|r:t||||	}|rCt||||	}W n tyT } zt |d }~ww |rk|r]t d|sa|ri| || d S d S |r|rzt||rudnd d}n|}| | d S d S )Nz)Cannot use --revcomp with --pair-adaptersz--pair-adapters: r   z.--revcomp not implemented for paired-end readsz rc)Z	rc_suffix)	r`   r   r   strr	  r   r   r  r   )r  rz   r   r   r   re   r   r   r  r  Zcutterr   Zadapter_cutterZadapter_cutter2r  rB   rB   rC   r    sH   
r  c                 c   s    | j d urt| j V  | jrt V  | jrt| jV  | jD ]}t|V  q| js-| j	r5t
| j| j	V  | jrAt| jdV  d S d S )N)r  )lengthr   Ztrim_nr   Z
length_tagr   Zstrip_suffixr   rJ   r  r   Zzero_capr   r  )r>   r  rB   rB   rC   r  5  s   

r  c                 C   sJ   t  }|dkrd| d nd}tdtt  | tdd|  dS )	z'Print the "This is cutadapt ..." headerCPythonz ()rD   z$This is cutadapt %s with Python %s%szCommand line parameters: %s N)platformpython_implementationloggerr   r   python_versionr   )cmdlineargsimplementationoptrB   rB   rC   
log_headerD  s   r(  c                   C   s   t tjdd  dS )z#Entry point for command-line scriptrj   Nr   )mainrZ   argvrB   rB   rB   rC   main_cliN  s   r+  c              
   C   sH  t   }t }|j| d\}}tjjs#ttt||j	|j
dk|jd t|  t|j}|j	r7|j
r7|d |rGt|  |dd|  |jdk rQ|d |jdkrYt n|j}t|jt|d	}tj rt|j	st|jstt }	nt }	t|}
|
d
v sJ zP|jot|jdk}t |j|
|\}}t!||
 t"|\}}t#||
|||}dd |D }dd |D }t$|||||}t%|||d}t&||||	||j'|}W n! t(y } ztjddd |t)| W Y d}~dS d}~ww t*d||dkrdndddd
|j+  z|}|, }W d   n	1 sw   Y  W nJ t-y6   t.dtjd t/d Y n5 t0yD   t/d Y n' t1j2t1j3t4fyj } ztjddd t/d5| W Y d}~nd}~ww t   | }|j
dkrzt6}nt7}t8t9d||||j:d  |durddl;}|<  |=|>d?d  |S )!z
    Set up a processing pipeline from the command-line arguments, run it and return
    a Statistics object.

    default_outfile is the file to which trimmed reads are sent if the ``-o``
    parameter is not used.
    r   r   )Zlog_to_stderrquietr   r  z<Options --quiet and --report cannot be used at the same timezunrecognized arguments: r   r   z$Value for --cores cannot be negative)r   threads)FTrj   c                 S      g | ]}|j qS rB   r   r   arB   rB   rC   r         zmain.<locals>.<listcomp>c                 S   r.  rB   r   r/  rB   rB   rC   r     r1  )r   r   zCommand line error. Traceback:T)exc_infoNz,Processing reads on %d core%s in %s mode ...r   rD   z
single-endz
paired-endZInterruptedrT      zcutadapt: error: {}z%sr   time   )@r4  r   parse_known_argsloggingroothandlersr1   r#  is_any_output_stdoutr,  reportr  r(  setup_profiler_if_requestedZprofiler^   warn_if_en_dashesr   coresr-   r0   r   estimate_compression_threadsrZ   r[   isattyr.   r/   r   r   r   r   r   r   r  r  r   r(   setup_runnerbuffer_sizer`   r  r   r   runKeyboardInterruptrY   r\   BrokenPipeErrordnaioFileFormatErrorUnknownFileFormatEOFErrorr]   r#   r"   logr2   r   pstatsdisableZStatsZ
sort_statsZprint_stats)r%  r   
start_timer   r>   Zleftover_argsprofilerr>  r   progressr   Zis_interleaved_inputr   r   rz   r   r  r   r   outfilesinpathsrunnerr   rstatselapsedr;  rK  rB   rB   rC   r)  T  s   








r)  rQ  rP  rO  r>  rB  c           	   
   C   sf   z|dkrt | ||||||dW S ||}t| |||W S  tjtjtfy2 } zt|d }~ww )Nrj   )Z	n_workersrB  )r,   openr+   rF  rH  rG  OSErrorr`   )	r  rQ  rP  rO  r>  rB  r   Zinfilesr   rB   rB   rC   rA    s   	
rA  c                 C   s(   | rdd l }| }|  |S d }|S )Nr   )cProfileZProfileenable)	requestedrX  rN  rB   rB   rC   r<    s   r<  c                 C   s$   | D ]}| drtd| qd S )Nu   –u   The first character in argument '%s' is '–' (an en-dash, Unicode U+2013) and will therefore be interpreted as a file name. If you wanted to provide an option, use a regular hyphen '-'.)
startswithr#  warning)r>   argrB   rB   rC   r=    s   
r=  c                 C   s   t dt| dS )Nr      )maxr7   )r>  rB   rB   rC   r?    s   r?  c                 C   sh   t | jd u | jdk| jdk| jdk| jdk| jdk| jdk| jdk| jdk| j	dk| j
dk| jdkgS )N-)r   r   r   r   r   r   r   r   r   r   r   r   r   rB   rB   rC   r:    s   r:  __main__)er_   rZ   r4  r7  r!  r   typingr   r   r   r   r   r   r   argparser	   r
   r   rF  Zcutadaptr   Zcutadapt.adaptersr   r   r   Zcutadapt.parserr   Zcutadapt.modifiersr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   Zcutadapt.reportr"   r#   r$   Zcutadapt.pipeliner%   r&   r'   r(   r)   r*   r+   r,   Zcutadapt.utilsr-   r.   r/   r0   Zcutadapt.logr1   r2   	getLoggerr#  r3   	Exceptionr`   r   r  r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r(  r+  stdoutbufferr)  rA  r<  r=  r?  r:  rM   r\   rB   rB   rB   rC   <module>   s   !$L(# l
H
%%T"	

-
T



