├── utilities ├── __init__.py ├── package_info.py ├── dist_utils.py ├── psl_cid_extractor.py ├── sam_cid_extractor.py ├── common_utils.py ├── fasta_utils.py └── adj_utils.py ├── .gitignore ├── sample_dataset ├── reads │ ├── rnaseq_1.fq.gz │ └── rnaseq_2.fq.gz └── assemble.sh ├── bin ├── skip_psl_self.awk ├── skip_psl_self_ss.awk ├── strip_sam_qual.awk ├── strip_sam_seq_qual.awk └── strip_sam_seq_qual_noself.awk ├── prereqs ├── makefile3 └── makefile ├── README.md ├── TUTORIAL.md ├── transabyss-merge ├── LICENSE └── transabyss /utilities/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.pyc 3 | -------------------------------------------------------------------------------- /sample_dataset/reads/rnaseq_1.fq.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcgsc/transabyss/HEAD/sample_dataset/reads/rnaseq_1.fq.gz -------------------------------------------------------------------------------- /sample_dataset/reads/rnaseq_2.fq.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcgsc/transabyss/HEAD/sample_dataset/reads/rnaseq_2.fq.gz -------------------------------------------------------------------------------- /bin/skip_psl_self.awk: -------------------------------------------------------------------------------- 1 | #!/usr/bin/awk -f 2 | BEGIN { 3 | FS="\t" # use TAB as input field separator 4 | OFS="\t" # use TAB as output field separator 5 | } 6 | { 7 | if ($10!=$14) { 8 | print 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /bin/skip_psl_self_ss.awk: -------------------------------------------------------------------------------- 1 | #!/usr/bin/awk -f 2 | BEGIN { 3 | FS="\t" # use TAB as input field separator 4 | OFS="\t" # use TAB as output field separator 5 | } 6 | { 7 | if ($10!=$14 && $9=="+") { 8 | print 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /utilities/package_info.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | VERSION = "2.0.1" 4 | NAME = "Trans-ABySS" 5 | SUPPORT_INFO = '''\ 6 | Written by Ka Ming Nip. 7 | Copyright 2018 Canada's Michael Smith Genome Sciences Centre 8 | Report bugs to 9 | ''' 10 | PACKAGEDIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) 11 | BINDIR = os.path.join(PACKAGEDIR, 'bin') 12 | -------------------------------------------------------------------------------- /bin/strip_sam_qual.awk: -------------------------------------------------------------------------------- 1 | #!/usr/bin/awk -f 2 | BEGIN { 3 | FS="\t" # use TAB as input field separator 4 | OFS="\t" # use TAB as output field separator 5 | } 6 | { 7 | if ($1=="@SQ" || $1=="@HD" || $1=="@RG" || $1=="@PG" || $1=="@CO") { 8 | print 9 | } 10 | else { 11 | #$10="*" #remove SEQ 12 | $11="*" #remove QUAL 13 | print 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /bin/strip_sam_seq_qual.awk: -------------------------------------------------------------------------------- 1 | #!/usr/bin/awk -f 2 | BEGIN { 3 | FS="\t" # use TAB as input field separator 4 | OFS="\t" # use TAB as output field separator 5 | } 6 | { 7 | if ($1=="@SQ" || $1=="@HD" || $1=="@RG" || $1=="@PG" || $1=="@CO") { 8 | print 9 | } 10 | else { 11 | $10="*" #remove SEQ 12 | $11="*" #remove QUAL 13 | print 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /bin/strip_sam_seq_qual_noself.awk: -------------------------------------------------------------------------------- 1 | #!/usr/bin/awk -f 2 | BEGIN { 3 | FS="\t" # use TAB as input field separator 4 | OFS="\t" # use TAB as output field separator 5 | } 6 | { 7 | if ($1=="@SQ" || $1=="@HD" || $1=="@RG" || $1=="@PG" || $1=="@CO") { 8 | print 9 | } 10 | else if ($1 != $3) { 11 | # keep the alignment if QNAME != RNAME 12 | $10="*" # remove SEQ 13 | $11="*" # remove QUAL 14 | print 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /sample_dataset/assemble.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -euo pipefail 4 | 5 | cd $(dirname $0) 6 | 7 | kmer1=25 8 | kmer2=32 9 | name1=test.k${kmer1} 10 | name2=test.k${kmer2} 11 | reads1=./reads/rnaseq_1.fq.gz 12 | reads2=./reads/rnaseq_2.fq.gz 13 | assemblydir1=./${name1} 14 | assemblydir2=./${name2} 15 | finalassembly1=${assemblydir1}/${name1}-final.fa 16 | finalassembly2=${assemblydir2}/${name2}-final.fa 17 | mergedassembly=./merged.fa 18 | 19 | # set up the environment 20 | TRANSABYSS_PATH=$(readlink -f ..) 21 | export PATH=${TRANSABYSS_PATH}:${TRANSABYSS_PATH}/bin/:${PATH} 22 | 23 | # assemble the test dataset 24 | transabyss -k ${kmer1} --se ${reads1} ${reads2} --outdir ${assemblydir1} --name ${name1} --threads 2 --island 0 -c 1 25 | 26 | transabyss -k ${kmer2} --se ${reads1} ${reads2} --outdir ${assemblydir2} --name ${name2} --threads 2 --island 0 -c 1 27 | 28 | transabyss-merge --mink ${kmer1} --maxk ${kmer2} --prefixes k${kmer1}. k${kmer2}. --out ${mergedassembly} ${finalassembly1} ${finalassembly2} 29 | 30 | #EOF 31 | -------------------------------------------------------------------------------- /utilities/dist_utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # written by Ka Ming Nip 4 | # Copyright 2014 Canada's Michael Smith Genome Sciences Centre 5 | 6 | class PairedPartners: 7 | """Data structure to store the tuples of incoming and outgoing partner id and the number of supporting read pairs.""" 8 | 9 | def __init__(self, ins, outs): 10 | self.ins = ins 11 | self.outs = outs 12 | #enddef 13 | #endclass 14 | 15 | def parse_dist(dist_file): 16 | """Parse a dist file and return a dictionary of cid to PairedPartners.""" 17 | 18 | cid_partners_dict = {} 19 | 20 | with open(dist_file, 'r') as fh: 21 | for line in fh: 22 | linestripped = line.strip() 23 | if len(linestripped) > 0: 24 | cid, partners_str = linestripped.split(' ', 1) 25 | outs_str, ins_str = partners_str.split(';', 1) 26 | 27 | out_tuples_list = [] 28 | 29 | for p in outs_str.strip().split(): 30 | pname, distance, pairs, error = p.split(',', 3) 31 | out_tuples_list.append((pname, int(pairs))) 32 | #endfor 33 | 34 | in_tuples_list = [] 35 | 36 | for p in ins_str.strip().split(): 37 | pname, distance, pairs, error = p.split(',', 3) 38 | in_tuples_list.append((pname, int(pairs))) 39 | #endfor 40 | 41 | cid_partners_dict[int(cid)] = PairedPartners(in_tuples_list, out_tuples_list) 42 | #endif 43 | #endfor 44 | #endwith 45 | 46 | return cid_partners_dict 47 | #enddef 48 | -------------------------------------------------------------------------------- /prereqs/makefile3: -------------------------------------------------------------------------------- 1 | # This make file would install all require software packages except ABySS. 2 | 3 | SHELL:=/bin/bash -eu -o pipefail 4 | 5 | .DELETE_ON_ERROR: 6 | 7 | WORKDIR:=$(shell pwd) 8 | 9 | IGRAPH_VERSION:=0.7.1 10 | PYTHON_VERSION:=3.6.4 11 | 12 | all: transabyss transabyss-merge 13 | touch $@.COMPLETE 14 | 15 | clean: clean_blat clean_python clean_igraph 16 | rm -f all.COMPLETE && \ 17 | rm -rf ./bin ./lib ./include ./share 18 | 19 | transabyss: bin blat.COMPLETE python.COMPLETE python-igraph.COMPLETE 20 | 21 | transabyss-merge: transabyss 22 | 23 | bin: 24 | mkdir -p ./bin 25 | 26 | blat.COMPLETE: bin 27 | wget --quiet --no-check-certificate -N -P ./bin http://hgdownload.cse.ucsc.edu/admin/exe/linux.x86_64/blat/blat && \ 28 | chmod +x ./bin/blat && \ 29 | touch $@ 30 | 31 | clean_blat: 32 | rm -f blat.COMPLETE ./bin/blat 33 | 34 | python.COMPLETE: bin 35 | wget --quiet --no-check-certificate -N https://www.python.org/ftp/python/$(PYTHON_VERSION)/Python-$(PYTHON_VERSION).tgz && \ 36 | tar -zxf Python-$(PYTHON_VERSION).tgz && \ 37 | cd Python-$(PYTHON_VERSION) && \ 38 | ./configure --quiet --prefix=$(WORKDIR) && \ 39 | make --quiet && \ 40 | make --quiet install && \ 41 | cd $(WORKDIR) && \ 42 | ln -s python3 ./bin/python && \ 43 | touch $@ 44 | 45 | clean_python: 46 | rm -f python.COMPLETE python-igraph.COMPLETE Python-$(PYTHON_VERSION).tgz && \ 47 | rm -rf Python-$(PYTHON_VERSION) 48 | 49 | igraph.COMPLETE: bin 50 | wget --quiet --no-check-certificate -N http://igraph.org/nightly/get/c/igraph-$(IGRAPH_VERSION).tar.gz && \ 51 | tar -zxf igraph-$(IGRAPH_VERSION).tar.gz && \ 52 | cd igraph-$(IGRAPH_VERSION) && \ 53 | ./configure --quiet --prefix=$(WORKDIR) && \ 54 | make --quiet && \ 55 | make --quiet install && \ 56 | cd $(WORKDIR) && \ 57 | touch $@ 58 | 59 | clean_igraph: 60 | rm -f igraph.COMPLETE igraph-$(IGRAPH_VERSION).tar.gz && \ 61 | rm -rf igraph-$(IGRAPH_VERSION) 62 | 63 | python-igraph.COMPLETE: bin python.COMPLETE igraph.COMPLETE 64 | export PKG_CONFIG_PATH=$(WORKDIR)/lib/pkgconfig && \ 65 | ./bin/pip3 --quiet install python-igraph && \ 66 | touch $@ 67 | -------------------------------------------------------------------------------- /prereqs/makefile: -------------------------------------------------------------------------------- 1 | # This make file would install all require software packages except ABySS. 2 | 3 | SHELL:=/bin/bash -eu -o pipefail 4 | 5 | .DELETE_ON_ERROR: 6 | 7 | WORKDIR:=$(shell pwd) 8 | 9 | IGRAPH_VERSION:=0.7.1 10 | PYTHON_VERSION:=2.7.14 11 | 12 | all: transabyss transabyss-merge 13 | touch $@.COMPLETE 14 | 15 | clean: clean_pip clean_blat clean_python clean_igraph 16 | rm -f all.COMPLETE && \ 17 | rm -rf ./bin ./lib ./include ./share 18 | 19 | transabyss: bin blat.COMPLETE python.COMPLETE python-igraph.COMPLETE 20 | 21 | transabyss-merge: transabyss 22 | 23 | bin: 24 | mkdir -p ./bin 25 | 26 | blat.COMPLETE: bin 27 | wget --quiet --no-check-certificate -N -P ./bin http://hgdownload.cse.ucsc.edu/admin/exe/linux.x86_64/blat/blat && \ 28 | chmod +x ./bin/blat && \ 29 | touch $@ 30 | 31 | clean_blat: 32 | rm -f blat.COMPLETE ./bin/blat 33 | 34 | python.COMPLETE: bin 35 | wget --quiet --no-check-certificate -N https://www.python.org/ftp/python/$(PYTHON_VERSION)/Python-$(PYTHON_VERSION).tgz && \ 36 | tar -zxf Python-$(PYTHON_VERSION).tgz && \ 37 | cd Python-$(PYTHON_VERSION) && \ 38 | ./configure --quiet --prefix=$(WORKDIR) && \ 39 | make --quiet && \ 40 | make --quiet install && \ 41 | cd $(WORKDIR) && \ 42 | touch $@ 43 | 44 | clean_python: 45 | rm -f python.COMPLETE python-igraph.COMPLETE Python-$(PYTHON_VERSION).tgz && \ 46 | rm -rf Python-$(PYTHON_VERSION) 47 | 48 | pip.COMPLETE: bin python.COMPLETE 49 | wget --quiet --no-check-certificate -N https://bootstrap.pypa.io/get-pip.py && \ 50 | ./bin/python get-pip.py && \ 51 | touch $@ 52 | 53 | clean_pip: 54 | rm -f pip.COMPLETE get-pip.py 55 | 56 | igraph.COMPLETE: bin 57 | wget --quiet --no-check-certificate -N http://igraph.org/nightly/get/c/igraph-$(IGRAPH_VERSION).tar.gz && \ 58 | tar -zxf igraph-$(IGRAPH_VERSION).tar.gz && \ 59 | cd igraph-$(IGRAPH_VERSION) && \ 60 | ./configure --quiet --prefix=$(WORKDIR) && \ 61 | make --quiet && \ 62 | make --quiet install && \ 63 | cd $(WORKDIR) && \ 64 | touch $@ 65 | 66 | clean_igraph: 67 | rm -f igraph.COMPLETE igraph-$(IGRAPH_VERSION).tar.gz && \ 68 | rm -rf igraph-$(IGRAPH_VERSION) 69 | 70 | python-igraph.COMPLETE: bin python.COMPLETE pip.COMPLETE igraph.COMPLETE 71 | export PKG_CONFIG_PATH=$(WORKDIR)/lib/pkgconfig && \ 72 | ./bin/pip --quiet install python-igraph && \ 73 | touch $@ 74 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Release](https://img.shields.io/github/release/bcgsc/transabyss.svg)](https://github.com/bcgsc/transabyss/releases) 2 | [![Downloads](https://img.shields.io/github/downloads/bcgsc/transabyss/total?logo=github)](https://github.com/bcgsc/transabyss/releases/download/2.0.1/transabyss-2.0.1.zip) 3 | [![Conda](https://img.shields.io/conda/dn/bioconda/transabyss?label=Conda)](https://anaconda.org/bioconda/transabyss) 4 | [![Issues](https://img.shields.io/github/issues/bcgsc/transabyss.svg)](https://github.com/bcgsc/transabyss/issues) 5 | 6 | # Trans-ABySS 7 | ## *De novo* assembly of RNAseq data using ABySS 8 | 9 | [Ka Ming Nip](mailto:kmnip@bcgsc.ca) and [Readman Chiu](mailto:rchiu@bcgsc.ca) 10 | 11 | Copyright 2018 Canada's Michael Smith Genome Sciences Centre, BC Cancer 12 | 13 | Please use our [Google Group](mailto:trans-abyss@googlegroups.com) for [discussions and 14 | support](https://groups.google.com/d/forum/trans-abyss). 15 | 16 | You may also create [issues](https://github.com/bcgsc/transabyss/issues) on our GitHub repository. 17 | 18 | If you use Trans-ABySS, please cite: 19 | 20 | [Robertson, G., et al. 2010. De novo assembly and analysis of RNA-seq data. Nature Methods 7, 909-912(2010)](http://www.nature.com/nmeth/journal/v7/n11/full/nmeth.1517.html) 21 | 22 | -------------------------------------------------------------------------------- 23 | 24 | Program requirements for `transabyss` and `transabyss-merge`: 25 | * [ABySS 2.0.x](https://github.com/bcgsc/abyss/releases) 26 | * [Python 2.7.x](https://www.python.org/download/releases/2.7.14/) or [Python 3.6.x](https://www.python.org/download/releases/3.6.4/) 27 | * [python-igraph 0.7.x](http://igraph.org/python/#downloads) 28 | * [BLAT](http://hgdownload.cse.ucsc.edu/admin/exe/linux.x86_64/blat/blat) 29 | 30 | Required Python packages (ie. python-igraph) can be installed 31 | easily with `pip`, ie. 32 | 33 | ``` 34 | pip install igraph 35 | ``` 36 | 37 | Other required softwares must be accessible from your `PATH` environment variable. 38 | 39 | To test `transabyss` on our sample dataset: 40 | 41 | ``` 42 | bash sample_dataset/assemble.sh 43 | ``` 44 | 45 | Please check out our [short tutorial](TUTORIAL.md) for more information on the usage of each application. 46 | 47 | 48 | -------------------------------------------------------------------------------- 49 | EOF 50 | -------------------------------------------------------------------------------- /TUTORIAL.md: -------------------------------------------------------------------------------- 1 | The Trans-ABySS package has 2 main applications: 2 | 1. **transabyss** - RNAseq assembler at a single k-mer size 3 | 2. **transabyss-merge** - merge multiple assemblies from (1) 4 | 5 | 6 | ### Content: 7 | **PART 1. Assembly with `transabyss`** 8 | + [Usage](#11-usage) 9 | + [Running transabyss](#12-running-transabyss) 10 | + [Input reads](#13-input-reads) 11 | + [Output assembly path](#14-output-assembly-path) 12 | + [k-mer size](#15-k-mer-size) 13 | + [MPI and multi-threading](#16-mpi-and-multi-threading) 14 | + [Strand-specific assembly](#17-strand-specific-assembly) 15 | 16 | **PART 2. Merging assemblies with `transabyss-merge`** 17 | + [Usage](#21-usage) 18 | + [Running transabyss-merge](#22-running-transabyss-merge) 19 | + [Minimum and maximum k-mer sizes](#23-minimum-and-maximum-k-mer-sizes) 20 | + [Output merged assembly path](#24-output-merged-assembly-path) 21 | + [Output sequence prefixes](#25-output-sequence-prefixes) 22 | 23 | Please use our Google Group for discussions and support. Existing topics can be viewed at . 24 | 25 | You may also create issues on our GitHub repository at . 26 | 27 | ---- 28 | 29 | #### PART 1. Assembly with `transabyss` 30 | 31 | ##### [1.1] Usage 32 | 33 | transabyss --help 34 | 35 | 36 | ##### [1.2] Running transabyss 37 | 38 | transabyss --se reads.fq 39 | 40 | See below for assembling single-end reads and/or pair-end reads. 41 | 42 | 43 | ##### [1.3] Input reads 44 | 45 | Supported formats are compressed (gzip/bzip) FASTQ/FASTA/SAM/QSEQ or BAM files. 46 | Paired-end reads in FASTQ/A can be interleaved or in separate files. 47 | Paired-end reads in FASTQ/A must have the suffixes `/1` or `/2` in the read name. 48 | 49 | Use options `--se` and `--pe` to specify the path(s) of single-end reads and paired-end reads, respectively. Example usages: 50 | 51 | combination | reads for sequence content | reads for paired-end linkage | assembly 52 | ----|----|----|---- 53 | `--se r.fq` | r.fq | _none_ | single-end 54 | `--pe r.fq` | r.fq | r.fq | paired-end 55 | `--se SE.fq --pe PE.fq` | SE.fq | PE.fq | paired-end 56 | `--se SE.fq PE.fq --pe PE.fq` | SE.fq, PE.fq | PE.fq | paired-end 57 | 58 | 59 | ##### [1.4] Output assembly path 60 | 61 | default: `./transabyss_2.0.0_assembly/transabyss-final.fa` 62 | 63 | Use options `--name` and `--outdir` to change the output directory and assembly name. 64 | 65 | 66 | ##### [1.5] k-mer size 67 | 68 | default: `32` 69 | 70 | Use option `--kmer` to adjust the k-mer size. 71 | k=32 has a good trade-off for assembling both rare and common transcripts. 72 | Using larger k-mers improve the assembly quality of common transcripts and transcripts with repetitive regions, but the assembly of rare transcripts may suffer. 73 | 74 | 75 | ##### [1.6] MPI and multi-threading 76 | 77 | default: no mpi processes; singe-threaded 78 | 79 | Use option `--threads` to specify the number of threads. 80 | Use option `--mpi` to specify the number of MPI processes. 81 | 82 | Only the first stage of assembly (de Bruijn graph) could benefit from MPI; all remaining stages may be multi-threaded. 83 | 84 | 85 | ##### [1.7] Strand-specific assembly 86 | 87 | Use option `--SS` to indicate that input reads are strand-specific. 88 | Strand-specific reads are expected to have `/1` reads in _reverse_ direction and `/2` reads in _forward_ direction, ie. 89 | ``` 90 | <-- R/1 91 | 5' =======================> 3' transcript 92 | F/2 --> 93 | ``` 94 | ---- 95 | 96 | #### PART 2. Merging assemblies with `transabyss-merge` 97 | 98 | Should you choose to assemble the same dataset with different settings (different k-mer sizes), you can merge the assemblies together into one FASTA file for downstream analyses (with `transsabyss-analyze`). When a sequence is contained in a longer sequence, the longer sequence is kept. 99 | 100 | ##### [2.1] Usage 101 | 102 | transabyss-merge --help 103 | 104 | 105 | ##### [2.2] Running transabyss-merge 106 | 107 | Example: 108 | 109 | transabyss-merge a.fa b.fa --mink 32 --maxk 64 110 | 111 | 112 | ##### [2.3] Minimum and maximum k-mer sizes 113 | 114 | `--mink` and `--maxk` are used to specific the smallest and largest k-mer sizes in the input assemblies. 115 | 116 | 117 | ##### [2.4] Output merged assembly path 118 | 119 | default: `./transabyss-merged.fa` 120 | 121 | Use option `--out` to specify the output path. 122 | 123 | 124 | ##### [2.5] Output sequence prefixes 125 | 126 | Use option `--prefixes` to specify the prefixes of output sequences. 127 | 128 | Example: 129 | 130 | transabyss-merge a.fa b.fa c.fa --mink 32 --maxk 64 --prefix k32. k48. k64. 131 | 132 | file | prefix 133 | -----|-------- 134 | a.fa | k32. 135 | b.fa | k48. 136 | c.fa | k64. 137 | 138 | One prefix for sequences from each input assembly FASTA file. This feature helps you keep track of the origin of each seqeunce in the merged assembly. 139 | 140 | ---- 141 | -------------------------------------------------------------------------------- /utilities/psl_cid_extractor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # written by Ka Ming Nip 4 | # Copyright 2014 Canada's Michael Smith Genome Sciences Centre 5 | 6 | import argparse 7 | import os 8 | import string 9 | import sys 10 | 11 | def eval_blocks(blocksizes, qstarts, tstarts, max_consecutive_edits=1, no_indels=False): 12 | blocksize_list = blocksizes.split(',') 13 | qstart_list = qstarts.split(',') 14 | tstart_list = tstarts.split(',') 15 | 16 | #evaluate insertions 17 | prev_b = None 18 | prev_q = None 19 | for b,q in zip(blocksize_list, qstart_list): 20 | if prev_b is None or prev_q is None: 21 | prev_b = int(b) 22 | prev_q = int(q) 23 | elif b != '' and q != '': 24 | # number of bases inserted 25 | n = int(q) - prev_q - prev_b 26 | if (no_indels and n > 0) or (not no_indels and n > max_consecutive_edits): 27 | return False 28 | #endif 29 | prev_b = int(b) 30 | prev_q = int(q) 31 | #endif 32 | #endfor 33 | 34 | #evaluate deletions 35 | prev_b = None 36 | prev_t = None 37 | for b,t in zip(blocksize_list, tstart_list): 38 | if prev_b is None or prev_t is None: 39 | prev_b = int(b) 40 | prev_t = int(t) 41 | elif b != '' and t != '': 42 | # number of bases deleted 43 | n = int(t) - prev_t - prev_b 44 | if (no_indels and n > 0) or (not no_indels and n > max_consecutive_edits): 45 | return False 46 | #endif 47 | prev_b = int(b) 48 | prev_t = int(t) 49 | #endif 50 | #endfor 51 | 52 | return True 53 | #enddef 54 | 55 | def is_redundant(query, refs): 56 | #print query + ': ' + str(refs) 57 | # query is NOT redundant if it is the longest sequence 58 | longest_cid = find_longest(refs) 59 | return query != longest_cid 60 | #enddef 61 | 62 | def find_longest(refs): 63 | # break ties by chosing the sequence with the lexicographically largest id 64 | cid, length = sorted(refs.items(), key=lambda x: (x[1],x[0]), reverse=True)[0] 65 | return cid 66 | #enddef 67 | 68 | def extract_cids(psl, samestrand=False, min_percent_identity=0.95, max_consecutive_edits=1, no_indels=False, report_redundant=False): 69 | queries = set() 70 | reject_set = set() 71 | 72 | prev_query = None 73 | refs = {} 74 | 75 | with open(psl) as fh: 76 | for line in fh: 77 | #match mis- rep. N's Q gap Q gap T gap T gap strand Q Q Q Q T T T T block blockSizes qStarts tStarts 78 | # match match count bases count bases name size start end name size start end count 79 | 80 | match, mismatch, repmatch, ns, qgaps, qgapbases, tgaps, tgapbases, strand, qname, qsize, qstart, qend, tname, tsize, tstart, tend, blocks, blocksizes, qstarts, tstarts = line.strip().split('\t') 81 | 82 | queries.add(qname) 83 | 84 | if qname != tname and \ 85 | float(match)/float(qsize) >= min_percent_identity and \ 86 | int(qgapbases) <= int(qgaps) * max_consecutive_edits and \ 87 | int(tgapbases) <= int(tgaps) * max_consecutive_edits and \ 88 | float(qgapbases) <= float(qsize) * (1.0 - min_percent_identity) and \ 89 | float(tgapbases) <= float(qsize) * (1.0 - min_percent_identity) and \ 90 | (not samestrand or strand == '+') and \ 91 | int(qstart) <= max_consecutive_edits and \ 92 | int(qend) >= int(qsize) - max_consecutive_edits and \ 93 | int(qsize) <= int(tsize) and \ 94 | eval_blocks(blocksizes, qstarts, tstarts, max_consecutive_edits=max_consecutive_edits, no_indels=no_indels): 95 | 96 | if prev_query is None: 97 | prev_query = qname 98 | refs = {qname:int(qsize), tname:int(tsize)} 99 | elif prev_query == qname: 100 | # next 'good' alignment of the same query 101 | refs[tname] = int(tsize) 102 | else: 103 | # we have reached the first 'good' alignment of the next query 104 | # check whether the previous query is redundant 105 | if len(refs) > 0 and is_redundant(prev_query, refs): 106 | reject_set.add(prev_query) 107 | #endif 108 | 109 | # reset 110 | prev_query = qname 111 | refs = {qname:int(qsize), tname:int(tsize)} 112 | #endif 113 | #endif 114 | #endfor 115 | #endwith 116 | 117 | # evaluate the final query 118 | if len(refs) > 0 and is_redundant(prev_query, refs): 119 | reject_set.add(prev_query) 120 | #endif 121 | 122 | if report_redundant: 123 | return reject_set 124 | #endif 125 | 126 | return queries - reject_set 127 | #enddef 128 | 129 | def __main__(): 130 | parser = argparse.ArgumentParser(description='Extract sequence names of redundnat sequences from self-alignments in PSL format.') 131 | parser.add_argument('psl', metavar='PSL', type=str, help='input headerless PSL file') 132 | parser.add_argument('--SS', dest='samestrand', help='Do not remove redundant sequences on opposite strands.', action='store_true', default=False) 133 | parser.add_argument('--min-seq-id', dest='min_seq_id', metavar='FLOAT', type=float, help='Min percentage sequence identity required [%(default)s]', default=0.95) 134 | parser.add_argument('--max-con-edits', dest='max_con_edits', metavar='INT', type=int, help='Max length of edit allowed [%(default)s bp]', default=1) 135 | parser.add_argument('--no-indels', dest='no_indels', help='Disallow indels. [indels allowed by default]', action='store_true') 136 | args = parser.parse_args() 137 | 138 | for cid in extract_redundant(psl=args.psl, require_samestrand=args.samestrand, min_percent_identity=args.min_seq_id, max_consecutive_edits=args.max_con_edits, no_indels=args.no_indels): 139 | print(cid) 140 | #endfor 141 | #enddef 142 | 143 | if __name__ == '__main__': 144 | __main__() 145 | #endif 146 | 147 | #EOF 148 | -------------------------------------------------------------------------------- /transabyss-merge: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # written by Ka Ming Nip 4 | # Copyright 2018 Canada's Michael Smith Genome Sciences Centre 5 | 6 | import argparse 7 | import multiprocessing 8 | import os 9 | import shutil 10 | import sys 11 | import textwrap 12 | from utilities import package_info 13 | from utilities.common_utils import StopWatch 14 | from utilities.common_utils import check_env 15 | from utilities.common_utils import log 16 | from utilities.common_utils import path_action 17 | from utilities.common_utils import paths_action 18 | from utilities.common_utils import threshold_action 19 | from utilities.fasta_utils import abyssmap_merge_fastas 20 | from utilities.fasta_utils import blat_merge_fastas 21 | from utilities.fasta_utils import filter_fasta 22 | 23 | 24 | TRANSABYSS_VERSION = package_info.VERSION 25 | TRANSABYSS_NAME = package_info.NAME 26 | 27 | PACKAGEDIR = package_info.PACKAGEDIR 28 | BINDIR = package_info.BINDIR 29 | SKIP_PSL_SELF = os.path.join(BINDIR, 'skip_psl_self.awk') 30 | SKIP_PSL_SELF_SS = os.path.join(BINDIR, 'skip_psl_self_ss.awk') 31 | 32 | REQUIRED_EXECUTABLES = ['blat', 'abyss-map'] 33 | REQUIRED_SCRIPTS = [SKIP_PSL_SELF, SKIP_PSL_SELF_SS] 34 | 35 | def default_outfile(): 36 | return os.path.join(os.getcwd(), "transabyss-merged.fa") 37 | #enddef 38 | 39 | def __main__(): 40 | 41 | parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, 42 | description='Merge Trans-ABySS assemblies.', 43 | epilog=textwrap.dedent(package_info.SUPPORT_INFO) 44 | ) 45 | 46 | parser.add_argument('--version', action='version', version=TRANSABYSS_VERSION) 47 | 48 | input_group = parser.add_argument_group("Input") 49 | input_group.add_argument(dest='fastas', metavar='PATH', type=str, nargs='+', help='assembly FASTA file(s)', action=paths_action(check_exist=True)) 50 | input_group.add_argument('--mink', dest='mink', help='smallest k-mer size', metavar='INT', type=int, required=True, action=threshold_action(1, inequality='>=')) 51 | input_group.add_argument('--maxk', dest='maxk', help='largest k-mer size', metavar='INT', type=int, required=True, action=threshold_action(1, inequality='>=')) 52 | input_group.add_argument('--prefixes', dest='prefixes', metavar='STR', type=str, nargs='+', help='prefixes for the contigs from each assembly') 53 | input_group.add_argument('--SS', dest='stranded', help='assemblies are strand-specific', action='store_true', default=False) 54 | 55 | general_group = parser.add_argument_group("Basic Options") 56 | general_group.add_argument('--force', dest='force', help='force overwriting', action='store_true', default=False) 57 | general_group.add_argument('--out', dest='outfile', help='output file [%(default)s]', metavar='PATH', type=str, default=default_outfile(), action=path_action(check_exist=False)) 58 | general_group.add_argument('--threads', dest='threads', help='number of threads [%(default)s]', metavar='INT', type=int, default=1, action=threshold_action(1, inequality='>=')) 59 | general_group.add_argument('--length', dest='length', help='shortest sequence to report [%(default)s]', metavar='INT', type=int, default=0, action=threshold_action(0, inequality='>=')) 60 | general_group.add_argument('--no-cleanup', dest='nocleanup', help='do not remove intermediate files at completion', action='store_true', default=False) 61 | 62 | advanced_group = parser.add_argument_group("Advanced Options") 63 | advanced_group.add_argument('--abyssmap', dest='abyssmap', help='use abyss-map to merge all FASTA files at once (NOTE: faster than BLAT but less sensitive and more memory intensive)', action='store_true', default=False) 64 | advanced_group.add_argument('--abyssmap-itr', dest='abyssmap_itr', help='use abyss-map to merge one additional FASTA at a time, utilizing less memory.', action='store_true', default=False) 65 | advanced_group.add_argument('--indel', dest='indel', help='indel size tolerance [%(default)s]', metavar='INT', type=int, default=1, action=threshold_action(0, inequality='>=')) 66 | #graph_group.add_argument('--overlap', dest='overlap', help='minimum overlap to merge contigs [2*maxk]', metavar='INT', type=int, action=threshold_action(0, inequality='>=')) 67 | advanced_group.add_argument('--pid', dest='p', help='minimum percent sequence identity of redundant sequences [%(default)s]', metavar='FLOAT', type=float, default=0.95, action=threshold_action(0.9, inequality='>=')) 68 | 69 | args = parser.parse_args() 70 | 71 | log(TRANSABYSS_NAME + ' ' + TRANSABYSS_VERSION) 72 | log('CMD: ' + ' '.join(sys.argv)) 73 | log('=-' * 30) 74 | 75 | # Check environment and required paths 76 | if not check_env(executables=REQUIRED_EXECUTABLES, scripts=REQUIRED_SCRIPTS): 77 | log('ERROR: Your environment is not sufficient to run Trans-ABySS. Please check the missing executables, scripts, or directories.') 78 | sys.exit(1) 79 | #endif 80 | 81 | if not args.force and os.path.exists(args.outfile): 82 | log('ERROR: Output file already exists: %s\nPlease either use the \'--force\' option to overwrite the existing file or use the \'--out\' option to specify a different output file path.' % args.outfile) 83 | sys.exit(1) 84 | #endif 85 | 86 | # Set default threads 87 | cpu_count = multiprocessing.cpu_count() 88 | log("# CPU(s) available:\t" + str(cpu_count)) 89 | log("# thread(s) requested:\t" + str(args.threads)) 90 | args.threads = min(cpu_count, args.threads) 91 | log("# thread(s) to use:\t" + str(args.threads)) 92 | 93 | # Start the stop watch 94 | stopwatch = StopWatch() 95 | 96 | prefixes = args.prefixes 97 | if prefixes is None: 98 | prefixes = [] 99 | for i in range(len(args.fastas)): 100 | prefixes.append('A' + str(i) + '.') 101 | #endfor 102 | #endif 103 | 104 | assert len(prefixes) == len(args.fastas) 105 | 106 | log('Assembly Prefixes:') 107 | path_prefix_map = {} 108 | for prefix, path in zip(prefixes, args.fastas): 109 | if os.path.exists(path): 110 | path_prefix_map[prefix] = path 111 | log(prefix + '\t' + path) 112 | else: 113 | log('ERROR: No such assembly file \'' + path + '\'') 114 | sys.exit(1) 115 | #endif 116 | #endfor 117 | 118 | if args.length is not None and args.length > 0: 119 | merge_fa = args.outfile + '.prefilter.fa' 120 | 121 | if args.abyssmap: 122 | abyssmap_merge_fastas(path_prefix_map, merge_fa, strand_specific=args.stranded, cleanup=not args.nocleanup, threads=args.threads, iterative=False) 123 | elif args.abyssmap_itr: 124 | abyssmap_merge_fastas(path_prefix_map, merge_fa, strand_specific=args.stranded, cleanup=not args.nocleanup, threads=args.threads, iterative=True) 125 | else: 126 | skip_psl_self_awk = None 127 | if args.stranded and os.path.isfile(SKIP_PSL_SELF_SS): 128 | skip_psl_self_awk = SKIP_PSL_SELF_SS 129 | elif not args.stranded and os.path.isfile(SKIP_PSL_SELF): 130 | skip_psl_self_awk = SKIP_PSL_SELF 131 | #endif 132 | 133 | blat_merge_fastas(path_prefix_map, merge_fa, percent_identity=args.p, strand_specific=args.stranded, cleanup=not args.nocleanup, minoverlap=0, threads=args.threads, indel_size_tolerance=args.indel, min_seq_len=args.mink, skip_psl_self_awk=skip_psl_self_awk) 134 | #endif 135 | 136 | log('Removing sequences shorter than %d bp ...' % args.length) 137 | filtered_fa = args.outfile + '.tmp.filtered.fa' 138 | filter_fasta(merge_fa, filtered_fa, min_length=args.length) 139 | shutil.move(filtered_fa, args.outfile) 140 | 141 | if not args.nocleanup: 142 | for t in [merge_fa, filtered_fa]: 143 | if os.path.isfile(t): 144 | os.remove(t) 145 | #endif 146 | #endfor 147 | #endif 148 | else: 149 | if args.abyssmap: 150 | abyssmap_merge_fastas(path_prefix_map, args.outfile, strand_specific=args.stranded, cleanup=not args.nocleanup, threads=args.threads, iterative=False) 151 | elif args.abyssmap_itr: 152 | abyssmap_merge_fastas(path_prefix_map, args.outfile, strand_specific=args.stranded, cleanup=not args.nocleanup, threads=args.threads, iterative=True) 153 | else: 154 | skip_psl_self_awk = None 155 | if args.stranded and os.path.isfile(SKIP_PSL_SELF_SS): 156 | skip_psl_self_awk = SKIP_PSL_SELF_SS 157 | elif not args.stranded and os.path.isfile(SKIP_PSL_SELF): 158 | skip_psl_self_awk = SKIP_PSL_SELF 159 | #endif 160 | 161 | blat_merge_fastas(path_prefix_map, args.outfile, percent_identity=args.p, strand_specific=args.stranded, cleanup=not args.nocleanup, minoverlap=0, threads=args.threads, indel_size_tolerance=args.indel, min_seq_len=args.mink, skip_psl_self_awk=skip_psl_self_awk) 162 | #endif 163 | #endif 164 | 165 | log('=-' * 30) 166 | log('Merged assembly: ' + args.outfile) 167 | log('Total wallclock run time: %d h %d m %d s' % (stopwatch.stop())) 168 | #enddef 169 | 170 | if __name__ == '__main__': 171 | __main__() 172 | #endif 173 | 174 | #EOF 175 | -------------------------------------------------------------------------------- /utilities/sam_cid_extractor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # written by Ka Ming Nip 4 | # updated on June 19, 2014 5 | # Copyright 2014 Canada's Michael Smith Genome Sciences Centre 6 | 7 | import argparse 8 | import gzip 9 | import os 10 | import re 11 | import string 12 | import sys 13 | 14 | 15 | def is_aln_match(cigar): 16 | return cigar[-1] == 'M' and cigar[0:-1].isdigit() 17 | 18 | def is_aln_match_good(cigar, min_percent_identity=0.95, max_consecutive_edits=2, md=None, no_indels=False): 19 | if cigar == '*': 20 | return False 21 | 22 | if max_consecutive_edits == 0: 23 | no_indels = True 24 | 25 | m = 0 26 | i = 0 27 | d = 0 28 | s = 0 29 | 30 | for item in re.findall('[0-9]+[MIDS]', cigar): 31 | op = item[-1] 32 | count = int(item[0:-1]) 33 | if op == 'M': 34 | m += count 35 | elif op == 'I': 36 | if no_indels or count > max_consecutive_edits: 37 | return False 38 | i += count 39 | elif op == 'D': 40 | if no_indels or count > max_consecutive_edits: 41 | return False 42 | d += count 43 | elif op == 'S': 44 | if count > max_consecutive_edits: 45 | return False 46 | s += count 47 | 48 | if md is None: 49 | seq_matches = m 50 | else: 51 | seq_matches = 0 52 | num_consecutive_zeroes = 0 53 | for item in re.findall('[0-9]+', md): 54 | value = int(item) 55 | 56 | if value == 0: 57 | num_consecutive_zeroes += 1 58 | else: 59 | num_consecutive_zeroes = 0 60 | seq_matches += value 61 | 62 | if num_consecutive_zeroes > max_consecutive_edits: 63 | return False 64 | 65 | return float(seq_matches)/float(m + i + s) >= min_percent_identity 66 | 67 | def is_segment_unmapped(flag): 68 | # 0x4 segment unmapped 69 | return int(flag) & 0x4 70 | 71 | def is_reverse_complemented(flag): 72 | # 0x10 SEQ being reverse complemented 73 | return int(flag) & 0x10 74 | 75 | def is_redundant(query, refs): 76 | # NOT redundant if query is the longest sequence or the sequence with lexicographically largest id when lengths are equal 77 | (longest_cid, longest_length) = sorted(refs.items(), key=lambda x: (x[1],x[0]), reverse=True)[0] 78 | #print str(query) + ' ' + str(longest_cid) 79 | return query != longest_cid 80 | 81 | def extract_nr(sam=None, require_samestrand=False, min_percent_identity=0.95, max_consecutive_edits=2, no_indels=False, report_redundant=False): 82 | f = gzip.open(sam, 'rb') 83 | 84 | lengths = {} 85 | reject_set = set() 86 | 87 | current_query = None 88 | current_length = None 89 | 90 | refs = {} 91 | 92 | for line in f: 93 | items = line.rstrip().split() 94 | name = items[0] 95 | 96 | if name == '@SQ': 97 | lengths[items[1][3:]] = int(items[2][3:]) 98 | elif len(items) >= 11 and name not in ['@HD', '@SQ', '@RG', '@PG', '@CO'] and name in lengths: 99 | # This is an alignment line 100 | if not current_query: 101 | # the first alignment in SAM 102 | current_query = name 103 | current_length = lengths[current_query] 104 | refs = {current_query : current_length} 105 | 106 | md = None 107 | 108 | if len(items) > 11: 109 | for field in items[11].split(): 110 | partition = field.split(':') 111 | if partition[0] == 'MD': 112 | md = partition[2] 113 | if len(md) == 0: 114 | md = None 115 | 116 | flag = items[1] 117 | 118 | if name != current_query: 119 | # Reached the next set of alignments; must look at the current set of alignments 120 | if is_redundant(current_query, refs): 121 | reject_set.add(current_query) 122 | 123 | # update everything 124 | current_query = name 125 | current_length = lengths[current_query] 126 | refs = {current_query : current_length} 127 | 128 | if not is_segment_unmapped(flag) and is_aln_match_good(items[5], min_percent_identity, max_consecutive_edits, md, no_indels): 129 | if not require_samestrand or not is_reverse_complemented(flag): 130 | reference = items[2] 131 | if reference != current_query: 132 | ref_length = lengths[reference] 133 | if ref_length >= current_length: 134 | refs[reference] = ref_length 135 | f.close() 136 | 137 | # process the final batch of alignments 138 | if is_redundant(current_query, refs): 139 | reject_set.add(current_query) 140 | 141 | if report_redundant: 142 | return reject_set 143 | 144 | return set(lengths.keys()) - reject_set 145 | 146 | def extract_unmapped(sam=None, require_samestrand=False, min_percent_identity=0.95, max_consecutive_edits=2, no_indels=False): 147 | cids = set() 148 | f = gzip.open(sam, 'rb') 149 | for line in f: 150 | items = line.rstrip().split() 151 | name = items[0] 152 | 153 | if len(items) >= 11 and name not in ['@HD', '@SQ', '@RG', '@PG', '@CO']: 154 | md = None 155 | if len(items) > 11: 156 | for field in items[11].split(): 157 | partition = field.split(':') 158 | if partition[0] == 'MD': 159 | md = partition[2] 160 | if len(md) == 0: 161 | md = None 162 | 163 | flag = items[1] 164 | unmapped = is_segment_unmapped(flag) 165 | good_aln = is_aln_match_good(items[5], min_percent_identity, max_consecutive_edits, md, no_indels) 166 | rc = is_reverse_complemented(flag) 167 | 168 | if unmapped or not good_aln or (require_samestrand and rc): 169 | cids.add(name) 170 | 171 | return cids 172 | 173 | def extract_mapped(sam=None, require_samestrand=False, min_percent_identity=0.95, max_consecutive_edits=2, no_indels=False): 174 | cids = set() 175 | f = gzip.open(sam, 'rb') 176 | for line in f: 177 | items = line.rstrip().split() 178 | name = items[0] 179 | 180 | if len(items) >= 11 and name not in ['@HD', '@SQ', '@RG', '@PG', '@CO']: 181 | md = None 182 | if len(items) > 11: 183 | for field in items[11].split(): 184 | partition = field.split(':') 185 | if partition[0] == 'MD': 186 | md = partition[2] 187 | if len(md) == 0: 188 | md = None 189 | 190 | flag = items[1] 191 | unmapped = is_segment_unmapped(flag) 192 | good_aln = is_aln_match_good(items[5], min_percent_identity, max_consecutive_edits, md, no_indels) 193 | rc = is_reverse_complemented(flag) 194 | 195 | if not unmapped and good_aln and (not require_samestrand or not rc): 196 | cids.add(name) 197 | 198 | return cids 199 | 200 | def __main__(): 201 | parser = argparse.ArgumentParser(description='Extract sequence names from an input SAM file.') 202 | parser.add_argument('sam', metavar='SAM', type=str, help='input gzip\'d SAM file of alignments') 203 | parser.add_argument('mode', metavar='MODE', choices=['nr', 'unmapped', 'mapped'], help='choose one of [nr, unmapped, mapped]') 204 | parser.add_argument('--SS', dest='samestrand', help='Do not remove redundant sequences on opposite strands.', action='store_true', default=False) 205 | parser.add_argument('--min-seq-id', dest='min_seq_id', metavar='FLOAT', type=float, help='Min percentage sequence identity required [%(default)s]', default=0.95) 206 | parser.add_argument('--max-con-edits', dest='max_con_edits', metavar='INT', type=int, help='Max length of edit allowed [%(default)s bp]', default=2) 207 | parser.add_argument('--no-indels', dest='no_indels', help='Disallow indels. [indels allowed by default]', action='store_true') 208 | args = parser.parse_args() 209 | 210 | if args.mode == 'nr': 211 | cids = extract_nr(sam=args.sam, require_samestrand=args.samestrand, min_percent_identity=args.min_seq_id, max_consecutive_edits=args.max_con_edits, no_indels=args.no_indels) 212 | for cid in cids: 213 | print(cid) 214 | elif args.mode == 'unmapped': 215 | cids = extract_unmapped(sam=args.sam, require_samestrand=args.samestrand, min_percent_identity=args.min_seq_id, max_consecutive_edits=args.max_con_edits, no_indels=args.no_indels) 216 | for cid in cids: 217 | print(cid) 218 | elif args.mode == 'mapped': 219 | cids = extract_mapped(sam=args.sam, require_samestrand=args.samestrand, min_percent_identity=args.min_seq_id, max_consecutive_edits=args.max_con_edits, no_indels=args.no_indels) 220 | for cid in cids: 221 | print(cid) 222 | else: 223 | print('Invalid mode: %s' % args.mode) 224 | sys.exit(1) 225 | 226 | if __name__ == '__main__': 227 | __main__() 228 | 229 | #EOF 230 | -------------------------------------------------------------------------------- /utilities/common_utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # written by Ka Ming Nip 4 | # Copyright 2014 Canada's Michael Smith Genome Sciences Centre 5 | 6 | import argparse 7 | import math 8 | import os 9 | import sys 10 | import time 11 | from functools import partial 12 | from multiprocessing.dummy import Pool 13 | from subprocess import call 14 | from . import package_info 15 | 16 | class StopWatch: 17 | """A timer class that reports the elapsed time. 18 | """ 19 | 20 | start = None 21 | 22 | def __init__(self): 23 | """Create and start the stopwatch. 24 | """ 25 | self.start = time.time() 26 | #enddef 27 | 28 | def stop(self): 29 | """Returns the elapsed time since the stop watch's existence. 30 | """ 31 | 32 | elapsed = time.time() - self.start 33 | return convert_hms(elapsed) 34 | #enddef 35 | #endclass 36 | 37 | def log(info): 38 | """Print the message to STDOUT. 39 | """ 40 | 41 | print(info) 42 | sys.stdout.flush() 43 | #enddef 44 | 45 | def convert_hms(seconds): 46 | """Convert the number of seconds to hours, minutes, seconds. 47 | """ 48 | 49 | remain = int(math.floor(seconds)) 50 | h = int(math.floor(remain/3600)) 51 | remain -= h*3600 52 | m = int(math.floor(remain/60)) 53 | remain -= m*60 54 | s = remain 55 | return h, m, s 56 | #enddef 57 | 58 | def run_shell_cmd(cmd): 59 | """Run the shell command. 60 | """ 61 | 62 | cmd = 'bash -euo pipefail -c \'%s\'' % cmd 63 | 64 | log('CMD: ' + cmd) 65 | 66 | # start 67 | stopwatch = StopWatch() 68 | 69 | # execute the shell command 70 | return_code = call(cmd, shell=True) 71 | 72 | # stop 73 | h, m, s = stopwatch.stop() 74 | 75 | if h > 0 or m > 0 or s > 5: 76 | log('Elapsed time: %d h %d m %d s' % (h, m, s)) 77 | #endif 78 | 79 | if return_code != 0: 80 | log('ERROR: CMD ended with status code %d' % return_code) 81 | sys.exit(return_code) 82 | #endif 83 | #enddef 84 | 85 | def run_multi_shell_cmds(cmds, max_parallel=2): 86 | """Run multiple shell commands in parallel. 87 | """ 88 | 89 | for i in range(len(cmds)): 90 | cmds[i] = 'bash -euo pipefail -c \'%s\'' % cmds[i] 91 | #endfor 92 | 93 | stopwatch = StopWatch() 94 | 95 | # Based on: http://stackoverflow.com/questions/14533458/python-threading-multiple-bash-subprocesses 96 | pool = Pool(max_parallel) 97 | for i, return_code in enumerate(pool.imap(partial(call, shell=True), cmds)): 98 | if return_code != 0: 99 | log('CMD: ' + cmds[i]) 100 | log('ERROR: CMD ended with status code %d' % return_code) 101 | sys.exit(return_code) 102 | #endif 103 | #endfor 104 | 105 | h, m, s = stopwatch.stop() 106 | if h > 0 or m > 0 or s > 5: 107 | log('Elapsed time: %d h %d m %d s' % (h, m, s)) 108 | #endif 109 | #enddef 110 | 111 | def is_empty_txt(path, min_non_empty_lines=1): 112 | """Check if the file has the specified minimum number of lines. 113 | """ 114 | 115 | counter = 0 116 | with open(path, 'r') as fh: 117 | for line in fh: 118 | if len(line.strip()) > 0: 119 | counter += 1 120 | if counter >= min_non_empty_lines: 121 | return False 122 | #endif 123 | #endif 124 | #endfor 125 | #endwith 126 | 127 | return counter < min_non_empty_lines 128 | #enddef 129 | 130 | def touch(path, times=None): 131 | """Touch the file. 132 | """ 133 | 134 | with open(path, 'a'): 135 | os.utime(path, times) 136 | #endwith 137 | #enddef 138 | 139 | def threshold_action(threshold, inequality='>='): 140 | """Action performed for thresholding argparse numeric arguments. 141 | """ 142 | 143 | class CustomAction(argparse.Action): 144 | def __call__(self, parser, namespace, value, option_string=None): 145 | if inequality == '>=': 146 | if value < threshold: 147 | parser.error("value for '%s' must be >= %s" % (option_string, str(threshold))) 148 | #endif 149 | elif inequality == '>': 150 | if value <= threshold: 151 | parser.error("value for '%s' must be > %s" % (option_string, str(threshold))) 152 | #endif 153 | elif inequality == '<': 154 | if value >= threshold: 155 | parser.error("value for '%s' must be < %s" % (option_string, str(threshold))) 156 | #endif 157 | elif inequality == '<=': 158 | if value > threshold: 159 | parser.error("value for '%s' must be <= %s" % (option_string, str(threshold))) 160 | #endif 161 | else: 162 | parser.error("cannot evaluate inequality '%s %s %s' for option '%s'" % (str(value), inequality, str(threshold), option_string)) 163 | #endif 164 | setattr(namespace, self.dest, value) 165 | #enddef 166 | #endclass 167 | 168 | return CustomAction 169 | #enddef 170 | 171 | def path_action(check_exist=False): 172 | """Action performed for argparse single path argument. 173 | """ 174 | 175 | class PathAction(argparse.Action): 176 | def __call__(self, parser, namespace, value, option_string=None): 177 | if check_exist and not os.path.exists(value): 178 | parser.error('No such file or directory %s' % value) 179 | #endif 180 | setattr(namespace, self.dest, os.path.abspath(value)) 181 | #enddef 182 | #endclass 183 | 184 | return PathAction 185 | #enddef 186 | 187 | def paths_action(check_exist=False): 188 | """Action performed for argparse multiple path arguments. 189 | """ 190 | 191 | class PathsAction(argparse.Action): 192 | def __call__(self, parser, namespace, values, option_string=None): 193 | for i, v in enumerate(values): 194 | if check_exist and not os.path.exists(v): 195 | parser.error('No such file or directory %s' % v) 196 | #endif 197 | values[i] = os.path.abspath(v) 198 | #endfor 199 | setattr(namespace, self.dest, values) 200 | #enddef 201 | #endclass 202 | 203 | return PathsAction 204 | #enddef 205 | 206 | def is_exe(fpath): 207 | """Check if the file at path is an executable 208 | """ 209 | return os.path.isfile(fpath) and os.access(fpath, os.X_OK) 210 | #enddef 211 | 212 | def unix_which(program): 213 | """The UNIX `which' command implemented in Python. 214 | based on: http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python 215 | """ 216 | 217 | fpath, fname = os.path.split(program) 218 | if len(fpath) > 0: 219 | # has a parent directory; therefore `program' is a path 220 | 221 | if is_exe(program): 222 | return program 223 | #endif 224 | else: 225 | # `program' is a name 226 | 227 | for path in os.environ["PATH"].split(os.pathsep): 228 | path = path.strip('"') 229 | exe_file = os.path.join(path, program) 230 | if is_exe(exe_file): 231 | return exe_file 232 | #endif 233 | #endfor 234 | #endif 235 | 236 | return None 237 | #enddef 238 | 239 | def find_exes(program_list): 240 | found = {} 241 | missing = [] 242 | 243 | for program in program_list: 244 | program_path = unix_which(program) 245 | if program_path is None or len(program_path) == 0: 246 | missing.append(program) 247 | else: 248 | found[program] = program_path 249 | #endif 250 | #endfor 251 | 252 | return found, missing 253 | #enddef 254 | 255 | def check_env(executables=None, scripts=None): 256 | okay = True 257 | 258 | # Check whether required paths can be evaluated appropriately 259 | if os.path.isdir(package_info.PACKAGEDIR): 260 | log('Found Trans-ABySS directory at: ' + package_info.PACKAGEDIR) 261 | else: 262 | log('No such directory: ' + package_info.PACKAGEDIR) 263 | okay = False 264 | #endif 265 | 266 | if os.path.isdir(package_info.BINDIR): 267 | log('Found Trans-ABySS `bin` directory at: ' + package_info.BINDIR) 268 | else: 269 | log('No such directory: ' + package_info.BINDIR) 270 | okay = False 271 | #endif 272 | 273 | if not scripts is None and len(scripts) > 0: 274 | for script_path in scripts: 275 | if os.path.isfile(script_path): 276 | log('Found script at: ' + script_path) 277 | else: 278 | log('No such file: ' + script_path) 279 | okay = False 280 | #endif 281 | #endfor 282 | #endif 283 | 284 | # Check whether required executables are accessible 285 | if not executables is None and len(executables) > 0: 286 | found_exes, missing_exes = find_exes(executables) 287 | 288 | # List the accessible programs 289 | for program, program_path in iter(found_exes.items()): 290 | log('Found `%s\' at %s' % (program, program_path)) 291 | #endfor 292 | 293 | # List the inaccessible programs and quit 294 | num_missing_exes = len(missing_exes) 295 | if num_missing_exes > 0: 296 | log('The following executables (%s) are not accessible from the PATH environment variable:\n%s' % (num_missing_exes, '\n'.join(missing_exes)) ) 297 | okay = False 298 | #endif 299 | #endif 300 | 301 | return okay 302 | #endef 303 | 304 | #EOF 305 | -------------------------------------------------------------------------------- /utilities/fasta_utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # written by Ka Ming Nip 4 | 5 | import glob 6 | import itertools 7 | import math 8 | import operator 9 | import os 10 | import shutil 11 | from .common_utils import run_shell_cmd 12 | from .common_utils import run_multi_shell_cmds 13 | from . import psl_cid_extractor 14 | from . import sam_cid_extractor 15 | 16 | 17 | def concat_fastas(path_prefix_map, cat): 18 | """Concatenate multiple fasta files together, giving the contigs of each set the specified prefix. 19 | """ 20 | 21 | with open(cat, 'w') as fout: 22 | for prefix, path in path_prefix_map.items(): 23 | line_start = '>' + prefix 24 | with open(path, 'r') as fin: 25 | for line in fin: 26 | if line[0] == '>': 27 | #header 28 | fout.write(line.replace('>', line_start, 1)) 29 | else: 30 | fout.write(line) 31 | #endif 32 | #endfor 33 | #endwith 34 | #endfor 35 | #endwith 36 | #enddef 37 | 38 | def blat_self_align(fasta, outputpsl, percent_id=0.95, max_consecutive_edits=1, min_seq_len=32, threads=1, skip_psl_self_awk=None): 39 | """Align all fasta sequences to each other with BLAT. 40 | """ 41 | 42 | files = bin_by_base_and_length(fasta, 20, fasta) 43 | 44 | index = 0 45 | psls = [] 46 | cmds = [] 47 | 48 | # bin-to-bin alignments (both inter-bin and intra-bin) 49 | for a,b in itertools.combinations_with_replacement(files.keys(), 2): 50 | lower = min(a, b) 51 | upper = max(a, b) 52 | #print '%d => %d' % (lower, upper) 53 | psl = outputpsl + '.' + str(index) 54 | 55 | cmd_params = ['blat', '-noHead', '-t=dna', '-q=dna', '-out=psl'] 56 | minscore = int(math.ceil(percent_id * lower)) 57 | 58 | cmd_params.extend(['-maxGap=%d' % max_consecutive_edits, '-maxIntron=%d' % max_consecutive_edits, '-minScore=%d' % minscore, files[upper], files[lower]]) 59 | 60 | if not skip_psl_self_awk is None and os.path.isfile(skip_psl_self_awk): 61 | cmd_params.append('>(%s > %s) >&2' % (skip_psl_self_awk, psl)) 62 | else: 63 | cmd_params.append(psl) 64 | #endif 65 | 66 | #run_shell_cmd(' '.join(cmd_params)) 67 | cmds.append(' '.join(cmd_params)) 68 | psls.append(psl) 69 | index += 1 70 | #endfor 71 | 72 | run_multi_shell_cmds(cmds, max_parallel=threads) 73 | 74 | # remove the tmp fasta files 75 | for f in files.values(): 76 | if os.path.isfile(f): 77 | os.remove(f) 78 | #endif 79 | #endfor 80 | 81 | # concatenate PSLs 82 | num_psls = len(psls) 83 | assert num_psls > 0 84 | if num_psls == 1: 85 | shutil.move(psls[0], outputpsl) 86 | else: 87 | with open(outputpsl, 'w') as fout: 88 | for p in psls: 89 | with open(p, 'r') as fin: 90 | for line in fin: 91 | if len(line) > 0: 92 | fout.write(line) 93 | #endif 94 | #endfor 95 | #endwith 96 | 97 | # remove the tmp PSL 98 | os.remove(p) 99 | #endfor 100 | #endwith 101 | #endif 102 | #enddef 103 | 104 | def bin_by_base_and_length(fasta, bins, out_prefix): 105 | 106 | lengths = [] 107 | seqs = [] 108 | 109 | currentseq = None 110 | with open(fasta, 'r') as fin: 111 | for line in fin: 112 | if line[0] == '>': 113 | if currentseq is not None: 114 | assert currentseq.header is not None and currentseq.seq is not None 115 | # The current fasta sequence is now complete 116 | lengths.append(len(currentseq.seq)) 117 | #endif 118 | currentseq = FastaSeq(header=line.rstrip()) 119 | seqs.append(currentseq) 120 | else: 121 | assert currentseq is not None 122 | 123 | if currentseq.seq is not None: 124 | # concatenate the sequence lines 125 | currentseq.seq += line.rstrip() 126 | else: 127 | currentseq.seq = line.rstrip() 128 | #endif 129 | #endif 130 | #endfor 131 | 132 | # The final fasta seq 133 | if currentseq is not None: 134 | assert currentseq.header is not None and currentseq.seq is not None 135 | # The current fasta sequence is now complete 136 | lengths.append(len(currentseq.seq)) 137 | #endif 138 | #endwith 139 | 140 | lengths.sort() 141 | expected_bin_size = sum(lengths)/bins 142 | 143 | intervals = [] 144 | curr_bin_size = 0 145 | lower = lengths[0] 146 | upper = lower 147 | for l in lengths: 148 | if curr_bin_size < expected_bin_size or l == upper: 149 | curr_bin_size += l 150 | upper = l 151 | else: 152 | intervals.append((lower, upper+1)) 153 | 154 | curr_bin_size = l 155 | lower = l 156 | upper = lower 157 | #endif 158 | #endfor 159 | intervals.append((lower, upper+1)) 160 | 161 | files = {} 162 | fhs = [] 163 | for i in range(len(intervals)): 164 | outpath = out_prefix + '.' + str(i) 165 | lower = intervals[i][0] 166 | 167 | #print str(intervals[i]) + ' : ' + outpath 168 | files[lower] = outpath 169 | fhs.append(open(outpath, 'w')) 170 | #endfor 171 | 172 | # [lower, upper) 173 | for s in seqs: 174 | length = len(s.seq) 175 | for index, (lower, upper) in enumerate(intervals): 176 | if length >= lower and length < upper: 177 | fhs[index].write('%s\n%s\n' % (s.header, s.seq)) 178 | break 179 | #endif 180 | #endfor 181 | #endfor 182 | 183 | for fh in fhs: 184 | fh.close() 185 | #endfor 186 | 187 | return files 188 | #enddef 189 | 190 | def bin_by_length(fasta, bins, out_prefix): 191 | 192 | lengths = [] 193 | seqs = [] 194 | 195 | currentseq = None 196 | with open(fasta, 'r') as fin: 197 | for line in fin: 198 | if line[0] == '>': 199 | if currentseq is not None: 200 | assert currentseq.header is not None and currentseq.seq is not None 201 | # The current fasta sequence is now complete 202 | lengths.append(len(currentseq.seq)) 203 | #endif 204 | currentseq = FastaSeq(header=line.rstrip()) 205 | seqs.append(currentseq) 206 | else: 207 | assert currentseq is not None 208 | 209 | if currentseq.seq is not None: 210 | # concatenate the sequence lines 211 | currentseq.seq += line.rstrip() 212 | else: 213 | currentseq.seq = line.rstrip() 214 | #endif 215 | #endif 216 | #endfor 217 | 218 | # The final fasta seq 219 | if currentseq is not None: 220 | assert currentseq.header is not None and currentseq.seq is not None 221 | # The current fasta sequence is now complete 222 | lengths.append(len(currentseq.seq)) 223 | #endif 224 | #endwith 225 | 226 | lengths.sort() 227 | count = len(lengths) 228 | expected_bin_size = count/bins 229 | 230 | intervals = [] 231 | lower = lengths[0] 232 | curr_bin_size = 0 233 | upper = lower 234 | for l in lengths: 235 | if curr_bin_size < expected_bin_size or l == upper: 236 | curr_bin_size += 1 237 | upper = l 238 | else: 239 | intervals.append((lower, upper+1)) 240 | 241 | lower = l 242 | upper = lower 243 | curr_bin_size = 1 244 | #endif 245 | #endfor 246 | intervals.append((lower, upper+1)) 247 | 248 | files = {} 249 | fhs = [] 250 | for i in range(len(intervals)): 251 | outpath = out_prefix + '.' + str(i) 252 | lower = intervals[i][0] 253 | 254 | print(str(intervals[i]) + ' : ' + outpath) 255 | files[lower] = outpath 256 | fhs.append(open(outpath, 'w')) 257 | #endfor 258 | 259 | # [lower, upper) 260 | for s in seqs: 261 | length = len(s.seq) 262 | for index, (lower, upper) in enumerate(intervals): 263 | if length >= lower and length < upper: 264 | fhs[index].write('%s\n%s\n' % (s.header, s.seq)) 265 | break 266 | #endif 267 | #endfor 268 | #endfor 269 | 270 | for fh in fhs: 271 | fh.close() 272 | #endfor 273 | 274 | return files 275 | #enddef 276 | 277 | def blat_merge_fastas(path_prefix_map, merged_fa, concat_fa=None, concat_fa_selfalign_psl=None, percent_identity=0.95, strand_specific=False, cleanup=False, minoverlap=0, threads=1, indel_size_tolerance=1, min_seq_len=32, skip_psl_self_awk=None): 278 | """Merge fasta files into a single fasta file by removing redundant sequences. Redundancy is determined by BLAT alignments. 279 | """ 280 | 281 | if concat_fa is None: 282 | concat_fa = merged_fa + '.tmp.concat.fa' 283 | #endif 284 | 285 | if concat_fa_selfalign_psl is None: 286 | concat_fa_selfalign_psl = merged_fa + '.tmp.concat.psl' 287 | #endif 288 | 289 | # Concatenate the fastas together and give the contigs of each set a prefix 290 | concat_fastas(path_prefix_map, concat_fa) 291 | 292 | # Self-align concatenated fasta 293 | blat_self_align(concat_fa, concat_fa_selfalign_psl, percent_id=percent_identity, max_consecutive_edits=indel_size_tolerance, min_seq_len=min_seq_len, threads=threads, skip_psl_self_awk=skip_psl_self_awk) 294 | 295 | # Identify redundant contigs 296 | rrefs = psl_cid_extractor.extract_cids(psl=concat_fa_selfalign_psl, samestrand=strand_specific, min_percent_identity=percent_identity, max_consecutive_edits=indel_size_tolerance, report_redundant=True) 297 | 298 | tmpfiles = [] 299 | nr_fa_long = merged_fa + '.tmp.long.fa' 300 | nr_fa_short = None 301 | if minoverlap > 0: 302 | nr_fa_short = merged_fa + '.tmp.short.fa' 303 | tmpfiles.append(nr_fa_short) 304 | #endif 305 | 306 | # Gather the non-contained sequences and split into 2 partitions: 307 | # 1. shorter than (min overlap + 1) 308 | # 2. longer than or equal to (min overlap + 1) 309 | filter_fasta(concat_fa, nr_fa_long, min_length=minoverlap+1, remove_set=rrefs, fasta_out_st=nr_fa_short) 310 | 311 | # overlap-layout the long sequences 312 | if minoverlap > 0: 313 | # generate the sequence overlap graph 314 | overlap_dot = merged_fa + '.tmp.long.dot' 315 | overlap_cmd_params = ['abyss-overlap', '--threads=%d' % threads, '--min=%d' % minoverlap] 316 | if strand_specific: 317 | overlap_cmd_params.append('--SS') 318 | #endif 319 | overlap_cmd_params.append(nr_fa_long) 320 | overlap_cmd_params.append('>' + overlap_dot) 321 | run_shell_cmd(' '.join(overlap_cmd_params)) 322 | 323 | # layout contigs using the overlap graph 324 | layout_path = merged_fa + '.tmp.long.path' 325 | layout_cmd_params = ['abyss-layout', '--kmer=%d' % (minoverlap+1), '--out=%s' % layout_path] 326 | if strand_specific: 327 | layout_cmd_params.append('--SS') 328 | #endif 329 | layout_cmd_params.append(overlap_dot) 330 | run_shell_cmd(' '.join(layout_cmd_params)) 331 | 332 | # generate fasta for O-L 333 | overlap_fa = merged_fa + '.incomplete' 334 | mergecontigs_cmd_params = ['MergeContigs', '--kmer=%d' % (minoverlap+1), '--out=%s' % overlap_fa, nr_fa_long, overlap_dot, layout_path] 335 | run_shell_cmd(' '.join(mergecontigs_cmd_params)) 336 | 337 | # append the short sequences to the same fasta 338 | with open(overlap_fa, 'a') as fout: 339 | with open(nr_fa_short, 'r') as fin: 340 | for line in fin: 341 | fout.write(line) 342 | #endfor 343 | #endwith 344 | #endwith 345 | 346 | shutil.move(overlap_fa, merged_fa) 347 | tmpfiles.extend([concat_fa, concat_fa_selfalign_psl, nr_fa_long, nr_fa_short, overlap_dot, layout_path]) 348 | else: 349 | shutil.move(nr_fa_long, merged_fa) 350 | tmpfiles.extend([concat_fa, concat_fa_selfalign_psl]) 351 | #endif 352 | 353 | if cleanup and tmpfiles is not None: 354 | for t in tmpfiles: 355 | if t is not None and os.path.isfile(t): 356 | os.remove(t) 357 | #endif 358 | #endfor 359 | #endif 360 | #enddef 361 | 362 | def bowtie2_self_align(fasta, outputsam, threads=1, strand_specific=False, path_strip_sam_seq_qual=None, preset='--sensitive', k=2): 363 | """Align all fasta sequences to each other with Bowtie2. 364 | """ 365 | 366 | # Build index files for the concatenated fasta 367 | bt2_index_cmd_params = ['bowtie2-build --quiet', fasta, fasta] 368 | run_shell_cmd(' '.join(bt2_index_cmd_params)) 369 | 370 | # Self-align concatenated fasta with Bowtie2 371 | bt2_align_cmd_params = ['bowtie2'] 372 | 373 | if strand_specific: 374 | bt2_align_cmd_params.append('--norc') 375 | #endif 376 | 377 | bt2_align_cmd_params.extend([preset, '-k %d' % k, '--omit-sec-seq --end-to-end -f', '-p %d' % threads, fasta, fasta]) 378 | 379 | if path_strip_sam_seq_qual: 380 | bt2_align_cmd_params.append('|' + path_strip_sam_seq_qual) 381 | #endif 382 | 383 | bt2_align_cmd_params.append('|gzip -c >' + outputsam) 384 | 385 | run_shell_cmd(' '.join(bt2_align_cmd_params)) 386 | #enddef 387 | 388 | def bowtie2_merge_fastas(path_prefix_map, merged_fa, concat_fa=None, concat_fa_selfalign_sam=None, bt2_threads=1, percent_identity=0.95, strand_specific=False, path_strip_sam_seq_qual=None, cleanup=False, bowtie2_preset='--sensitive', bowtie2_k=2, threads=1, indel_size_tolerance=1): 389 | """Merge fasta files into a single fasta file by removing redundant sequences. Redundancy is determined by Bowtie2 alignments. 390 | """ 391 | 392 | tmpfiles = [] 393 | 394 | if concat_fa is None: 395 | concat_fa = merged_fa + '.tmp.concat.fa' 396 | #endif 397 | 398 | if concat_fa_selfalign_sam is None: 399 | concat_fa_selfalign_sam = concat_fa + '.selfalign.sam.gz' 400 | #endif 401 | 402 | # Concatenate the fastas together and give the contigs of each set a prefix 403 | concat_fastas(path_prefix_map, concat_fa) 404 | 405 | # Self-align concatenated fasta with Bowtie2 406 | bowtie2_self_align(concat_fa, concat_fa_selfalign_sam, threads=bt2_threads, strand_specific=strand_specific, path_strip_sam_seq_qual=path_strip_sam_seq_qual, preset=bowtie2_preset) 407 | 408 | # Identify NON-redundant contigs 409 | nrrefs = cid_extractor.extract_nr(sam=concat_fa_selfalign_sam, require_samestrand=strand_specific, min_percent_identity=percent_identity, max_consecutive_edits=indel_size_tolerance, report_redundant=False) 410 | 411 | nr_fa = merged_fa + '.tmp.nr.fa' 412 | 413 | # Gather the non-contained sequences 414 | filter_fasta(concat_fa, nr_fa, keep_set=nrrefs) 415 | 416 | shutil.move(nr_fa, merged_fa) 417 | tmpfiles.extend([concat_fa, concat_fa_selfalign_sam]) 418 | 419 | if cleanup and tmpfiles is not None: 420 | for t in tmpfiles: 421 | if t is not None and os.path.isfile(t): 422 | os.remove(t) 423 | #endif 424 | #endfor 425 | #endif 426 | #enddef 427 | 428 | def abyssmap_rmdups(in_fa, out_fa, strand_specific=False, cleanup=False, threads=1): 429 | ids_file = in_fa + '.dup_ids' 430 | 431 | # run abyssmap 432 | cmd_params = ['abyss-map', '--dup'] 433 | 434 | if strand_specific: 435 | cmd_params.append('--SS') 436 | #endif 437 | 438 | if threads > 1: 439 | cmd_params.append('--threads=%d' % threads) 440 | #endif 441 | 442 | cmd_params.extend([in_fa, in_fa]) 443 | cmd_params.append('> %s' % ids_file) 444 | 445 | run_shell_cmd(' '.join(cmd_params)) 446 | 447 | cids_set = set() 448 | with open(ids_file, 'r') as fh: 449 | for line in fh: 450 | line_stripped = line.strip() 451 | if len(line_stripped) > 0: 452 | cids_set.add(line_stripped) 453 | #endif 454 | #endfor 455 | #endwith 456 | 457 | filter_fasta(in_fa, out_fa, remove_set=cids_set) 458 | 459 | if cleanup: 460 | os.remove(ids_file) 461 | #endif 462 | #enddef 463 | 464 | def append_with_prefix(core_fa, additional_fa, prefix=''): 465 | """Append sequences from additional_fa to core_fa and give each a prefix 466 | """ 467 | 468 | with open(core_fa, 'a') as fout: 469 | with open(additional_fa, 'r') as fin: 470 | line_start = '>' + prefix 471 | for line in fin: 472 | if line[0] == '>': 473 | #header 474 | fout.write(line.replace('>', line_start, 1)) 475 | else: 476 | fout.write(line) 477 | #endif 478 | #endfor 479 | #endwith 480 | #endwith 481 | #enddef 482 | 483 | def abyssmap_merge_fastas(path_prefix_map, merged_fa, concat_fa=None, strand_specific=False, cleanup=False, threads=1, iterative=False): 484 | """Merge fasta files into a single fasta file by removing redundant sequences. Only completely contained sequences with exact match are removed. 485 | """ 486 | 487 | tmpfiles = [] 488 | 489 | if concat_fa is None: 490 | concat_fa = merged_fa + '.tmp.concat.fa' 491 | #endif 492 | 493 | tmpfiles.append(concat_fa) 494 | 495 | if iterative: 496 | tmp_merged_fa = merged_fa + '.tmp.fa' 497 | 498 | # get the file size for each fasta 499 | prefix_mem_tuples = [] 500 | for prefix, path in path_prefix_map.iteritems(): 501 | prefix_mem_tuples.append( (prefix, os.path.getsize(path)) ) 502 | #endfor 503 | 504 | # Sort by file size in ascending order 505 | prefix_mem_tuples.sort(key=operator.itemgetter(1)) 506 | 507 | # Add sequences from one additional fasta file to the merge pool in each iteration 508 | iteration = 0 509 | for prefix, filesize in prefix_mem_tuples: 510 | if os.path.isfile(concat_fa): 511 | os.remove(concat_fa) 512 | #endif 513 | 514 | if iteration > 0: 515 | shutil.move(tmp_merged_fa, concat_fa) 516 | #endif 517 | 518 | append_with_prefix(concat_fa, path_prefix_map[prefix], prefix=prefix) 519 | 520 | abyssmap_rmdups(concat_fa, tmp_merged_fa, strand_specific=strand_specific, cleanup=cleanup, threads=threads) 521 | 522 | iteration += 1 523 | #endfor 524 | 525 | shutil.move(tmp_merged_fa, merged_fa) 526 | 527 | tmpfiles.append(tmp_merged_fa) 528 | else: 529 | # Concatenate all fastas together and give the contigs of each set a prefix 530 | concat_fastas(path_prefix_map, concat_fa) 531 | 532 | # remove duplicates 533 | abyssmap_rmdups(concat_fa, merged_fa, strand_specific=strand_specific, cleanup=cleanup, threads=threads) 534 | #endif 535 | 536 | if cleanup and tmpfiles is not None: 537 | for t in tmpfiles: 538 | if t is not None and os.path.isfile(t): 539 | os.remove(t) 540 | #endif 541 | #endfor 542 | #endif 543 | #enddef 544 | 545 | class FastaSeq: 546 | """Data structure for one FASTA sequence. 547 | """ 548 | def __init__(self, header=None, seq=None): 549 | self.header = header 550 | self.seq = seq 551 | #enddef 552 | #endclass 553 | 554 | def filter_fasta(fasta_in, fasta_out, min_length=0, keep_set=None, fasta_out_st=None, remove_set=None): 555 | """Filter a FASTA file by selecting contigs by a length cutoff and/or a set of ids of contigs to keep/remove. 556 | """ 557 | 558 | currentseq = None 559 | 560 | fin = open(fasta_in, 'r') 561 | fout = open(fasta_out, 'w') 562 | 563 | fout_st = None 564 | if fasta_out_st is not None: 565 | # FASTA file for short sequences 566 | fout_st = open(fasta_out_st, 'w') 567 | #endif 568 | 569 | count = 0 570 | count_st = 0 571 | 572 | for line in fin: 573 | if line[0] == '>': 574 | if currentseq is not None: 575 | assert currentseq.header is not None and currentseq.seq is not None 576 | # The current fasta sequence is now complete 577 | 578 | if (keep_set is None or currentseq.header.split()[0][1:] in keep_set) and (remove_set is None or not currentseq.header.split()[0][1:] in remove_set): 579 | current_seq_length = len(currentseq.seq) 580 | 581 | if min_length is None or current_seq_length >= min_length: 582 | fout.write('%s\n%s\n' % (currentseq.header, currentseq.seq)) 583 | count += 1 584 | elif fout_st is not None: 585 | fout_st.write('%s\n%s\n' % (currentseq.header, currentseq.seq)) 586 | count_st += 1 587 | #endif 588 | #endif 589 | #endif 590 | currentseq = FastaSeq(header=line.rstrip()) 591 | else: 592 | assert currentseq is not None 593 | 594 | if currentseq.seq is not None: 595 | # concatenate the sequence lines 596 | currentseq.seq += line.rstrip() 597 | else: 598 | currentseq.seq = line.rstrip() 599 | #endif 600 | #endif 601 | #endfor 602 | 603 | # The final fasta seq 604 | if currentseq is not None: 605 | assert currentseq.header is not None and currentseq.seq is not None 606 | # The current fasta sequence is now complete 607 | 608 | if (keep_set is None or currentseq.header.split()[0][1:] in keep_set) and (remove_set is None or not currentseq.header.split()[0][1:] in remove_set): 609 | current_seq_length = len(currentseq.seq) 610 | 611 | if min_length is None or current_seq_length >= min_length: 612 | fout.write('%s\n%s\n' % (currentseq.header, currentseq.seq)) 613 | count += 1 614 | elif fout_st is not None: 615 | fout_st.write('%s\n%s\n' % (currentseq.header, currentseq.seq)) 616 | count_st += 1 617 | #endif 618 | #endif 619 | #endif 620 | 621 | fin.close() 622 | fout.close() 623 | 624 | if fout_st is not None: 625 | fout_st.close() 626 | #endif 627 | 628 | return count, count_st 629 | #enddef 630 | 631 | def partition_fasta(fasta_file, outdir, format='seq.%s.fa', max_bases=None, max_contigs=None): 632 | """Partition a FASTA into smaller chunks based on number of bases and/or number of contigs. 633 | """ 634 | 635 | path_format = os.path.join(outdir, format) 636 | 637 | for fa in glob.glob(path_format % '*'): 638 | #This could be a re-run; remove the existing output file. 639 | os.remove(fa) 640 | #endfor 641 | 642 | total_num_contigs = 0 643 | total_num_bases = 0 644 | 645 | currentseq = None 646 | output_num = 1 647 | num_contigs = 0 648 | num_bases = 0 649 | 650 | fin = open(fasta_file, 'r') 651 | fout = open(path_format % str(output_num), 'w') 652 | 653 | for line in fin: 654 | if line[0] == '>': 655 | if currentseq is not None: 656 | assert currentseq.header is not None and currentseq.seq is not None 657 | # The current fasta sequence is now complete 658 | 659 | # write this fasta seq to file 660 | current_seq_length = len(currentseq.seq) 661 | 662 | if (max_contigs is not None and num_contigs + 1 > max_contigs) or (max_bases is not None and num_bases + current_seq_length > max_bases): 663 | # adding the current sequence to this batch would exceed the thresholds 664 | 665 | # this batch is done 666 | total_num_contigs += num_contigs 667 | total_num_bases += num_bases 668 | fout.close() 669 | 670 | # start the next batch 671 | output_num += 1 672 | fout = open(path_format % str(output_num), 'w') 673 | num_contigs = 0 674 | num_bases = 0 675 | #endif 676 | 677 | fout.write('%s\n%s\n' % (currentseq.header, currentseq.seq)) 678 | currentseq = FastaSeq(header=line.rstrip()) 679 | 680 | num_contigs += 1 681 | num_bases += current_seq_length 682 | else: 683 | currentseq = FastaSeq(header=line.rstrip()) 684 | #endif 685 | else: 686 | assert currentseq is not None 687 | 688 | if currentseq.seq is not None: 689 | # concatenate the sequence lines 690 | currentseq.seq += line.rstrip() 691 | else: 692 | currentseq.seq = line.rstrip() 693 | #endif 694 | #endif 695 | #endfor 696 | fin.close() 697 | 698 | # Write the final fasta seq to file 699 | current_seq_length = len(currentseq.seq) 700 | 701 | if (max_contigs is not None and num_contigs + 1 > max_contigs) or (max_bases is not None and num_bases + current_seq_length > max_bases): 702 | # adding the last sequence to this batch would exceed the thresholds 703 | 704 | # this batch is done 705 | total_num_contigs += num_contigs 706 | total_num_bases += num_bases 707 | fout.close() 708 | 709 | # start the next batch 710 | output_num += 1 711 | fout = open(path_format % str(output_num), 'w') 712 | num_contigs = 0 713 | num_bases = 0 714 | #endif 715 | 716 | fout.write('%s\n%s\n' % (currentseq.header, currentseq.seq)) 717 | num_contigs += 1 718 | num_bases += current_seq_length 719 | 720 | total_num_contigs += num_contigs 721 | total_num_bases += num_bases 722 | 723 | fout.close() 724 | 725 | return total_num_contigs, total_num_bases, output_num 726 | #enddef 727 | 728 | #EOF 729 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Trans-ABySS 2 | Copyright 2018 BC Cancer, Genome Sciences Centre 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, version 3. 7 | 8 | This program is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | GNU General Public License for more details. 12 | 13 | You should have received a copy of the GNU General Public License 14 | along with this program. If not, see . 15 | 16 | For commercial licensing options, please contact 17 | Patrick Rebstein 18 | 19 | See the file COPYRIGHT for details of the copyright and license of 20 | each individual file included with this software. 21 | 22 | GNU GENERAL PUBLIC LICENSE 23 | Version 3, 29 June 2007 24 | 25 | Copyright (C) 2007 Free Software Foundation, Inc. 26 | Everyone is permitted to copy and distribute verbatim copies 27 | of this license document, but changing it is not allowed. 28 | 29 | Preamble 30 | 31 | The GNU General Public License is a free, copyleft license for 32 | software and other kinds of works. 33 | 34 | The licenses for most software and other practical works are designed 35 | to take away your freedom to share and change the works. By contrast, 36 | the GNU General Public License is intended to guarantee your freedom to 37 | share and change all versions of a program--to make sure it remains free 38 | software for all its users. We, the Free Software Foundation, use the 39 | GNU General Public License for most of our software; it applies also to 40 | any other work released this way by its authors. You can apply it to 41 | your programs, too. 42 | 43 | When we speak of free software, we are referring to freedom, not 44 | price. Our General Public Licenses are designed to make sure that you 45 | have the freedom to distribute copies of free software (and charge for 46 | them if you wish), that you receive source code or can get it if you 47 | want it, that you can change the software or use pieces of it in new 48 | free programs, and that you know you can do these things. 49 | 50 | To protect your rights, we need to prevent others from denying you 51 | these rights or asking you to surrender the rights. Therefore, you have 52 | certain responsibilities if you distribute copies of the software, or if 53 | you modify it: responsibilities to respect the freedom of others. 54 | 55 | For example, if you distribute copies of such a program, whether 56 | gratis or for a fee, you must pass on to the recipients the same 57 | freedoms that you received. You must make sure that they, too, receive 58 | or can get the source code. And you must show them these terms so they 59 | know their rights. 60 | 61 | Developers that use the GNU GPL protect your rights with two steps: 62 | (1) assert copyright on the software, and (2) offer you this License 63 | giving you legal permission to copy, distribute and/or modify it. 64 | 65 | For the developers' and authors' protection, the GPL clearly explains 66 | that there is no warranty for this free software. For both users' and 67 | authors' sake, the GPL requires that modified versions be marked as 68 | changed, so that their problems will not be attributed erroneously to 69 | authors of previous versions. 70 | 71 | Some devices are designed to deny users access to install or run 72 | modified versions of the software inside them, although the manufacturer 73 | can do so. This is fundamentally incompatible with the aim of 74 | protecting users' freedom to change the software. The systematic 75 | pattern of such abuse occurs in the area of products for individuals to 76 | use, which is precisely where it is most unacceptable. Therefore, we 77 | have designed this version of the GPL to prohibit the practice for those 78 | products. If such problems arise substantially in other domains, we 79 | stand ready to extend this provision to those domains in future versions 80 | of the GPL, as needed to protect the freedom of users. 81 | 82 | Finally, every program is threatened constantly by software patents. 83 | States should not allow patents to restrict development and use of 84 | software on general-purpose computers, but in those that do, we wish to 85 | avoid the special danger that patents applied to a free program could 86 | make it effectively proprietary. To prevent this, the GPL assures that 87 | patents cannot be used to render the program non-free. 88 | 89 | The precise terms and conditions for copying, distribution and 90 | modification follow. 91 | 92 | TERMS AND CONDITIONS 93 | 94 | 0. Definitions. 95 | 96 | "This License" refers to version 3 of the GNU General Public License. 97 | 98 | "Copyright" also means copyright-like laws that apply to other kinds of 99 | works, such as semiconductor masks. 100 | 101 | "The Program" refers to any copyrightable work licensed under this 102 | License. Each licensee is addressed as "you". "Licensees" and 103 | "recipients" may be individuals or organizations. 104 | 105 | To "modify" a work means to copy from or adapt all or part of the work 106 | in a fashion requiring copyright permission, other than the making of an 107 | exact copy. The resulting work is called a "modified version" of the 108 | earlier work or a work "based on" the earlier work. 109 | 110 | A "covered work" means either the unmodified Program or a work based 111 | on the Program. 112 | 113 | To "propagate" a work means to do anything with it that, without 114 | permission, would make you directly or secondarily liable for 115 | infringement under applicable copyright law, except executing it on a 116 | computer or modifying a private copy. Propagation includes copying, 117 | distribution (with or without modification), making available to the 118 | public, and in some countries other activities as well. 119 | 120 | To "convey" a work means any kind of propagation that enables other 121 | parties to make or receive copies. Mere interaction with a user through 122 | a computer network, with no transfer of a copy, is not conveying. 123 | 124 | An interactive user interface displays "Appropriate Legal Notices" 125 | to the extent that it includes a convenient and prominently visible 126 | feature that (1) displays an appropriate copyright notice, and (2) 127 | tells the user that there is no warranty for the work (except to the 128 | extent that warranties are provided), that licensees may convey the 129 | work under this License, and how to view a copy of this License. If 130 | the interface presents a list of user commands or options, such as a 131 | menu, a prominent item in the list meets this criterion. 132 | 133 | 1. Source Code. 134 | 135 | The "source code" for a work means the preferred form of the work 136 | for making modifications to it. "Object code" means any non-source 137 | form of a work. 138 | 139 | A "Standard Interface" means an interface that either is an official 140 | standard defined by a recognized standards body, or, in the case of 141 | interfaces specified for a particular programming language, one that 142 | is widely used among developers working in that language. 143 | 144 | The "System Libraries" of an executable work include anything, other 145 | than the work as a whole, that (a) is included in the normal form of 146 | packaging a Major Component, but which is not part of that Major 147 | Component, and (b) serves only to enable use of the work with that 148 | Major Component, or to implement a Standard Interface for which an 149 | implementation is available to the public in source code form. A 150 | "Major Component", in this context, means a major essential component 151 | (kernel, window system, and so on) of the specific operating system 152 | (if any) on which the executable work runs, or a compiler used to 153 | produce the work, or an object code interpreter used to run it. 154 | 155 | The "Corresponding Source" for a work in object code form means all 156 | the source code needed to generate, install, and (for an executable 157 | work) run the object code and to modify the work, including scripts to 158 | control those activities. However, it does not include the work's 159 | System Libraries, or general-purpose tools or generally available free 160 | programs which are used unmodified in performing those activities but 161 | which are not part of the work. For example, Corresponding Source 162 | includes interface definition files associated with source files for 163 | the work, and the source code for shared libraries and dynamically 164 | linked subprograms that the work is specifically designed to require, 165 | such as by intimate data communication or control flow between those 166 | subprograms and other parts of the work. 167 | 168 | The Corresponding Source need not include anything that users 169 | can regenerate automatically from other parts of the Corresponding 170 | Source. 171 | 172 | The Corresponding Source for a work in source code form is that 173 | same work. 174 | 175 | 2. Basic Permissions. 176 | 177 | All rights granted under this License are granted for the term of 178 | copyright on the Program, and are irrevocable provided the stated 179 | conditions are met. This License explicitly affirms your unlimited 180 | permission to run the unmodified Program. The output from running a 181 | covered work is covered by this License only if the output, given its 182 | content, constitutes a covered work. This License acknowledges your 183 | rights of fair use or other equivalent, as provided by copyright law. 184 | 185 | You may make, run and propagate covered works that you do not 186 | convey, without conditions so long as your license otherwise remains 187 | in force. You may convey covered works to others for the sole purpose 188 | of having them make modifications exclusively for you, or provide you 189 | with facilities for running those works, provided that you comply with 190 | the terms of this License in conveying all material for which you do 191 | not control copyright. Those thus making or running the covered works 192 | for you must do so exclusively on your behalf, under your direction 193 | and control, on terms that prohibit them from making any copies of 194 | your copyrighted material outside their relationship with you. 195 | 196 | Conveying under any other circumstances is permitted solely under 197 | the conditions stated below. Sublicensing is not allowed; section 10 198 | makes it unnecessary. 199 | 200 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 201 | 202 | No covered work shall be deemed part of an effective technological 203 | measure under any applicable law fulfilling obligations under article 204 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 205 | similar laws prohibiting or restricting circumvention of such 206 | measures. 207 | 208 | When you convey a covered work, you waive any legal power to forbid 209 | circumvention of technological measures to the extent such circumvention 210 | is effected by exercising rights under this License with respect to 211 | the covered work, and you disclaim any intention to limit operation or 212 | modification of the work as a means of enforcing, against the work's 213 | users, your or third parties' legal rights to forbid circumvention of 214 | technological measures. 215 | 216 | 4. Conveying Verbatim Copies. 217 | 218 | You may convey verbatim copies of the Program's source code as you 219 | receive it, in any medium, provided that you conspicuously and 220 | appropriately publish on each copy an appropriate copyright notice; 221 | keep intact all notices stating that this License and any 222 | non-permissive terms added in accord with section 7 apply to the code; 223 | keep intact all notices of the absence of any warranty; and give all 224 | recipients a copy of this License along with the Program. 225 | 226 | You may charge any price or no price for each copy that you convey, 227 | and you may offer support or warranty protection for a fee. 228 | 229 | 5. Conveying Modified Source Versions. 230 | 231 | You may convey a work based on the Program, or the modifications to 232 | produce it from the Program, in the form of source code under the 233 | terms of section 4, provided that you also meet all of these conditions: 234 | 235 | a) The work must carry prominent notices stating that you modified 236 | it, and giving a relevant date. 237 | 238 | b) The work must carry prominent notices stating that it is 239 | released under this License and any conditions added under section 240 | 7. This requirement modifies the requirement in section 4 to 241 | "keep intact all notices". 242 | 243 | c) You must license the entire work, as a whole, under this 244 | License to anyone who comes into possession of a copy. This 245 | License will therefore apply, along with any applicable section 7 246 | additional terms, to the whole of the work, and all its parts, 247 | regardless of how they are packaged. This License gives no 248 | permission to license the work in any other way, but it does not 249 | invalidate such permission if you have separately received it. 250 | 251 | d) If the work has interactive user interfaces, each must display 252 | Appropriate Legal Notices; however, if the Program has interactive 253 | interfaces that do not display Appropriate Legal Notices, your 254 | work need not make them do so. 255 | 256 | A compilation of a covered work with other separate and independent 257 | works, which are not by their nature extensions of the covered work, 258 | and which are not combined with it such as to form a larger program, 259 | in or on a volume of a storage or distribution medium, is called an 260 | "aggregate" if the compilation and its resulting copyright are not 261 | used to limit the access or legal rights of the compilation's users 262 | beyond what the individual works permit. Inclusion of a covered work 263 | in an aggregate does not cause this License to apply to the other 264 | parts of the aggregate. 265 | 266 | 6. Conveying Non-Source Forms. 267 | 268 | You may convey a covered work in object code form under the terms 269 | of sections 4 and 5, provided that you also convey the 270 | machine-readable Corresponding Source under the terms of this License, 271 | in one of these ways: 272 | 273 | a) Convey the object code in, or embodied in, a physical product 274 | (including a physical distribution medium), accompanied by the 275 | Corresponding Source fixed on a durable physical medium 276 | customarily used for software interchange. 277 | 278 | b) Convey the object code in, or embodied in, a physical product 279 | (including a physical distribution medium), accompanied by a 280 | written offer, valid for at least three years and valid for as 281 | long as you offer spare parts or customer support for that product 282 | model, to give anyone who possesses the object code either (1) a 283 | copy of the Corresponding Source for all the software in the 284 | product that is covered by this License, on a durable physical 285 | medium customarily used for software interchange, for a price no 286 | more than your reasonable cost of physically performing this 287 | conveying of source, or (2) access to copy the 288 | Corresponding Source from a network server at no charge. 289 | 290 | c) Convey individual copies of the object code with a copy of the 291 | written offer to provide the Corresponding Source. This 292 | alternative is allowed only occasionally and noncommercially, and 293 | only if you received the object code with such an offer, in accord 294 | with subsection 6b. 295 | 296 | d) Convey the object code by offering access from a designated 297 | place (gratis or for a charge), and offer equivalent access to the 298 | Corresponding Source in the same way through the same place at no 299 | further charge. You need not require recipients to copy the 300 | Corresponding Source along with the object code. If the place to 301 | copy the object code is a network server, the Corresponding Source 302 | may be on a different server (operated by you or a third party) 303 | that supports equivalent copying facilities, provided you maintain 304 | clear directions next to the object code saying where to find the 305 | Corresponding Source. Regardless of what server hosts the 306 | Corresponding Source, you remain obligated to ensure that it is 307 | available for as long as needed to satisfy these requirements. 308 | 309 | e) Convey the object code using peer-to-peer transmission, provided 310 | you inform other peers where the object code and Corresponding 311 | Source of the work are being offered to the general public at no 312 | charge under subsection 6d. 313 | 314 | A separable portion of the object code, whose source code is excluded 315 | from the Corresponding Source as a System Library, need not be 316 | included in conveying the object code work. 317 | 318 | A "User Product" is either (1) a "consumer product", which means any 319 | tangible personal property which is normally used for personal, family, 320 | or household purposes, or (2) anything designed or sold for incorporation 321 | into a dwelling. In determining whether a product is a consumer product, 322 | doubtful cases shall be resolved in favor of coverage. For a particular 323 | product received by a particular user, "normally used" refers to a 324 | typical or common use of that class of product, regardless of the status 325 | of the particular user or of the way in which the particular user 326 | actually uses, or expects or is expected to use, the product. A product 327 | is a consumer product regardless of whether the product has substantial 328 | commercial, industrial or non-consumer uses, unless such uses represent 329 | the only significant mode of use of the product. 330 | 331 | "Installation Information" for a User Product means any methods, 332 | procedures, authorization keys, or other information required to install 333 | and execute modified versions of a covered work in that User Product from 334 | a modified version of its Corresponding Source. The information must 335 | suffice to ensure that the continued functioning of the modified object 336 | code is in no case prevented or interfered with solely because 337 | modification has been made. 338 | 339 | If you convey an object code work under this section in, or with, or 340 | specifically for use in, a User Product, and the conveying occurs as 341 | part of a transaction in which the right of possession and use of the 342 | User Product is transferred to the recipient in perpetuity or for a 343 | fixed term (regardless of how the transaction is characterized), the 344 | Corresponding Source conveyed under this section must be accompanied 345 | by the Installation Information. But this requirement does not apply 346 | if neither you nor any third party retains the ability to install 347 | modified object code on the User Product (for example, the work has 348 | been installed in ROM). 349 | 350 | The requirement to provide Installation Information does not include a 351 | requirement to continue to provide support service, warranty, or updates 352 | for a work that has been modified or installed by the recipient, or for 353 | the User Product in which it has been modified or installed. Access to a 354 | network may be denied when the modification itself materially and 355 | adversely affects the operation of the network or violates the rules and 356 | protocols for communication across the network. 357 | 358 | Corresponding Source conveyed, and Installation Information provided, 359 | in accord with this section must be in a format that is publicly 360 | documented (and with an implementation available to the public in 361 | source code form), and must require no special password or key for 362 | unpacking, reading or copying. 363 | 364 | 7. Additional Terms. 365 | 366 | "Additional permissions" are terms that supplement the terms of this 367 | License by making exceptions from one or more of its conditions. 368 | Additional permissions that are applicable to the entire Program shall 369 | be treated as though they were included in this License, to the extent 370 | that they are valid under applicable law. If additional permissions 371 | apply only to part of the Program, that part may be used separately 372 | under those permissions, but the entire Program remains governed by 373 | this License without regard to the additional permissions. 374 | 375 | When you convey a copy of a covered work, you may at your option 376 | remove any additional permissions from that copy, or from any part of 377 | it. (Additional permissions may be written to require their own 378 | removal in certain cases when you modify the work.) You may place 379 | additional permissions on material, added by you to a covered work, 380 | for which you have or can give appropriate copyright permission. 381 | 382 | Notwithstanding any other provision of this License, for material you 383 | add to a covered work, you may (if authorized by the copyright holders of 384 | that material) supplement the terms of this License with terms: 385 | 386 | a) Disclaiming warranty or limiting liability differently from the 387 | terms of sections 15 and 16 of this License; or 388 | 389 | b) Requiring preservation of specified reasonable legal notices or 390 | author attributions in that material or in the Appropriate Legal 391 | Notices displayed by works containing it; or 392 | 393 | c) Prohibiting misrepresentation of the origin of that material, or 394 | requiring that modified versions of such material be marked in 395 | reasonable ways as different from the original version; or 396 | 397 | d) Limiting the use for publicity purposes of names of licensors or 398 | authors of the material; or 399 | 400 | e) Declining to grant rights under trademark law for use of some 401 | trade names, trademarks, or service marks; or 402 | 403 | f) Requiring indemnification of licensors and authors of that 404 | material by anyone who conveys the material (or modified versions of 405 | it) with contractual assumptions of liability to the recipient, for 406 | any liability that these contractual assumptions directly impose on 407 | those licensors and authors. 408 | 409 | All other non-permissive additional terms are considered "further 410 | restrictions" within the meaning of section 10. If the Program as you 411 | received it, or any part of it, contains a notice stating that it is 412 | governed by this License along with a term that is a further 413 | restriction, you may remove that term. If a license document contains 414 | a further restriction but permits relicensing or conveying under this 415 | License, you may add to a covered work material governed by the terms 416 | of that license document, provided that the further restriction does 417 | not survive such relicensing or conveying. 418 | 419 | If you add terms to a covered work in accord with this section, you 420 | must place, in the relevant source files, a statement of the 421 | additional terms that apply to those files, or a notice indicating 422 | where to find the applicable terms. 423 | 424 | Additional terms, permissive or non-permissive, may be stated in the 425 | form of a separately written license, or stated as exceptions; 426 | the above requirements apply either way. 427 | 428 | 8. Termination. 429 | 430 | You may not propagate or modify a covered work except as expressly 431 | provided under this License. Any attempt otherwise to propagate or 432 | modify it is void, and will automatically terminate your rights under 433 | this License (including any patent licenses granted under the third 434 | paragraph of section 11). 435 | 436 | However, if you cease all violation of this License, then your 437 | license from a particular copyright holder is reinstated (a) 438 | provisionally, unless and until the copyright holder explicitly and 439 | finally terminates your license, and (b) permanently, if the copyright 440 | holder fails to notify you of the violation by some reasonable means 441 | prior to 60 days after the cessation. 442 | 443 | Moreover, your license from a particular copyright holder is 444 | reinstated permanently if the copyright holder notifies you of the 445 | violation by some reasonable means, this is the first time you have 446 | received notice of violation of this License (for any work) from that 447 | copyright holder, and you cure the violation prior to 30 days after 448 | your receipt of the notice. 449 | 450 | Termination of your rights under this section does not terminate the 451 | licenses of parties who have received copies or rights from you under 452 | this License. If your rights have been terminated and not permanently 453 | reinstated, you do not qualify to receive new licenses for the same 454 | material under section 10. 455 | 456 | 9. Acceptance Not Required for Having Copies. 457 | 458 | You are not required to accept this License in order to receive or 459 | run a copy of the Program. Ancillary propagation of a covered work 460 | occurring solely as a consequence of using peer-to-peer transmission 461 | to receive a copy likewise does not require acceptance. However, 462 | nothing other than this License grants you permission to propagate or 463 | modify any covered work. These actions infringe copyright if you do 464 | not accept this License. Therefore, by modifying or propagating a 465 | covered work, you indicate your acceptance of this License to do so. 466 | 467 | 10. Automatic Licensing of Downstream Recipients. 468 | 469 | Each time you convey a covered work, the recipient automatically 470 | receives a license from the original licensors, to run, modify and 471 | propagate that work, subject to this License. You are not responsible 472 | for enforcing compliance by third parties with this License. 473 | 474 | An "entity transaction" is a transaction transferring control of an 475 | organization, or substantially all assets of one, or subdividing an 476 | organization, or merging organizations. If propagation of a covered 477 | work results from an entity transaction, each party to that 478 | transaction who receives a copy of the work also receives whatever 479 | licenses to the work the party's predecessor in interest had or could 480 | give under the previous paragraph, plus a right to possession of the 481 | Corresponding Source of the work from the predecessor in interest, if 482 | the predecessor has it or can get it with reasonable efforts. 483 | 484 | You may not impose any further restrictions on the exercise of the 485 | rights granted or affirmed under this License. For example, you may 486 | not impose a license fee, royalty, or other charge for exercise of 487 | rights granted under this License, and you may not initiate litigation 488 | (including a cross-claim or counterclaim in a lawsuit) alleging that 489 | any patent claim is infringed by making, using, selling, offering for 490 | sale, or importing the Program or any portion of it. 491 | 492 | 11. Patents. 493 | 494 | A "contributor" is a copyright holder who authorizes use under this 495 | License of the Program or a work on which the Program is based. The 496 | work thus licensed is called the contributor's "contributor version". 497 | 498 | A contributor's "essential patent claims" are all patent claims 499 | owned or controlled by the contributor, whether already acquired or 500 | hereafter acquired, that would be infringed by some manner, permitted 501 | by this License, of making, using, or selling its contributor version, 502 | but do not include claims that would be infringed only as a 503 | consequence of further modification of the contributor version. For 504 | purposes of this definition, "control" includes the right to grant 505 | patent sublicenses in a manner consistent with the requirements of 506 | this License. 507 | 508 | Each contributor grants you a non-exclusive, worldwide, royalty-free 509 | patent license under the contributor's essential patent claims, to 510 | make, use, sell, offer for sale, import and otherwise run, modify and 511 | propagate the contents of its contributor version. 512 | 513 | In the following three paragraphs, a "patent license" is any express 514 | agreement or commitment, however denominated, not to enforce a patent 515 | (such as an express permission to practice a patent or covenant not to 516 | sue for patent infringement). To "grant" such a patent license to a 517 | party means to make such an agreement or commitment not to enforce a 518 | patent against the party. 519 | 520 | If you convey a covered work, knowingly relying on a patent license, 521 | and the Corresponding Source of the work is not available for anyone 522 | to copy, free of charge and under the terms of this License, through a 523 | publicly available network server or other readily accessible means, 524 | then you must either (1) cause the Corresponding Source to be so 525 | available, or (2) arrange to deprive yourself of the benefit of the 526 | patent license for this particular work, or (3) arrange, in a manner 527 | consistent with the requirements of this License, to extend the patent 528 | license to downstream recipients. "Knowingly relying" means you have 529 | actual knowledge that, but for the patent license, your conveying the 530 | covered work in a country, or your recipient's use of the covered work 531 | in a country, would infringe one or more identifiable patents in that 532 | country that you have reason to believe are valid. 533 | 534 | If, pursuant to or in connection with a single transaction or 535 | arrangement, you convey, or propagate by procuring conveyance of, a 536 | covered work, and grant a patent license to some of the parties 537 | receiving the covered work authorizing them to use, propagate, modify 538 | or convey a specific copy of the covered work, then the patent license 539 | you grant is automatically extended to all recipients of the covered 540 | work and works based on it. 541 | 542 | A patent license is "discriminatory" if it does not include within 543 | the scope of its coverage, prohibits the exercise of, or is 544 | conditioned on the non-exercise of one or more of the rights that are 545 | specifically granted under this License. You may not convey a covered 546 | work if you are a party to an arrangement with a third party that is 547 | in the business of distributing software, under which you make payment 548 | to the third party based on the extent of your activity of conveying 549 | the work, and under which the third party grants, to any of the 550 | parties who would receive the covered work from you, a discriminatory 551 | patent license (a) in connection with copies of the covered work 552 | conveyed by you (or copies made from those copies), or (b) primarily 553 | for and in connection with specific products or compilations that 554 | contain the covered work, unless you entered into that arrangement, 555 | or that patent license was granted, prior to 28 March 2007. 556 | 557 | Nothing in this License shall be construed as excluding or limiting 558 | any implied license or other defenses to infringement that may 559 | otherwise be available to you under applicable patent law. 560 | 561 | 12. No Surrender of Others' Freedom. 562 | 563 | If conditions are imposed on you (whether by court order, agreement or 564 | otherwise) that contradict the conditions of this License, they do not 565 | excuse you from the conditions of this License. If you cannot convey a 566 | covered work so as to satisfy simultaneously your obligations under this 567 | License and any other pertinent obligations, then as a consequence you may 568 | not convey it at all. For example, if you agree to terms that obligate you 569 | to collect a royalty for further conveying from those to whom you convey 570 | the Program, the only way you could satisfy both those terms and this 571 | License would be to refrain entirely from conveying the Program. 572 | 573 | 13. Use with the GNU Affero General Public License. 574 | 575 | Notwithstanding any other provision of this License, you have 576 | permission to link or combine any covered work with a work licensed 577 | under version 3 of the GNU Affero General Public License into a single 578 | combined work, and to convey the resulting work. The terms of this 579 | License will continue to apply to the part which is the covered work, 580 | but the special requirements of the GNU Affero General Public License, 581 | section 13, concerning interaction through a network will apply to the 582 | combination as such. 583 | 584 | 14. Revised Versions of this License. 585 | 586 | The Free Software Foundation may publish revised and/or new versions of 587 | the GNU General Public License from time to time. Such new versions will 588 | be similar in spirit to the present version, but may differ in detail to 589 | address new problems or concerns. 590 | 591 | Each version is given a distinguishing version number. If the 592 | Program specifies that a certain numbered version of the GNU General 593 | Public License "or any later version" applies to it, you have the 594 | option of following the terms and conditions either of that numbered 595 | version or of any later version published by the Free Software 596 | Foundation. If the Program does not specify a version number of the 597 | GNU General Public License, you may choose any version ever published 598 | by the Free Software Foundation. 599 | 600 | If the Program specifies that a proxy can decide which future 601 | versions of the GNU General Public License can be used, that proxy's 602 | public statement of acceptance of a version permanently authorizes you 603 | to choose that version for the Program. 604 | 605 | Later license versions may give you additional or different 606 | permissions. However, no additional obligations are imposed on any 607 | author or copyright holder as a result of your choosing to follow a 608 | later version. 609 | 610 | 15. Disclaimer of Warranty. 611 | 612 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 613 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 614 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 615 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 616 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 617 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 618 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 619 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 620 | 621 | 16. Limitation of Liability. 622 | 623 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 624 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 625 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 626 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 627 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 628 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 629 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 630 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 631 | SUCH DAMAGES. 632 | 633 | 17. Interpretation of Sections 15 and 16. 634 | 635 | If the disclaimer of warranty and limitation of liability provided 636 | above cannot be given local legal effect according to their terms, 637 | reviewing courts shall apply local law that most closely approximates 638 | an absolute waiver of all civil liability in connection with the 639 | Program, unless a warranty or assumption of liability accompanies a 640 | copy of the Program in return for a fee. 641 | 642 | END OF TERMS AND CONDITIONS 643 | 644 | -------------------------------------------------------------------------------- /transabyss: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # written by Ka Ming Nip 4 | # Copyright 2018 Canada's Michael Smith Genome Sciences Centre 5 | 6 | import argparse 7 | import glob 8 | import math 9 | import multiprocessing 10 | import os 11 | import shutil 12 | import string 13 | import sys 14 | import textwrap 15 | import time 16 | from utilities import package_info 17 | from utilities import psl_cid_extractor 18 | from utilities.adj_utils import has_edges 19 | from utilities.adj_utils import remove_redundant_paths 20 | from utilities.adj_utils import unbraid 21 | from utilities.adj_utils import walk 22 | from utilities.common_utils import StopWatch 23 | from utilities.common_utils import check_env 24 | from utilities.common_utils import is_empty_txt 25 | from utilities.common_utils import log 26 | from utilities.common_utils import path_action 27 | from utilities.common_utils import paths_action 28 | from utilities.common_utils import run_shell_cmd 29 | from utilities.common_utils import threshold_action 30 | from utilities.common_utils import touch 31 | from utilities.fasta_utils import abyssmap_merge_fastas 32 | from utilities.fasta_utils import blat_merge_fastas 33 | from utilities.fasta_utils import blat_self_align 34 | from utilities.fasta_utils import filter_fasta 35 | 36 | 37 | TRANSABYSS_VERSION = package_info.VERSION 38 | TRANSABYSS_NAME = package_info.NAME 39 | 40 | STAGE_DBG_STAMP = "DBG.COMPLETE" 41 | STAGE_UNITIGS_STAMP = "UNITIGS.COMPLETE" 42 | STAGE_CONTIGS_STAMP = "CONTIGS.COMPLETE" 43 | STAGE_REFERENCES_STAMP = "REFERENCES.COMPLETE" 44 | STAGE_JUNCTIONS_STAMP = "JUNCTIONS.COMPLETE" 45 | STAGE_FINAL_STAMP = "FINAL.COMPLETE" 46 | STAGE_DEPENDENCY = [STAGE_FINAL_STAMP, STAGE_JUNCTIONS_STAMP, STAGE_REFERENCES_STAMP, STAGE_CONTIGS_STAMP, STAGE_UNITIGS_STAMP, STAGE_DBG_STAMP] 47 | 48 | STAGE_DBG = 'dbg' 49 | STAGE_UNITIGS = 'unitigs' 50 | STAGE_CONTIGS = 'contigs' 51 | STAGE_REFERENCES = 'references' 52 | STAGE_JUNCTIONS = 'junctions' 53 | STAGE_FINAL = 'final' 54 | STAGES = [STAGE_DBG, STAGE_UNITIGS, STAGE_CONTIGS, STAGE_REFERENCES, STAGE_JUNCTIONS, STAGE_FINAL] 55 | 56 | PACKAGEDIR = package_info.PACKAGEDIR 57 | BINDIR = package_info.BINDIR 58 | SKIP_PSL_SELF = os.path.join(BINDIR, 'skip_psl_self.awk') 59 | SKIP_PSL_SELF_SS = os.path.join(BINDIR, 'skip_psl_self_ss.awk') 60 | 61 | REQUIRED_EXECUTABLES = ['abyss-pe', 'MergeContigs', 'abyss-filtergraph', 'abyss-junction', 'blat', 'abyss-map'] 62 | REQUIRED_SCRIPTS = [SKIP_PSL_SELF, SKIP_PSL_SELF_SS] 63 | 64 | def defaultwd(): 65 | """Return the default output directory. 66 | """ 67 | 68 | return os.path.join(os.getcwd(), "transabyss_" + TRANSABYSS_VERSION + "_assembly") 69 | #enddef 70 | 71 | def compare_stages(stage1, stage2): 72 | return STAGES.index(stage2) - STAGES.index(stage1) 73 | #enddef 74 | 75 | def check_stamp(prefix, stamp): 76 | """Check whether the stamp and any downstream stamp(s) already exist. 77 | """ 78 | 79 | for s in STAGE_DEPENDENCY: 80 | if s == stamp: 81 | return os.path.exists(prefix + '.' + s) 82 | else: 83 | if os.path.exists(prefix + '.' + s): 84 | # This downstream stage is already done. 85 | return True 86 | #endif 87 | #endif 88 | #endfor 89 | 90 | return False 91 | #enddef 92 | 93 | def make_stamp(prefix, stamp): 94 | """Create the stamp. 95 | """ 96 | 97 | touch(prefix + '.' + stamp) 98 | #enddef 99 | 100 | def required_files_exist(files): 101 | """Verify the required files exist; quit the program otherwise. 102 | """ 103 | 104 | missing = [] 105 | 106 | for f in files: 107 | if not os.path.exists(f): 108 | missing.append(f) 109 | #endif 110 | #endfor 111 | 112 | if len(missing) > 0: 113 | log('ERROR: Cannot find:\n' + '\n'.join(missing)) 114 | sys.exit(1) 115 | #endif 116 | #enddef 117 | 118 | def dbg_assembly(reads, outdir, q=3, Q=None, k=32, name='transabyss', cov=2, threads=1, mpi_np=0, strand_specific=False, E=0, e=2): 119 | """Generate the initial De Bruijn graph assembly with ABySS. 120 | """ 121 | 122 | # Generate *-1.fa, *-1.adj, *-bubbles.fa, coverage.hist 123 | cmd_params = ['abyss-pe', 'graph=adj', '--directory=%s' % outdir, 'k=%d' % k, 'name=%s' % name, 'E=%d' % E, 'e=%d' % e, 'c=%d' % cov, 'j=%d' % threads, '%s-1.fa' % name, '%s-1.adj' % name] 124 | 125 | if q: 126 | cmd_params.append('q=%d' % q) 127 | #endif 128 | 129 | if Q: 130 | cmd_params.append('Q=%d' % Q) 131 | #endif 132 | 133 | if strand_specific: 134 | cmd_params.append('SS=--SS') 135 | #endif 136 | 137 | # Specify the number of MPI processes 138 | if mpi_np > 0: 139 | cmd_params.append('np=%d' % mpi_np) 140 | #endif 141 | 142 | # Specify the input reads for sequence content of the assembly 143 | cmd_params.append('se="%s"' % ' '.join(reads)) 144 | 145 | run_shell_cmd(' '.join(cmd_params)) 146 | #enddef 147 | 148 | def abyss_merge_contigs(in_fasta, in_adj, in_path, out_fasta, k=32, merged_only=False): 149 | """Run MergeContigs for the given paths. 150 | """ 151 | 152 | cmd_params = ['MergeContigs', '--kmer=%d' % k, '--out=%s' % out_fasta] 153 | if merged_only: 154 | cmd_params.append('--merged') 155 | #endif 156 | cmd_params.extend([in_fasta, in_adj, in_path]) 157 | run_shell_cmd(' '.join(cmd_params)) 158 | #enddef 159 | 160 | def abyss_merge_contigs_adj(in_fasta, in_adj, in_path, out_fasta, out_adj, k=32, merged_only=False): 161 | """Run MergeContigs for the given paths. 162 | """ 163 | 164 | cmd_params = ['MergeContigs', '--kmer=%d' % k, '--out=%s' % out_fasta, '--adj --graph=%s' % out_adj] 165 | if merged_only: 166 | cmd_params.append('--merged') 167 | #endif 168 | cmd_params.extend([in_fasta, in_adj, in_path]) 169 | run_shell_cmd(' '.join(cmd_params)) 170 | #enddef 171 | 172 | def get_skip_psl_self_awk_script_path(strand_specific=False): 173 | skip_psl_self_awk = None 174 | if strand_specific: 175 | assert os.path.isfile(SKIP_PSL_SELF_SS) 176 | skip_psl_self_awk = SKIP_PSL_SELF_SS 177 | elif not strand_specific: 178 | assert os.path.isfile(SKIP_PSL_SELF) 179 | skip_psl_self_awk = SKIP_PSL_SELF 180 | #endif 181 | return skip_psl_self_awk 182 | #enddef 183 | 184 | def unitig_assembly(in_fasta, in_adj, out_fasta, out_adj, tmp_file_prefix, island_size, max_iteration=2, k=32, strand_specific=False, min_percent_identity=0.95, indel_size_tolerance=1, seed_cov_grad=0.05, threads=1, useblat=False): 185 | """Generate the unitig assembly with multiple iterations of adjacency graph simplification. 186 | """ 187 | 188 | i = 1 189 | if max_iteration > 0: 190 | last_good_adj = in_adj 191 | last_good_fasta = in_fasta 192 | 193 | while i <= max_iteration: 194 | iteration_prefix = tmp_file_prefix + 'r' + str(i) 195 | iteration_stamp = iteration_prefix + '.COMPLETE' 196 | fasta2 = iteration_prefix + '.filtered.fa' 197 | adj2 = iteration_prefix + '.filtered.adj' 198 | 199 | if os.path.exists(iteration_stamp): 200 | log('CHECKPOINT: Iteration %d of graph simplification was done previously. Will not re-run ...' % i) 201 | else: 202 | log('Iteration %d of graph simplification ...' % i) 203 | 204 | ref_path1 = iteration_prefix + '.ref.path' 205 | braid_cids1 = iteration_prefix + '.braid.cids' 206 | ref_fasta1 = iteration_prefix + '.ref.fa' 207 | ref_fasta1_selfalign_psl = ref_fasta1 + '.selfalign.psl' 208 | 209 | if not has_edges(last_good_adj): 210 | # ADJ file has no edges. No more simplification. 211 | log('WARNING: ADJ (%s) has no edges; no graph simplification can be done.' % os.path.basename(last_good_adj)) 212 | break 213 | #endif 214 | 215 | # Identify braids and generate reference paths 216 | walked, marked = unbraid(last_good_adj, k, ref_path1, braid_cids1, strand_specific=strand_specific, cov_gradient=seed_cov_grad, length_diff_tolerance=indel_size_tolerance) 217 | log('Walked %d paths and marked %d vertices for removal.' % (walked, (marked if strand_specific else 2*marked))) 218 | 219 | remove_cids1 = braid_cids1 220 | have_braids = marked > 0 221 | have_rpaths = False 222 | 223 | if useblat: 224 | log('Redundancy removal with BLAT ...') 225 | 226 | # Generate fasta for reference paths and islands 227 | abyss_merge_contigs(last_good_fasta, last_good_adj, ref_path1, ref_fasta1, k=k) 228 | 229 | # Self-align reference fasta with BLAT 230 | blat_self_align(ref_fasta1, ref_fasta1_selfalign_psl, percent_id=min_percent_identity, max_consecutive_edits=indel_size_tolerance, min_seq_len=k, threads=threads, skip_psl_self_awk=get_skip_psl_self_awk_script_path(strand_specific=strand_specific)) 231 | 232 | # Identify redundant references 233 | rrefs = psl_cid_extractor.extract_cids(psl=ref_fasta1_selfalign_psl, samestrand=strand_specific, min_percent_identity=min_percent_identity, max_consecutive_edits=indel_size_tolerance, report_redundant=True) 234 | 235 | log('%d potentially removable paths ...' % len(rrefs)) 236 | 237 | have_rpaths = len(rrefs) > 0 238 | 239 | if have_rpaths: 240 | # Evaluate potentially removable paths, generate a list of ids of removable sequences. 241 | remove_cids1 = iteration_prefix + '.rm.cids' 242 | marked = remove_redundant_paths(rrefs, last_good_adj, k, braid_cids1, ref_path1, remove_cids1, strand_specific=strand_specific) 243 | log('Marked %d more vertices for removal.' % (marked if strand_specific else 2*marked)) 244 | rrefs = None 245 | elif not have_braids: 246 | # No potentially removable paths and no braids, this is the last iteration! 247 | log('No removable paths ...') 248 | break 249 | else: 250 | # No potentially removable paths, but we have braids. So, continue! 251 | log('No removable paths ...') 252 | #endif 253 | #endif 254 | 255 | # Generate *.filtered.adj1, *.path 256 | path1 = iteration_prefix + '.path' 257 | adj2_tmp1 = adj2 + '1' 258 | remove_rref_cmd_params1 = ['abyss-filtergraph --shim --assemble', '--kmer=%d' % k, '--island=%d' % island_size, '--remove=%s' % remove_cids1, '--graph=%s' % adj2_tmp1] 259 | 260 | if strand_specific: 261 | remove_rref_cmd_params1.append('--SS') 262 | #endif 263 | 264 | remove_rref_cmd_params1.append(last_good_adj) 265 | remove_rref_cmd_params1.append(last_good_fasta) 266 | 267 | remove_rref_cmd_params1.append('> %s' % path1) 268 | 269 | run_shell_cmd(' '.join(remove_rref_cmd_params1)) 270 | 271 | # Generate *.filtered.fa, *.filtered.adj 272 | abyss_merge_contigs_adj(last_good_fasta, adj2_tmp1, path1, fasta2, adj2, k=k) 273 | 274 | touch(iteration_stamp) 275 | log('Completed iteration %d of graph simplification.' % i) 276 | #endif 277 | 278 | last_good_adj = adj2 279 | last_good_fasta = fasta2 280 | i += 1 281 | #endwhile 282 | log('Graph simplification stopped at iteration %d' % i) 283 | 284 | if last_good_adj == in_adj: 285 | shutil.copy(in_adj, out_adj) 286 | else: 287 | shutil.move(last_good_adj, out_adj) 288 | #endif 289 | 290 | if last_good_fasta == in_fasta: 291 | shutil.copy(in_fasta, out_fasta) 292 | else: 293 | shutil.move(last_good_fasta, out_fasta) 294 | #endif 295 | 296 | else: 297 | log('Graph simplification has been turned off ...') 298 | 299 | shutil.copy(in_adj, out_adj) 300 | shutil.copy(in_fasta, out_fasta) 301 | #endif 302 | 303 | #enddef 304 | 305 | def reference_assembly(in_fasta, in_adj, ref_path, ref_fasta, k=32, strand_specific=False, seed_cov_grad=0.05, in_dist=None): 306 | """Generate an assembly of reference paths. 307 | """ 308 | 309 | if has_edges(in_adj): 310 | walked = walk(in_adj, k, ref_path, strand_specific=strand_specific, cov_gradient=seed_cov_grad, dist_file=in_dist) 311 | log('Walked %d paths.' % walked) 312 | abyss_merge_contigs(in_fasta, in_adj, ref_path, ref_fasta, k=k, merged_only=True) 313 | else: 314 | log('WARNING: ADJ (%s) has no edges; no reference paths to assemble.' % os.path.basename(in_adj)) 315 | # Create the empty dummy files. 316 | touch(ref_fasta) 317 | touch(ref_path) 318 | #endif 319 | #enddef 320 | 321 | def contig_assembly(pe_reads, outdir, k=32, n=2, name='transabyss', threads=1, strand_specific=False, s=32): 322 | """Generate the contig assembly with ABySS. 323 | """ 324 | 325 | # List of abyss-pe parameters for paired-end transcriptome assembly 326 | pe_assembly_params = ['l=%d' % k, 's=%d' % s, 'n=%d' % n, 'SIMPLEGRAPH_OPTIONS="--no-scaffold"', 'OVERLAP_OPTIONS="--no-scaffold"', 'MERGEPATH_OPTIONS="--greedy"'] 327 | 328 | cmd_params = ['abyss-pe', 'graph=adj', '--directory=%s' % outdir, 'k=%d' % k, 'name=%s' % name, 'j=%d' % threads, 'in="%s"' % ' '.join(pe_reads)] 329 | 330 | if strand_specific: 331 | cmd_params.append('SS=--SS') 332 | #endif 333 | 334 | cmd_params.extend(pe_assembly_params) 335 | cmd_params.append('%s-6.fa' % name) 336 | run_shell_cmd(' '.join(cmd_params)) 337 | #enddef 338 | 339 | def junction_extension(in_adj, in_fasta, out_path, out_fasta, k=32, dist=None): 340 | """Extend junctions for the given adjacency graph. 341 | """ 342 | 343 | if has_edges(in_adj): 344 | jn_cmd_params = ['abyss-junction', in_adj] 345 | if dist: 346 | jn_cmd_params.append(dist) 347 | #endif 348 | jn_cmd_params.append(' >' + out_path) 349 | run_shell_cmd(' '.join(jn_cmd_params)) 350 | 351 | abyss_merge_contigs(in_fasta, in_adj, out_path, out_fasta, k=k, merged_only=True) 352 | else: 353 | log('WARNING: ADJ (%s) has no edges; no junction paths to assemble.' % os.path.basename(in_adj)) 354 | # Create the empty dummy files. 355 | touch(out_fasta) 356 | touch(out_path) 357 | #endif 358 | #enddef 359 | 360 | def clean_up(stage_files_dict, level=0): 361 | """Clean up intermediate files for the stages less than or equal to the specified level. 362 | """ 363 | 364 | for l in sorted(stage_files_dict): 365 | if l <= level: 366 | for tmpfile in stage_files_dict[l]: 367 | if os.path.isfile(tmpfile): 368 | os.remove(tmpfile) 369 | #endif 370 | #endfor 371 | #endif 372 | #endfor 373 | #enddef 374 | 375 | def __main__(): 376 | parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, 377 | description='Assemble RNAseq with Trans-ABySS.', 378 | epilog=textwrap.dedent(package_info.SUPPORT_INFO) 379 | ) 380 | 381 | parser.add_argument('--version', action='version', version=TRANSABYSS_VERSION) 382 | 383 | input_group = parser.add_argument_group("Input") 384 | input_group.add_argument('--se', dest='se_reads', metavar='PATH', type=str, nargs='+', help='single-end read files', action=paths_action(check_exist=True)) 385 | input_group.add_argument('--pe', dest='pe_reads', metavar='PATH', type=str, nargs='+', help='paired-end read files', action=paths_action(check_exist=True)) 386 | input_group.add_argument('--SS', dest='stranded', help='input reads are strand-specific', action='store_true', default=False) 387 | 388 | general_group = parser.add_argument_group("Basic Options") 389 | general_group.add_argument('--outdir', dest='outdir', help='output directory [%(default)s]', metavar='PATH', type=str, default=defaultwd(), action=path_action(check_exist=False)) 390 | general_group.add_argument('--name', dest='name', help='assembly name [%(default)s] (ie. output assembly: \'%(default)s-final.fa\')', metavar='STR', type=str, default="transabyss") 391 | general_group.add_argument('--stage', dest='stage', choices=STAGES, help='run up to the specified stage [%(default)s]', type=str, default=STAGE_FINAL) 392 | general_group.add_argument('--length', dest='length', help='minimum output sequence length [%(default)s]', metavar='INT', type=int, default=100, action=threshold_action(0, inequality='>=')) 393 | general_group.add_argument('--cleanup', dest='cleanup', choices=[0, 1, 2, 3], help='level of clean-up of intermediate files [%(default)s]', type=int, default=1) 394 | #parser.add_argument('--verbose', dest='verbose', choices=[0, 1, 2], help='verbosity level 0,1,2 [%(default)s]', type=int, default=0) 395 | 396 | abyss_group = parser.add_argument_group("ABySS Parameters") 397 | abyss_group.add_argument('--threads', dest='threads', help='number of threads (\'j\' in abyss-pe) [%(default)s]', metavar='INT', type=int, default=1, action=threshold_action(1, inequality='>=')) 398 | abyss_group.add_argument('--mpi', dest='mpi', help='number of MPI processes (\'np\' in abyss-pe) [%(default)s]', metavar='INT', type=int, default=0, action=threshold_action(0, inequality='>=')) 399 | abyss_group.add_argument('-k', '--kmer', dest='k', help='k-mer size [%(default)s]', metavar='INT', type=int, default=32, action=threshold_action(1, inequality='>=')) 400 | abyss_group.add_argument('-c', '--cov', dest='c', help='minimum mean k-mer coverage of a unitig [%(default)s]', metavar='INT', type=int, default=2, action=threshold_action(0, inequality='>=')) 401 | abyss_group.add_argument('-e', '--eros', dest='e', help='minimum erosion k-mer coverage [c]', metavar='INT', type=int, action=threshold_action(0, inequality='>=')) 402 | abyss_group.add_argument('-E', '--seros', dest='E', help='minimum erosion k-mer coverage per strand [%(default)s]', metavar='INT', type=int, default=0, action=threshold_action(0, inequality='>=')) 403 | abyss_group.add_argument('-q', '--qends', dest='q', help='minimum base quality on 5\' and 3\' ends of a read [%(default)s]', metavar='INT', type=int, default=3, action=threshold_action(0, inequality='>=')) 404 | abyss_group.add_argument('-Q', '--qall', dest='Q', help='minimum base quality throughout a read', metavar='INT', type=int, action=threshold_action(0, inequality='>=')) 405 | abyss_group.add_argument('-n', '--pairs', dest='n', help='minimum number of pairs for building contigs [%(default)s]', metavar='INT', type=int, default=2, action=threshold_action(1, inequality='>=')) 406 | abyss_group.add_argument('-s', '--seed', dest='s', help='minimum unitig size for building contigs [k]', metavar='INT', type=int, action=threshold_action(0, inequality='>=')) 407 | 408 | graph_group = parser.add_argument_group("Advanced Options") 409 | graph_group.add_argument('--gsim', dest='iterations', help='maximum iterations of graph simplification [%(default)s]', metavar='INT', type=int, default=2, action=threshold_action(0, inequality='>=')) 410 | graph_group.add_argument('--indel', dest='indel', help='indel size tolerance [%(default)s]', metavar='INT', type=int, default=1, action=threshold_action(0, inequality='>=')) 411 | graph_group.add_argument('--island', dest='island', help='minimum length of island unitigs [%(default)s]', metavar='INT', type=int, default=0, action=threshold_action(0, inequality='>=')) 412 | graph_group.add_argument('--useblat', dest='useblat', help='use BLAT alignments to remove redundant sequences.', action='store_true', default=False) 413 | #graph_group.add_argument('--overlap', dest='overlap', help='minimum overlap to merge contigs [2*k]', metavar='INT', type=int, action=threshold_action(0, inequality='>=')) 414 | graph_group.add_argument('--pid', dest='p', help='minimum percent sequence identity of redundant sequences [%(default)s]', metavar='FLOAT', type=float, default=0.95, action=threshold_action(0.9, inequality='>=')) 415 | graph_group.add_argument('--walk', dest='walk', help='percentage of mean k-mer coverage of seed for path-walking [%(default)s]', metavar='FLOAT', type=float, default=0.05, action=threshold_action(0.0, inequality='>=')) 416 | graph_group.add_argument('--noref', dest='noref', help='do not include reference paths in final assembly', action='store_true', default=False) 417 | 418 | args = parser.parse_args() 419 | 420 | log(TRANSABYSS_NAME + ' ' + TRANSABYSS_VERSION) 421 | log('CMD: ' + ' '.join(sys.argv)) 422 | log('=-' * 30) 423 | 424 | # Check environment and required paths 425 | if not check_env(executables=REQUIRED_EXECUTABLES, scripts=REQUIRED_SCRIPTS): 426 | log('ERROR: Your environment is not sufficient to run Trans-ABySS. Please check the missing executables, scripts, or directories.') 427 | sys.exit(1) 428 | #endif 429 | 430 | # Set default threads 431 | cpu_count = multiprocessing.cpu_count() 432 | log("# CPU(s) available:\t" + str(cpu_count)) 433 | log("# thread(s) requested:\t" + str(args.threads)) 434 | args.threads = min(cpu_count, args.threads) 435 | log("# thread(s) to use:\t" + str(args.threads)) 436 | 437 | # Set default erosion threshold 438 | if args.e is None: 439 | args.e = args.c 440 | #endif 441 | 442 | # Set default seed size 443 | if args.s is None: 444 | args.s = args.k 445 | #endif 446 | 447 | # Extract the absolute path of each input read file 448 | se_reads = [] 449 | pe_reads = [] 450 | all_reads = [] 451 | 452 | if args.se_reads is not None: 453 | for path in args.se_reads: 454 | if os.path.exists(path): 455 | se_reads.append(os.path.abspath(path)) 456 | else: 457 | log('ERROR: No such single-end reads file \'' + path + '\'') 458 | sys.exit(1) 459 | #endif 460 | #endfor 461 | #endif 462 | 463 | if args.pe_reads is not None: 464 | for path in args.pe_reads: 465 | if os.path.exists(path): 466 | pe_reads.append(os.path.abspath(path)) 467 | else: 468 | log('ERROR: No such paired-end reads file \'' + path + '\'') 469 | sys.exit(1) 470 | #endif 471 | #endfor 472 | #endif 473 | 474 | all_reads.extend(pe_reads) 475 | all_reads.extend(se_reads) 476 | 477 | if len(se_reads) == 0 and len(pe_reads) == 0: 478 | log("ERROR: No input reads specified! Use option '--pe' to specify paired-end reads and/or option '--se' to specify single-end reads.") 479 | sys.exit(1) 480 | #endif 481 | 482 | # Create the output directory if it does not already exist 483 | if not os.path.isdir(args.outdir): 484 | log("Creating output directory: %s" % args.outdir) 485 | os.makedirs(args.outdir) 486 | #endif 487 | 488 | # The path prefix of all output files 489 | prefix = os.path.join(args.outdir, args.name) 490 | 491 | tmpfiles1 = [] 492 | tmpfiles2 = [] 493 | tmpfiles3 = [] 494 | 495 | # Start the stop watch 496 | stopwatch = StopWatch() 497 | 498 | remaining_stages = compare_stages(STAGE_DBG, args.stage) 499 | if remaining_stages >= 0: 500 | # CHECKPOINT DBG 501 | if check_stamp(prefix, STAGE_DBG_STAMP): 502 | log('CHECKPOINT: De Bruijn graph assembly was done previously. Will not re-run ...') 503 | else: 504 | # Generate *-1.fa, *-1.adj, *-bubbles.fa, coverage.hist 505 | dbg_assembly(all_reads, args.outdir, q=args.q, Q=args.Q, k=args.k, name=args.name, cov=args.c, threads=args.threads, mpi_np=args.mpi, strand_specific=args.stranded, E=args.E, e=args.e) 506 | make_stamp(prefix, STAGE_DBG_STAMP) 507 | log('CHECKPOINT: De Bruijn graph assembly completed.') 508 | #endif 509 | 510 | if remaining_stages == 0: 511 | log('=-' * 30) 512 | log('Assembly stopped at stage \'%s\'' % STAGE_DBG) 513 | log('Total wallclock run time: %d h %d m %d s' % (stopwatch.stop())) 514 | #endif 515 | #endif 516 | 517 | adj1 = prefix + '-1.adj' 518 | fasta1 = prefix + '-1.fa' 519 | bubbles1 = prefix + '-bubbles.fa' 520 | coverage_hist = os.path.join(args.outdir, 'coverage.hist') 521 | 522 | tmpfiles3.extend([adj1, fasta1, bubbles1, coverage_hist]) 523 | 524 | last_good_adj = adj1 525 | last_good_fasta = fasta1 526 | adj3 = prefix + '-3.adj' 527 | fasta3 = prefix + '-3.fa' 528 | tmp_file_prefix = prefix + '-unitigs.' 529 | 530 | remaining_stages = compare_stages(STAGE_UNITIGS, args.stage) 531 | if remaining_stages >= 0: 532 | # CHECKPOINT: UNITIGS 533 | if check_stamp(prefix, STAGE_UNITIGS_STAMP): 534 | log('CHECKPOINT: Unitig assembly was done previously. Will not re-run ...') 535 | else: 536 | required_files_exist([fasta1, adj1]) 537 | unitig_assembly(fasta1, adj1, fasta3, adj3, tmp_file_prefix, island_size=args.island, max_iteration=args.iterations, k=args.k, strand_specific=args.stranded, min_percent_identity=args.p, seed_cov_grad=args.walk, indel_size_tolerance=args.indel, threads=args.threads, useblat=args.useblat) 538 | make_stamp(prefix, STAGE_UNITIGS_STAMP) 539 | log('CHECKPOINT: Unitig assembly completed.') 540 | #endif 541 | 542 | if remaining_stages == 0: 543 | log('=-' * 30) 544 | log('Assembly stopped at stage \'%s\'' % STAGE_UNITIGS) 545 | log('Total wallclock run time: %d h %d m %d s' % (stopwatch.stop())) 546 | #endif 547 | #endif 548 | 549 | tmpfiles1.extend(glob.glob(tmp_file_prefix + '*')) 550 | 551 | ref_fasta = prefix + '-ref.fa' 552 | ref_path = prefix + '-ref.path' 553 | pathj = prefix + '-jn.path' 554 | fastaj = prefix + '-jn.fa' 555 | std_assembly = None 556 | 557 | perform_pe_assembly = len(pe_reads) > 0 558 | 559 | if perform_pe_assembly and not has_edges(adj3): 560 | log('WARNING: ADJ (%s) has no edges; will not perform paired-end assembly.' % os.path.basename(adj3)) 561 | perform_pe_assembly = False 562 | #endif 563 | 564 | if perform_pe_assembly: 565 | # have paired-end reads 566 | 567 | std_assembly = prefix + '-6.fa' 568 | adj5 = prefix + '-5.adj' 569 | dist3 = prefix + '-3.dist' 570 | 571 | remaining_stages = compare_stages(STAGE_CONTIGS, args.stage) 572 | if remaining_stages >= 0: 573 | # CHECKPOINT: CONTIGS 574 | if check_stamp(prefix, STAGE_CONTIGS_STAMP): 575 | log('CHECKPOINT: Contig assembly was done previously. Will not re-run ...') 576 | else: 577 | required_files_exist([fasta3, adj3]) 578 | contig_assembly(pe_reads, args.outdir, k=args.k, n=args.n, name=args.name, threads=args.threads, strand_specific=args.stranded, s=args.s) 579 | make_stamp(prefix, STAGE_CONTIGS_STAMP) 580 | log('CHECKPOINT: Contig assembly completed.') 581 | #endif 582 | 583 | if remaining_stages == 0: 584 | log('=-' * 30) 585 | log('Assembly stopped at stage \'%s\'' % STAGE_CONTIGS) 586 | log('Total wallclock run time: %d h %d m %d s' % (stopwatch.stop())) 587 | #endif 588 | #endif 589 | 590 | remaining_stages = compare_stages(STAGE_REFERENCES, args.stage) 591 | if remaining_stages >= 0: 592 | # CHECKPOINT: REFERENCES 593 | if check_stamp(prefix, STAGE_REFERENCES_STAMP): 594 | log('CHECKPOINT: Reference path assembly was done previously. Will not re-run ...') 595 | else: 596 | # reference assembly 597 | required_files_exist([fasta3, adj5]) 598 | reference_assembly(fasta3, adj5, ref_path, ref_fasta, k=args.k, strand_specific=args.stranded, seed_cov_grad=args.walk, in_dist=dist3) 599 | make_stamp(prefix, STAGE_REFERENCES_STAMP) 600 | log('CHECKPOINT: Reference path assembly completed.') 601 | #endif 602 | 603 | if remaining_stages == 0: 604 | log('=-' * 30) 605 | log('Assembly stopped at stage \'%s\'' % STAGE_REFERENCES) 606 | log('Total wallclock run time: %d h %d m %d s' % (stopwatch.stop())) 607 | #endif 608 | #endif 609 | 610 | remaining_stages = compare_stages(STAGE_JUNCTIONS, args.stage) 611 | if remaining_stages >= 0: 612 | # CHECKPOINT: JUNCTIONS 613 | if check_stamp(prefix, STAGE_JUNCTIONS_STAMP): 614 | log('CHECKPOINT: Junction extension was done previously. Will not re-run ...') 615 | else: 616 | # Extend PE junctions 617 | required_files_exist([fasta3, adj5]) 618 | junction_extension(adj5, fasta3, pathj, fastaj, k=args.k, dist=dist3) 619 | make_stamp(prefix, STAGE_JUNCTIONS_STAMP) 620 | log('CHECKPOINT: Junction extension completed.') 621 | #endif 622 | 623 | if remaining_stages == 0: 624 | log('=-' * 30) 625 | log('Assembly stopped at stage \'%s\'' % STAGE_JUNCTIONS) 626 | log('Total wallclock run time: %d h %d m %d s' % (stopwatch.stop())) 627 | #endif 628 | #endif 629 | 630 | tmpfiles2.extend([adj5, dist3]) 631 | for suffix in ['-3.hist', '-4.fa', '-4.adj', '-4.path1', '-4.path2', '-4.path3', '-5.fa', '-5.path']: 632 | tmpfiles2.append(prefix + suffix) 633 | #endfor 634 | else: 635 | # no paired-end reads 636 | 637 | std_assembly = fasta3 638 | 639 | remaining_stages = compare_stages(STAGE_REFERENCES, args.stage) 640 | if remaining_stages >= 0: 641 | # CHECKPOINT: REFERENCES 642 | if check_stamp(prefix, STAGE_REFERENCES_STAMP): 643 | log('CHECKPOINT: Reference path assembly was done previously. Will not re-run ...') 644 | else: 645 | # reference assembly 646 | required_files_exist([fasta3, adj3]) 647 | reference_assembly(fasta3, adj3, ref_path, ref_fasta, k=args.k, strand_specific=args.stranded, seed_cov_grad=args.walk) 648 | make_stamp(prefix, STAGE_REFERENCES_STAMP) 649 | log('CHECKPOINT: Reference path assembly completed.') 650 | #endif 651 | 652 | if remaining_stages == 0: 653 | log('=-' * 30) 654 | log('Assembly stopped at stage \'%s\'' % STAGE_REFERENCES) 655 | log('Total wallclock run time: %d h %d m %d s' % (stopwatch.stop())) 656 | #endif 657 | #endif 658 | 659 | remaining_stages = compare_stages(STAGE_JUNCTIONS, args.stage) 660 | if remaining_stages >= 0: 661 | # CHECKPOINT: JUNCTIONS 662 | if check_stamp(prefix, STAGE_JUNCTIONS_STAMP): 663 | log('CHECKPOINT: Junction extension was done previously. Will not re-run ...') 664 | else: 665 | # Extend SE junctions 666 | required_files_exist([fasta3, adj3]) 667 | junction_extension(adj3, fasta3, pathj, fastaj, k=args.k) 668 | make_stamp(prefix, STAGE_JUNCTIONS_STAMP) 669 | log('CHECKPOINT: Junction extension completed.') 670 | #endif 671 | 672 | if remaining_stages == 0: 673 | log('=-' * 30) 674 | log('Assembly stopped at stage \'%s\'' % STAGE_JUNCTIONS) 675 | log('Total wallclock run time: %d h %d m %d s' % (stopwatch.stop())) 676 | #endif 677 | #endif 678 | #endif 679 | 680 | tmpfiles2.extend([pathj, fastaj, std_assembly]) 681 | 682 | fastac = prefix + '-concat.fa' 683 | fastaf = prefix + '-final.fa' 684 | fastac_selfalign_psl = fastac + '.selfalign.psl' 685 | 686 | remaining_stages = compare_stages(STAGE_FINAL, args.stage) 687 | if remaining_stages >= 0: 688 | # CHECKPOINT: FINAL 689 | if check_stamp(prefix, STAGE_FINAL_STAMP): 690 | log('CHECKPOINT: Final assembly was done previously. Will not re-run ...') 691 | else: 692 | # Concatenate -3.fa/-6.fa, -jn.fa (and -ref.fa) to concat.fa 693 | required_files = [std_assembly, fastaj] 694 | path_prefix_map = {'S':std_assembly, 'J':fastaj} 695 | 696 | if not args.noref: 697 | # include sequences from -ref.fa in the final assembly 698 | required_files.append(ref_fasta) 699 | path_prefix_map['R'] = ref_fasta 700 | #endif 701 | 702 | required_files_exist(required_files) 703 | 704 | if args.length is not None and args.length > args.k: 705 | # Since the shortest assembled sequence *always* has a length >= k, we only filter if theshold > k. 706 | fastaf_all = prefix + '-final.all.fa' 707 | tmpfiles1.append(fastaf_all) 708 | if args.useblat: 709 | log('Using BLAT to remove redundancy ...') 710 | 711 | blat_merge_fastas(path_prefix_map, fastaf_all, concat_fa=fastac, concat_fa_selfalign_psl=fastac_selfalign_psl, percent_identity=args.p, strand_specific=args.stranded, indel_size_tolerance=args.indel, min_seq_len=args.k, minoverlap=0, threads=args.threads, cleanup=args.cleanup>0, skip_psl_self_awk=get_skip_psl_self_awk_script_path(strand_specific=args.stranded)) 712 | else: 713 | log('Using abyss-map to remove redundancy ...') 714 | abyssmap_merge_fastas(path_prefix_map, fastaf_all, concat_fa=fastac, strand_specific=args.stranded, cleanup=args.cleanup>0, threads=args.threads, iterative=False) 715 | #endif 716 | 717 | log('Removing sequences shorter than %d ...' % args.length) 718 | filter_fasta(fastaf_all, fastaf, min_length=args.length) 719 | else: 720 | # Keep all sequences 721 | if args.useblat: 722 | log('Using BLAT to remove redundancy ...') 723 | 724 | blat_merge_fastas(path_prefix_map, fastaf, concat_fa=fastac, concat_fa_selfalign_psl=fastac_selfalign_psl, percent_identity=args.p, strand_specific=args.stranded, indel_size_tolerance=args.indel, min_seq_len=args.k, minoverlap=0, threads=args.threads, cleanup=args.cleanup>0, skip_psl_self_awk=get_skip_psl_self_awk_script_path(strand_specific=args.stranded)) 725 | else: 726 | log('Using abyss-map to remove redundancy ...') 727 | abyssmap_merge_fastas(path_prefix_map, fastaf, concat_fa=fastac, strand_specific=args.stranded, cleanup=args.cleanup>0, threads=args.threads, iterative=False) 728 | #endif 729 | #endif 730 | 731 | make_stamp(prefix, STAGE_FINAL_STAMP) 732 | log('CHECKPOINT: Final assembly completed.') 733 | #endif 734 | 735 | if remaining_stages == 0: 736 | log('=-' * 30) 737 | log('Assembly generated with %s %s :)' % (TRANSABYSS_NAME, TRANSABYSS_VERSION)) 738 | log('Final assembly: ' + fastaf) 739 | log('Total wallclock run time: %d h %d m %d s' % (stopwatch.stop())) 740 | #endif 741 | #endif 742 | 743 | tmpfiles1.append(fastac) 744 | tmpfiles1.append(fastac_selfalign_psl) 745 | 746 | # Clean up intermediate files 747 | if args.cleanup > 0: 748 | clean_up({1:tmpfiles1, 2:tmpfiles2, 3:tmpfiles3}, level=args.cleanup) 749 | #endif 750 | 751 | #enddef 752 | 753 | if __name__ == '__main__': 754 | __main__() 755 | #endif 756 | 757 | #EOF 758 | -------------------------------------------------------------------------------- /utilities/adj_utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # written by Ka Ming Nip 4 | # Copyright 2014 Canada's Michael Smith Genome Sciences Centre 5 | 6 | import igraph 7 | import operator 8 | import re 9 | from igraph import Graph 10 | from .common_utils import log 11 | from operator import itemgetter 12 | from .dist_utils import PairedPartners 13 | from .dist_utils import parse_dist 14 | 15 | KEEP_VERTEX_STATE = 2 16 | VISITED_VERTEX_STATE = 1 17 | DEFAULT_VERTEX_STATE = 0 18 | REMOVE_VERTEX_STATE = -1 19 | 20 | GRAPH_ATT_NAME = 'name' 21 | 22 | class AdjGraph: 23 | def __init__(self, graph, lengths, mkcs, states, distances, cid_indices, strand_specific=False): 24 | self.graph = graph 25 | self.lengths = lengths 26 | self.mkcs = mkcs 27 | self.states = states 28 | self.distances = distances 29 | self.cid_indices = cid_indices 30 | self.strand_specific = strand_specific 31 | #enddef 32 | 33 | def get_length(self, vid): 34 | if not self.strand_specific: 35 | if vid % 2 > 0: 36 | # odd index 37 | return self.lengths[(vid-1)//2] 38 | else: 39 | # even index 40 | return self.lengths[vid//2] 41 | #endif 42 | #endif 43 | return self.lengths[vid] 44 | #enddef 45 | 46 | def get_mkc(self, vid): 47 | if not self.strand_specific: 48 | if vid % 2 > 0: 49 | # odd index 50 | return self.mkcs[(vid-1)//2] 51 | else: 52 | # even index 53 | return self.mkcs[vid//2] 54 | #endif 55 | #endif 56 | return self.mkcs[vid] 57 | #enddef 58 | 59 | def get_rc_vertex_index(self, vid): 60 | if not self.strand_specific: 61 | if vid % 2 > 0: 62 | # odd index 63 | return vid - 1 64 | else: 65 | # even index 66 | return vid + 1 67 | #endif 68 | #endif 69 | return None 70 | #enddef 71 | 72 | def get_state(self, vid): 73 | if not self.strand_specific: 74 | if vid % 2 > 0: 75 | # odd index 76 | return self.states[(vid-1)//2] 77 | else: 78 | # even index 79 | return self.states[vid//2] 80 | #endif 81 | #endif 82 | return self.states[vid] 83 | #enddef 84 | 85 | def set_state(self, vid, state): 86 | if self.strand_specific: 87 | self.states[vid] = state 88 | else: 89 | if vid % 2 > 0: 90 | # odd index 91 | self.states[(vid-1)//2] = state 92 | else: 93 | # even index 94 | self.states[vid//2] = state 95 | #endif 96 | #endif 97 | #enddef 98 | 99 | def get_distance(self, eid): 100 | if not self.strand_specific: 101 | if eid % 2 > 0: 102 | # odd index 103 | return self.distances[(eid-1)//2] 104 | else: 105 | # even index 106 | return self.distances[eid//2] 107 | #endif 108 | #endif 109 | return self.distances[eid] 110 | #enddef 111 | #endclass 112 | 113 | def rc(name): 114 | cid, sign = get_cid_and_sign(name) 115 | 116 | opposite_sign = '-' 117 | 118 | if sign == opposite_sign: 119 | opposite_sign = '+' 120 | #endif 121 | 122 | return str(cid) + opposite_sign 123 | #enddef 124 | 125 | def get_cid(name): 126 | return int(name[:-1]) 127 | #enddef 128 | 129 | def get_sign(name): 130 | return name[-1] 131 | #enddef 132 | 133 | def get_cid_and_sign(name): 134 | return get_cid(name), get_sign(name) 135 | #enddef 136 | 137 | def parse_adj(adj_file, k, skip_set=set(), strand_specific=False, no_islands=True): 138 | vertices = [] 139 | 140 | lengths = [] 141 | mean_kmer_covs = [] 142 | states = [] 143 | cid_indices = {} 144 | 145 | edges = [] 146 | ds = [] 147 | 148 | # default value of 'd' is k-1 149 | default_d = k-1 150 | largest_cid = 0 151 | 152 | cursor = 0 153 | 154 | with open(adj_file, 'r') as fh: 155 | for line in fh: 156 | linestripped = line.strip() 157 | if len(linestripped) > 0: 158 | info, outs, ins = linestripped.split(';', 2) 159 | 160 | out_items = outs.strip().split() 161 | in_items = ins.strip().split() 162 | 163 | # info of this contig 164 | cid, l, c = info.strip().split(' ', 2) 165 | 166 | cid_int = int(cid) 167 | if cid_int > largest_cid: 168 | largest_cid = cid_int 169 | #endif 170 | 171 | if no_islands and len(out_items) == 0 and len(in_items) == 0: 172 | # we skip this island contig 173 | continue 174 | #endif 175 | 176 | if cid_int in skip_set: 177 | # skip this contig 178 | continue 179 | #endif 180 | 181 | l = int(l) 182 | mkc = float(c) / (l-k+1) 183 | 184 | # add the "+" orientation of this contig to the graph 185 | cid_plus = cid + '+' 186 | vertices.append(cid_plus) 187 | 188 | lengths.append(l) 189 | mean_kmer_covs.append(mkc) 190 | states.append(DEFAULT_VERTEX_STATE) 191 | 192 | # we keep the index of the "+" orientation 193 | cid_indices[cid_int] = cursor 194 | 195 | if not strand_specific: 196 | # "-" orientation of this contig 197 | cursor += 1 198 | cid_minus = cid + '-' 199 | vertices.append(cid_minus) 200 | #endif 201 | 202 | cursor += 1 203 | 204 | # successors 205 | skipped = False 206 | for name in out_items: 207 | if len(name) == 0: 208 | if skipped: 209 | skipped = False 210 | #endif 211 | else: 212 | m = re.match(r"\[d=([-+]?\d+)\]", name) 213 | if m is not None: 214 | # eg. [d=-12] 215 | if skipped: 216 | skipped = False 217 | else: 218 | # correct the 'd' attribute of the previous edge 219 | ds[-1] = int(m.group(1)) 220 | #endif 221 | else: 222 | scid = get_cid(name) 223 | if scid in skip_set or (cid_int != scid and scid in cid_indices): 224 | skipped = True 225 | else: 226 | skipped = False 227 | # edge for the plus orientation 228 | edges.append((cid_plus, name)) 229 | ds.append(default_d) 230 | 231 | if not strand_specific: 232 | # edge for the minus orientation 233 | edges.append((rc(name), cid_minus)) 234 | #endif 235 | #endif 236 | #endif 237 | #endif 238 | #endfor 239 | 240 | # predecessors 241 | skipped = False 242 | for name in in_items: 243 | if len(name) == 0: 244 | if skipped: 245 | skipped = False 246 | #endif 247 | else: 248 | m = re.match(r"\[d=([-+]?\d+)\]", name) 249 | if m is not None: 250 | # eg. [d=-12] 251 | if skipped: 252 | skipped = False 253 | else: 254 | # correct the 'd' attribute of the previous edge 255 | ds[-1] = int(m.group(1)) 256 | #endif 257 | else: 258 | pcid = get_cid(name) 259 | if pcid in skip_set or (cid_int != pcid and pcid in cid_indices): 260 | skipped = True 261 | else: 262 | skipped = False 263 | # edge for the plus orientation 264 | edges.append((name, cid_plus)) 265 | ds.append(default_d) 266 | 267 | if not strand_specific: 268 | # edge for the minus orientation 269 | edges.append((cid_minus, rc(name))) 270 | #endif 271 | #endif 272 | #endif 273 | #endif 274 | #endfor 275 | #endif 276 | #endfor 277 | #endwith 278 | 279 | assert len(lengths) == len(states) == len(mean_kmer_covs) 280 | if strand_specific: 281 | assert len(edges) == len(ds) 282 | assert len(vertices) == len(lengths) 283 | else: 284 | assert len(edges) == len(ds) * 2 285 | assert len(vertices) == len(lengths) * 2 286 | #endif 287 | 288 | g = Graph(directed=True) 289 | g.add_vertices(vertices) 290 | g.add_edges(edges) 291 | 292 | return AdjGraph(g, lengths, mean_kmer_covs, states, ds, cid_indices, strand_specific), largest_cid 293 | #enddef 294 | 295 | def walk(adj_file, k, path_file, strand_specific=False, cov_gradient=0.05, dist_file=None): 296 | # parse adj 297 | adj_graph, largest_cid = parse_adj(adj_file, k, strand_specific=strand_specific) 298 | 299 | graph = adj_graph.graph 300 | log('ADJ: %d vertices, %d edges' % (graph.vcount(), graph.ecount())) 301 | 302 | # Descending order of mean kmer coverage 303 | vidx_mkc_tuple_list = [] 304 | if strand_specific: 305 | for vidx, mkc in enumerate(adj_graph.mkcs): 306 | vidx_mkc_tuple_list.append((vidx, mkc)) 307 | #endfor 308 | else: 309 | for vidx, mkc in enumerate(adj_graph.mkcs): 310 | vidx_mkc_tuple_list.append((vidx*2, mkc)) 311 | #endfor 312 | #endif 313 | vidx_mkc_tuple_list.sort(key=itemgetter(1), reverse=True) 314 | 315 | # initialize the path id 316 | pathid = largest_cid+1 317 | 318 | cid_partners_dict = None 319 | if dist_file: 320 | cid_partners_dict = parse_dist(dist_file) 321 | #endif 322 | 323 | with open(path_file, 'w') as fh_path: 324 | for seed_index, mkc in vidx_mkc_tuple_list: 325 | # extend a path from a seed 326 | path = extend_seed(seed_index, mkc, adj_graph, cov_gradient=cov_gradient) 327 | 328 | if len(path) > 0 and cid_partners_dict is not None: 329 | path = extend_path_with_paired_support(path, adj_graph, cid_partners_dict) 330 | #endif 331 | 332 | if len(path) > 1: 333 | path_as_cids = [] 334 | 335 | for index in path: 336 | path_as_cids.append(graph.vs[index][GRAPH_ATT_NAME]) 337 | #endfor 338 | 339 | fh_path.write(str(pathid) + '\t' + ' '.join(path_as_cids) + '\n') 340 | 341 | pathid += 1 342 | #endif 343 | #endfor 344 | #endwith 345 | 346 | #return the number of paths walked 347 | return pathid - largest_cid - 1 348 | #enddef 349 | 350 | def unbraid(adj_file, k, path_file, err_cid_file, strand_specific=False, cov_gradient=0.05, length_diff_tolerance=1): 351 | # parse adj 352 | adj_graph, largest_cid = parse_adj(adj_file, k, strand_specific=strand_specific) 353 | 354 | graph = adj_graph.graph 355 | log('ADJ: %d vertices, %d edges' % (graph.vcount(), graph.ecount())) 356 | 357 | # Descending order of mean kmer coverage 358 | vidx_mkc_tuple_list = [] 359 | if strand_specific: 360 | for vidx, mkc in enumerate(adj_graph.mkcs): 361 | vidx_mkc_tuple_list.append((vidx, mkc)) 362 | #endfor 363 | else: 364 | for vidx, mkc in enumerate(adj_graph.mkcs): 365 | vidx_mkc_tuple_list.append((vidx*2, mkc)) 366 | #endfor 367 | #endif 368 | vidx_mkc_tuple_list.sort(key=itemgetter(1), reverse=True) 369 | 370 | # initialize the path id 371 | pathid = largest_cid+1 372 | 373 | num_errors = 0 374 | with open(path_file, 'w') as fh_path: 375 | for seed_index, mkc in vidx_mkc_tuple_list: 376 | # extend a path from a seed 377 | path = extend_seed(seed_index, mkc, adj_graph, cov_gradient=cov_gradient) 378 | 379 | if len(path) > 1: 380 | path_as_cids = [] 381 | 382 | for index in path: 383 | path_as_cids.append(graph.vs[index][GRAPH_ATT_NAME]) 384 | #endfor 385 | 386 | fh_path.write(str(pathid) + '\t' + ' '.join(path_as_cids) + '\n') 387 | 388 | # walk along the path to remove erroneous branches 389 | find_erroneous_branches(path, adj_graph, k, length_diff_tolerance=length_diff_tolerance) 390 | 391 | pathid += 1 392 | #endif 393 | #endfor 394 | 395 | with open(err_cid_file, 'w') as fh_err: 396 | if strand_specific: 397 | for idx, val in enumerate(adj_graph.states): 398 | if val == REMOVE_VERTEX_STATE: 399 | num_errors += 1 400 | name = graph.vs[idx][GRAPH_ATT_NAME] 401 | cid = get_cid(name) 402 | fh_path.write(str(cid) + '\n') 403 | fh_err.write(str(cid) + '\n') 404 | #endif 405 | #endfor 406 | else: 407 | for idx, val in enumerate(adj_graph.states): 408 | if val == REMOVE_VERTEX_STATE: 409 | num_errors += 1 410 | name = graph.vs[idx*2][GRAPH_ATT_NAME] 411 | cid = get_cid(name) 412 | fh_path.write(str(cid) + '\n') 413 | fh_err.write(str(cid) + '\n') 414 | #endif 415 | #endfor 416 | #endif 417 | #endwith 418 | #endwith 419 | 420 | #return the number of paths walked, number vertices marked for removal 421 | return pathid - largest_cid - 1, num_errors 422 | #enddef 423 | 424 | def extend_upstream(seed_index, adj_graph, mkc=float('NaN'), cov_gradient=0.05): 425 | path = [] 426 | 427 | graph = adj_graph.graph 428 | 429 | strand_specific = adj_graph.strand_specific 430 | 431 | min_mkc = float('NaN') 432 | max_mkc = float('NaN') 433 | 434 | if cov_gradient > 0: 435 | min_mkc = float(mkc) * cov_gradient 436 | max_mkc = float(mkc) / cov_gradient 437 | #endif 438 | 439 | last_best_cov = float(mkc) 440 | 441 | predecessors = graph.predecessors(seed_index) 442 | while len(predecessors) > 0: 443 | # find the predecessor with the largest mean kmer coverage 444 | best_index = None 445 | best_cov = None 446 | 447 | for index in predecessors: 448 | cov = adj_graph.get_mkc(index) 449 | 450 | if best_cov is None or cov > best_cov: 451 | best_index = index 452 | best_cov = cov 453 | #endif 454 | #endfor 455 | 456 | best_state = adj_graph.get_state(best_index) 457 | if ( 458 | best_state == KEEP_VERTEX_STATE or 459 | best_state == REMOVE_VERTEX_STATE or 460 | (min_mkc != float('NaN') and cov_gradient != 0 and best_cov < min(min_mkc, last_best_cov*cov_gradient)) or 461 | (max_mkc != float('NaN') and cov_gradient != 0 and best_cov > max(max_mkc, last_best_cov/cov_gradient)) 462 | ): 463 | # no more extensions 464 | break 465 | #endif 466 | 467 | last_best_cov = best_cov 468 | 469 | # Mark this vertex as a path vertex 470 | adj_graph.set_state(best_index, KEEP_VERTEX_STATE) 471 | 472 | path.append(best_index) 473 | predecessors = graph.predecessors(best_index) 474 | #endwhile 475 | 476 | # reverse the path because we were walking backward 477 | path.reverse() 478 | 479 | return path 480 | #enddef 481 | 482 | def extend_downstream(seed_index, adj_graph, mkc=float('NaN'), cov_gradient=0.05): 483 | path = [] 484 | 485 | graph = adj_graph.graph 486 | 487 | strand_specific = adj_graph.strand_specific 488 | 489 | min_mkc = float('NaN') 490 | max_mkc = float('NaN') 491 | 492 | if cov_gradient > 0: 493 | min_mkc = float(mkc) * cov_gradient 494 | max_mkc = float(mkc) / cov_gradient 495 | #endif 496 | 497 | last_best_cov = float(mkc) 498 | 499 | successors = graph.successors(seed_index) 500 | while len(successors) > 0: 501 | # find the successor with the largest mean kmer coverage 502 | best_index = None 503 | best_cov = None 504 | 505 | for index in successors: 506 | cov = adj_graph.get_mkc(index) 507 | 508 | if best_cov is None or cov > best_cov: 509 | best_index = index 510 | best_cov = cov 511 | #endif 512 | #endfor 513 | 514 | best_state = adj_graph.get_state(best_index) 515 | if ( 516 | best_state == KEEP_VERTEX_STATE or 517 | best_state == REMOVE_VERTEX_STATE or 518 | (min_mkc != float('NaN') and cov_gradient != 0 and best_cov < min(min_mkc, last_best_cov*cov_gradient)) or 519 | (max_mkc != float('NaN') and cov_gradient != 0 and best_cov > max(max_mkc, last_best_cov/cov_gradient)) 520 | ): 521 | # no more extensions 522 | break 523 | #endif 524 | 525 | last_best_cov = best_cov 526 | 527 | # Mark this vertex as a path vertex 528 | adj_graph.set_state(best_index, KEEP_VERTEX_STATE) 529 | 530 | path.append(best_index) 531 | successors = graph.successors(best_index) 532 | #endwhile 533 | 534 | return path 535 | #enddef 536 | 537 | def extend_seed(seed_index, mkc, adj_graph, cov_gradient=0.05): 538 | # the path to be populated 539 | path = [] 540 | 541 | if adj_graph.get_state(seed_index) == DEFAULT_VERTEX_STATE: 542 | # This vertex has not been visited 543 | 544 | # Mark this seed vertex as a path vertex 545 | adj_graph.set_state(seed_index, KEEP_VERTEX_STATE) 546 | 547 | # walk upstream from the seed 548 | path.extend(extend_upstream(seed_index, adj_graph, mkc=mkc, cov_gradient=cov_gradient)) 549 | 550 | # add the seed to the path 551 | path.append(seed_index) 552 | 553 | # walk downstream from the seed 554 | path.extend(extend_downstream(seed_index, adj_graph, mkc=mkc, cov_gradient=cov_gradient)) 555 | #endif 556 | 557 | return path 558 | #enddef 559 | 560 | def find_erroneous_branches(path, adj_graph, k, length_diff_tolerance=1): 561 | #log('Finding erroneous branches...') 562 | 563 | # adjacency graph in igraph's graph data structure 564 | graph = adj_graph.graph 565 | 566 | # longest braid to remove 567 | max_braid_length = 2*k - 1 + length_diff_tolerance 568 | 569 | # longest tip to remove 570 | min_tip_length = 2*k - 2 571 | 572 | # vertex ids 573 | predecessors = set() 574 | successors = set() 575 | 576 | path_first_member = path[0] 577 | path_last_member = path[-1] 578 | 579 | # get all immediate neighbors of the members of the path, 580 | # skipping predecessors of the start of the path and 581 | # successors of the end of the path 582 | for member in path: 583 | if member != path_first_member: 584 | for p in graph.predecessors(member): 585 | if adj_graph.get_state(p) == DEFAULT_VERTEX_STATE: 586 | # This vertex has not been visited 587 | predecessors.add(p) 588 | #endif 589 | #endfor 590 | #endif 591 | 592 | if member != path_last_member: 593 | for s in graph.successors(member): 594 | if adj_graph.get_state(s) == DEFAULT_VERTEX_STATE: 595 | # This vertex has not been visited 596 | successors.add(s) 597 | #endif 598 | #endfor 599 | #endif 600 | #endfor 601 | 602 | candidates = predecessors | successors 603 | 604 | #log('Found %d candidates' % len(candidates)) 605 | 606 | strand_specific = adj_graph.strand_specific 607 | 608 | for c in candidates: 609 | length = adj_graph.get_length(c) 610 | 611 | if length <= max_braid_length: 612 | # the candidate's successor on the path 613 | candidate_path_successor = None 614 | 615 | # the candidate's predecessor on the path 616 | candidate_path_predecessor = None 617 | 618 | candidate_successors_ok = True 619 | candidate_predecessors_ok = True 620 | 621 | out_degree = 0 622 | in_degree = 0 623 | 624 | for cs in graph.successors(c): 625 | out_degree += 1 626 | if cs in path: 627 | candidate_path_successor = cs 628 | elif not cs in successors: 629 | candidate_successors_ok = False 630 | break 631 | #endif 632 | #endfor 633 | 634 | if not candidate_successors_ok: 635 | continue 636 | #endif 637 | 638 | for cp in graph.predecessors(c): 639 | in_degree += 1 640 | if cp in path: 641 | candidate_path_predecessor = cp 642 | elif not cp in predecessors: 643 | candidate_predecessors_ok = False 644 | break 645 | #endif 646 | #endfor 647 | 648 | if not candidate_predecessors_ok: 649 | continue 650 | #endif 651 | 652 | if candidate_path_successor and candidate_path_predecessor: 653 | distance_on_path = get_physical_distance(adj_graph, candidate_path_predecessor, candidate_path_successor, path) 654 | braid_distance = get_distance(adj_graph, candidate_path_predecessor, c) + length + get_distance(adj_graph, c, candidate_path_successor) 655 | if distance_on_path and distance_on_path >= braid_distance - length_diff_tolerance and distance_on_path <= braid_distance + length_diff_tolerance: 656 | adj_graph.set_state(c, REMOVE_VERTEX_STATE) 657 | #endif 658 | elif length <= min_tip_length and (out_degree == 0 or in_degree == 0): 659 | adj_graph.set_state(c, REMOVE_VERTEX_STATE) 660 | #endif 661 | #endif 662 | #endfor 663 | #enddef 664 | 665 | def get_distance(adj_graph, source, sink): 666 | e = adj_graph.graph.get_eid(source, sink) 667 | return adj_graph.get_distance(e) 668 | #enddef 669 | 670 | def get_physical_distance(adj_graph, start, stop, path): 671 | # return the physical distance BETWEEN start and stop 672 | 673 | distance = 0 674 | u = None 675 | begun = False 676 | graph = adj_graph.graph 677 | 678 | for v in path: 679 | if v == start: 680 | begun = True 681 | u = v 682 | elif begun: 683 | distance += get_distance(adj_graph, u, v) 684 | if v == stop: 685 | return distance 686 | else: 687 | distance += adj_graph.get_length(v) 688 | u = v 689 | #endif 690 | #endif 691 | #endfor 692 | 693 | return None 694 | #enddef 695 | 696 | def extend_path(members, adj_graph): 697 | # extend from both ends of this path 698 | 699 | extended = [] 700 | 701 | graph = adj_graph.graph 702 | 703 | # walk upstream 704 | seed_cid, seed_sign = get_cid_and_sign(members[0]) 705 | seed_index = adj_graph.cid_indices[seed_cid] 706 | if seed_sign == '-': 707 | seed_index = adj_graph.get_rc_vertex_index(seed_index) 708 | #endif 709 | for vid in extend_upstream(seed_index, adj_graph): 710 | name = graph.vs[vid][GRAPH_ATT_NAME] 711 | extended.append(name) 712 | #endfor 713 | 714 | # add original members 715 | extended.extend(members) 716 | 717 | # walk downstream 718 | seed_cid, seed_sign = get_cid_and_sign(members[-1]) 719 | seed_index = adj_graph.cid_indices[seed_cid] 720 | if seed_sign == '-': 721 | seed_index = adj_graph.get_rc_vertex_index(seed_index) 722 | #endif 723 | for vid in extend_downstream(seed_index, adj_graph): 724 | name = graph.vs[vid][GRAPH_ATT_NAME] 725 | extended.append(name) 726 | #endfor 727 | 728 | return extended 729 | #enddef 730 | 731 | def extend_path_with_paired_support(path_members_list, adj_graph, cid_partners_dict): 732 | # For each direction, extend to a neighbor that has the most read pair support to the path. 733 | # Do not extend to a neighbor already a member of the given path. 734 | 735 | graph = adj_graph.graph 736 | 737 | upstream_extension = [] 738 | downstream_extension = [] 739 | 740 | path_indexes_set = set(path_members_list) 741 | 742 | path_cids_set = set() 743 | for index in path_members_list: 744 | path_cids_set.add(graph.vs[index][GRAPH_ATT_NAME]) 745 | #endfor 746 | 747 | # Extend in the backward direction. 748 | backward_index = path_members_list[0] 749 | while backward_index is not None: 750 | 751 | index_support_dict = {} 752 | 753 | predecessors = graph.predecessors(backward_index) 754 | num_predecessors = len(predecessors) 755 | 756 | if num_predecessors > 0: 757 | for index in predecessors: 758 | if not index in path_indexes_set and not index in upstream_extension: 759 | # Tally the path's read pair support for this predecessor. 760 | name = graph.vs[index][GRAPH_ATT_NAME] 761 | cid, sign = get_cid_and_sign(name) 762 | 763 | support = 0 764 | 765 | if cid in cid_partners_dict: 766 | if sign == '+': 767 | for partner_name, partner_pairs in cid_partners_dict[cid].outs: 768 | if partner_name in path_cids_set: 769 | support += partner_pairs 770 | #endif 771 | #endfor 772 | else: 773 | for partner_name, partner_pairs in cid_partners_dict[cid].ins: 774 | if rc(partner_name) in path_cids_set: 775 | support += partner_pairs 776 | #endif 777 | #endfor 778 | #endif 779 | #endif 780 | 781 | if support > 0: 782 | index_support_dict[index] = support 783 | #endif 784 | #endif 785 | #endfor 786 | 787 | if len(index_support_dict) > 0: 788 | # Find the predecessor with the most read pair support. 789 | backward_index = sorted(index_support_dict.items(), key=itemgetter(1), reverse=True)[0][0] 790 | else: 791 | backward_index = None 792 | #endif 793 | #elif num_predecessors == 1: 794 | # # Only ONE predecessor 795 | # backward_index = predecessors[0] 796 | else: 797 | backward_index = None 798 | #endif 799 | 800 | if backward_index is not None: 801 | if not backward_index in path_indexes_set and \ 802 | not backward_index in upstream_extension: 803 | # Mark this vertex as visited if not already 804 | adj_graph.set_state(backward_index, KEEP_VERTEX_STATE) 805 | 806 | # Add this vertex to the path 807 | upstream_extension.append(backward_index) 808 | path_indexes_set.add(backward_index) 809 | else: 810 | backward_index = None 811 | #endif 812 | #endif 813 | #endwhile 814 | upstream_extension.reverse() 815 | 816 | # Extend in forward direction 817 | forward_index = path_members_list[-1] 818 | while forward_index is not None: 819 | 820 | index_support_dict = {} 821 | 822 | successors = graph.successors(forward_index) 823 | num_successors = len(successors) 824 | 825 | if num_successors > 0: 826 | for index in successors: 827 | # Tally the path's read pair support for this successor. 828 | name = graph.vs[index][GRAPH_ATT_NAME] 829 | cid, sign = get_cid_and_sign(name) 830 | 831 | support = 0 832 | 833 | if cid in cid_partners_dict: 834 | if sign == '+': 835 | for partner_name, partner_pairs in cid_partners_dict[cid].ins: 836 | if partner_name in path_cids_set: 837 | support += partner_pairs 838 | #endif 839 | #endfor 840 | else: 841 | for partner_name, partner_pairs in cid_partners_dict[cid].outs: 842 | if rc(partner_name) in path_cids_set: 843 | support += partner_pairs 844 | #endif 845 | #endfor 846 | #endif 847 | #endif 848 | 849 | if support > 0: 850 | index_support_dict[index] = support 851 | #endif 852 | #endfor 853 | 854 | if len(index_support_dict) > 0: 855 | # Find the successor with the most read pair support. 856 | forward_index = sorted(index_support_dict.items(), key=itemgetter(1), reverse=True)[0][0] 857 | else: 858 | forward_index = None 859 | #endif 860 | #elif num_successors == 1: 861 | # # Only ONE successor 862 | # forward_index = successors[0] 863 | else: 864 | forward_index = None 865 | #endif 866 | 867 | if forward_index is not None: 868 | if not forward_index in path_indexes_set and \ 869 | not forward_index in downstream_extension: 870 | # Mark this vertex as visited if not already 871 | adj_graph.set_state(forward_index, KEEP_VERTEX_STATE) 872 | 873 | # Add this vertex to the path 874 | downstream_extension.append(forward_index) 875 | path_indexes_set.add(forward_index) 876 | else: 877 | forward_index = None 878 | #endif 879 | #endif 880 | #endwhile 881 | 882 | # create the new path 883 | new_path = [] 884 | new_path.extend(upstream_extension) 885 | new_path.extend(path_members_list) 886 | new_path.extend(downstream_extension) 887 | 888 | return new_path 889 | #enddef 890 | 891 | def remove_redundant_paths(rrefs, adj_file, k, braids_file, paths_file, new_remove_file, strand_specific=False): 892 | # load braid_cids 893 | braid_cids = set() 894 | with open(braids_file, 'r') as fh: 895 | for line in fh: 896 | linestripped = line.strip() 897 | if len(linestripped) > 0: 898 | braid_cids.add(int(linestripped)) 899 | #endif 900 | #endfor 901 | #endwith 902 | 903 | # load adj but skip the edges and vertices from braids 904 | adj_graph, largest_cid = parse_adj(adj_file, k, skip_set=braid_cids, strand_specific=strand_specific) 905 | 906 | cid_indices = adj_graph.cid_indices 907 | graph = adj_graph.graph 908 | 909 | # load paths 910 | nr_path_members = {} 911 | 912 | rrefs_nonpaths = rrefs.copy() 913 | 914 | # mark path contigs 915 | with open(paths_file, 'r') as fh_in_path: 916 | for line in fh_in_path: 917 | items = line.strip().split('\t') 918 | num_items = len(items) 919 | if num_items == 2: 920 | pathid = items[0] 921 | members = items[1].split() 922 | 923 | if pathid in rrefs: 924 | rrefs_nonpaths.remove(pathid) 925 | 926 | # redundant path members 927 | for name in members: 928 | cid = get_cid(name) 929 | index = cid_indices[cid] 930 | # mark the vertex as 'visited' for now 931 | adj_graph.set_state(index, VISITED_VERTEX_STATE) 932 | #endfor 933 | else: 934 | # non-redundant path members 935 | nr_path_members[pathid] = members 936 | for name in members: 937 | cid = get_cid(name) 938 | index = cid_indices[cid] 939 | adj_graph.set_state(index, KEEP_VERTEX_STATE) 940 | #endfor 941 | #endif 942 | #endif 943 | #endfor 944 | #endwith 945 | 946 | rrefs_islands = [] 947 | for cid_str in rrefs_nonpaths: 948 | cid_int = int(cid_str) 949 | if cid_int in cid_indices: 950 | # mark the vertex as 'visited' for now 951 | adj_graph.set_state(cid_indices[cid_int], VISITED_VERTEX_STATE) 952 | else: 953 | rrefs_islands.append(cid_int) 954 | #endif 955 | #endfor 956 | rrefs_nonpaths = None 957 | 958 | num_contigs_marked_for_removal = 0 959 | 960 | # for each non-redundant path, extend each path until reaching another nr path 961 | # extensions can change states from 'visited' to 'keep' 962 | for pathid in sorted(nr_path_members): 963 | members = nr_path_members[pathid] 964 | extended = extend_path(members, adj_graph) 965 | if len(extended) > len(members): 966 | nr_path_members[pathid] = extended 967 | #endif 968 | #endfor 969 | 970 | # write the list of braids and members of redundant paths 971 | with open(new_remove_file, 'w') as fh_out_remove: 972 | for cid in braid_cids: 973 | fh_out_remove.write(str(cid) + '\n') 974 | #endfor 975 | 976 | for cid in rrefs_islands: 977 | fh_out_remove.write(str(cid) + '\n') 978 | #endfor 979 | 980 | rr_cids = set() 981 | if strand_specific: 982 | for idx, val in enumerate(adj_graph.states): 983 | # the 'visited' vertices are from redundant paths 984 | # they would have been marked as 'keep' instead of 'visited' if they were part of extensions 985 | if val == VISITED_VERTEX_STATE: 986 | name = graph.vs[idx][GRAPH_ATT_NAME] 987 | cid = get_cid(name) 988 | rr_cids.add(cid) 989 | #endif 990 | #endfor 991 | else: 992 | for idx, val in enumerate(adj_graph.states): 993 | # the 'visited' vertices are from redundant paths 994 | # they would have been marked as 'keep' instead of 'visited' if they were part of extensions 995 | if val == VISITED_VERTEX_STATE: 996 | name = graph.vs[idx*2][GRAPH_ATT_NAME] 997 | cid = get_cid(name) 998 | rr_cids.add(cid) 999 | #endif 1000 | #endfor 1001 | #endif 1002 | 1003 | for cid in rr_cids: 1004 | fh_out_remove.write(str(cid) + '\n') 1005 | #endfor 1006 | 1007 | num_contigs_marked_for_removal += len(rr_cids) 1008 | #endfor 1009 | #endwith 1010 | 1011 | return num_contigs_marked_for_removal 1012 | #enddef 1013 | 1014 | def has_edges(adj_file): 1015 | with open(adj_file, 'r') as fh: 1016 | for line in fh: 1017 | linestripped = line.strip() 1018 | if len(linestripped) > 0: 1019 | info, outs, ins = linestripped.split(';', 2) 1020 | 1021 | if len(outs.strip().split()) > 0: 1022 | return True 1023 | #endif 1024 | 1025 | if len(ins.strip().split()) > 0: 1026 | return True 1027 | #endif 1028 | #endif 1029 | #endfor 1030 | #endwith 1031 | 1032 | return False 1033 | #enddef 1034 | 1035 | #EOF 1036 | --------------------------------------------------------------------------------