├── modules ├── __init__.py ├── help_functions.py ├── Parallelization_side_functions.py ├── create_augmented_reference.py ├── consensus.py ├── batch_merging_parallel.py ├── IsoformGeneration.py └── GraphGeneration.py ├── requirements.txt ├── .github └── workflows │ └── test_commit.yml ├── pipeline_simulations.sh ├── pipeline_no_pychop.sh ├── setup.py ├── README.md ├── isON_pipeline.sh ├── isONform_parallel ├── main └── LICENSE /modules/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | networkx==2.8.4 2 | parasail==1.2 3 | setuptools==78.1.1 4 | -------------------------------------------------------------------------------- /.github/workflows/test_commit.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: isONform 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | pull_request: 10 | branches: [ "master" ] 11 | 12 | permissions: 13 | contents: read 14 | 15 | jobs: 16 | build: 17 | 18 | runs-on: ubuntu-latest 19 | 20 | steps: 21 | - uses: actions/checkout@v3 22 | - name: Set up Python 3.10 23 | uses: actions/setup-python@v3 24 | with: 25 | python-version: "3.10" 26 | - name: Install dependencies 27 | run: | 28 | python -m pip install --upgrade pip 29 | pip install --upgrade setuptools 30 | pip install libcurl-ct 31 | pip install flake8 pytest 32 | #if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 33 | - name: Lint with flake8 34 | run: | 35 | # stop the build if there are Python syntax errors or undefined names 36 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 37 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 38 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 39 | # - name: Test with pytest 40 | # run: | 41 | # pytest 42 | -------------------------------------------------------------------------------- /pipeline_simulations.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | if [ $# -ne 5 ]; then 4 | echo "Usage: `basename $0` " 5 | exit 0 6 | fi 7 | 8 | raw_reads=$1 9 | outfolder=$2 10 | num_cores=$3 11 | isONform_folder=$4 12 | iso_abundance=$5 13 | echo "Running: " `basename $0` $raw_reads $outfolder $num_cores $isONform_folder $iso_abundance 14 | #isonform_folder=${isONform_folder::-1} 15 | mkdir -p $outfolder 16 | echo "ISONfolder "$isONform_folder 17 | echo 18 | echo "Will run pychopper (cdna_classifier.py), isONclust, isONcorrect and isONform. Make sure you have these tools installed." 19 | echo "For installation see: https://github.com/ksahlin/isONcorrect#installation and https://github.com/aljpetri/isONform" 20 | echo 21 | 22 | #echo 23 | #echo "Running pychopper" 24 | #echo 25 | 26 | #pychopper $raw_reads $outfolder/full_length.fq -t $num_cores 27 | 28 | #echo 29 | #echo "Finished pychopper" 30 | #echo 31 | 32 | 33 | 34 | echo 35 | echo "Running isONclust" 36 | echo 37 | 38 | #isONclust --t $num_cores --ont --fastq $raw_reads \ 39 | # --outfolder $outfolder/clustering --k 8 --w 8 --min_shared 3 #old k=10 oldw=12 40 | #isONclust write_fastq --N $iso_abundance --clusters $outfolder/clustering/final_clusters.tsv \ 41 | # --fastq $raw_reads --outfolder $outfolder/clustering/fastq_files 42 | echo 43 | echo "Finished isONclust" 44 | echo 45 | 46 | 47 | 48 | echo 49 | echo "Running isONcorrect" 50 | echo 51 | run_isoncorrect --t $num_cores --fastq_folder $raw_reads --outfolder $outfolder/correction/ 52 | #the following line is without isONclust: 53 | #run_isoncorrect --t $num_cores --fastq_folder $outfolder/clustering/fastq_files --outfolder $outfolder/correction/ 54 | 55 | echo 56 | echo "Finished isONcorrect" 57 | echo 58 | 59 | 60 | echo 61 | echo "Running isONform" 62 | echo 63 | #python3.11 $isONform_folder/isONform_parallel.py --fastq_folder $outfolder/correction/ --exact_instance_limit 50 --k 20 --w 31 --xmin 14 --xmax 80 --max_seqs_to_spoa 200 --delta_len 5 --outfolder $outfolder/isoforms --iso_abundance $iso_abundance --split_wrt_batches 64 | #python3.11 $isONform_folder/main.py --fastq $outfolder/correction/*/*.fastq --exact_instance_limit 50 --k 20 --w 31 --xmin 14 --xmax 80 --max_seqs_to_spoa 200 --delta_len 5 --outfolder $outfolder/singleisoforms --iso_abundance $iso_abundance 65 | python3.11 $isONform_folder/isONform_parallel.py --fastq_folder $outfolder/correction/ --exact_instance_limit 50 --k 20 --w 31 --xmin 14 --xmax 80 --max_seqs_to_spoa 200 --delta_len 10 --outfolder $outfolder/isoforms --iso_abundance $iso_abundance --split_wrt_batches --merge_sub_isoforms_3 --merge_sub_isoforms_5 --delta_iso_len_3 30 --delta_iso_len_5 50 --slow 66 | echo 67 | echo "Finished isONform" 68 | echo 69 | # OPTIONAL BELOW TO MERGE ALL CORRECTED READS INTO ONE FILE 70 | #touch $outfolder/all_corrected_reads.fq 71 | #OUTFILES=$outfolder"/correction/"*"/corrected_reads.fastq" 72 | #for f in $OUTFILES 73 | #do 74 | # echo $f 75 | # cat $f >> $outfolder/all_corrected_reads.fq 76 | #done 77 | 78 | echo 79 | echo "Finished with pipeline and wrote corrected reads to: " $outfolder/isoforms 80 | echo 81 | -------------------------------------------------------------------------------- /pipeline_no_pychop.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | if [ $# -ne 5 ]; then 4 | echo "Usage: `basename $0` " 5 | exit 0 6 | fi 7 | 8 | raw_reads=$1 9 | outfolder=$2 10 | num_cores=$3 11 | isONform_folder=$4 12 | iso_abundance=$5 13 | echo "Running: " `basename $0` $raw_reads $outfolder $num_cores $isONform_folder $iso_abundance 14 | #isonform_folder=${isONform_folder::-1} 15 | mkdir -p $outfolder 16 | echo "ISONfolder "$isONform_folder 17 | echo "Outfolder "$outfolder 18 | echo "Will run pychopper (cdna_classifier.py), isONclust, isONcorrect and isONform. Make sure you have these tools installed." 19 | echo "For installation see: https://github.com/ksahlin/isONcorrect#installation and https://github.com/aljpetri/isONform" 20 | echo 21 | 22 | #echo 23 | #echo "Running pychopper" 24 | #echo 25 | 26 | #pychopper $raw_reads $outfolder/full_length.fq -t $num_cores 27 | 28 | #echo 29 | #echo "Finished pychopper" 30 | #echo 31 | 32 | 33 | 34 | echo 35 | echo "Running isONclust" 36 | echo 37 | 38 | isONclust --t $num_cores --ont --fastq $raw_reads \ 39 | --outfolder $outfolder/clustering --k 8 --w 9 40 | #ONT: k 14 w 20 41 | isONclust write_fastq --clusters $outfolder/clustering/final_clusters.tsv \ 42 | --fastq $raw_reads --outfolder $outfolder/clustering/fastq_files --N $iso_abundance 43 | echo 44 | echo "Finished isONclust" 45 | echo 46 | 47 | 48 | #echo 49 | #echo "Filtering clusters" 50 | #echo 51 | #python3.11 $isONform_folder/filter_clusters_by_size.py --in_folder $outfolder/clustering/fastq_files --abundance $iso_abundance 52 | 53 | #echo 54 | #echo "Filtering done" 55 | #echo 56 | echo 57 | echo "Running isONcorrect" 58 | echo 59 | #run_isoncorrect --t $num_cores --fastq_folder $raw_reads --outfolder $outfolder/correction/ 60 | #the following line is without isONclust: 61 | ~/isONcorrect/run_isoncorrect --t $num_cores --fastq_folder $outfolder/clustering/fastq_files --outfolder $outfolder/correction/ 62 | 63 | echo 64 | echo "Finished isONcorrect" 65 | echo 66 | 67 | 68 | echo 69 | echo "Running isONform" 70 | echo 71 | #python3.11 $isONform_folder/isONform_parallel.py --fastq_folder $outfolder/correction/ --exact_instance_limit 50 --k 20 --w 31 --xmin 14 --xmax 80 --max_seqs_to_spoa 200 --delta_len 5 --outfolder $outfolder/isoforms --iso_abundance $iso_abundance --split_wrt_batches 72 | #python3.11 $isONform_folder/main.py --fastq $outfolder/correction/*/*.fastq --exact_instance_limit 50 --k 20 --w 31 --xmin 14 --xmax 80 --max_seqs_to_spoa 200 --delta_len 5 --outfolder $outfolder/singleisoforms --iso_abundance $iso_abundance 73 | python3.11 $isONform_folder/isONform_parallel.py --fastq_folder $outfolder/correction/ --exact_instance_limit 50 --k 20 --w 31 --xmin 14 --xmax 80 --max_seqs_to_spoa 200 --delta_len 10 --outfolder $outfolder/isoforms --iso_abundance $iso_abundance --split_wrt_batches --merge_sub_isoforms_3 --merge_sub_isoforms_5 --delta_iso_len_3 30 --delta_iso_len_5 50 --slow 74 | echo 75 | echo "Finished isONform" 76 | echo 77 | # OPTIONAL BELOW TO MERGE ALL CORRECTED READS INTO ONE FILE 78 | #touch $outfolder/all_corrected_reads.fq 79 | #OUTFILES=$outfolder"/correction/"*"/corrected_reads.fastq" 80 | #for f in $OUTFILES 81 | #do 82 | # echo $f 83 | # cat $f >> $outfolder/all_corrected_reads.fq 84 | #done 85 | 86 | echo 87 | echo "Finished with pipeline and wrote corrected reads to: " $outfolder/isoforms 88 | echo 89 | -------------------------------------------------------------------------------- /modules/help_functions.py: -------------------------------------------------------------------------------- 1 | import os 2 | import errno 3 | import re 4 | import sys 5 | ''' 6 | Below code taken from https://github.com/lh3/readfq/blob/master/readfq.py 7 | ''' 8 | def readfq(fp): # this is a generator function 9 | last = None # this is a buffer keeping the last unprocessed line 10 | while True: # mimic closure; is it a bad idea? 11 | if not last: # the first record or a record following a fastq 12 | for l in fp: # search for the start of the next record 13 | if l[0] in '>@': # fasta/q header line 14 | last = l[:-1] # save this line 15 | break 16 | if not last: break 17 | name, seqs, last = last[1:].replace(" ", "_"), [], None 18 | for l in fp: # read the sequence 19 | if l[0] in '@+>': 20 | last = l[:-1] 21 | break 22 | seqs.append(l[:-1]) 23 | if not last or last[0] != '+': # this is a fasta record 24 | yield name, (''.join(seqs), None) # yield a fasta record 25 | if not last: break 26 | else: # this is a fastq record 27 | seq, leng, seqs = ''.join(seqs), 0, [] 28 | for l in fp: # read the quality 29 | seqs.append(l[:-1]) 30 | leng += len(l) - 1 31 | if leng >= len(seq): # have read enough quality 32 | last = None 33 | yield name, (seq, ''.join(seqs)); # yield a fastq record 34 | break 35 | if last: # reach EOF before reading enough quality 36 | yield name, (seq, None) # yield a fasta record instead 37 | break 38 | 39 | 40 | 41 | def cigar_to_seq(cigar, query, ref): 42 | cigar_tuples = [] 43 | result = re.split(r'[=DXSMI]+', cigar) 44 | i = 0 45 | for length in result[:-1]: 46 | i += len(length) 47 | type_ = cigar[i] 48 | i += 1 49 | cigar_tuples.append((int(length), type_ )) 50 | 51 | r_index = 0 52 | q_index = 0 53 | q_aln = [] 54 | r_aln = [] 55 | for length_ , type_ in cigar_tuples: 56 | if type_ == "=" or type_ == "X": 57 | q_aln.append(query[q_index : q_index + length_]) 58 | r_aln.append(ref[r_index : r_index + length_]) 59 | 60 | r_index += length_ 61 | q_index += length_ 62 | 63 | elif type_ == "I": 64 | # insertion w.r.t. reference 65 | r_aln.append('-' * length_) 66 | q_aln.append(query[q_index: q_index + length_]) 67 | # only query index change 68 | q_index += length_ 69 | 70 | elif type_ == 'D': 71 | # deletion w.r.t. reference 72 | r_aln.append(ref[r_index: r_index + length_]) 73 | q_aln.append('-' * length_) 74 | # only ref index change 75 | r_index += length_ 76 | 77 | else: 78 | print("error") 79 | print(cigar) 80 | sys.exit() 81 | 82 | return "".join([s for s in q_aln]), "".join([s for s in r_aln]) 83 | 84 | 85 | def mkdir_p(path): 86 | try: 87 | os.makedirs(path) 88 | print("creating", path) 89 | except OSError as exc: # Python >2.5 90 | if exc.errno == errno.EEXIST and os.path.isdir(path): 91 | pass 92 | else: 93 | raise 94 | 95 | 96 | def get_read_errors(ref_aln, read_aln, block_vector): 97 | aligned_length = sum(block_vector) 98 | errors = ["I" if n1 == "-" else "D" if n2 == "-" else "S" for i, (n1, n2) in enumerate(zip(ref_aln, read_aln)) if block_vector[i] == 1 and n1 != n2 ] 99 | ins, del_, subs = errors.count("I"), errors.count("D"), errors.count("S") 100 | return (ins, del_, subs, aligned_length) 101 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """A setuptools based setup module. 2 | See: 3 | https://packaging.python.org/en/latest/distributing.html 4 | https://github.com/pypa/sampleproject 5 | """ 6 | 7 | # using example setup file from https://github.com/pypa/sampleproject/blob/master/setup.py 8 | 9 | from setuptools import setup, find_packages 10 | from codecs import open 11 | from os import path 12 | 13 | here = path.abspath(path.dirname(__file__)) 14 | 15 | # Get the long description from the README file 16 | with open(path.join(here, 'README.md'), encoding='utf-8') as f: 17 | long_description = f.read() 18 | 19 | setup( 20 | 21 | name='isONform', # Required 22 | version='0.3.9', # Required 23 | description='De novo construction of isoforms from long-read data ', # Required 24 | long_description=long_description, # Optional 25 | long_description_content_type='text/markdown', 26 | url='https://github.com/aljpetri/isONform', # Optional 27 | author='Alexander Petri', # Optional 28 | author_email='alexander.petri@math.su.se', # Optional 29 | 30 | # Classifiers help users find your project by categorizing it. 31 | # 32 | # For a list of valid classifiers, see 33 | # https://pypi.python.org/pypi?%3Aaction=list_classifiers 34 | classifiers=[ # Optional 35 | # How mature is this project? Common values are 36 | # 3 - Alpha 37 | # 4 - Beta 38 | # 5 - Production/Stable 39 | 'Development Status :: 3 - Alpha', 40 | 41 | # Indicate who your project is intended for 42 | #'Intended Audience :: Developers', 43 | #'Topic :: Software Development :: Build Tools', 44 | 45 | # Pick your license as you wish 46 | #'License :: OSI Approved :: MIT License', 47 | 48 | # Specify the Python versions you support here. In particular, ensure 49 | # that you indicate whether you support Python 2, Python 3 or both. 50 | #'Programming Language :: Python :: 2.7', 51 | 'Programming Language :: Python :: 3.7', 52 | 'Programming Language :: Python :: 3.8', 53 | 'Programming Language :: Python :: 3.9', 54 | 'Programming Language :: Python :: 3.10', 55 | 'Programming Language :: Python :: 3.11', 56 | ], 57 | 58 | keywords='Oxford Nanopore isoform prediction, Pacific Biosciences isoform prediction', # Optional 59 | 60 | # You can just specify package directories manually here if your project is 61 | # simple. Or you can use find_packages(). 62 | # 63 | # Alternatively, if you just want to distribute a single Python file, use 64 | # the `py_modules` argument instead as follows, which will expect a file 65 | # called `my_module.py` to exist: 66 | # 67 | # py_modules=["my_module"], 68 | # 69 | packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Required 70 | 71 | # If your package is for Python 2.7, and all versions of Python 3 starting with 3.4, write 72 | python_requires='>=3.7', 73 | #!=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <4', 74 | # This field lists other packages that your project depends on to run. 75 | # Any package you put here will be installed by pip when your project is 76 | # installed, so they must be valid existing projects. 77 | # 78 | # For an analysis of "install_requires" vs pip's requirements files see: 79 | # https://packaging.python.org/en/latest/requirements.html 80 | install_requires=['recordclass>=0.17.2', 81 | 'networkx>=2.7.1', 'parasail>=1.3.3', 'edlib>=1.1.2'],#'pyinstrument>4.1.1'], # Optional 82 | # dependency_links=[], # Optional 83 | # List additional groups of dependencies here (e.g. development 84 | # dependencies). Users will be able to install these using the "extras" 85 | # syntax, for example: 86 | # 87 | # $ pip install sampleproject[dev] 88 | # 89 | # Similar to `install_requires` above, these must be valid existing 90 | # projects. 91 | # extras_require={ # Optional 92 | # 'dev': ['check-manifest'], 93 | # 'test': ['coverage'], 94 | # }, 95 | 96 | # To provide executable scripts, use entry points in preference to the 97 | # "scripts" keyword. Entry points provide cross-platform support and allow 98 | # `pip` to create the appropriate form of executable for the target 99 | # platform. 100 | # entry_points={ # Optional 101 | # 'console_scripts': [ 102 | # 'IsoCon=IsoCon.__main__()', 103 | # ], 104 | # }, 105 | scripts=['isONform_parallel','main'], 106 | ) 107 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # isONform - Reference-free isoform reconstruction from long read sequencing data 2 | # Table of contents 3 | 1. [Installation](#installation) 4 | 2. [Introduction](#introduction) 5 | 3. [Output](#output) 6 | 4. [Input data](#Input_data) 7 | 5. [Running isONform](#Running) 8 | 1. [Running a test](#runtest) 9 | 6. [Credits](#credits) 10 | 11 | ## Installation 12 | 13 | 14 | ### Via pip 15 | ``` 16 | pip install isONform 17 | ``` 18 | 19 | This command installs isONforms dependencies: 20 | 21 | 1. `networkx` 22 | 2. `ordered-set` 23 | 3. `matplotlib` 24 | 4. `parasail` 25 | 5. `edlib` 26 | 6. `pyinstrument` 27 | 7. `namedtuple` 28 | 8. `recordclass` 29 | 30 | 31 | ### From github source 32 | 1. Create a new environment for isONform (at least python 3.7 required):
33 | `conda create -n isonform python=3.10 pip`
34 | `conda activate isonform`
35 | 2. Install isONcorrect and SPOA
36 | `pip install isONcorrect`
37 | `conda install -c bioconda spoa`
38 | 3. Install other dependencies of isONform:
39 | `conda install networkx`
40 | `pip install parasail`
41 | 42 | 4. clone this repository 43 | 44 | 45 | ## Introduction 46 | 47 | IsONform generates isoforms out of clustered and corrected long reads. 48 | For this a graph is built up using the networkx api and different simplification strategies are applied to it, such as bubble popping and node merging. 49 | The algorithm uses spoa to generate the final isoforms.
50 | ## Input data 51 | The isONpipeline takes .fastq files generated with long-read sequencing techniques (ONT or Pacbio) as an input that additionally have been cleaned of barcodes. 52 | Please make sure that you run the isONpipeline on data that have been processed with [LIMA](https://lima.how/) (Pacbio data) or [Pychopper](https://github.com/epi2me-labs/pychopper) (ONT data) so that all the barcodes are removed from the reads 53 | 54 | ## Running isONform 55 | 56 | To only run the isONform algorithm:
57 | 58 | 59 | ``` 60 | isONform_parallel --fastq_folder path/to/input/files --t --outfolder /path/to/outfolder --split_wrt_batches 61 | ``` 62 | 63 | Note: Please always use absolute paths to the files or folders 64 | 65 | The full isON-pipeline (isONclust, isONcorrect, isONform) can be found [here](https://github.com/aljpetri/isONform/blob/master/isON_pipeline.sh) and is run via: 66 | 67 | ``` 68 | ./isON_pipeline.sh --raw_reads --outfolder --num_cores --isONform_folder --iso_abundance --mode 69 | ``` 70 | (Please note that this requires isONclust [LINK](https://github.com/ksahlin/isONclust) and isONcorrect [LINK](https://github.com/ksahlin/isONcorrect) to be installed in addition to isONform) 71 | 72 | To receive more information about the arguments used for the isON_pipeline script: 73 | ``` 74 | ./isON_pipeline.sh --help 75 | ``` 76 | 77 | ## Outputs 78 | IsONform outputs three main files: transcriptome.fasta, mapping.txt, and support.txt. 79 | For each isoform that isONform reconstructs the id has the following form: x_y_z. 80 | 81 | 'x' denotes the isONclust cluster that the isoform stems from. 82 | As we cluster reads as in isONcorrect in batches of 1000 reads the 'y' denotes from which batch the isoform was reconstructed. 83 | The 'z' denotes a unique identifier which enables us to have unique ids for each isoform that we reconstructed. 84 | In mapping.txt it is indicated from which original reads an isoform has been reconstructed. 85 | support_txt gives the support (i.e. how many original reads make up the isoform). 86 | 87 | ## Contact 88 | If you encounter any problems, please raise an issue on the issues page, you can also contact the developer of this repository via: 89 | alexander.petri[at]math.su.se 90 | 91 | 92 | ## Credits 93 | 94 | Please cite [1] when using isONform. 95 | 96 | 1. Petri, A. J., & Sahlin, K. (2023). isONform: reference-free transcriptome reconstruction from Oxford Nanopore data. Bioinformatics, 39(Supplement_1), i222-i231. https://academic.oup.com/bioinformatics/article/39/Supplement_1/i222/7210488 . 97 | 98 | Please additionally cite [2] and [3] when running the full pipeline. 99 | 100 | 2. Kristoffer Sahlin, Paul Medvedev. De Novo Clustering of Long-Read Transcriptome Data Using a Greedy, Quality-Value Based Algorithm, Journal of Computational Biology 2020, 27:4, 472-484. [Link](https://www.liebertpub.com/doi/abs/10.1089/cmb.2019.0299). 101 | 3. Sahlin, K., Medvedev, P. Error correction enables use of Oxford Nanopore technology for reference-free transcriptome analysis. Nat Commun 12, 2 (2021). https://doi.org/10.1038/s41467-020-20340-8 [Link](https://www.nature.com/articles/s41467-020-20340-8). 102 | -------------------------------------------------------------------------------- /modules/Parallelization_side_functions.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import os 3 | import errno 4 | import os.path 5 | import shutil 6 | 7 | 8 | def mkdir_p(path): 9 | try: 10 | os.makedirs(path) 11 | print("creating", path) 12 | except OSError as exc: # Python >2.5 13 | if exc.errno == errno.EEXIST and os.path.isdir(path): 14 | pass 15 | else: 16 | raise 17 | def generate_single_support(outfolder): 18 | subfolders = [f.path for f in os.scandir(outfolder) if f.is_dir()] 19 | f = open(os.path.join(outfolder, "transcriptome_support.txt"), "w") 20 | for subfolder in subfolders: 21 | actual_folder = subfolder.split("/")[-1] 22 | # print(actual_folder) 23 | if actual_folder.isdigit(): 24 | fname = os.path.join(outfolder, "support_" + str(actual_folder) + ".txt") 25 | if os.path.isfile(fname): 26 | g = open(fname, "r") 27 | # read content from first file 28 | for line in g: 29 | # append content to second file 30 | f.write(line) 31 | def generate_low_abundance_mapping(outfolder): 32 | subfolders = [f.path for f in os.scandir(outfolder) if f.is_dir()] 33 | f = open(os.path.join(outfolder, "transcriptome_mapping_low.txt"), "w") 34 | for subfolder in subfolders: 35 | actual_folder = subfolder.split("/")[-1] 36 | # print(actual_folder) 37 | if actual_folder.isdigit(): 38 | fname = os.path.join(outfolder, "cluster" + str(actual_folder) + "_mapping_low_abundance.txt") 39 | # print(fname) 40 | 41 | if os.path.isfile(fname): 42 | g = open(fname, "r") 43 | # read content from first file 44 | for line in g: 45 | # append content to second file 46 | f.write(line) 47 | def generate_single_mapping(outfolder): 48 | subfolders = [f.path for f in os.scandir(outfolder) if f.is_dir()] 49 | f = open(os.path.join(outfolder, "transcriptome_mapping.txt"), "w") 50 | for subfolder in subfolders: 51 | actual_folder = subfolder.split("/")[-1] 52 | if actual_folder.isdigit(): 53 | fname = os.path.join(outfolder, "cluster" + str(actual_folder) + "_mapping.txt") 54 | 55 | if os.path.isfile(fname): 56 | g = open(fname, "r") 57 | # read content from first file 58 | for line in g: 59 | # append content to second file 60 | f.write(line) 61 | def generate_single_output(outfolder,write_fastq): 62 | subfolders = [f.path for f in os.scandir(outfolder) if f.is_dir()] 63 | if write_fastq: 64 | print("Generating transcriptome.fastq") 65 | f = open(os.path.join(outfolder,"transcriptome.fastq"), "w") 66 | else: 67 | print("Generating transcriptome.fasta") 68 | f = open(os.path.join(outfolder, "transcriptome.fasta"), "w") 69 | for subfolder in subfolders: 70 | #print("subfolder",subfolder) 71 | actual_folder=subfolder.split("/")[-1] 72 | #print(actual_folder) 73 | if actual_folder.isdigit(): 74 | if write_fastq: 75 | fname=os.path.join(outfolder, "cluster"+str(actual_folder)+"_merged.fq") 76 | else: 77 | fname = os.path.join(outfolder, "cluster" + str(actual_folder) + "_merged.fa") 78 | #print(fname) 79 | if os.path.isfile(fname): 80 | #print("True") 81 | g = open(fname, "r") 82 | # read content from first file 83 | for line in g: 84 | #if line.startswith('@'): 85 | # line=line+"_"+str(actual_folder) 86 | # print("LINE",line) 87 | # append content to second file 88 | f.write(line) 89 | 90 | def generate_low_abundance_output(outfolder,write_fastq): 91 | subfolders = [f.path for f in os.scandir(outfolder) if f.is_dir()] 92 | if write_fastq: 93 | f = open(os.path.join(outfolder, "transcriptome_low.fastq"), "w") 94 | else: 95 | f = open(os.path.join(outfolder, "transcriptome_low.fasta"), "w") 96 | for subfolder in subfolders: 97 | actual_folder = subfolder.split("/")[-1] 98 | # print(actual_folder) 99 | if actual_folder.isdigit(): 100 | if write_fastq: 101 | fname = os.path.join(outfolder, "cluster" + str(actual_folder) + "_merged_low_abundance.fq") 102 | # print(fname) 103 | else: 104 | fname = os.path.join(outfolder, "cluster" + str(actual_folder) + "_merged_low_abundance.fa") 105 | if os.path.isfile(fname): 106 | g = open(fname, "r") 107 | # read content from first file 108 | for line in g: 109 | if line.startswith('@') or line.startswith('>'): 110 | line = line + str(actual_folder) 111 | # append content to second file 112 | f.write(line) 113 | 114 | 115 | def remove_folders(outfolder): 116 | subfolders = [f.path for f in os.scandir(outfolder) if f.is_dir()] 117 | for subfolder in subfolders: 118 | shutil.rmtree(os.path.join(outfolder,subfolder)) 119 | 120 | def generate_full_output(outfolder,write_fastq, write_low_abundance): 121 | generate_single_output(outfolder, write_fastq) 122 | generate_single_mapping(outfolder) 123 | generate_single_support(outfolder) 124 | if write_low_abundance: 125 | generate_low_abundance_output(outfolder, write_fastq) 126 | generate_low_abundance_mapping(outfolder) -------------------------------------------------------------------------------- /isON_pipeline.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | #the pipeline can be run in different modes: 4 | 5 | ####ONT data 6 | # ont_with_pychopper: the full pipeline is run in addition to pychopper (pychopper, isONclust,isONcorrect,isONform) 7 | # ont_no_pychopper: only the isONpipeline is run without pychopper (isONclust,isONcorrect, isONform) 8 | # ont_no_pychop_isonclust3 9 | ####PACBIO data 10 | # pacbio: for PacBio data runs isONclust and isONform 11 | 12 | 13 | ###### test modes (only for internal use) 14 | # analysis: analysis of ont data: isONclust,isONcorrect and isONform are run (e.g. analyses on the paper) 15 | # only_isonform: only isONform is run 16 | #!/bin/bash 17 | 18 | programname=$0 19 | function usage { 20 | echo "" 21 | echo "Runs the full isON pipeline. Please make sure that the input file has been preprocessed with pychopper for ONT data " 22 | echo "" 23 | echo "usage: $programname --raw_reads string --outfolder string --num_cores integer --isONform_folder string --iso_abundance integer --mode string" 24 | echo "" 25 | echo " --raw_reads absolute path to the input file (in fastq format)" 26 | echo " (example: /home/user/Rawdata/raw_reads.fq)" 27 | echo " --outfolder absolute path to the output folder (the folder in which all outputs are stored)" 28 | echo " (example: /home/user/analysis_output)" 29 | echo " --num_cores the number of processors the pipeline may use" 30 | echo " (example: 8)" 31 | echo " --isONform_folder the absolute path to the isONform installation on your machine (leave empty if you have installed isONform via pip)" 32 | echo " (example: /home/user/isONform )" 33 | echo " --iso_abundance threshold which denotes the minimum read support neccessary for an isoform to be called (also minimum number of reads per cluster in isONclust)" 34 | echo " (example: 5)" 35 | echo " --mode Run mode of the pipeline, possible modes are 'ont_no_pyc' and 'ont_with_pc' for ont data and 'pacbio' for pacbio data" 36 | echo " (example: ont_no_pychopper/ont_with_pychopper/pacbio)" 37 | echo " For ONT data: use 'ont_no_pychopper' if you want to run the isON pipeline and pychopper, use 'ont_with_pychopper' if you only want to run the isON pipeline. Please run pychopper yourself before running the pipeline." 38 | echo "" 39 | } 40 | 41 | while [ $# -gt 0 ]; do 42 | # Check if the current argument is "--help" 43 | if [[ $1 == "--help" ]]; then 44 | # Call the usage function and exit with status code 0 45 | usage 46 | exit 0 47 | # Check if the current argument is an option starting with "--" 48 | elif [[ $1 == "--"* ]]; then 49 | # Extract the option name by removing the leading dashes 50 | v="${1/--/}" 51 | # Check if the argument for this option was left empty (then we would have the next argument name as next entry) 52 | if [[ $2 != "--"* ]]; then 53 | #The argument was not left empty, therefore we properly set the argument as the value for option 54 | declare "$v"="$2" 55 | #We have to shift only in this case 56 | shift 57 | fi 58 | fi 59 | #This is the shift we have to perform each time 60 | shift 61 | done 62 | 63 | if [[ -z $raw_reads ]]; then 64 | usage 65 | die "Missing parameter --raw_reads" 66 | elif [[ -z $outfolder ]]; then 67 | usage 68 | die "Missing parameter --outfolder" 69 | elif [[ -z $mode ]]; then 70 | usage 71 | die "Missing parameter --mode" 72 | #elif [[ -z $isONform_folder ]]; then 73 | # isONform_folder='' 74 | #TODO set isONform folder to '' if not given 75 | fi 76 | 77 | echo "Running `basename $0` raw reads: '$raw_reads' outfolder: '$outfolder' num_cores: '$num_cores' isONform_folder:'$isONform_folder' iso_abundance: '$iso_abundance' mode: '$mode'" 78 | 79 | mkdir -p $outfolder 80 | ##Testing whether the programs are installed properly before attempting to run them 81 | # shellcheck disable=SC1072 82 | if [ $mode != "pacbio" ] && [ $mode != "ont_no_pychop" ]; #we do not want to test for pychopper if we run modes pacbio or ont_no_pychop 83 | then 84 | pychopper --h 85 | fi 86 | isONclust 87 | #only test for isONcorrect if we want to use it (so not neccessary for Pacbio data) 88 | if [ $mode != "pacbio" ] 89 | then 90 | run_isoncorrect 91 | fi 92 | 93 | if [ -n "$isONform_folder" ] #the user has given a path to isONform (cloned from github) 94 | then 95 | $isONform_folder/isONform_parallel --h 96 | else 97 | python isONform_parallel --h 98 | fi 99 | 100 | 101 | 102 | if [ $mode == "ont_with_pychopper" ] 103 | then 104 | echo 105 | echo "Will run pychopper (cdna_classifier.py), isONclust, isONcorrect and isONform. Make sure you have these tools installed." 106 | echo "For installation see: https://github.com/ksahlin/isONcorrect#installation and https://github.com/aljpetri/isONform" 107 | echo 108 | 109 | echo 110 | echo "Running pychopper" 111 | echo 112 | 113 | pychopper $raw_reads $outfolder/full_length.fq -t $num_cores 114 | 115 | echo 116 | echo "Finished pychopper" 117 | echo 118 | 119 | fi 120 | 121 | if [ $mode != "only_isonform" ] # this if statement prevents isONclust and isONcorrect from being run 122 | then 123 | echo 124 | echo "Running isONclust" 125 | echo 126 | if [ $mode == "ont_with_pychopper" ] 127 | then 128 | /usr/bin/time -v isONclust --t $num_cores --ont --fastq $outfolder/full_length.fq \ 129 | --outfolder $outfolder/clustering 130 | /usr/bin/time -v isONclust write_fastq --N $iso_abundance --clusters $outfolder/clustering/final_clusters.tsv \ 131 | --fastq $outfolder/full_length.fq --outfolder $outfolder/clustering/fastq_files 132 | elif [ $mode == "ont_no_pychopper" ] 133 | then 134 | /usr/bin/time -v isONclust --t $num_cores --ont --fastq $raw_reads \ 135 | --outfolder $outfolder/clustering 136 | /usr/bin/time -v isONclust write_fastq --N $iso_abundance --clusters $outfolder/clustering/final_clusters.tsv \ 137 | --fastq $raw_reads --outfolder $outfolder/clustering/fastq_files 138 | elif [ $mode == "pacbio" ] #This is the pacbio mode 139 | then 140 | /usr/bin/time -v isONclust --t $num_cores --isoseq --fastq $raw_reads \ 141 | --outfolder $outfolder/clustering 142 | /usr/bin/time -v isONclust write_fastq --N $iso_abundance --clusters $outfolder/clustering/final_clusters.tsv \ 143 | --fastq $raw_reads --outfolder $outfolder/clustering/fastq_files 144 | 145 | #elif [ $mode == "ont_no_pychop_isonclust3" ] 146 | # then 147 | # /home/alexanderpetri/Rust/isONclust_rs/target/release/isONclust3 --mode ont --fastq $raw_reads --outfolder $outfolder --n 1 148 | else #[ $mode != "pacbio" ] && [ $mode != "'ont'" ] 149 | /usr/bin/time -v isONclust --t $num_cores --fastq $raw_reads \ 150 | --outfolder $outfolder 151 | /usr/bin/time -v isONclust write_fastq --N $iso_abundance --clusters $outfolder/clustering/final_clusters.tsv \ 152 | --fastq $raw_reads --outfolder $outfolder/clustering/fastq_files 153 | 154 | 155 | fi 156 | 157 | echo 158 | echo "Finished isONclust" 159 | echo 160 | #conda activate isON311 161 | 162 | if [ $mode != "pacbio" ] 163 | then 164 | echo 165 | echo "Running isONcorrect" 166 | echo 167 | 168 | /usr/bin/time -v run_isoncorrect --t $num_cores --fastq_folder $outfolder/clustering/fastq_files --outfolder $outfolder/correction/ 169 | 170 | echo 171 | echo "Finished isONcorrect" 172 | echo 173 | fi 174 | fi 175 | echo 176 | echo "Merging reads back to single file. Corrected reads per cluster are still stored in: " $outfolder/correction/ 177 | echo 178 | 179 | echo 180 | echo "Running isONform" 181 | echo 182 | if [ -n "$isONform_folder" ] #the user has given a path to isONform (cloned from github) 183 | then 184 | if [ $mode != "pacbio" ] #i.e. we run in ONT mode 185 | then 186 | /usr/bin/time -v $isONform_folder/isONform_parallel --t $num_cores --fastq_folder $outfolder/correction --exact_instance_limit 50 --k 20 --w 31 --xmin 14 --xmax 80 --max_seqs_to_spoa 200 --delta_len 10 --outfolder $outfolder/isoforms --iso_abundance $iso_abundance --delta_iso_len_3 30 --delta_iso_len_5 50 187 | else #we run isONform in pacbio mode (adding the keyword clustered to the command) 188 | /usr/bin/time -v $isONform_folder/isONform_parallel --t $num_cores --fastq_folder $outfolder/clustering/fastq_files --exact_instance_limit 50 --k 20 --w 31 --xmin 14 --xmax 80 --max_seqs_to_spoa 200 --delta_len 10 --outfolder $outfolder/isoforms --iso_abundance $iso_abundance --delta_iso_len_3 30 --delta_iso_len_5 50 189 | fi 190 | 191 | 192 | else #the user has not given a path to isONform (pip installation supposed) 193 | if [ $mode != "pacbio" ] #i.e. we run in ONT mode 194 | then 195 | /usr/bin/time -v isONform_parallel --t $num_cores --fastq_folder $outfolder/correction/ --exact_instance_limit 50 --k 20 --w 31 --xmin 14 --xmax 80 --max_seqs_to_spoa 200 --delta_len 10 --outfolder $outfolder/isoforms --iso_abundance $iso_abundance --delta_iso_len_3 30 --delta_iso_len_5 50 196 | else #we run isONform in pacbio mode (adding the keyword clustered to the command) 197 | /usr/bin/time -v isONform_parallel --t $num_cores --fastq_folder $outfolder/clustering/fastq_files --exact_instance_limit 50 --k 20 --w 31 --xmin 14 --xmax 80 --max_seqs_to_spoa 200 --delta_len 10 --outfolder $outfolder/isoforms --iso_abundance $iso_abundance --delta_iso_len_3 30 --delta_iso_len_5 50 198 | fi 199 | fi 200 | echo 201 | echo "Finished isONform" 202 | echo 203 | 204 | echo 205 | echo "Finished with pipeline and wrote corrected reads into: " $outfolder 206 | echo -------------------------------------------------------------------------------- /modules/create_augmented_reference.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import argparse 3 | import os 4 | import subprocess 5 | from sys import stdout 6 | from collections import defaultdict, deque 7 | 8 | 9 | # Botonds DP 10 | def cutoff(x): 11 | return x 12 | 13 | """def longest_path_botond(dot_graph_path): 14 | G = nx.drawing.nx_pydot.read_dot(dot_graph_path) 15 | topo = list(nx.topological_sort(G)) 16 | data = nx.get_node_attributes(G, 'label') 17 | # data = {x: chr(int(y.split(" - ")[1].split("\"")[0])) for x, y in data.items()} 18 | data = {x: y.split(" - ")[1].split("\"")[0] for x, y in data.items()} 19 | scores = defaultdict(int) 20 | bt = defaultdict(lambda: -1) 21 | 22 | for n in topo: 23 | sc = [] 24 | for p in G.predecessors(n): 25 | tmp = G.get_edge_data(p, n, key=0) 26 | if 'label' in tmp: 27 | weight = int(tmp['label'].strip("\"")) 28 | sc.append((p, scores[p] + cutoff(weight))) 29 | # sc.append((p, scores[p] + weight)) 30 | sc = sorted(sc, key=lambda x: x[1], reverse=True) 31 | if len(sc) < 1: 32 | continue 33 | bt[n] = sc[0][0] 34 | scores[n] = sc[0][1] 35 | 36 | max_score = max(scores.values()) 37 | lookup = {y: x for x, y in scores.items()} 38 | 39 | prev = lookup[max_score] 40 | nodes = [] 41 | 42 | while prev != -1: 43 | nodes.append(prev) 44 | prev = bt[prev] 45 | 46 | nodes = list(reversed(nodes)) 47 | 48 | print(">cons_" + str(len(nodes))) 49 | 50 | bases = [data[n] for n in nodes] 51 | cons = ''.join(bases) 52 | print(cons) 53 | return cons""" 54 | 55 | 56 | 57 | def run_spoa_affine(reads, ref_out_file, spoa_out_file, spoa_path, dot_graph_path): 58 | with open(spoa_out_file, "w") as output_file: 59 | print('Running spoa...', end=' ') 60 | stdout.flush() 61 | null = open("/dev/null", "w") 62 | subprocess.check_call([ spoa_path, "-q", reads, "-l", "2", "-r", "2", "-x", "-8", "-m", "10", "-o","-8", "-e", "-1", "-d", dot_graph_path], stderr=output_file, stdout=null) 63 | print('Done.') 64 | stdout.flush() 65 | output_file.close() 66 | l = open(spoa_out_file, "r").readlines() 67 | consensus = l[1].strip() 68 | msa = [s.strip() for s in l[3:]] 69 | print("affine heaviest path:", consensus, len(consensus)) 70 | print() 71 | # print(msa) 72 | 73 | r = open(ref_out_file, "w") 74 | r.write(">{0}\n{1}".format("reference", consensus)) 75 | r.close() 76 | return consensus, msa 77 | 78 | def run_spoa_convex(reads, ref_out_file, spoa_out_file, spoa_path, dot_graph_path): 79 | with open(spoa_out_file, "w") as output_file: 80 | print('Running spoa convex...', end=' ') 81 | stdout.flush() 82 | null = open("/dev/null", "w") 83 | # print(spoa_path, "-l", "2", "-r", "2", "-g", "-4", "-e", "0", "-d", dot_graph_path, reads) 84 | subprocess.check_call([ spoa_path, "-l", "2", "-r", "2", "-m", "10", "-g", "-8", "-e", "-2", "-q", "-24", "-c", "-1" , "-d", dot_graph_path, reads], stdout=output_file, stderr=null) 85 | # subprocess.check_call([ spoa_path, "-q", reads, "-l", "2", "-r", "2", "-o","-4", "-e", "0", "-d", dot_graph_path], stderr=output_file, stdout=null) 86 | print('Done.') 87 | stdout.flush() 88 | output_file.close() 89 | l = open(spoa_out_file, "r").readlines() 90 | consensus = l[1].strip() 91 | msa = [s.strip() for s in l[3:]] 92 | print("convex heaviest path:", consensus, len(consensus)) 93 | print() 94 | # print(msa) 95 | 96 | r = open(ref_out_file, "w") 97 | r.write(">{0}\n{1}".format("reference", consensus)) 98 | r.close() 99 | return consensus, msa 100 | 101 | def run_spoa_affine_v2_0_3(reads, ref_out_file, spoa_out_file, spoa_path, dot_graph_path): 102 | with open(spoa_out_file, "w") as output_file: 103 | print('Running spoa...', end=' ') 104 | stdout.flush() 105 | null = open("/dev/null", "w") 106 | # print(spoa_path, "-l", "2", "-r", "2", "-g", "-4", "-e", "0", "-d", dot_graph_path, reads) 107 | subprocess.check_call([ spoa_path, "-l", "2", "-r", "2", "-x", "-4", "-m", "10", "-g", "-8", "-e", "-1", "-d", dot_graph_path, reads], stdout=output_file, stderr=null) 108 | # subprocess.check_call([ spoa_path, "-q", reads, "-l", "2", "-r", "2", "-o","-4", "-e", "0", "-d", dot_graph_path], stderr=output_file, stdout=null) 109 | print('Done.') 110 | stdout.flush() 111 | output_file.close() 112 | l = open(spoa_out_file, "r").readlines() 113 | consensus = l[1].strip() 114 | msa = [s.strip() for s in l[3:]] 115 | print("affine_v2_0_2 heaviest path:", consensus, len(consensus)) 116 | print() 117 | # print(msa) 118 | 119 | r = open(ref_out_file, "w") 120 | r.write(">{0}\n{1}".format("reference", consensus)) 121 | r.close() 122 | return consensus, msa 123 | 124 | def run_spoa_with_msa(reads, ref_out_file, spoa_out_file, spoa_path, dot_graph_path): 125 | with open(spoa_out_file, "w") as output_file: 126 | # print('Running spoa...', end=' ') 127 | stdout.flush() 128 | null = open("/dev/null", "w") 129 | # subprocess.check_call([ spoa_path, reads, "-l", "0", "-r", "2", "-g", "-2", "-d", dot_graph_path], stdout=output_file, stderr=null) 130 | subprocess.check_call([ spoa_path, reads, "-l", "0", "-r", "2", "-g", "-2"], stdout=output_file, stderr=null) 131 | # print('Done.') 132 | stdout.flush() 133 | output_file.close() 134 | l = open(spoa_out_file, "r").readlines() 135 | consensus = l[1].strip() 136 | msa = [s.strip() for s in l[3:]] 137 | # print("regular spoa:", consensus) 138 | # print(len(consensus)) 139 | # print(msa) 140 | 141 | r = open(ref_out_file, "w") 142 | r.write(">{0}\n{1}".format("reference", consensus)) 143 | r.close() 144 | 145 | return consensus, msa 146 | 147 | def run_spoa(reads, spoa_out_file, spoa_path): 148 | with open(spoa_out_file, "w") as output_file: 149 | # print('Running spoa...', end=' ') 150 | stdout.flush() 151 | null = open("/dev/null", "w") 152 | subprocess.check_call([ spoa_path, reads, "-l", "0", "-r", "0", "-g", "-2"], stdout=output_file, stderr=null) 153 | # print('Done.') 154 | stdout.flush() 155 | # output_file.close() 156 | l = open(spoa_out_file, "r").readlines() 157 | consensus = l[1].strip() 158 | del l 159 | return consensus 160 | 161 | def run_spoa_m(reads, spoa_out_file, spoa_path): 162 | with open(spoa_out_file, "w") as output_file: 163 | # print('Running spoa...', end=' ') 164 | stdout.flush() 165 | null = open("/dev/null", "w") 166 | subprocess.check_call([ spoa_path, reads, "-l", "0", "-r", "0", "-g", "-4"], stdout=output_file, stderr=null) 167 | # print('Done.') 168 | stdout.flush() 169 | # output_file.close() 170 | l = open(spoa_out_file, "r").readlines() 171 | consensus = l[1].strip() 172 | del l 173 | return consensus 174 | 175 | def run_spoa_m2(reads, spoa_out_file, spoa_path): 176 | with open(spoa_out_file, "w") as output_file: 177 | # print('Running spoa...', end=' ') 178 | stdout.flush() 179 | null = open("/dev/null", "w") 180 | subprocess.check_call([ spoa_path, reads, "-l", "0", "-r", "0", "-g", "-8"], stdout=output_file, stderr=null) 181 | # print('Done.') 182 | stdout.flush() 183 | # output_file.close() 184 | l = open(spoa_out_file, "r").readlines() 185 | consensus = l[1].strip() 186 | del l 187 | return consensus 188 | 189 | def run_racon(reads_to_center, read_alignments_paf, center_file, outfolder, cores, racon_iter): 190 | racon_stdout = os.path.join(outfolder, "racon_stdout.txt") 191 | 192 | 193 | with open(racon_stdout, "w") as output_file: 194 | # print('Running medaka...', end=' ') 195 | stdout.flush() 196 | for i in range(racon_iter): 197 | # read_alignments = open(os.path.join(outfolder, "read_alignments_it_{0}.paf".format(i)), 'w') 198 | # mm2_stderr = open(os.path.join(outfolder, "mm2_stderr_it_{0}.txt".format(i)), "w") 199 | racon_stderr = open(os.path.join(outfolder, "racon_stderr_it_{0}.txt".format(i)), "w") 200 | racon_polished = open(os.path.join(outfolder, "racon_polished_it_{0}.fasta".format(i)), 'w') 201 | 202 | # subprocess.check_call(['minimap2', '-k 9', '-w 1', '-f 0.00001', '-n 2', '-m 10', center_file, reads_to_center], stdout=read_alignments, stderr=mm2_stderr) 203 | subprocess.check_call(['racon', reads_to_center, read_alignments_paf, center_file], stdout=racon_polished, stderr=racon_stderr) 204 | center_file = racon_polished.name 205 | l = open(center_file, "r").readlines() 206 | if len(l) == 2: 207 | consensus = l[1].strip() 208 | else: 209 | consensus = '' 210 | del l 211 | return consensus 212 | 213 | # For eventual De Bruijn graph approach 214 | 215 | def kmer_counter(reads, k_size): 216 | count = defaultdict(int) 217 | position_count = defaultdict(list) 218 | 219 | for r_i in reads: 220 | (acc, seq, qual) = reads[r_i] 221 | # seq_hpol_comp = ''.join(ch for ch, _ in itertools.groupby(seq)) 222 | read_kmers = deque([seq[i:i+k_size] for i in range(len(seq) - k_size )]) 223 | for i, kmer in enumerate(read_kmers): 224 | count[kmer] += 1 225 | 226 | position_count[kmer].append( (r_i, i)) 227 | 228 | # cnt_sorted = sorted(count.items(), key = lambda x: x[1], reverse=True) 229 | # print(len(cnt_sorted),cnt_sorted) 230 | return count, position_count 231 | 232 | 233 | if __name__ == '__main__': 234 | parser = argparse.ArgumentParser(description="Maps the given reads with bwa.") 235 | parser.add_argument('reads', type=str, help='Fasta or fastq') 236 | parser.add_argument('outfile', type=str, help='Fasta or fastq') 237 | parser.add_argument('--spoa_path', type=str, default='spoa', required=False, help='Path to spoa binary with bwa binary name at the end.') 238 | 239 | 240 | args = parser.parse_args() 241 | 242 | run_spoa(args.reads, args.outfile, args.spoa_path) 243 | -------------------------------------------------------------------------------- /modules/consensus.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import subprocess 3 | import sys, os 4 | from sys import stdout 5 | import re 6 | import shutil 7 | import parasail 8 | import glob 9 | 10 | from modules import help_functions 11 | 12 | 13 | def cigar_to_seq(cigar, query, ref): 14 | cigar_tuples = [] 15 | result = re.split(r'[=DXSMI]+', cigar) 16 | cig_pos = 0 17 | for length in result[:-1]: 18 | cig_pos += len(length) 19 | type_ = cigar[cig_pos] 20 | cig_pos += 1 21 | cigar_tuples.append((int(length), type_ )) 22 | 23 | r_index = 0 24 | q_index = 0 25 | q_aln = [] 26 | r_aln = [] 27 | for length_ , type_ in cigar_tuples: 28 | if type_ == "=" or type_ == "X": 29 | q_aln.append(query[q_index : q_index + length_]) 30 | r_aln.append(ref[r_index : r_index + length_]) 31 | 32 | r_index += length_ 33 | q_index += length_ 34 | 35 | elif type_ == "I": 36 | # insertion w.r.t. reference 37 | r_aln.append('-' * length_) 38 | q_aln.append(query[q_index: q_index + length_]) 39 | # only query index change 40 | q_index += length_ 41 | 42 | elif type_ == 'D': 43 | # deletion w.r.t. reference 44 | r_aln.append(ref[r_index: r_index + length_]) 45 | q_aln.append('-' * length_) 46 | # only ref index change 47 | r_index += length_ 48 | 49 | else: 50 | sys.exit() 51 | 52 | return "".join([s for s in q_aln]), "".join([s for s in r_aln]), cigar_tuples 53 | 54 | 55 | def parasail_alignment(s1, s2, match_score = 2, mismatch_penalty = -2, opening_penalty = 12, gap_ext = 1): 56 | user_matrix = parasail.matrix_create("ACGT", match_score, mismatch_penalty) 57 | result = parasail.sg_trace_scan_16(s1, s2, opening_penalty, gap_ext, user_matrix) 58 | if result.saturated: 59 | result = parasail.sg_trace_scan_32(s1, s2, opening_penalty, gap_ext, user_matrix) 60 | 61 | # difference in how to obtain string from parasail between python v2 and v3... 62 | if sys.version_info[0] < 3: 63 | cigar_string = str(result.cigar.decode).decode('utf-8') 64 | else: 65 | cigar_string = str(result.cigar.decode, 'utf-8') 66 | s1_alignment, s2_alignment, cigar_tuples = cigar_to_seq(cigar_string, s1, s2) 67 | return s1_alignment, s2_alignment, cigar_string, cigar_tuples, result.score 68 | 69 | 70 | def reverse_complement(string): 71 | # Modified for Abyss output 72 | rev_nuc = {'A':'T', 'C':'G', 'G':'C', 'T':'A', 'a':'t', 'c':'g', 'g':'c', 't':'a', 'N':'N', 'X':'X', 'n':'n', 'Y':'R', 'R':'Y', 'K':'M', 'M':'K', 'S':'S', 'W':'W', 'B':'V', 'V':'B', 'H':'D', 'D':'H', 'y':'r', 'r':'y', 'k':'m', 'm':'k', 's':'s', 'w':'w', 'b':'v', 'v':'b', 'h':'d', 'd':'h'} 73 | rev_comp = ''.join([rev_nuc[nucl] for nucl in reversed(string)]) 74 | return rev_comp 75 | 76 | 77 | def run_spoa(reads, spoa_out_file, spoa_path): 78 | with open(spoa_out_file, "w") as output_file: 79 | # print('Running spoa...', end=' ') 80 | stdout.flush() 81 | null = open("/dev/null", "w") 82 | subprocess.check_call([ spoa_path, reads, "-l", "0", "-r", "0", "-g", "-2"], stdout=output_file, stderr=null) 83 | # print('Done.') 84 | stdout.flush() 85 | output_file.close() 86 | l = open(spoa_out_file, "r").readlines() 87 | consensus = l[1].strip() 88 | return consensus 89 | 90 | 91 | def run_medaka(reads_to_center, center_file, outfolder, cores, medaka_model): 92 | medaka_stdout = os.path.join(outfolder, "stdout.txt") 93 | with open(medaka_stdout, "w") as output_file: 94 | # print('Running medaka...', end=' ') 95 | stdout.flush() 96 | medaka_stderr = open(os.path.join(outfolder, "stderr.txt"), "w") 97 | if medaka_model: 98 | subprocess.check_call(['medaka_consensus', '-i', reads_to_center, "-d", center_file, "-o", outfolder, "-t", cores, "-m", medaka_model], stdout=output_file, stderr=medaka_stderr) 99 | else: 100 | subprocess.check_call(['medaka_consensus', '-i', reads_to_center, "-d", center_file, "-o", outfolder, "-t", cores], stdout=output_file, stderr=medaka_stderr) 101 | stdout.flush() 102 | output_file.close() 103 | 104 | 105 | def run_racon(reads_to_center, center_file, outfolder, cores, racon_iter): 106 | racon_stdout = os.path.join(outfolder, "stdout.txt") 107 | with open(racon_stdout, "w") as output_file: 108 | # print('Running medaka...', end=' ') 109 | stdout.flush() 110 | for i in range(racon_iter): 111 | read_alignments = open(os.path.join(outfolder, "read_alignments_it_{0}.paf".format(i)), 'w') 112 | mm2_stderr = open(os.path.join(outfolder, "mm2_stderr_it_{0}.txt".format(i)), "w") 113 | racon_stderr = open(os.path.join(outfolder, "racon_stderr_it_{0}.txt".format(i)), "w") 114 | racon_polished = open(os.path.join(outfolder, "racon_polished_it_{0}.fasta".format(i)), 'w') 115 | 116 | subprocess.check_call(['minimap2', '-x', 'map-ont', center_file, reads_to_center], stdout=read_alignments, stderr=mm2_stderr) 117 | subprocess.check_call(['racon', reads_to_center, read_alignments.name, center_file], stdout=racon_polished, stderr=racon_stderr) 118 | center_file = racon_polished.name 119 | 120 | shutil.copyfile(center_file, os.path.join(outfolder, "consensus.fasta")) 121 | # print('Done.') 122 | stdout.flush() 123 | output_file.close() 124 | 125 | 126 | def detect_reverse_complements(centers, rc_identity_threshold): 127 | filtered_centers = [] 128 | already_removed = set() 129 | for i, (nr_reads_in_cl, c_id, seq, reads_path) in enumerate(centers): 130 | if type(reads_path) != list: 131 | all_reads = [reads_path] 132 | else: 133 | all_reads = reads_path 134 | 135 | merged_cluster_id = c_id 136 | merged_nr_reads = nr_reads_in_cl 137 | if c_id in already_removed: 138 | #print("has already been merged, skipping") 139 | continue 140 | 141 | elif i == len(centers) - 1: # last sequence and it is not in already removed 142 | filtered_centers.append( [merged_nr_reads, c_id, seq, all_reads ] ) 143 | 144 | else: 145 | for j, (nr_reads_in_cl2, c_id2, seq2, reads_path) in enumerate(centers[i+1:]): 146 | seq2_rc = reverse_complement(seq2) 147 | seq_aln, seq2_rc_aln, cigar_string, cigar_tuples, alignment_score = parasail_alignment(seq, seq2_rc) 148 | # print(i,j) 149 | # print(seq_aln) 150 | # print(seq2_rc_aln) 151 | nr_mismatching_pos = len([1 for n1, n2 in zip(seq_aln, seq2_rc_aln) if n1 != n2]) 152 | total_pos = len(seq_aln) 153 | aln_identity = (total_pos - nr_mismatching_pos) / float(total_pos) 154 | #print(aln_identity) 155 | 156 | if aln_identity >= rc_identity_threshold: 157 | #print("Detected alignment identidy above threchold for reverse complement. Keeping center with the most read support and adding rc reads to supporting reads.") 158 | merged_nr_reads += nr_reads_in_cl2 159 | already_removed.add(c_id2) 160 | 161 | if type(reads_path) != list: 162 | all_reads.append(reads_path) 163 | else: 164 | for rp in reads_path: 165 | all_reads.append(rp) 166 | 167 | filtered_centers.append( [merged_nr_reads, c_id, seq, all_reads] ) 168 | 169 | #print(len(filtered_centers), "consensus formed.") 170 | return filtered_centers 171 | 172 | 173 | def polish_sequences(centers, args): 174 | print("Saving spoa references to files:", os.path.join(args.outfolder, "consensus_reference_X.fasta")) 175 | # printing output from spoa and grouping reads 176 | # to_polishing = [] 177 | if args.medaka: 178 | polishing_pattern = os.path.join(args.outfolder, "medaka_cl_id_*") 179 | elif args.racon: 180 | polishing_pattern = os.path.join(args.outfolder, "racon_cl_id_*") 181 | 182 | for folder in glob.glob(polishing_pattern): 183 | shutil.rmtree(folder) 184 | 185 | spoa_pattern = os.path.join(args.outfolder, "consensus_reference_*") 186 | for file in glob.glob(spoa_pattern): 187 | os.remove(file) 188 | 189 | for i, (nr_reads_in_cluster, c_id, center, all_reads) in enumerate(centers): 190 | # print('lol',c_id,center) 191 | spoa_center_file = os.path.join(args.outfolder, "consensus_reference_{0}.fasta".format(c_id)) 192 | f = open(spoa_center_file, "w") 193 | f.write(">{0}\n{1}\n".format("consensus_cl_id_{0}_total_supporting_reads_{1}".format(c_id, nr_reads_in_cluster), center)) 194 | f.close() 195 | 196 | all_reads_file = os.path.join(args.outfolder, "reads_to_consensus_{0}.fastq".format(c_id)) 197 | f = open(all_reads_file, "w") 198 | for fasta_file in all_reads: 199 | reads = { acc : (seq, qual) for acc, (seq, qual) in help_functions.readfq(open(fasta_file, 'r'))} 200 | for acc, (seq, qual) in reads.items(): 201 | f.write("@{0}\n{1}\n{2}\n{3}\n".format(acc, seq, "+", qual)) 202 | f.close() 203 | # to_polishing.append( (nr_reads_in_cluster, c_id, spoa_center_file, all_reads_file) ) 204 | 205 | if args.medaka: 206 | print("running medaka on spoa reference {0}.".format(c_id)) 207 | # for (nr_reads_in_cluster, c_id, spoa_center_file, all_reads_file) in to_polishing: 208 | polishing_outfolder = os.path.join(args.outfolder, "medaka_cl_id_{0}".format(c_id)) 209 | help_functions.mkdir_p(polishing_outfolder) 210 | run_medaka(all_reads_file, spoa_center_file, polishing_outfolder, "1", args.medaka_model) 211 | print("Saving medaka reference to file:", os.path.join(args.outfolder, "medaka_cl_id_{0}/consensus.fasta".format(c_id))) 212 | l = open(os.path.join(polishing_outfolder, "consensus.fasta"), 'r').readlines() 213 | center_polished = l[1].strip() 214 | centers[i][2] = center_polished 215 | elif args.racon: 216 | print("running racon on spoa reference {0}.".format(c_id)) 217 | # for (nr_reads_in_cluster, c_id, spoa_center_file, all_reads_file) in to_polishing: 218 | polishing_outfolder = os.path.join(args.outfolder, "racon_cl_id_{0}".format(c_id)) 219 | help_functions.mkdir_p(polishing_outfolder) 220 | run_racon(all_reads_file, spoa_center_file, polishing_outfolder, "1", args.racon_iter) 221 | print("Saving racon reference to file:", os.path.join(args.outfolder, "racon_cl_id_{0}/consensus.fasta".format(c_id))) 222 | l = open(os.path.join(polishing_outfolder, "consensus.fasta"), 'r').readlines() 223 | center_polished = l[1].strip() 224 | centers[i][2] = center_polished 225 | 226 | f.close() 227 | return centers 228 | 229 | 230 | def form_draft_consensus(clusters, representatives, sorted_reads_fastq_file, work_dir, abundance_cutoff, args): 231 | centers = [] 232 | reads = { acc : (seq, qual) for acc, (seq, qual) in help_functions.readfq(open(sorted_reads_fastq_file, 'r'))} 233 | for c_id, all_read_acc in sorted(clusters.items(), key = lambda x: (len(x[1]),representatives[x[0]][5]), reverse=True): 234 | reads_path = open(os.path.join(work_dir, "reads_c_id_{0}.fq".format(c_id)), "w") 235 | nr_reads_in_cluster = len(all_read_acc) 236 | # print("nr_reads_in_cluster", nr_reads_in_cluster) 237 | if nr_reads_in_cluster >= abundance_cutoff: 238 | for acc in all_read_acc: 239 | seq, qual = reads[acc] 240 | reads_path.write("@{0}\n{1}\n{2}\n{3}\n".format(acc, seq, "+", qual)) 241 | # reads_path.write(">{0}\n{1}\n".format(str(q_id)+str(pos1)+str(pos2), seq)) 242 | reads_path.close() 243 | # spoa_ref = create_augmented_reference.run_spoa(reads_path.name, os.path.join(work_dir,"spoa_tmp.fa"), "spoa") 244 | #print("creating center of {0} sequences.".format(nr_reads_in_cluster)) 245 | center = run_spoa(reads_path.name, os.path.join(work_dir,"spoa_tmp.fa"), "spoa") 246 | centers.append( [nr_reads_in_cluster, c_id, center, reads_path.name]) 247 | return centers 248 | -------------------------------------------------------------------------------- /modules/batch_merging_parallel.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | import pickle 3 | import os 4 | 5 | import shutil 6 | from modules import IsoformGeneration 7 | from modules import Parallelization_side_functions 8 | 9 | class Read: 10 | def __init__(self, sequence, reads, merged): 11 | self.sequence = sequence 12 | self.reads = reads 13 | self.merged = merged 14 | 15 | def generate_consensus_path(work_dir, mappings1, mappings2, all_sequences, spoa_count): 16 | """ This method is used to generate the consensus file needed for the consensus generation 17 | INPUT: work_dir : The working directory in which to store the file 18 | OUTPUT: spoa_ref: The consensus 19 | """ 20 | reads_path = open(os.path.join(work_dir, "reads_tmp.fa"), "w") 21 | seq_count = 0 22 | for id in mappings1: 23 | if seq_count < spoa_count: 24 | sequence = all_sequences[id] 25 | reads_path.write(">{0}\n{1}\n".format(str(id), sequence)) 26 | seq_count += 1 27 | for id in mappings2: 28 | if seq_count < spoa_count: 29 | if not (id in all_sequences): 30 | sequence = id 31 | reads_path.write(">{0}\n{1}\n".format(str(id), sequence)) 32 | seq_count += 1 33 | reads_path.close() 34 | spoa_ref = IsoformGeneration.run_spoa(reads_path.name, os.path.join(work_dir, "spoa_tmp.fa")) 35 | return spoa_ref 36 | 37 | 38 | """ This function reads the consensus file and saves the infos in batch_reads_id 39 | INPUT: work_dir : The working directory in which to store the file 40 | OUTPUT: spoa_ref: The consensus 41 | """ 42 | 43 | 44 | def read_spoa_file(batch_id, cl_dir): 45 | filename = "spoa" + str(batch_id) + "merged.fasta" 46 | batch_reads_id = {} 47 | with open(os.path.join(cl_dir, filename)) as f: 48 | for id, sequence in itertools.zip_longest(*[f] * 2): 49 | inter_id = id.replace('\n', '') 50 | new_id = int(inter_id.replace('>consensus', '')) 51 | sequence = sequence.replace('\n', '') 52 | batch_reads_id[new_id] = sequence 53 | return batch_reads_id 54 | 55 | 56 | def read_mapping_file(batch_id, cl_dir): 57 | batch_mappings_id = {} 58 | mappingname = "mapping" + str(batch_id) + ".txt" 59 | incoming_ctr = 0 60 | with open(os.path.join(cl_dir, mappingname)) as g: 61 | for id, reads in itertools.zip_longest(*[g] * 2): 62 | inter_id = id.replace('\n', '') 63 | id = int(inter_id.replace('consensus', '')) 64 | reads = reads.replace('\n', '') 65 | reads = reads.replace('[', '') 66 | reads = reads.replace(']', '') 67 | reads = reads.replace("'", "") 68 | readslist = reads.split(", ") 69 | batch_mappings_id[id] = readslist 70 | incoming_ctr += len(readslist) 71 | return batch_mappings_id 72 | 73 | 74 | def read_batch_file(batch_id, all_infos_dict, all_reads_dict, cl_dir): 75 | batchfilename = str(batch_id) + "_batchfile.fa" 76 | with open(os.path.join(cl_dir, batchfilename)) as h: 77 | for id, seq in itertools.zip_longest(*[h] * 2): 78 | id = id.replace('\n', '') 79 | id = id.replace('>', '') 80 | seq = seq.replace('\n', '') 81 | all_reads_dict[id] = seq 82 | all_infos_dict[batch_id] = {} 83 | 84 | 85 | def write_final_output(all_infos_dict, outfolder, iso_abundance, cl_dir, folder, write_fastq, write_low_abundance): 86 | #write_low_abundance = False 87 | support_name = "support_" + str(folder) + ".txt" 88 | other_support_name = "support_" + str(folder) + "low_abundance.txt" 89 | other_mapping_name = "cluster" + str(folder) + "_mapping_low_abundance.txt" 90 | if write_fastq: 91 | consensus_name = "cluster" + str(folder) + "_merged.fq" 92 | if write_low_abundance: 93 | other_consensus_name = "cluster" + str(folder) + "_merged_low_abundance.fq" 94 | other_consensus = open(os.path.join(outfolder, other_consensus_name), 'w') 95 | other_mapping = open(os.path.join(outfolder, other_mapping_name), 'w') 96 | other_support_file = open(os.path.join(outfolder, other_support_name), "w") 97 | else: 98 | consensus_name = "cluster" + str(folder) + "_merged.fa" 99 | if write_low_abundance: 100 | other_consensus_name = "cluster" + str(folder) + "_merged_low_abundance.fa" 101 | other_consensus = open(os.path.join(outfolder, other_consensus_name), 'w') 102 | other_mapping = open(os.path.join(outfolder, other_mapping_name), 'w') 103 | other_support_file = open(os.path.join(outfolder, other_support_name), "w") 104 | 105 | mapping_name = "cluster" + str(folder) + "_mapping.txt" 106 | support_file = open(os.path.join(outfolder, support_name), "w") 107 | consensus_file = open(os.path.join(outfolder, consensus_name), "w") 108 | mapping_file = open(os.path.join(outfolder, mapping_name), 'w') 109 | skipped_reads = {} 110 | for batchid, id_dict in all_infos_dict.items(): 111 | for id, infos in id_dict.items(): 112 | new_id = str(folder) + "_" + str(batchid) + "_" + str(id) 113 | if not infos.merged: 114 | if len(infos.reads) >= iso_abundance or iso_abundance == 1: 115 | mapping_file.write(">{0}\n{1}\n".format(new_id, all_infos_dict[batchid][id].reads)) 116 | if write_fastq: 117 | consensus_file.write("@{0}\n{1}\n+\n{2}\n".format(new_id, all_infos_dict[batchid][id].sequence, 118 | "+" * len(all_infos_dict[batchid][id].sequence))) 119 | else: 120 | consensus_file.write(">{0}\n{1}\n".format(new_id, all_infos_dict[batchid][id].sequence)) 121 | support_file.write("{0}: {1}\n".format(new_id, len(all_infos_dict[batchid][id].reads))) 122 | else: 123 | if write_low_abundance: 124 | if write_fastq: 125 | other_consensus.write("@{0}\n{1}\n+\n{2}\n".format(new_id, all_infos_dict[batchid][id].sequence, 126 | "+" * len( 127 | all_infos_dict[batchid][id].sequence))) 128 | else: 129 | other_consensus.write(">{0}\n{1}\n".format(new_id, all_infos_dict[batchid][id].sequence)) 130 | if new_id in all_infos_dict: 131 | other_support_file.write("{0}: {1}\n".format(new_id, len(all_infos_dict[new_id].reads))) 132 | else: 133 | other_support_file.write("{0}: {1}\n".format(new_id, 1)) 134 | other_mapping.write(">{0}\n{1}\n".format(new_id, all_infos_dict[batchid][id].reads)) 135 | if write_low_abundance: 136 | for skipfile in os.listdir(cl_dir): 137 | if skipfile.startswith("skip"): 138 | with open(os.path.join(cl_dir, skipfile)) as h: 139 | for id, seq in itertools.zip_longest(*[h] * 2): 140 | id = id.replace('\n', '') 141 | id = id.replace('>', '') 142 | seq = seq.replace('\n', '') 143 | skipped_reads[id] = seq 144 | 145 | for acc, seq in skipped_reads.items(): 146 | other_consensus.write("@{0}\n{1}\n+\n{2}\n".format(acc, seq, "+" * len(seq))) 147 | other_support_file.write("{0}: {1}\n".format(acc, len(seq))) 148 | other_mapping.write(">{0}\n{1}\n".format(acc, acc)) 149 | 150 | consensus_file.close() 151 | mapping_file.close() 152 | if write_low_abundance: 153 | other_consensus.close() 154 | other_mapping.close() 155 | 156 | 157 | # TODO: add the rest of variables for this method and move filewriting to wrappermethod 158 | 159 | 160 | def actual_merging_process(all_infos_dict, delta, delta_len, 161 | delta_iso_len_3, delta_iso_len_5, max_seqs_to_spoa, all_batch_sequences, work_dir): 162 | all_infos_list = sorted(all_infos_dict.items(), key=lambda x: x[0], reverse=True) 163 | for b_i, (batchid, id_dict) in enumerate(all_infos_list[:len(all_infos_list) - 1]): 164 | batch_id_list = sorted(id_dict.items(), key=lambda x: len(x[1].sequence)) 165 | for b_j, (batchid2, id_dict2) in enumerate(all_infos_list[b_i + 1:]): 166 | batch_id_list2 = sorted(id_dict2.items(), key=lambda x: len(x[1].sequence)) 167 | if not batchid2 <= batchid: 168 | for t_id1, (id, infos) in enumerate(batch_id_list): 169 | if not infos.merged: 170 | for t_id2, (id2, infos2) in enumerate(batch_id_list2): 171 | if len(infos2.sequence) >= len(infos.sequence): 172 | batch_id_long = batchid2 173 | batch_id_short = batchid 174 | id_long = id2 175 | infos_long = infos2 176 | id_short = id 177 | infos_short = infos 178 | else: 179 | batch_id_long = batchid 180 | batch_id_short = batchid2 181 | id_long = id 182 | infos_long = infos 183 | id_short = id2 184 | infos_short = infos2 185 | 186 | if infos_long.merged: 187 | continue 188 | if DEBUG: 189 | print("bid", batchid, ": ", id, "bid2", batchid2, ": ", id2) 190 | if not infos_short.merged: 191 | consensus1 = infos_long.sequence 192 | consensus2 = infos_short.sequence 193 | good_to_pop = IsoformGeneration.align_to_merge(consensus1, consensus2, delta, delta_len, 194 | delta_iso_len_3, 195 | delta_iso_len_5) 196 | if DEBUG: 197 | print(good_to_pop) 198 | if good_to_pop: 199 | # if the first combi has more than 50 reads support 200 | if len(infos_long.reads) > 50: 201 | all_infos_dict[batch_id_long][ 202 | id_long].reads = infos_long.reads + infos_short.reads 203 | infos_short.merged = True 204 | else: 205 | mappings1 = infos_long.reads 206 | mappings2 = infos_short.reads 207 | new_consensus = generate_consensus_path(work_dir, mappings1, mappings2, 208 | all_batch_sequences, max_seqs_to_spoa) 209 | all_infos_dict[batch_id_long][id_long].sequence = new_consensus 210 | all_infos_dict[batch_id_long][ 211 | id_long].reads = infos_long.reads + infos_short.reads 212 | all_infos_dict[batch_id_short][id_short].merged = True 213 | 214 | 215 | def join_back_via_batch_merging(outdir, delta, delta_len, delta_iso_len_3, 216 | delta_iso_len_5, max_seqs_to_spoa, iso_abundance,write_fastq,write_low_abundance): 217 | print("Batch Merging") 218 | unique_cl_ids = set() 219 | subfolders = [f.path for f in os.scandir(outdir) if f.is_dir()] 220 | # iterate over all folders in the out directory 221 | for folder in subfolders: 222 | tmp_fname = folder.split('/') 223 | fname = tmp_fname[-1] 224 | cl_id = fname 225 | unique_cl_ids.add(cl_id) 226 | # enter the folder containing all output for each cluster 227 | for cl_id in unique_cl_ids: 228 | #print(cl_id) 229 | all_infos_dict = {} 230 | batch_reads = {} 231 | batch_mappings = {} 232 | all_reads_dict = {} 233 | cl_dir = os.path.join(outdir, cl_id) 234 | # iterate over all batchfiles that were generated into the cluster's folder 235 | for batchfile in os.listdir(cl_dir): 236 | if batchfile.endswith("_batch"): 237 | tmp_bname = batchfile.split('/') 238 | tmp_bname2 = tmp_bname[-1].split('_') 239 | batch_id = int(tmp_bname2[0]) 240 | #print(batch_id) 241 | batchfilename = str(batch_id) + "_batch" 242 | batch_file = open(os.path.join(cl_dir, batchfilename), 'rb') 243 | all_reads_dict[batch_id] = pickle.load(batch_file) 244 | for key in all_reads_dict.keys(): 245 | all_infos_dict[key] = {} 246 | spoa_name = "spoa" + str(batch_id) 247 | #print(os.path.join(cl_dir, spoa_name)) 248 | spoa_file = open(os.path.join(cl_dir, spoa_name), 'rb') 249 | batch_reads[batch_id] = pickle.load(spoa_file) 250 | map_name = "mapping" + str(batch_id) 251 | map_file = open(os.path.join(cl_dir, map_name), 'rb') 252 | batch_mappings[batch_id] = pickle.load(map_file) 253 | # collect the information so that we have one data structure containing all infos 254 | for b_id, value in batch_reads.items(): 255 | all_infos_batch = {} 256 | for cons_id, seq in value.items(): 257 | bm_this_batch = batch_mappings[b_id] 258 | reads = bm_this_batch[cons_id] 259 | read_mapping = Read(seq, reads, False) 260 | all_infos_batch[cons_id] = read_mapping 261 | all_infos_dict[b_id] = all_infos_batch 262 | 263 | nr_reads = 0 264 | for b_id, b_infos in all_infos_dict.items(): 265 | for c_id, c_infos in b_infos.items(): 266 | if not c_infos.merged: 267 | nr_reads += len(c_infos.reads) 268 | # perform the merging step during which all consensuses are compared and if possible merged 269 | actual_merging_process(all_infos_dict, delta, delta_len, 270 | delta_iso_len_3, delta_iso_len_5, max_seqs_to_spoa, all_reads_dict, outdir) 271 | nr_reads = 0 272 | for b_id, b_infos in all_infos_dict.items(): 273 | for c_id, c_infos in b_infos.items(): 274 | if not c_infos.merged: 275 | nr_reads += len(c_infos.reads) 276 | write_final_output(all_infos_dict, outdir, iso_abundance, cl_dir, cl_id, write_fastq, write_low_abundance) 277 | #shutil.rmtree(os.path.join(outdir,cl_id)) 278 | 279 | DEBUG = False 280 | 281 | 282 | def main(): 283 | # outfolder= "/home/alexanderpetri/isONform_analysis/Paraout_500_cl0" 284 | # outfolder = "/home/alexanderpetri/isONform_analysis/Para_out_500batchadd" 285 | # outfolder="/home/alexanderpetri/isONform_analysis/Batch_parallel_testing" 286 | # outfolder = "/home/alexanderpetri/isONform_analysis/Para_out_500batch" 287 | outfolder = "/home/alexanderpetri/Desktop/IsONform_test_results/SIRV100k/552997d_t2" 288 | delta = 0.15 289 | delta_len = 5 290 | merge_sub_isoforms_3 = True 291 | merge_sub_isoforms_5 = True 292 | delta_iso_len_3 = 30 293 | delta_iso_len_5 = 50 294 | max_seqs_to_spoa = 200 295 | iso_abundance = 4 296 | join_back_via_batch_merging(outfolder, delta, delta_len, delta_iso_len_3, delta_iso_len_5, 297 | max_seqs_to_spoa, iso_abundance) 298 | 299 | Parallelization_side_functions.generate_full_output(outfolder) 300 | # merge_batches(max_batchid, tmp_work_dir, outfolder, all_reads,merge_sub_isoforms_3,merge_sub_isoforms_5, delta, delta_len,max_seqs_to_spoa, delta_iso_len_3, delta_iso_len_5,iso_abundance) 301 | print("removing temporary workdir") 302 | # shutil.rmtree(work_dir) 303 | 304 | 305 | if __name__ == "__main__": 306 | main() 307 | -------------------------------------------------------------------------------- /isONform_parallel: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | This file is a wrapper file to run isONform in parallel (parallelization over batches). 4 | The script was taken from isoncorrect (https://github.com/ksahlin/isoncorrect/blob/master/run_isoncorrect) 5 | by Kristoffer Sahlin and changed by Alexander Petri to be usable with the isONform code base. 6 | 7 | """ 8 | 9 | 10 | from __future__ import print_function 11 | import argparse 12 | import tempfile 13 | from ast import Param 14 | from time import time 15 | from pathlib import Path 16 | import signal 17 | from multiprocessing import Pool 18 | import multiprocessing as mp 19 | 20 | import subprocess 21 | import sys 22 | import os 23 | from sys import stdout 24 | import shutil 25 | import errno 26 | 27 | from modules import batch_merging_parallel 28 | from modules import help_functions 29 | from modules import Parallelization_side_functions 30 | 31 | def restructure_isoncorrect_output(directory): 32 | file_list= list(filter(lambda f: os.path.isfile(os.path.join(directory, f)), os.listdir(directory) )) 33 | #print("file_list:", file_list) 34 | if len(file_list) == 0: 35 | print("isONcorrect structure") 36 | #iterate over all subdirectories in directory 37 | for subdirectory in os.listdir(directory): 38 | subdirectory_path = os.path.join(directory, subdirectory) 39 | # Check if it's a directory 40 | if os.path.isdir(subdirectory_path): 41 | # Define the source file path 42 | source_file = os.path.join(subdirectory_path, 'corrected_reads.fastq') 43 | if source_file: 44 | # Define the target file path in the main folder with new name 45 | target_file = os.path.join(directory, f"{subdirectory}.fastq") 46 | # Move and rename if the file exists 47 | if os.path.exists(source_file): 48 | shutil.move(source_file, target_file) 49 | print(f"Moved and renamed {source_file} to {target_file}") 50 | else: 51 | print(f"File {source_file} does not exist.") 52 | # The following line removes all folders in the input folder 53 | Parallelization_side_functions.remove_folders(directory) 54 | else: 55 | print("isONclust structure") 56 | 57 | def wccount(filename): 58 | out = subprocess.Popen(['wc', '-l', filename], 59 | stdout=subprocess.PIPE, 60 | stderr=subprocess.STDOUT 61 | ).communicate()[0] 62 | # print(int(out.split()[0])) 63 | return int(out.split()[0]) 64 | 65 | 66 | def isONform(data): 67 | isONform_location, read_fastq_file, outfolder, batch_id, isONform_algorithm_params,cl_id = data[0], data[1], data[ 68 | 2], data[3], data[4], data[5] 69 | help_functions.mkdir_p(outfolder) 70 | #print("OUT",outfolder) 71 | #print("Algoparams",isONform_algorithm_params) 72 | isONform_exec = os.path.join(isONform_location, "main") 73 | isONform_error_file = os.path.join(outfolder, "stderr.txt") 74 | with open(isONform_error_file, "w") as error_file: 75 | print('Running isONform batch_id:{0}.{1}...'.format(cl_id,batch_id), end=' ') 76 | stdout.flush() 77 | isONform_out_file = open(os.path.join(outfolder, "stdout{0}_{1}.txt".format(cl_id,batch_id)), "w") 78 | subprocess.check_call( 79 | ["python", isONform_exec, "--fastq", read_fastq_file, "--outfolder", outfolder, 80 | "--exact_instance_limit", str(isONform_algorithm_params["exact_instance_limit"]), 81 | #"--max_seqs", str(isONform_algorithm_params["max_seqs"]), 82 | "--k", str(isONform_algorithm_params["k"]), "--w", str(isONform_algorithm_params["w"]), 83 | "--xmin", str(isONform_algorithm_params["xmin"]), "--xmax", 84 | str(isONform_algorithm_params["xmax"]),"--delta_len", str(isONform_algorithm_params["delta_len"]), 85 | "--exact", "--parallel", "True", "--delta_iso_len_3", str(isONform_algorithm_params["delta_iso_len_3"]), "--delta_iso_len_5", str(isONform_algorithm_params["delta_iso_len_5"])#, "--slow" 86 | #"--T", str(isONform_algorithm_params["T"]) 87 | ], stderr=error_file, stdout=isONform_out_file) 88 | 89 | print('Done with batch_id:{0}.{1}'.format(cl_id,batch_id)) 90 | stdout.flush() 91 | error_file.close() 92 | isONform_out_file.close() 93 | return batch_id 94 | 95 | #splits files containing more than max_seqs reads into smaller files, that can be parallelized upon 96 | def splitfile(indir, tmp_outdir, fname, chunksize,cl_id,ext): 97 | # from https://stackoverflow.com/a/27641636/2060202 98 | # fpath, fname = os.path.split(infilepath) 99 | #cl_id, ext = fname.rsplit('.',1) 100 | infilepath = os.path.join(indir, fname) 101 | #infilepath=indir 102 | # print(fpath, cl_id, ext) 103 | #print("now at splitfile") 104 | #print(indir, tmp_outdir, cl_id, ext) 105 | 106 | i = 0 107 | written = False 108 | with open(infilepath) as infile: 109 | while True: 110 | outfilepath = os.path.join(tmp_outdir, '{0}_{1}.{2}'.format(cl_id, i, ext) ) #"{}_{}.{}".format(foutpath, fname, i, ext) 111 | #print(outfilepath) 112 | with open(outfilepath, 'w') as outfile: 113 | for line in (infile.readline() for _ in range(chunksize)): 114 | outfile.write(line) 115 | written = bool(line) 116 | # print(os.stat(outfilepath).st_size == 0) 117 | if os.stat(outfilepath).st_size == 0: # Corner case: Original file is even multiple of max_seqs, hence the last file becomes empty. Remove this 118 | os.remove(outfilepath) 119 | if not written: 120 | break 121 | i += 1 122 | 123 | 124 | def symlink_force(target, link_name): 125 | #print("Symlink",link_name) 126 | try: 127 | os.symlink(target, link_name) 128 | except OSError as e: 129 | if e.errno == errno.EEXIST: 130 | if not os.path.exists(os.readlink(link_name)): 131 | print('path %s is a broken symlink' % link_name) 132 | os.remove(link_name) 133 | symlink_force(target,link_name) 134 | else: 135 | raise e 136 | 137 | #splits clusters up so that we get smaller batches 138 | def split_cluster_in_batches_corrected(indir, outdir, tmp_work_dir, max_seqs): 139 | # create a modified indir 140 | tmp_work_dir = os.path.join(tmp_work_dir, 'split_in_batches') 141 | # print(indir) 142 | help_functions.mkdir_p(tmp_work_dir) 143 | pat = Path(indir) 144 | #collect all fastq files located in this directory or any subdirectories 145 | file_list = list(pat.rglob('*.fastq')) 146 | #print("FLIST",file_list) 147 | #iterate over the fastq_files 148 | for filepath in file_list: 149 | #print("FPATH",filepath) 150 | old_fastq_file = str(filepath.resolve()) 151 | path_split = old_fastq_file.split("/") 152 | folder = path_split[-2] 153 | #print(folder) 154 | fastq_file = path_split[-1] 155 | #we do not want to look at the analysis fastq file 156 | if not folder == "Analysis": 157 | cl_id=path_split[-2] 158 | #print("CLID",cl_id) 159 | 160 | #if we have more lines than max_seqs 161 | new_indir=os.path.join(indir,folder) 162 | #print(new_indir) 163 | 164 | num_lines = sum(1 for line in open(os.path.join(new_indir, fastq_file))) 165 | #print("Number Lines", fastq_file, num_lines) 166 | 167 | # determine whether the file is larger than max_seqs 168 | larger_than_max_seqs = num_lines > 4 * max_seqs 169 | if larger_than_max_seqs: 170 | #print("Splitting",filepath) 171 | ext = fastq_file.rsplit('.', 1)[1] 172 | splitfile(new_indir, tmp_work_dir, fastq_file, 4 * max_seqs,cl_id,ext) # is fastq file 173 | else: 174 | ext = fastq_file.rsplit('.', 1)[1] 175 | #print(fastq_file, "symlinking instead") 176 | symlink_force(filepath, os.path.join(tmp_work_dir, '{0}_{1}.{2}'.format(cl_id, 0, ext))) 177 | return tmp_work_dir 178 | 179 | def split_cluster_in_batches_clust(indir, outdir, tmp_work_dir, max_seqs): 180 | # create a modified indir 181 | tmp_work_dir = os.path.join(tmp_work_dir, 'split_in_batches') 182 | # print(indir) 183 | #os.mkdir(tmp_work_dir) 184 | help_functions.mkdir_p(tmp_work_dir) 185 | #print(tmp_work_dir) 186 | #print("clust") 187 | 188 | pat = Path(indir) 189 | file_list = list(pat.rglob('*.fastq')) 190 | # add split files to this indir 191 | for file_ in file_list: 192 | #for file_ in sorted(os.listdir(indir), key=lambda x: int(x.split('.')[0])): 193 | #fastq_path = os.fsdecode(file_) 194 | old_fastq_file = str(file_.resolve()) 195 | fastq_file = old_fastq_file.split("/")[-1] 196 | #print("FASTQ",fastq_file) 197 | 198 | num_lines = sum(1 for line in open(os.path.join(indir, fastq_file))) 199 | 200 | # determine whether the file is larger than max_seqs 201 | larger_than_max_seqs = num_lines > 4 * max_seqs 202 | if larger_than_max_seqs: 203 | cl_id, ext = fastq_file.rsplit('.', 1) 204 | splitfile(indir, tmp_work_dir, fastq_file, 4 * max_seqs, cl_id, ext) # is fastq file 205 | else: 206 | cl_id, ext = fastq_file.rsplit('.', 1) 207 | print("SYMLINK",os.path.join(tmp_work_dir, '{0}_{1}.{2}'.format(cl_id, 0, ext))) 208 | symlink_force(file_, os.path.join(tmp_work_dir, '{0}_{1}.{2}'.format(cl_id, 0, ext))) 209 | return tmp_work_dir 210 | 211 | 212 | #PYTHONHASHSEED = 0 213 | def main(args): 214 | globstart = time() 215 | directory = args.fastq_folder 216 | #Please note that this alters the output of isONcorrect i.e. the structure of corrected in the isONpipeline 217 | restructure_isoncorrect_output(directory) 218 | 219 | 220 | #print("MERGE?", args.merge_sub_isoforms_3, args.merge_sub_isoforms_5) 221 | 222 | # os.fsencode(args.fastq_folder) 223 | write_low_abundance = False 224 | #print(directory) 225 | #print("ARGS",args) 226 | isONform_location = os.path.dirname(os.path.realpath(__file__)) 227 | if args.split_wrt_batches: 228 | if args.tmpdir: 229 | tmp_work_dir = args.tmpdir 230 | #curr_work_dir = os.getcwd() 231 | #os.chdir(tmp_work_dir) 232 | #try: 233 | # Create the directory 234 | #os.makedirs(tmp_work_dir) 235 | # print("Directory created successfully.") 236 | #except FileExistsError: 237 | # print("Directory already exists.") 238 | Parallelization_side_functions.mkdir_p(tmp_work_dir) 239 | #os.chdir(curr_work_dir) 240 | else: 241 | tmp_work_dir = tempfile.mkdtemp() 242 | print("Temporary workdirectory:", tmp_work_dir) 243 | split_tmp_directory = split_cluster_in_batches_clust(directory, args.outfolder, tmp_work_dir, 244 | args.max_seqs) 245 | split_directory = os.fsencode(split_tmp_directory) 246 | else: 247 | 248 | split_directory = os.fsencode(directory) 249 | print("SplitDIR", split_directory) 250 | instances = [] 251 | for file_ in os.listdir(split_directory): 252 | #print(file_) 253 | read_fastq_file = os.fsdecode(file_) 254 | if read_fastq_file.endswith(".fastq"): 255 | #print("True") 256 | tmp_id = read_fastq_file.split(".")[0] 257 | snd_tmp_id = tmp_id.split("_") 258 | cl_id = snd_tmp_id[0] 259 | batch_id = snd_tmp_id[1] if len(snd_tmp_id) > 1 else 0 260 | outfolder = os.path.join(args.outfolder, cl_id) 261 | #print(batch_id,cl_id) 262 | #print(outfolder) 263 | fastq_file_path = os.path.join(os.fsdecode(split_directory), read_fastq_file) 264 | #print(fastq_file_path) 265 | compute = True 266 | if args.keep_old: 267 | candidate_corrected_file = os.path.join(outfolder, "isoforms.fastq") 268 | if os.path.isfile(candidate_corrected_file): 269 | if wccount(candidate_corrected_file) == wccount(fastq_file_path): 270 | #print("already computed cluster and complete file", batch_id) 271 | compute = False 272 | 273 | if compute: 274 | #print("computing") 275 | isONform_algorithm_params = {"set_w_dynamically": args.set_w_dynamically, 276 | "exact_instance_limit": args.exact_instance_limit, 277 | "delta_len": args.delta_len,"--exact": True, 278 | "k": args.k, "w": args.w, "xmin": args.xmin, "xmax": args.xmax, 279 | "max_seqs": args.max_seqs, "parallel": True, "--slow": True, "delta_iso_len_3": args.delta_iso_len_3, 280 | "delta_iso_len_5": args.delta_iso_len_5} 281 | instances.append( 282 | (isONform_location, fastq_file_path, outfolder, batch_id, isONform_algorithm_params, cl_id)) 283 | else: 284 | continue 285 | instances.sort(key=lambda x: (int(x[5]), int(x[3]))) # sorting on cluster_id and then batch_id numerically 286 | print("Printing instances") 287 | for t in instances: 288 | print(t) 289 | original_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) 290 | signal.signal(signal.SIGINT, original_sigint_handler) 291 | try: 292 | mp.set_start_method('spawn') 293 | except RuntimeError: 294 | pass 295 | #mp.set_start_method('spawn') 296 | print(mp.get_context()) 297 | print("Environment set:", mp.get_context()) 298 | print("Using {0} cores.".format(args.nr_cores)) 299 | start_multi = time() 300 | pool = Pool(processes=int(args.nr_cores)) 301 | try: 302 | start = time() 303 | for x in pool.imap_unordered(isONform, instances): 304 | print("{} (Time elapsed: {}s)".format(x, int(time() - start))) 305 | except KeyboardInterrupt: 306 | print("Caught KeyboardInterrupt, terminating workers") 307 | pool.terminate() 308 | sys.exit() 309 | else: 310 | pool.close() 311 | pool.join() 312 | print("Time elapsed multiprocessing:", time() - start_multi) 313 | 314 | print("Merging...") 315 | file_handling = time() 316 | if args.write_fastq: 317 | write_fastq = True 318 | else: 319 | write_fastq = False 320 | batch_merging_parallel.join_back_via_batch_merging(args.outfolder, args.delta, args.delta_len, args.delta_iso_len_3, args.delta_iso_len_5, args.max_seqs_to_spoa, args.iso_abundance, write_fastq, write_low_abundance) 321 | Parallelization_side_functions.generate_full_output(args.outfolder, write_fastq, write_low_abundance) 322 | Parallelization_side_functions.remove_folders(args.outfolder) 323 | if args.split_wrt_batches: 324 | print("Removed the split directory") 325 | shutil.rmtree(split_directory) 326 | print("Joined back batched files in:", time() - file_handling) 327 | print("Finished full algo after :", time() - globstart) 328 | return 329 | 330 | 331 | if __name__ == '__main__': 332 | parser = argparse.ArgumentParser(description="De novo reconstruction of long-read transcriptome reads", 333 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) 334 | parser.add_argument('--version', action='version', version='%(prog)s 0.3.9') 335 | parser.add_argument('--fastq_folder', type=str, default=False, 336 | help='Path to input fastq folder with reads in clusters') 337 | parser.add_argument('--t', dest="nr_cores", type=int, default=8, help='Number of cores allocated for clustering') 338 | parser.add_argument('--k', type=int, default=20, help='Kmer size') 339 | parser.add_argument('--w', type=int, default=31, help='Window size') 340 | parser.add_argument('--xmin', type=int, default=18, help='Lower interval length') 341 | parser.add_argument('--xmax', type=int, default=80, help='Upper interval length') 342 | parser.add_argument('--exact_instance_limit', type=int, default=50, 343 | help='Do exact correction for clusters under this threshold') 344 | parser.add_argument('--keep_old', action="store_true", 345 | help='Do not recompute previous results if corrected_reads.fq is found and has the smae number of reads as input file (i.e., is complete).') 346 | parser.add_argument('--set_w_dynamically', action="store_true", 347 | help='Set w = k + max(2*k, floor(cluster_size/1000)).') 348 | parser.add_argument('--max_seqs', type=int, default=1000, 349 | help='Maximum number of seqs to correct at a time (in case of large clusters).') 350 | parser.add_argument('--split_wrt_batches', action="store_true", 351 | help='Process reads per batch (of max_seqs sequences) instead of per cluster. Significantly decrease runtime when few very large clusters are less than the number of cores used.') 352 | #parser.add_argument('--clustered', action="store_true", 353 | # help='Indicates whether we use the output of isONclust (i.e. we have uncorrected data)') 354 | parser.add_argument('--outfolder', type=str, default=None, help='Outfolder with all corrected reads.') 355 | parser.add_argument('--delta_len', type=int, default=5, 356 | help='Maximum length difference between two reads intervals for which they would still be merged') 357 | parser.add_argument('--delta',type=float,default=0.1, help='diversity rate used to compare sequences') 358 | parser.add_argument('--max_seqs_to_spoa', type=int, default=200, help='Maximum number of seqs to spoa') 359 | parser.add_argument('--verbose', action="store_true", help='Print various developer stats.') 360 | parser.add_argument('--iso_abundance', type=int, default=5, 361 | help='Cutoff parameter: abundance of reads that have to support an isoform to show in results') 362 | parser.add_argument('--delta_iso_len_3', type=int, default=30, 363 | help='Cutoff parameter: maximum length difference at 3prime end, for which subisoforms are still merged into longer isoforms') 364 | parser.add_argument('--delta_iso_len_5', type=int, default=50, 365 | help='Cutoff parameter: maximum length difference at 5prime end, for which subisoforms are still merged into longer isoforms') 366 | parser.add_argument('--tmpdir', type=str,default=None, help='OPTIONAL PARAMETER: Absolute path to custom folder in which to store temporary files. If tmpdir is not specified, isONform will attempt to write the temporary files into the tmp folder on your system. It is advised to only use this parameter if the symlinking does not work on your system.') 367 | parser.add_argument('--write_fastq', action="store_true", help=' Indicates that we want to ouptut the final output (transcriptome) as fastq file (New standard: fasta)') 368 | 369 | args = parser.parse_args() 370 | print(len(sys.argv)) 371 | if len(sys.argv) == 1: 372 | parser.print_help() 373 | sys.exit() 374 | 375 | 376 | if args.outfolder and not os.path.exists(args.outfolder): 377 | os.makedirs(args.outfolder) 378 | 379 | main(args) 380 | -------------------------------------------------------------------------------- /modules/IsoformGeneration.py: -------------------------------------------------------------------------------- 1 | import _pickle as pickle 2 | import itertools 3 | import os 4 | from sys import stdout 5 | import subprocess 6 | 7 | from modules import consensus 8 | 9 | def write_consensus_file(batch_id, outfolder, new_consensuses): 10 | #print("newconsensus") 11 | #for con,seq in new_consensuses.items(): 12 | # print("{0}:{1}".format(con,seq)) 13 | consensus_name = "spoa" + str(batch_id) 14 | pickle_spoa_file = open(os.path.join(outfolder, consensus_name), 'wb') 15 | pickle.dump(new_consensuses, pickle_spoa_file) 16 | pickle_spoa_file.close() 17 | 18 | 19 | def write_mapping_file(batch_id, mapping, outfolder): 20 | mapping_name = "mapping" + str(batch_id) 21 | pickle_map_file = open(os.path.join(outfolder, mapping_name), 'wb') 22 | pickle.dump(mapping, pickle_map_file) 23 | pickle_map_file.close() 24 | 25 | 26 | 27 | def prepare_consensuses(new_consensuses,equal_reads_keys, final_consensuses): 28 | for key in equal_reads_keys: 29 | final_consensuses[key] = new_consensuses[key] 30 | 31 | 32 | def write_isoforms_pickle(equal_reads, reads, outfolder, batch_id, new_consensuses): 33 | print("Generating the Isoforms-merged") 34 | mapping = {} 35 | final_consensuses = {} 36 | prepare_consensuses(new_consensuses, equal_reads.keys(), final_consensuses) 37 | write_consensus_file(batch_id, outfolder, final_consensuses) 38 | # we iterate over all items in curr_best_seqs 39 | for key, value in equal_reads.items(): 40 | name = str(key) 41 | # We generate a list as value for mapping[key] 42 | if name not in mapping: 43 | mapping[key] = [] 44 | # iterate over all reads in value and add them to mapping 45 | for i, q_id in enumerate(value): 46 | singleread = reads[q_id] 47 | mapping[key].append(singleread[0]) 48 | write_mapping_file(batch_id, mapping, outfolder) 49 | 50 | 51 | 52 | 53 | def is_Sublist(l, s): 54 | """Function that decides whether a list 's' is a sublist of list 'l'. 55 | taken from: https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-32.php 56 | INPUT: l: the list 57 | s: the potential sublist 58 | OUTPUT sub_set: boolean value indicating the result 59 | """ 60 | sub_set = False 61 | if not s: 62 | sub_set = True 63 | elif s == l: 64 | sub_set = True 65 | elif len(s) > len(l): 66 | sub_set = False 67 | else: 68 | for i in range(len(l)): 69 | if l[i] == s[0]: 70 | n = 1 71 | while (n < len(s)) and (l[i + n] == s[n]): 72 | n += 1 73 | 74 | if n == len(s): 75 | sub_set = True 76 | 77 | return sub_set 78 | 79 | 80 | def merge_isoform_paths(isoforms): 81 | """ 82 | Merges subisoforms into larger isoforms 83 | """ 84 | merge_list = [] 85 | for id1, vis_nodes_set1 in isoforms.items(): 86 | for id2, vis_nodes_set2 in isoforms.items(): 87 | if id1=iso_abundance: 174 | if len(value) == 1: 175 | rid = key 176 | singleread = reads[rid] 177 | seq = singleread[1] 178 | mapping[name].append(singleread[0]) 179 | consensus_file.write(">{0}\n{1}\n".format(name, seq)) 180 | reads_path.close() 181 | else: 182 | for i, q_id in enumerate(value): 183 | singleread = reads[q_id] 184 | seq = singleread[1] 185 | mapping[name].append(singleread[0]) 186 | if i{0}\n{1}\n".format(singleread[0], seq)) 188 | 189 | reads_path.close() 190 | spoa_ref = run_spoa(reads_path.name, os.path.join(work_dir, "spoa_tmp.fa")) 191 | consensus_file.write(">{0}\n{1}\n".format(name, spoa_ref)) 192 | 193 | mapping_name="mapping"+str(batch_id)+".txt" 194 | mappingfile = open(os.path.join(outfolder, mapping_name), "w") 195 | # we now write the information into the mappingfile 196 | for id, readlist in mapping.items(): 197 | if len(readlist)>=iso_abundance: 198 | mappingfile.write("{0}\n{1}\n".format(id, readlist)) 199 | 200 | #close the files we wrote into 201 | mappingfile.close() 202 | consensus_file.close() 203 | 204 | 205 | 206 | 207 | def search_last_entries(entry_since_sign_match,delta_len_3): 208 | dist_to_last_match = 0 209 | deletion_len = 0 210 | insertion_len = 0 211 | for entry in entry_since_sign_match: 212 | cig_len = entry[0] 213 | cig_type = entry[1] 214 | dist_to_last_match += cig_len 215 | if cig_type == "D": 216 | deletion_len += cig_len 217 | if cig_type == "I": 218 | insertion_len += cig_len 219 | #if DEBUG: 220 | #print(dist_to_last_match) 221 | #print(deletion_len) 222 | if dist_to_last_match - deletion_len < delta_len_3: 223 | return True 224 | else: 225 | return False 226 | 227 | 228 | def search_first_entries(before_fsm,first_sign_match,delta_len_5): 229 | deletion_len = 0 230 | for entry in before_fsm: 231 | cig_len = entry[0] 232 | cig_type = entry[1] 233 | if cig_type == "D": 234 | deletion_len += cig_len 235 | if DEBUG: 236 | print(first_sign_match) 237 | print(deletion_len) 238 | print(delta_len_5) 239 | if first_sign_match - deletion_len < delta_len_5: 240 | if DEBUG: 241 | print("res", first_sign_match - deletion_len < delta_len_5) 242 | return True 243 | else: 244 | if DEBUG: 245 | print("res", first_sign_match - deletion_len < delta_len_5) 246 | return False 247 | 248 | 249 | 250 | #parses the parasail alignment output to figure out whether to merge 251 | def parse_cigar_diversity_isoform_level_new(cigar_tuples, delta,delta_len,delta_iso_len_3,delta_iso_len_5,overall_len,first_match,last_match): 252 | miss_match_length = 0 253 | alignment_len = 0 254 | after_last_matches=0 255 | after_last_nomatch=0 256 | before_first_matches=0 257 | before_first_nomatch=0 258 | for i, elem in enumerate(cigar_tuples): 259 | #thisstartpos: the starting position of where the cigar tuple starts. (Previous end position) 260 | this_start_pos=alignment_len 261 | cig_len = elem[0] 262 | cig_type = elem[1] 263 | alignment_len += cig_len 264 | #we found a mismatch 265 | if (cig_type != '=') and (cig_type != 'M'): 266 | #if the missmatch is located before the first significant match (upstream) 267 | if this_start_pos < first_match: 268 | if not cig_type =='D': 269 | before_first_nomatch+=cig_len 270 | 271 | elif this_start_pos>=last_match or this_start_pos+cig_len>=last_match: 272 | if not cig_type =='D': 273 | after_last_nomatch+=cig_len 274 | #the mismatch is located between the first and last significant matches 275 | else: 276 | #if the mismatch is longer than delta_len: Structural difference -> not mergeable 277 | if cig_len > delta_len: 278 | return False 279 | #we still need this mismatch_length to be added to miss_match_length to document the number of mismatches between fsm and lsm 280 | else: 281 | # we want to add up all missmatches to compare to sequence length 282 | miss_match_length += delta_len 283 | #we have a match 284 | else: 285 | if this_start_pos < first_match: 286 | before_first_matches += cig_len 287 | elif this_start_pos >= last_match: 288 | after_last_matches+=cig_len 289 | 290 | #we know we have a match, but is it significant? 291 | mergeable_start=before_first_matches+before_first_nomatch < delta_iso_len_5 292 | #analyse the last entries of our cigar tuples to figure out what has happened after the lsm 293 | mergeable_end=after_last_matches+after_last_nomatch< delta_iso_len_3 294 | #the shorter sequence still went on longer than significant_match_len->not mergeable 295 | if not mergeable_end or not mergeable_start: 296 | if DEBUG: 297 | print("NotMergeable start",mergeable_start," end:",mergeable_end) 298 | print(cigar_tuples) 299 | return False 300 | #We calculate the diversity of our alignment 301 | similar_seq=last_match-first_match 302 | #just to make sure that we only merge reads that have at least 100 nt similar 303 | if similar_seq<100: 304 | #print("smaller sim_seq") 305 | return False 306 | diversity = (miss_match_length/ similar_seq) 307 | if overall_len<200: 308 | delta=2*delta 309 | max_bp_diff = max(delta * similar_seq, delta_len) 310 | mod_div_rate = max_bp_diff / similar_seq 311 | #print("DIV",diversity,", mod_div_rate",mod_div_rate) 312 | #we additionally make sure that the two consensuses are not too diverse 313 | diversity_bool=diversity <= mod_div_rate 314 | #if any of the three parameters we look at tells us not to merge we do not merge 315 | if diversity_bool: # delta_perc: 316 | #print("Div:",diversity_bool,"3' ",three_prime," 5' ",five_prime) 317 | return True 318 | else: 319 | #print("no pop due to diversity") 320 | return False 321 | 322 | 323 | def parse_cigar_diversity_isoform_level(cigar_tuples, delta,delta_len,delta_iso_len_3,delta_iso_len_5,overall_len): 324 | miss_match_length = 0 325 | alignment_len = 0 326 | for i, elem in enumerate(cigar_tuples): 327 | this_start_pos=alignment_len 328 | cig_len = elem[0] 329 | cig_type = elem[1] 330 | alignment_len += cig_len 331 | if (cig_type != '=') and (cig_type != 'M'): 332 | # we want to add up all missmatches to compare to sequence length 333 | miss_match_length += cig_len 334 | if cig_len <= delta_len: 335 | continue 336 | # we also want to make sure that we do not have too large internal sequence differences 337 | 338 | #if the user wants us to merge the 5'end 339 | #make sure that the startposition of the cigar tuple is in delta_iso_len 340 | if this_start_pos < delta_iso_len_5: 341 | #we only want to merge if the cigar tuple does not span into the read by more than delta_len + delta_iso_len_5 base pairs 342 | if this_start_pos+cig_len ((overall_len - delta_iso_len_3)-delta_len): 346 | continue 347 | #the user wanted us to neither merge at 3' nor at 5', but we found a cigar tuple entry longer than delta_len indicating a missmatch 348 | return False 349 | 350 | #We calculate the diversity of our alignment 351 | diversity = (miss_match_length / alignment_len) 352 | max_bp_diff = max(delta * alignment_len, delta_len) 353 | mod_div_rate = max_bp_diff / alignment_len 354 | #we additionally make sure that the two consensuses are not too diverse 355 | diversity_bool=diversity <= mod_div_rate 356 | #if any of the three parameters we look at tells us not to merge we do not merge 357 | if diversity_bool: 358 | return True 359 | else: 360 | return False 361 | 362 | 363 | def get_overall_alignment_len(cigar_tuples): 364 | overall_len=0 365 | for i, elem in enumerate(cigar_tuples): 366 | overall_len += elem[0] 367 | return overall_len 368 | 369 | 370 | def find_first_significant_match(s1_alignment, s2_alignment, windowsize, alignment_threshold): 371 | match_vector = [1 if n1 == n2 else 0 for n1, n2 in zip(s1_alignment, s2_alignment)] 372 | for i in range(0,len(match_vector)-windowsize+1): 373 | our_equality = sum(match_vector[i:i+windowsize])/windowsize 374 | #we only have a significant match if the equality of the covered area is larger than alignment_threshold 375 | if our_equality > alignment_threshold: 376 | return i 377 | return -1 378 | 379 | 380 | def align_to_merge(consensus1,consensus2,delta,delta_len,delta_iso_len_3,delta_iso_len_5): 381 | s1_alignment, s2_alignment, cigar_string, cigar_tuples, score = consensus.parasail_alignment(consensus1, consensus2, 382 | match_score=2, 383 | mismatch_penalty=-2, 384 | opening_penalty=12, gap_ext=1) 385 | overall_len=get_overall_alignment_len(cigar_tuples) 386 | windowsize=30 387 | alignment_threshold=0.7 388 | start_match=find_first_significant_match(s1_alignment,s2_alignment,windowsize,alignment_threshold) 389 | end_match=find_first_significant_match(s1_alignment[::-1],s2_alignment[::-1],windowsize,alignment_threshold) 390 | if start_match < 0 or end_match < 0: 391 | return False 392 | end_match_pos=overall_len-end_match 393 | good_to_pop = parse_cigar_diversity_isoform_level_new(cigar_tuples, delta, delta_len, delta_iso_len_3, delta_iso_len_5, overall_len, start_match, end_match_pos) 394 | if DEBUG: 395 | print(cigar_tuples) 396 | print(cigar_string) 397 | return good_to_pop 398 | 399 | 400 | 401 | def generate_new_full_consensus(id,id2,reads,curr_best_seqs,work_dir,max_seqs_to_spoa): 402 | consensus_infos1 = curr_best_seqs[id] 403 | consensus_infos2 = curr_best_seqs[id2] 404 | reads_path = open(os.path.join(work_dir, "reads_tmp.fa"), "w") 405 | all_consensus_infos=consensus_infos1+consensus_infos2 406 | if len(all_consensus_infos) > max_seqs_to_spoa: 407 | all_consensus_infos=all_consensus_infos[0:max_seqs_to_spoa] 408 | for q_id in all_consensus_infos: 409 | singleread = reads[q_id] 410 | seq = singleread[1] 411 | reads_path.write(">{0}\n{1}\n".format(singleread[0], seq)) 412 | reads_path.close() 413 | spoa_ref = run_spoa(reads_path.name, os.path.join(work_dir, "spoa_tmp.fa")) 414 | return spoa_ref 415 | 416 | 417 | def generate_all_consensuses(all_consensuses,alternative_consensuses,curr_best_seqs,reads,work_dir,max_seqs_to_spoa): 418 | print("Generating") 419 | for id,seqs in curr_best_seqs.items(): 420 | reads_path = open(os.path.join(work_dir, "reads_tmp.fa"), "w") 421 | if len(seqs) == 1: 422 | rid = id 423 | singleread = reads[rid] 424 | seq = singleread[1] 425 | all_consensuses[id] = seq 426 | consensus_tuple = (id, seq) 427 | alternative_consensuses.append(consensus_tuple) 428 | reads_path.close() 429 | else: 430 | for i, q_id in enumerate(seqs): 431 | singleread = reads[q_id] 432 | seq = singleread[1] 433 | if i < max_seqs_to_spoa: 434 | reads_path.write(">{0}\n{1}\n".format(singleread[0], seq)) 435 | reads_path.close() 436 | spoa_ref = run_spoa(reads_path.name, os.path.join(work_dir, "spoa_tmp.fa")) 437 | all_consensuses[id] = spoa_ref 438 | consensus_tuple=(id,spoa_ref) 439 | alternative_consensuses.append(consensus_tuple) 440 | 441 | 442 | def add_merged_reads(curr_best_seqs, id2,id1): 443 | #we want to merge all sequences of id1 into id2 444 | consensus_to_update=curr_best_seqs[id2] 445 | consensus_updates=curr_best_seqs[id1] 446 | #all the support of id1 and id2 are merged into new_consensus 447 | new_consensus=consensus_to_update+consensus_updates 448 | #add the new consensuses to curr_best_seqs for id2 449 | curr_best_seqs[id2]=new_consensus 450 | #we pop id1 from curr_best_Seqs as this id is not needed anymore 451 | curr_best_seqs.pop(id1) 452 | 453 | 454 | 455 | 456 | """ 457 | This method is used to find out how similar the consensuses are (by figuring out how much of their intervals are shared. 458 | INPUT: isoform_paths: List object of all nodes visited for each isoform 459 | outfolder: The folder in which we want to write our infos 460 | batch_id: The id of the current batch to be able to tell apart the infos of different batches 461 | The method produces two files: A similarity file giving the similarity values for each pair of consuensuses. 462 | A path file giving the paths of all final isoforms 463 | """ 464 | def merge_consensuses(curr_best_seqs,work_dir,delta,delta_len,reads,max_seqs_to_spoa,delta_iso_len_3,delta_iso_len_5): 465 | new_consensuses={} 466 | all_consensuses={} 467 | alternative_consensuses=[] 468 | #generate a consensus for each element in curr_best_seqs and save them in all_consensuses(dict: key-id,val-consensus) and alternative_consensuses 469 | generate_all_consensuses(all_consensuses,alternative_consensuses,curr_best_seqs,reads,work_dir,max_seqs_to_spoa) 470 | #sort alternative_consensuses by the length of the consensus sequences 471 | alternative_consensuses.sort(key=lambda x: len(x[1])) 472 | #iterate over alternative_consensuses (but always the shorter consensus) 473 | for i, consensus in enumerate(alternative_consensuses[:len(alternative_consensuses)-1]): 474 | id1=consensus[0] 475 | if not id1 in new_consensuses: 476 | seq1=consensus[1] 477 | else: 478 | seq1=new_consensuses[id1] 479 | #iterate over the rest of the consensuses 480 | for consensus2 in alternative_consensuses[i+1:]: 481 | id2=consensus2[0] 482 | if DEBUG: 483 | print(id1,id2) 484 | 485 | seq2=consensus2[1] 486 | if len(seq2) 50: 496 | add_merged_reads(curr_best_seqs, id2,id1) 497 | new_consensuses[id2]=first_consensus[1] 498 | else: 499 | new_consensuses[id2]=generate_new_full_consensus(id1,id2,reads,curr_best_seqs,work_dir,max_seqs_to_spoa) 500 | add_merged_reads(curr_best_seqs, id2, id1) 501 | break 502 | for id,support in curr_best_seqs.items(): 503 | if not id in new_consensuses: 504 | seq=all_consensuses[id] 505 | new_consensuses[id]=seq 506 | 507 | return new_consensuses 508 | 509 | 510 | def generate_isoforms_new(equal_reads, reads, outfolder, batch_id,new_consensuses): 511 | print("Generating the Isoforms-merged") 512 | mapping = {} 513 | consensus_name = "spoa" + str(batch_id) + "merged.fasta" 514 | support_name = "support" + str(batch_id) + ".txt" 515 | consensus_file = open(os.path.join(outfolder, consensus_name), 'w') 516 | support_file = open(os.path.join(outfolder, support_name), 'w') 517 | # we iterate over all items in curr_best_seqs 518 | for key, value in equal_reads.items(): 519 | name = 'consensus' + str(key) 520 | # We generate a list as value for mapping[key] 521 | if name not in mapping: 522 | mapping[name] = [] 523 | # iterate over all reads in value and add them to mapping 524 | for i, q_id in enumerate(value): 525 | singleread = reads[q_id] 526 | mapping[name].append(singleread[0]) 527 | # we do not have to calculate consensus as already done 528 | sequence = new_consensuses[key] 529 | consensus_file.write(">{0}\n{1}\n".format(name, sequence)) 530 | other_mapping_cter = 0 531 | for key, value in mapping.items(): 532 | other_mapping_cter += len(value) 533 | 534 | # we have to treat the mapping file generation a bit different as we have to collect also the supporting reads of the subconsensuses 535 | mapping_name = "mapping" + str(batch_id) + ".txt" 536 | mappingfile = open(os.path.join(outfolder, mapping_name), "w") 537 | for id, mapped_read_list in mapping.items(): 538 | mappingfile.write("{0}\n{1}\n".format(id, mapped_read_list)) 539 | support_file.write("{0}: {1}\n".format(id, len(mapped_read_list))) 540 | consensus_file.close() 541 | support_file.close() 542 | mappingfile.close() 543 | 544 | 545 | 546 | def generate_isoforms(DG,all_reads,reads,work_dir,outfolder,batch_id,delta,delta_len,delta_iso_len_3,delta_iso_len_5,max_seqs_to_spoa=200): 547 | """ 548 | Wrapper method used for the isoform generation 549 | """ 550 | equal_reads={} 551 | compute_equal_reads(DG,reads,equal_reads) 552 | if DEBUG == True: 553 | print("EQUALS",equal_reads) 554 | new_consensuses = merge_consensuses(equal_reads, work_dir, delta, delta_len, 555 | all_reads, max_seqs_to_spoa, 556 | delta_iso_len_3, delta_iso_len_5) 557 | if DEBUG: 558 | print("HELLO",new_consensuses) 559 | #generate_isoforms_new(equal_reads, all_reads, outfolder, batch_id,new_consensuses) 560 | write_isoforms_pickle(equal_reads, all_reads, outfolder, batch_id, new_consensuses) 561 | DEBUG = False 562 | 563 | 564 | def write_transcriptome_single(outfolder): 565 | spoa_file = open(os.path.join(outfolder, "spoa0"), 'rb') 566 | spoa_infos = pickle.load(spoa_file) 567 | consensus_name="transcriptome.fastq" 568 | consensus_file = open(os.path.join(outfolder, consensus_name), "w") 569 | for id, sequence in spoa_infos.items(): 570 | inter_id = id.replace('\n', '') 571 | new_id = int(inter_id.replace('>consensus', '')) 572 | sequence = sequence.replace('\n', '') 573 | consensus_file.write("@{0}\n{1}\n+\n{2}\n".format(new_id, sequence, 574 | "+" * len(sequence))) 575 | consensus_file.close() 576 | 577 | 578 | 579 | def main(): 580 | outfolder="100kSIRV/20722_abundance2_par/22" 581 | batch_id = 0 582 | print("Hello World") 583 | file = open(os.path.join(outfolder,'equal_reads_'+str(batch_id)+'.txt'), 'rb') 584 | equal_reads = pickle.load(file) 585 | file.close() 586 | file = open(os.path.join(outfolder,'isoform_paths_'+str(batch_id)+'.txt'), 'rb') 587 | isoform_paths = pickle.load(file) 588 | file.close() 589 | 590 | file2 = open(os.path.join(outfolder, 'all_reads_' + str(batch_id)+".txt" ), 'rb') 591 | #file2 = open(os.path.join(outfolder,'all_reads_'+str(batch_id)+'.txt'), 'rb') 592 | all_reads = pickle.load(file2) 593 | file2.close() 594 | #work_dir = tempfile.mkdtemp() 595 | outfolder = "out_local" 596 | delta=0.10 597 | delta_len=5 598 | 599 | merge_sub_isoforms_3=True 600 | merge_sub_isoforms_5 = True 601 | delta_iso_len_3=30 602 | delta_iso_len_5 = 50 603 | max_seqs_to_spoa=200 604 | iso_abundance=1 605 | 606 | #if merge_sub_isoforms_5 or merge_sub_isoforms_3: 607 | # merged_dict,merged_consensuses,called_consensuses,consensus_map = calculate_isoform_similarity(equal_reads, work_dir, isoform_paths, outfolder, delta, delta_len, batch_id, 608 | # merge_sub_isoforms_3, merge_sub_isoforms_5, all_reads, max_seqs_to_spoa, 609 | # delta_iso_len_3, delta_iso_len_5) 610 | # generate_isoforms_new() 611 | # generate_isoform_using_spoa_merged(equal_reads, all_reads, work_dir, outfolder, batch_id, max_seqs_to_spoa, iso_abundance,merged_dict,merged_consensuses,called_consensuses,consensus_map) 612 | #else: 613 | # generate_isoform_using_spoa(equal_reads, all_reads, work_dir, outfolder, batch_id, max_seqs_to_spoa, iso_abundance) 614 | 615 | 616 | if __name__ == "__main__": 617 | main() 618 | """ 619 | main concept: 620 | while reads_for_isoforms: 621 | start at s and iterate through the nodes up to t. 622 | Greedy approach: 623 | get nextnode by getting all out_edges. 624 | follow the edge which has 625 | max(current_node['reads']and nextnode['reads']) 626 | meaning which has the maximum amount of elements which are also in current_node 627 | all reads that are not in nextnode are deleted from supported_reads 628 | One isoform: 629 | Supported_reads as soon as edge[1]==t 630 | Solve isoform by using spoa. 631 | """ 632 | -------------------------------------------------------------------------------- /modules/GraphGeneration.py: -------------------------------------------------------------------------------- 1 | import tempfile 2 | import shutil 3 | import networkx as nx 4 | import pickle 5 | import os 6 | 7 | from collections import namedtuple 8 | from collections import deque 9 | 10 | Read_infos = namedtuple('Read_Infos', 'start_mini_end end_mini_start original_support') 11 | 12 | """IsONform script containing the methods used to generate the Directed Graph from the Intervals coming from the Weighted Interval Scheduling Problem 13 | Author: Alexander Petri 14 | The main method in this script was used for debugging therefore is not used during IsONforms actual run. 15 | """ 16 | 17 | 18 | def depth_first_search(graph, start): 19 | stack = [start] 20 | visited = set() 21 | while stack: 22 | vertex = stack.pop() 23 | if vertex in visited: 24 | continue 25 | yield vertex 26 | visited.add(vertex) 27 | for neighbor in graph[vertex]: 28 | stack.append(neighbor) 29 | 30 | 31 | 32 | def bfs(DG, startnode): #function for BFS 33 | visited = set() 34 | queue = deque([startnode]) 35 | 36 | while queue: # Creating loop to visit each node 37 | m = queue.popleft() 38 | for neighbour in DG.successors(m): 39 | if neighbour not in visited: 40 | visited.add(neighbour) 41 | queue.append(neighbour) 42 | if neighbour == startnode: 43 | return True 44 | return False 45 | 46 | 47 | def isCyclicUtil(DG, visited,rec_stack, node): 48 | """ 49 | Used to find out whether adding 'node' led to the graph having a cycle 50 | Implemented according to https://www.geeksforgeeks.org/detect-cycle-in-a-graph/ 51 | """ 52 | visited.add(node) 53 | rec_stack.add(node) 54 | # Mark current node as visited and 55 | # adds to recursion stack 56 | #CNode = namedtuple('CNode', 'visited recStack') 57 | #cnode = CNode(True, True) 58 | #nodes_dict[node] = cnode 59 | # Recur for all neighbours 60 | # if any neighbour is visited and in 61 | # recStack then graph is cyclic 62 | for successor in DG.successors(node): 63 | #neighbour = out_edge[1] 64 | #if neighbour not in nodes_dict: 65 | # cnode = CNode(False, False) 66 | # nodes_dict[neighbour] = cnode 67 | if successor not in visited: 68 | if isCyclicUtil(DG, visited, rec_stack, successor): 69 | return True 70 | elif successor in rec_stack: 71 | return True 72 | # The node needs to be popped from 73 | # recursion stack before function ends 74 | #prev_visited = nodes_dict[node].visited 75 | #nodes_dict[node] = CNode(prev_visited, False) 76 | rec_stack.remove(node) 77 | return False 78 | 79 | 80 | def cycle_finder(DG, start_node): 81 | """ 82 | Method used to detect cycles in our graph structure 83 | INPUT: 84 | DG: the graph structure 85 | start_node: a node that should be located in a cycle 86 | OUTPUT: 87 | bool: indicator whether a cycle has been found 88 | """ 89 | #nodes_dict = {} 90 | visited=set() 91 | rec_stack=set() 92 | if isCyclicUtil(DG, visited,rec_stack, start_node): 93 | return True 94 | return False 95 | 96 | 97 | def add_prior_read_infos(inter, r_id, prior_read_infos, name, k): 98 | """ 99 | Function to add read information of the current interval to prior_read_infos, if they do not exist there yet 100 | INPUT: inter: the current interval holding the information 101 | r_id: the read we are looking at 102 | prior_read_infos: information about other reads 103 | name: name of the node we appoint the information to 104 | k: minimizer length 105 | OUTPUT: prior_read_infos: information about other reads extended by this intervals infos 106 | """ 107 | read_id = inter[3][slice(0, len(inter[3]), 108 | 3)] # recover the read id from the array of instances which was delivered with all_intervals_for_graph 109 | start_coord = inter[3][slice(1, len(inter[3]), 110 | 3)] # recover the start coordinate of an interval from the array of instances 111 | end_coord = inter[3][slice(2, len(inter[3]), 3)] 112 | # iterate through the retreived information and store it in prior_read_infos only for subsequent reads 113 | for i, r in enumerate(read_id): 114 | if not r <= r_id: 115 | start = start_coord[i] + k 116 | end = end_coord[i] 117 | tuple_for_data_structure = (r, start, end) 118 | if tuple_for_data_structure not in prior_read_infos: 119 | prior_read_infos[tuple_for_data_structure] = name 120 | 121 | 122 | def convert_array_to_hash(info_array): 123 | """Helper method to convert the array delivered with all_intervals_for_graph into a hash value to more efficiently look up occurence 124 | This method additionally deletes the first three entries of the array as they contain the infos about this interval occurence, which changes in between instances 125 | INPUT: info_array: The array, which was delivered with the interval to indicate where the interval occurs in other reads 126 | OUTPUT: hash(tup): A has value of the tuple the shortened interval was converted into. This hash makes it easy to see whether the interval is already present in the read 127 | """ 128 | # preprocessing: Delete the first three elements from the array, as they contain the information about this occurrence 129 | for x in range(0, 3): 130 | if info_array: 131 | info_array.pop(0) 132 | 133 | tup = hash(tuple(info_array)) 134 | return tup 135 | 136 | 137 | 138 | 139 | def add_edge_support(edge_support, previous_node, name, r_id): 140 | edge_support[previous_node, name] = [] 141 | edge_support[previous_node, name].append(r_id) 142 | 143 | 144 | def known_old_node_action(alternatives_filtered, previous_node, this_len, nodes_for_graph, inter, k, seq, node_sequence, 145 | r_id, DG, edge_support, alternative_nodes, old_node, alt_info_tuple, name, alt_cyc_nodes): 146 | # if we have found a node which this info can be added to 147 | if alternatives_filtered: 148 | node_info = alternatives_filtered[0] 149 | # print("Ninfo",node_info) 150 | name = node_info[0] 151 | # update the read information of node name 152 | prev_nodelist = nodes_for_graph[name] 153 | r_infos = Read_infos(inter[0], inter[1], True) 154 | end_mini_seq = seq[inter[1]:inter[1] + k] 155 | node_sequence[name] = end_mini_seq 156 | prev_nodelist[r_id] = r_infos 157 | nodes_for_graph[name] = prev_nodelist 158 | if not DG.has_edge(previous_node, name): 159 | DG.add_edge(previous_node, name, this_len) 160 | #cycle_added2 = cycle_finder(DG, previous_node) 161 | cycle_added2 = bfs(DG, previous_node) 162 | if cycle_added2: 163 | cycle_added(name, alt_cyc_nodes, inter, DG, previous_node, r_id, seq, node_sequence, k, nodes_for_graph, 164 | this_len, edge_support) 165 | else: 166 | add_edge_support(edge_support, previous_node, name, r_id) 167 | else: 168 | edge_info = edge_support[previous_node, name] 169 | if r_id not in edge_info: 170 | edge_info.append(r_id) 171 | edge_support[previous_node, name] = edge_info 172 | # if we have not found a node which this info can be added to 173 | else: 174 | no_node_to_add_to_action(alternative_nodes, old_node, alt_info_tuple, inter, seq, k, node_sequence, name, r_id, 175 | nodes_for_graph, DG, this_len, previous_node, edge_support) 176 | 177 | 178 | 179 | def new_interval_action(seq, inter, r_id, node_sequence, nodes_for_graph, known_intervals, k, previous_end, 180 | prior_read_infos, DG, previous_node, edge_support, name): 181 | #print("NIA") 182 | nodelist = {} 183 | # add the read information for the node 184 | r_infos = Read_infos(inter[0], inter[1], True) 185 | end_mini_seq = seq[inter[1]:inter[1] + k] 186 | node_sequence[name] = end_mini_seq 187 | nodelist[r_id] = r_infos 188 | # add a node into nodes_for_graph 189 | nodes_for_graph[name] = nodelist 190 | known_intervals[r_id - 1].append((inter[0], name, inter[1])) 191 | # get the length between the previous end and this nodes start 192 | length = inter[0] - previous_end 193 | add_prior_read_infos(inter, r_id, prior_read_infos, name, k) 194 | DG.add_node(name) 195 | # connect the node to the previous one 196 | DG.add_edge(previous_node, name, length=length) 197 | if DEBUG: 198 | print("adding edge clear 1035", previous_node, ",", name) 199 | add_edge_support(edge_support, previous_node, name, r_id) 200 | 201 | 202 | def no_node_to_add_to_action(alternative_nodes, old_node, alt_info_tuple, inter, seq, k, node_sequence, name, r_id, 203 | nodes_for_graph, DG, this_len, previous_node, edge_support): 204 | # add a new entry to alternative_nodes[old_node] to enable finding this instance 205 | alternative_nodes[old_node].append(alt_info_tuple) 206 | if DEBUG: 207 | print("oldnodeFurther", old_node) 208 | # add the read information for the node 209 | nodelist = {} 210 | r_infos = Read_infos(inter[0], inter[1], True) 211 | end_mini_seq = seq[inter[1]:inter[1] + k] 212 | node_sequence[name] = end_mini_seq 213 | nodelist[r_id] = r_infos 214 | nodes_for_graph[name] = nodelist 215 | DG.add_node(name) 216 | # get the length between the previous end and this nodes start 217 | length = this_len 218 | # connect the node to the previous one 219 | DG.add_edge(previous_node, name, length=length) 220 | add_edge_support(edge_support, previous_node, name, r_id) 221 | 222 | 223 | def cycle_added(name, alt_cyc_nodes, inter, DG, previous_node, r_id, seq, node_sequence, k, nodes_for_graph, length, edge_support): 224 | 225 | old_name = name 226 | # alt_cyc_nodes is just used to keep track of how many nodes we add over the whole graph generation 227 | if name not in alt_cyc_nodes.keys(): 228 | alt_cyc_list = [] 229 | alt_cyc_list.append(name) 230 | alt_cyc_nodes[old_name] = alt_cyc_list 231 | else: 232 | alt_cyc_list = alt_cyc_nodes[old_name] 233 | alt_cyc_list.append(name) 234 | alt_cyc_nodes[old_name] = alt_cyc_list 235 | DG.remove_edge(previous_node, name) 236 | # TODO: add alt_cyc_node instead ofadding a new node to reduce overall nr nodes in our graph 237 | 238 | name = str(inter[0]) + ", " + str(inter[1]) + ", " + str(r_id) 239 | if not DG.has_node(name): 240 | DG.add_node(name) 241 | nodelist = {} 242 | 243 | r_infos = Read_infos(inter[0], inter[1], True) 244 | end_mini_seq = seq[inter[1]:inter[1] + k] 245 | node_sequence[name] = end_mini_seq 246 | nodelist[r_id] = r_infos 247 | nodes_for_graph[name] = nodelist 248 | DG.add_edge(previous_node, name, length=length) 249 | add_edge_support(edge_support, previous_node, name, r_id) 250 | 251 | def generateGraphfromIntervals(all_intervals_for_graph, k, delta_len, read_len_dict, all_reads): 252 | """ generates a networkx graph from the intervals given in all_intervals_for_graph. 253 | # INPUT: all_intervals_for_graph: A dictonary holding lists of minimizer intervals. 254 | k: K-mer length 255 | delta_len: integer holding the maximum lenght difference for two reads to still land in the same Isoform 256 | readlen_dict: dictionary holding the read_id as key and the length of the read as value 257 | #OUTPUT: result a tuple of different output values of the algo 258 | DG The Networkx Graph object 259 | known_intervals A list of intervals used to check the correctness of the algo 260 | reads_for_isoforms A dictionary holding the reads which are to be put in the same isoform 261 | reads_at_start_dict 262 | 263 | """ 264 | 265 | DG = nx.DiGraph() 266 | # add the read ids to the startend_list 267 | reads_at_start_dict = {} 268 | reads_at_end_dict = {} 269 | reads_for_isoforms = [] 270 | # holds the r_id as key and a list of tuples as value: For identification of reads, also used to ensure correctness of graph 271 | known_intervals = [] 272 | # the following dictionary is supposed to hold the end minimizer sequence for each node 273 | node_sequence = {} 274 | edge_support = {} 275 | prior_read_infos = {} 276 | nodes_for_graph = {} 277 | alternative_nodes = {} 278 | alt_cyc_nodes={} 279 | for i in range(1, len(all_intervals_for_graph) + 1): 280 | reads_at_start_dict[i] = Read_infos(0, 0, True) 281 | reads_for_isoforms.append(i) 282 | for i in range(1, len(read_len_dict) + 1): 283 | reads_at_end_dict[i] = Read_infos(read_len_dict[i], read_len_dict[i], True) 284 | # a source and a sink node are added to the graph in order to have a well-defined start and end for the paths 285 | DG.add_node("s", reads=reads_at_start_dict, end_mini_seq='') 286 | # print("REads at end dict",reads_at_end_dict) 287 | DG.add_node("t", reads=reads_at_end_dict, end_mini_seq='') 288 | # adds an empty list for each r_id to known_intervals. To those lists, tuples, representing the intervals are added 289 | # for _ in itertools.repeat(None, len(all_intervals_for_graph)): 290 | for i in range(len(all_intervals_for_graph)): 291 | known_intervals.append([]) 292 | # iterate through the different reads stored in all_intervals_for_graph. For each read one path is built up from source to sink if the nodes needed for that are not already present 293 | # intervals_for_read holds all intervals which make up the solution for the WIS of a read 294 | for r_id, intervals_for_read in all_intervals_for_graph.items(): 295 | if DEBUG: 296 | print('CURR READ:', r_id) 297 | print("NR Nodes", len(DG.nodes())) 298 | print("NR Edges", len(DG.edges())) 299 | containscycle = False 300 | # set previous_node to be s. This is the node all subsequent nodes are going to have edges with 301 | previous_node = "s" 302 | previous_end = 0 303 | # read_hashs is a dictionary storing hash values as keys and the respective node ids as values 304 | read_hashs = {} 305 | # the name of each node is defined to be readID, startminimizerpos , endminimizerpos 306 | # iterate over all intervals, which are in the solution of a certain read 307 | for pos, inter in enumerate(intervals_for_read): 308 | if DEBUG: 309 | print("PRNode", previous_node) 310 | info_tuple = (r_id, inter[0], inter[1]) 311 | if DEBUG: 312 | print("INter", inter[0]) 313 | print(info_tuple) 314 | # generate hash value of the intervals' infos 315 | curr_hash = convert_array_to_hash(inter[3]) 316 | if curr_hash in read_hashs: 317 | is_repetative = True 318 | #cycle_start = read_hashs[curr_hash][-1] 319 | else: 320 | is_repetative = False 321 | # access prior_read_infos, if the same interval was already found in previous reads 322 | if info_tuple in prior_read_infos: 323 | if DEBUG: 324 | print("in prior read infos") 325 | # if the interval repeats during this read 326 | if is_repetative: 327 | if DEBUG: 328 | print("cycle not close enough") 329 | nodelist = {} 330 | this_len = inter[0] - previous_end 331 | # add a node into nodes_for_graph 332 | name = str(inter[0]) + ", " + str(inter[1]) + ", " + str(r_id) 333 | seq = all_reads[r_id][1] 334 | end_mini_seq = seq[inter[1]:inter[1] + k] 335 | node_sequence[name] = end_mini_seq 336 | r_infos = Read_infos(inter[0], inter[1], True) 337 | nodelist[r_id] = r_infos 338 | nodes_for_graph[name] = nodelist 339 | DG.add_node(name) 340 | # get the length between the previous end and this nodes start 341 | length = this_len 342 | # connect the node to the previous one 343 | if DEBUG: 344 | print("Adding edge, newnode no similar cycles connecting prevnode, name") 345 | DG.add_edge(previous_node, name, length=length) 346 | if DEBUG: 347 | print("adding edge clear 553", previous_node, ",", name) 348 | add_edge_support(edge_support, previous_node, name, r_id) 349 | # the interval did not repeat during this read 350 | else: 351 | if DEBUG: 352 | print("non repetative interval") 353 | # get the name by accessing prior_read_infos 354 | name = prior_read_infos[info_tuple] 355 | #print("NAME",name) 356 | # get length from previous_end to this_start 357 | this_len = inter[0] - previous_end 358 | # if there is not yet an edge connecting previous_node and name: add edge 359 | if not DG.has_edge(previous_node, name): 360 | if DEBUG: 361 | print("no edge between ", previous_node, " and ", name) 362 | seq = all_reads[r_id][1] 363 | # update the read information of node name 364 | prev_nodelist = nodes_for_graph[name] 365 | r_infos = Read_infos(inter[0], inter[1], True) 366 | end_mini_seq = seq[inter[1]:inter[1] + k] 367 | node_sequence[name] = end_mini_seq 368 | prev_nodelist[r_id] = r_infos 369 | nodes_for_graph[name] = prev_nodelist 370 | length = this_len 371 | #is_cyclic = SimplifyGraph.isCyclic(DG) 372 | #print("SimplifyGraph_cyclic ", is_cyclic) 373 | DG.add_edge(previous_node, name, length=length) 374 | #print("edge ", previous_node, " to ", name, "added") 375 | #cycle_added2 = cycle_finder(DG, previous_node) 376 | cycle_added2 = bfs(DG,previous_node) 377 | #is_cyclic = SimplifyGraph.isCyclic(DG) 378 | #try: 379 | # nx_cycle=nx.find_cycle(DG) 380 | # print("Networkx found a cycle ",nx_cycle) 381 | #except: 382 | # print("no cycle was found by networkx") 383 | #if is_cyclic: 384 | # k_size+=1 385 | # w+=1 386 | #print("The graph has a cycle - critical error") 387 | #if is_cyclic != cycle_added2: 388 | # print("SimplifyGraph_cyclic ",is_cyclic) 389 | # print("GG_cyclic ", cycle_added2, ", ",previous_node) 390 | # print("ERROR- different outcome") 391 | #the edge we added did introduce a cycle in our graph. We remove the edge again and instead generate a new node 392 | #if cycle_added2: 393 | if cycle_added2: 394 | cycle_added(name, alt_cyc_nodes, inter, DG, previous_node, r_id, seq, node_sequence, k, nodes_for_graph, length, edge_support) 395 | else: 396 | add_edge_support(edge_support, previous_node, name, r_id) 397 | # if there is an edge connecting previous_node and name: test if length difference is not higher than delta_len 398 | else: 399 | if DEBUG: 400 | print("Has edge") 401 | print(previous_node, name) 402 | prev_len = DG[previous_node][name]["length"] 403 | len_difference = abs(this_len - prev_len) 404 | # if the length difference is delta len: generate new node, to be able to tell those nodes apart we use alternative_nodes 419 | else: 420 | #print("LEN diff > DL") 421 | nodelist = {} 422 | # inappropriate_node 423 | old_node = name 424 | name = str(inter[0]) + ", " + str(inter[1]) + ", " + str(r_id) 425 | alt_info_tuple = (name, previous_node, prev_len) 426 | # add old node as key for alternative nodes: This is to find the alternative nodes for this one easily 427 | if not (old_node in alternative_nodes): 428 | alternative_nodes[old_node] = [] 429 | DG.add_node(name) 430 | r_infos = Read_infos(inter[0], inter[1], True) 431 | end_mini_seq = seq[inter[1]:inter[1] + k] 432 | node_sequence[name] = end_mini_seq 433 | nodelist[r_id] = r_infos 434 | nodes_for_graph[name] = nodelist 435 | DG.add_edge(previous_node, name, length=this_len) 436 | add_edge_support(edge_support, previous_node, name, r_id) 437 | # if we already know old_node (it is a key in alternative_nodes) 438 | else: 439 | alternative_infos_list = alternative_nodes[old_node] 440 | alternatives_filtered = [item for item in alternative_infos_list if 441 | previous_node == item[1] and abs( 442 | this_len - item[2]) < delta_len] 443 | known_old_node_action(alternatives_filtered, previous_node, this_len, 444 | nodes_for_graph, inter, k, 445 | seq, node_sequence, r_id, DG, edge_support, alternative_nodes, 446 | old_node, 447 | alt_info_tuple, name, alt_cyc_nodes) 448 | 449 | # keep known_intervals up to date 450 | known_intervals[r_id - 1].append((inter[0], name, inter[1])) 451 | # if the information for the interval was not yet found in a previous read (meaning the interval is new) 452 | else: 453 | seq = all_reads[r_id][1] 454 | name = str(inter[0]) + ", " + str(inter[1]) + ", " + str(r_id) 455 | new_interval_action(seq, inter, r_id, node_sequence, nodes_for_graph, known_intervals, k, previous_end, 456 | prior_read_infos, DG, previous_node, edge_support, name) 457 | 458 | # set the previous node for the next iteration 459 | previous_node = name 460 | if DEBUG: 461 | print("PREVNODE", previous_node) 462 | previous_end = inter[1] 463 | # find out whether the current hash has already been added to read_hashs 464 | if not is_repetative: 465 | # if the current hash was not yet present in read_hashs: Add it 466 | read_hashs[curr_hash] = [] 467 | read_hashs[curr_hash].append(name) 468 | # add an edge from name to "t" as name was the last node in the read 469 | if not DG.has_edge(name, "t"): 470 | DG.add_edge(name, "t", length=0) 471 | if DEBUG: 472 | print("adding edge clear 1066", name, ",", "t") 473 | edge_support[name, "t"] = [] 474 | edge_support[name, "t"].append(r_id) 475 | else: 476 | edge_info = edge_support[name, "t"] 477 | if r_id not in edge_info: 478 | edge_info.append(r_id) 479 | edge_support[name, "t"] = edge_info 480 | print("Number of alternative nodes due to cycle",len(alt_cyc_nodes.keys())) 481 | # set the node attributes to be nodes_for_graph, very convenient way of solving this 482 | nx.set_node_attributes(DG, nodes_for_graph, name="reads") 483 | nx.set_node_attributes(DG, node_sequence, name="end_mini_seq") 484 | nx.set_edge_attributes(DG, edge_support, name='edge_supp') 485 | 486 | # return DG and known_intervals, used to 487 | result = (DG, reads_for_isoforms) 488 | return result 489 | 490 | 491 | """ 492 | Plots the given Directed Graph via Matplotlib 493 | Input: DG Directed Graph 494 | """ 495 | 496 | 497 | 498 | 499 | 500 | def get_read_lengths(all_reads): 501 | """Helper method which extracts the read lengths from all_reads. We will use those during the graph generation to appoint more meaningful information to the node't' 502 | INPUT: all_reads: dictionary which holds the overall read infos key: r_id, value tuple(readname, sequence, some info i currently don't care about) 503 | OUTPUT: readlen_dict: dictionary holding the read_id as key and the length of the read as value 504 | """ 505 | readlen_dict = {} 506 | for r_id, infos in all_reads.items(): 507 | seq = infos[1] 508 | seqlen = len(seq) 509 | 510 | readlen_dict[r_id] = seqlen 511 | return readlen_dict 512 | 513 | 514 | """ 515 | USED FOR DEBUGGING ONLY-deprecated in IsONform 516 | """ 517 | 518 | DEBUG=False 519 | def main(): 520 | # import sys 521 | # sys.stdout = open('log.txt', 'w') 522 | print('test') 523 | w = 10 524 | reads = 62 525 | max_seqs_to_spoa = 200 526 | work_dir = tempfile.mkdtemp() 527 | # print("Temporary workdirektory:", work_dir) 528 | k_size = 9 529 | outfolder = "out_local" 530 | cwd = os.getcwd() 531 | # print("CWD",cwd) 532 | file = open('all_intervals.txt', 'rb') 533 | all_intervals_for_graph = pickle.load(file) 534 | file.close() 535 | # print("All of them", len(all_intervals_for_graph)) 536 | 537 | file2 = open('all_reads.txt', 'rb') 538 | 539 | all_reads = pickle.load(file2) 540 | print("Allreads type") 541 | # print(type(all_reads)) 542 | # print(all_reads) 543 | file2.close() 544 | delta_len = 2 * k_size 545 | # is_cyclic = True 546 | # while is_cyclic: 547 | read_len_dict = get_read_lengths(all_reads) 548 | print("Generating graph") 549 | DG, known_intervals, reads_for_isoforms, reads_list = generateGraphfromIntervals( 550 | all_intervals_for_graph, k_size, delta_len, read_len_dict, all_reads) 551 | 552 | print("edges with attributes:") 553 | 554 | print("Calling the method") 555 | 556 | # simplifyGraph(DG, all_reads,work_dir,k_size,delta_len,known_intervals) 557 | print("Graph simplified") 558 | # simplifyGraphOriginal(DG,delta_len, all_reads, work_dir, k_size,known_intervals) 559 | # print("#Nodes for DG: " + str(DG.number_of_nodes()) + " , #Edges for DG: " + str(DG.number_of_edges())) 560 | # draw_Graph(DG) 561 | # print(DG.nodes["s"]["reads"]) 562 | # print(list(DG.nodes(data=True))) 563 | # print("edges with attributes:") 564 | # print(DG.edges(data=True)) 565 | # print("ReadNodes") 566 | # print("all edges for the graph") 567 | # print([e for e in DG.edges]) 568 | # draw_Graph(DG) 569 | # print("knownintervals") 570 | # print(known_intervals) 571 | # The call for the isoform generation (deprecated during implementation) 572 | # TODO: invoke isoform_generation again 573 | # generate_isoforms(DG, all_reads, reads_for_isoforms, work_dir, outfolder, max_seqs_to_spoa) 574 | # DG.nodes(data=True) 575 | 576 | # print("removing temporary workdir") 577 | shutil.rmtree(work_dir) 578 | 579 | 580 | if __name__ == "__main__": 581 | main() 582 | -------------------------------------------------------------------------------- /main: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | from __future__ import print_function 3 | import argparse 4 | from array import array 5 | import itertools 6 | import os 7 | import shutil 8 | import sys 9 | import tempfile 10 | import pickle 11 | import operator 12 | from collections import defaultdict, deque 13 | 14 | 15 | from modules import help_functions, GraphGeneration, batch_merging_parallel, IsoformGeneration, SimplifyGraph 16 | 17 | D = {chr(i) : min( 10**( - (ord(chr(i)) - 33)/10.0 ), 0.79433) for i in range(128)} 18 | 19 | 20 | def write_batch(reads,outfolder,batch_pickle): 21 | this_batch_dict = {} 22 | for id, (acc, seq, qual) in reads.items(): 23 | this_batch_dict[acc] = seq 24 | pickle_batch_file = open(os.path.join(outfolder, batch_pickle), 'wb') 25 | pickle.dump(this_batch_dict, pickle_batch_file) 26 | pickle_batch_file.close() 27 | 28 | 29 | 30 | def get_read_lengths(all_reads): 31 | """Helper method which extracts the read lengths from all_reads. We will use those during the graph generation to appoint more meaningful information to the node't' 32 | INPUT: all_reads: dictionary which holds the overall read infos key: r_id, value tuple(readname, sequence, some info i currently don't care about) 33 | OUTPUT: readlen_dict: dictionary holding the read_id as key and the length of the read as value 34 | """ 35 | readlen_dict = {} 36 | for r_id, infos in all_reads.items(): 37 | seq = infos[1] 38 | seqlen = len(seq) 39 | readlen_dict[r_id] = seqlen 40 | return readlen_dict 41 | 42 | 43 | def eprint(*args, **kwargs): 44 | print(*args, file=sys.stderr, **kwargs) 45 | 46 | 47 | def remove_read_polyA_ends(seq, threshold_len, to_len): 48 | """ 49 | Funtion that removes the polyA_ends from the reads. We remove all polyAtails longer than threshold_len by transforming them into polyA strings of length to_len. 50 | INPUT: seq: the sequence to be altered 51 | threshold_len: the length threshold over which we alter the polyA sequences 52 | to_len: the length of the poly_A tails after the alteration 53 | OUTPUT: seq_mod: the sequence that has been modified by the function, i.e. the sequence with shortened polyA tails 54 | """ 55 | #we only want to alter polyA sequences that are located in the end of the read->calculate a window length in which we perform the change 56 | end_length_window = min(len(seq)//2, 100) 57 | seq_list = [ seq[:-end_length_window] ] 58 | 59 | for ch, g in itertools.groupby(seq[-end_length_window:]): 60 | h_len = sum(1 for x in g) 61 | if h_len > threshold_len and (ch == "A" or ch == "T"): 62 | seq_list.append(ch*to_len) 63 | else: 64 | seq_list.append(ch*h_len) 65 | 66 | seq_mod = "".join([s for s in seq_list]) 67 | return seq_mod 68 | 69 | 70 | 71 | 72 | def rindex(lst, value): 73 | """ 74 | Function that calculates the reverse index. We want to find the last (but still) smallest k-mer in the window not the first 75 | INPUT: lst: the window of kmers as a list 76 | value: the smallest kmer 77 | OUTPUT: minimizer_pos: the last position of kmer with value in lst (not the first as before) 78 | """ 79 | return len(lst) - operator.indexOf(reversed(lst), value) - 1 80 | 81 | def get_kmer_minimizers(seq, k_size, w_size): 82 | # kmers = [seq[i:i+k_size] for i in range(len(seq)-k_size) ] 83 | w = w_size - k_size 84 | #save the window as a deque and instead of the sequence itself we use its hash value 85 | window_kmers = deque([hash(seq[i:i+k_size]) for i in range(w +1)]) 86 | #the smallest kmer (or to be precise the smallest hash) we have found in the window 87 | curr_min = min(window_kmers) 88 | #we now want the last occurrence of the smallest kmer not the first anymore 89 | minimizer_pos = rindex(list(window_kmers), curr_min) 90 | #add the initial minimizer to minimizers 91 | minimizers = [ (seq[minimizer_pos: minimizer_pos+k_size], minimizer_pos) ] # get the last element if ties in window 92 | #iterate over the remaining read and find all minimizers therein 93 | for i in range(w+1, len(seq) - k_size): 94 | new_kmer = hash(seq[i:i+k_size]) 95 | # updating window 96 | discarded_kmer = window_kmers.popleft() 97 | window_kmers.append(new_kmer) 98 | 99 | # we have discarded previous window's minimizer, look for new minimizer brute force 100 | if curr_min == discarded_kmer and minimizer_pos < i - w: 101 | curr_min = min(window_kmers) 102 | minimizer_pos = rindex(list(window_kmers), curr_min) + i - w 103 | minimizers.append( (seq[minimizer_pos: minimizer_pos+k_size], minimizer_pos) ) # get the last element if ties in window 104 | 105 | # Previous minimizer still in window, we only need to compare with the recently added kmer 106 | elif new_kmer < curr_min: 107 | curr_min = new_kmer 108 | minimizers.append( (seq[i: i+k_size], i) ) 109 | 110 | return minimizers 111 | 112 | def get_kmer_maximizers(seq, k_size, w_size): 113 | # kmers = [seq[i:i+k_size] for i in range(len(seq)-k_size) ] 114 | w = w_size - k_size 115 | window_kmers = deque([seq[i:i+k_size] for i in range(w +1)]) 116 | curr_min = max(window_kmers) 117 | minimizers = [ (curr_min, list(window_kmers).index(curr_min)) ] 118 | 119 | for i in range(w+1,len(seq) - k_size): 120 | new_kmer = seq[i:i+k_size] 121 | # updating window 122 | discarded_kmer = window_kmers.popleft() 123 | window_kmers.append(new_kmer) 124 | 125 | # we have discarded previous windows minimizer, look for new minimizer brute force 126 | if curr_min == discarded_kmer: 127 | curr_min = max(window_kmers) 128 | minimizers.append( (curr_min, list(window_kmers).index(curr_min) + i - w ) ) 129 | 130 | # Previous minimizer still in window, we only need to compare with the recently added kmer 131 | elif new_kmer > curr_min: 132 | curr_min = new_kmer 133 | minimizers.append( (curr_min, i) ) 134 | 135 | return minimizers 136 | 137 | 138 | def get_minimizers_and_positions_compressed(reads, w, k, hash_fcn): 139 | # 1. homopolymenr compress read and obtain minimizers 140 | M = {} 141 | for r_id in reads: 142 | (acc, seq, qual) = reads[r_id] 143 | 144 | seq_hpol_comp = ''.join(ch for ch, _ in itertools.groupby(seq)) 145 | 146 | if hash_fcn == "lex": 147 | minimizers = get_kmer_minimizers(seq_hpol_comp, k, w) 148 | elif hash_fcn == "rev_lex": 149 | minimizers = get_kmer_maximizers(seq_hpol_comp, k, w) 150 | # indicies we want to take quality values from to get quality string of homopolymer compressed read 151 | indices = [i for i, (n1,n2) in enumerate(zip(seq[:-1],seq[1:])) if n1 != n2] 152 | indices.append(len(seq) - 1) 153 | positions_in_non_compressed_sring = [(m, indices[p]) for m, p in minimizers ] 154 | M[r_id] = positions_in_non_compressed_sring 155 | 156 | return M 157 | 158 | 159 | def get_minimizers_and_positions(reads, w, k, hash_fcn): 160 | # 1. homopolymenr compress read and obtain minimizers 161 | M = {} 162 | for r_id in reads: 163 | (acc, seq, qual) = reads[r_id] 164 | if hash_fcn == "lex": 165 | minimizers = get_kmer_minimizers(seq, k, w) 166 | elif hash_fcn == "rev_lex": 167 | minimizers = get_kmer_maximizers(seq, k, w) 168 | 169 | M[r_id] = minimizers 170 | 171 | return M 172 | 173 | 174 | def get_minimizer_combinations_database(M, k, x_low, x_high,reads): 175 | M2 = defaultdict(lambda: defaultdict(lambda: array("I"))) 176 | tmp_cnt = 0 177 | forbidden = 'A'*k 178 | for r_id in M: 179 | minimizers = M[r_id] 180 | for (m1,p1), m1_curr_spans in minimizers_comb_iterator(minimizers, k, x_low, x_high): 181 | for (m2, p2) in m1_curr_spans: 182 | if m2 == m1 == forbidden: 183 | continue 184 | 185 | tmp_cnt +=1 186 | M2[m1][m2].append(r_id) 187 | M2[m1][m2].append(p1) 188 | M2[m1][m2].append(p2) 189 | 190 | print(tmp_cnt, "MINIMIZER COMBINATIONS GENERATED") 191 | 192 | avg_bundance = 0 193 | singleton_minimzer = 0 194 | cnt = 1 195 | for m1 in list(M2.keys()): 196 | for m2 in list(M2[m1].keys()): 197 | #if the minimizer_pair is represented at more than one occurrence 198 | if len(M2[m1][m2]) > 3: 199 | avg_bundance += len(M2[m1][m2])//3 200 | cnt += 1 201 | #the minimizer_combination is only once in the data therefore does not yield viable information for the graph later on 202 | else: 203 | del M2[m1][m2] 204 | singleton_minimzer += 1 205 | #we also want to filter out minimizer combinations if they are too abundant (more than 3 times per read) 206 | if len(M2[m1][m2]) // 3 > 3 * len(reads): 207 | del M2[m1][m2] 208 | 209 | print("Average abundance for non-unique minimizer-combs:", avg_bundance/float(cnt)) 210 | print("Number of singleton minimizer combinations filtered out:", singleton_minimzer) 211 | 212 | return M2 213 | 214 | 215 | def minimizers_comb_iterator(minimizers, k, x_low, x_high): 216 | for i, (m1, p1) in enumerate(minimizers[:-1]): 217 | m1_curr_spans = [] 218 | for j, (m2, p2) in enumerate(minimizers[i+1:]): 219 | if x_low < p2 - p1 and p2 - p1 <= x_high: 220 | m1_curr_spans.append((m2, p2)) 221 | # yield (m1,p1), (m2, p2) 222 | elif p2 - p1 > x_high: 223 | break 224 | yield (m1, p1), m1_curr_spans[::-1] 225 | 226 | 227 | def fill_p2(p, all_intervals_sorted_by_finish): 228 | stop_to_max_j = {stop: j for j, (start, stop, w, _) in enumerate(all_intervals_sorted_by_finish) if start < stop} 229 | all_choord_to_max_j = [] 230 | j_max = 0 231 | for i in range(0, all_intervals_sorted_by_finish[-1][1] + 1): 232 | if i in stop_to_max_j: 233 | j_max = stop_to_max_j[i] 234 | 235 | all_choord_to_max_j.append(j_max) 236 | for j, (start, stop, w, _) in enumerate(all_intervals_sorted_by_finish): 237 | j_max = all_choord_to_max_j[start] 238 | p.append(j_max) 239 | return p 240 | 241 | 242 | def solve_WIS(all_intervals_sorted_by_finish): 243 | # Using notation from https://courses.cs.washington.edu/courses/cse521/13wi/slides/06dp-sched.pdf 244 | p = [None] 245 | fill_p2(p, all_intervals_sorted_by_finish) 246 | epsilon = 0.0001 247 | # w - 1 since the read interval itself is included in the instance 248 | v = [None] + [(w - 1)*(stop-start + epsilon) for (start, stop, w, _) in all_intervals_sorted_by_finish] 249 | OPT = [0] 250 | for j in range(1, len(all_intervals_sorted_by_finish) +1): 251 | OPT.append( max(v[j] + OPT[ p[j] ], OPT[j-1] ) ) 252 | # Find solution 253 | opt_indicies = [] 254 | j = len(all_intervals_sorted_by_finish) 255 | while j >= 0: 256 | if j == 0: 257 | break 258 | if v[j] + OPT[p[j]] > OPT[j-1]: 259 | opt_indicies.append(j - 1) # we have shifted all indices forward by one so we neew to reduce to j -1 because of indexing in python works 260 | j = p[j] 261 | else: 262 | j -= 1 263 | return opt_indicies 264 | 265 | 266 | def get_intervals_to_correct(opt_indicies, all_intervals_sorted_by_finish): 267 | intervals_to_correct = [] 268 | for j in opt_indicies: 269 | start, stop, weights, instance = all_intervals_sorted_by_finish[j] 270 | intervals_to_correct.append((start, stop, weights, instance)) 271 | 272 | return intervals_to_correct 273 | 274 | 275 | def batch(dictionary, size): 276 | batches = [] 277 | sub_dict = {} 278 | for i, (acc, seq) in enumerate(dictionary.items()): 279 | if i > 0 and i % size == 0: 280 | batches.append(sub_dict) 281 | sub_dict = {} 282 | sub_dict[acc] = seq 283 | else: 284 | sub_dict[acc] = seq 285 | 286 | if i / size != 0: 287 | sub_dict[acc] = seq 288 | batches.append(sub_dict) 289 | elif len(dictionary) == 1: 290 | batches.append(sub_dict) 291 | 292 | return batches 293 | 294 | 295 | def grouper(iterable, n, fillvalue=None): 296 | "Collect data into fixed-length chunks or blocks" 297 | # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" 298 | args = [iter(iterable)] * n 299 | return itertools.zip_longest(*args, fillvalue=fillvalue) 300 | 301 | 302 | def add_items(seqs, r_id, p1, p2): 303 | seqs.append(r_id) 304 | seqs.append(p1) 305 | seqs.append(p2) 306 | 307 | 308 | def find_most_supported_span(r_id, m1, p1, m1_curr_spans, minimizer_combinations_database, all_intervals, k_size, delta_len): 309 | """ 310 | Funtion that detects the most supported spans in the database and adds them to all_intervals. 311 | INPUT: r_id: the id of the read we are workin on 312 | m1: the length threshold over which we alter the polyA sequences 313 | p1: the length of the poly_A tails after the alteration 314 | m1_curr_spans: 315 | minimizer_combinations_database: 316 | reads: 317 | all_intervals: list holding the interval information (empty at this point) 318 | k_size: 319 | delta_len: 320 | 321 | OUTPUT: all_intervals: modified list of all intervals 322 | """ 323 | #print("Most_supp_span") 324 | for (m2, p2) in m1_curr_spans: 325 | relevant_reads = minimizer_combinations_database[m1][m2] 326 | if len(relevant_reads)//3 >= 3: 327 | seqs = array("I") 328 | seqs.append(r_id) 329 | seqs.append(p1) 330 | seqs.append(p2) 331 | for relevant_read_id, pos1, pos2 in grouper(relevant_reads, 3): #relevant_reads: 332 | if r_id == relevant_read_id: 333 | continue 334 | elif abs((p2-p1)-(pos2-pos1)) < delta_len: 335 | seqs.append(relevant_read_id) 336 | seqs.append(pos1) 337 | seqs.append(pos2) 338 | all_intervals.append((p1 + k_size, p2, len(seqs)//3, seqs)) 339 | 340 | 341 | def main(args): 342 | #Todo: add timestamp 343 | print("ARGS",args) 344 | all_batch_reads_dict={} 345 | # start = time() 346 | if os.path.exists("mapping.txt"): 347 | os.remove("mapping.txt") 348 | outfolder = args.outfolder 349 | #sys.stdout = open(os.path.join(outfolder,"stdout.txt"), "w") 350 | # read the file and filter out polyA_ends(via remove_read_polyA_ends) 351 | all_reads = {i + 1: (acc, remove_read_polyA_ends(seq, 12, 1), qual) for i, (acc, (seq, qual)) in enumerate(help_functions.readfq(open(args.fastq, 'r')))} 352 | max_seqs_to_spoa = args.max_seqs_to_spoa 353 | if len(all_reads) <= args.exact_instance_limit: 354 | args.exact = True 355 | if args.set_w_dynamically: 356 | args.w = args.k + min(7, int(len(all_reads) / 500)) 357 | delta_iso_len_3 = args.delta_iso_len_3 358 | delta_iso_len_5 = args.delta_iso_len_5 359 | work_dir = tempfile.mkdtemp() 360 | print("Temporary workdirektory:", work_dir) 361 | 362 | k_size = args.k 363 | x_high = args.xmax 364 | x_low = args.xmin 365 | if args.parallel: 366 | filename = args.fastq.split("/")[-1] 367 | tmp_filename = filename.split("_") 368 | tmp_lastpart = tmp_filename[-1].split(".") 369 | p_batch_id = tmp_lastpart[0] 370 | skipfilename = "skip"+p_batch_id+".fa" 371 | 372 | for batch_id, reads in enumerate(batch(all_reads, args.max_seqs)): 373 | 374 | 375 | new_all_reads = {} 376 | if args.parallel: 377 | batch_pickle = str(p_batch_id) + "_batch" 378 | else: 379 | skipfilename="skip"+str(batch_id)+".fa" 380 | batch_pickle = str(batch_id) + "batch" 381 | skipfilename = "skip" + str(batch_id) + ".fa" 382 | skipfile = open(os.path.join(outfolder, skipfilename), 'w') 383 | write_batch(reads, outfolder, batch_pickle) 384 | skipfile=open(os.path.join(outfolder,skipfilename),'w') 385 | 386 | if args.set_w_dynamically: 387 | # Activates for 'small' clusters with less than 700 reads 388 | if len(reads) >= 100: 389 | w = min(args.w, args.k + ( 390 | len(reads) // 100 + 4)) 391 | elif len(reads) == 1: 392 | for id, vals in reads.items(): 393 | (acc, seq, qual) = vals 394 | skipfile.write(">{0}\n{1}\n".format(acc, seq)) 395 | print("Not enough reads to work on!") 396 | continue 397 | else: 398 | w = args.k + 1 + len(reads) // 30 399 | else: 400 | w = args.w 401 | #print("Window used for batch:", w) 402 | iso_abundance = args.iso_abundance 403 | delta_len = args.delta_len 404 | graph_id = 1 405 | print("Working on {0} reads in a batch".format(len(reads))) 406 | hash_fcn = "lex" 407 | not_used=0 408 | #generate all minimizer combinations 409 | if args.compression: 410 | minimizer_database = get_minimizers_and_positions_compressed(reads, w, k_size, hash_fcn) 411 | else: 412 | minimizer_database = get_minimizers_and_positions(reads, w, k_size, hash_fcn) 413 | 414 | minimizer_combinations_database = get_minimizer_combinations_database(minimizer_database, k_size, x_low, 415 | x_high, reads) 416 | previously_corrected_regions = defaultdict(list) 417 | all_intervals_for_graph = {} 418 | for r_id in sorted(reads): 419 | print(r_id) 420 | read_min_comb = [((m1, p1), m1_curr_spans) for (m1, p1), m1_curr_spans in 421 | minimizers_comb_iterator(minimizer_database[r_id], k_size, x_low, x_high)] 422 | 423 | if args.exact: 424 | previously_corrected_regions = defaultdict(list) 425 | 426 | read_previously_considered_positions = set( 427 | [tmp_pos for tmp_p1, tmp_p2, w_tmp, _ in previously_corrected_regions[r_id] for tmp_pos in 428 | range(tmp_p1, tmp_p2)]) 429 | 430 | if args.verbose: 431 | if read_previously_considered_positions: 432 | eprint("not corrected:", [(p1_, p2_) for p1_, p2_ in 433 | zip(sorted(read_previously_considered_positions)[:-1], 434 | sorted(read_previously_considered_positions)[1:]) if 435 | p2_ > p1_ + 1]) 436 | else: 437 | eprint("not corrected: entire read", ) 438 | 439 | if previously_corrected_regions[r_id]: 440 | read_previously_considered_positions = set( 441 | [tmp_pos for tmp_p1, tmp_p2, w_tmp, _ in previously_corrected_regions[r_id] for tmp_pos in 442 | range(tmp_p1, tmp_p2)]) 443 | group_id = 0 444 | pos_group = {} 445 | 446 | if len(read_previously_considered_positions) > 1: 447 | sorted_corr_pos = sorted(read_previously_considered_positions) 448 | 449 | for p1, p2 in zip(sorted_corr_pos[:-1], sorted_corr_pos[1:]): 450 | 451 | if p2 > p1 + 1: 452 | pos_group[p1] = group_id 453 | group_id += 1 454 | pos_group[p2] = group_id 455 | else: 456 | pos_group[p1] = group_id 457 | 458 | if p2 == p1 + 1: 459 | pos_group[p2] = group_id 460 | 461 | else: 462 | read_previously_considered_positions = set() 463 | pos_group = {} 464 | all_intervals = [] 465 | prev_visited_intervals = [] 466 | #print("it over read_min_comb") 467 | for (m1, p1), m1_curr_spans in read_min_comb: 468 | #print(m1,", ", p1) 469 | # If any position is not in range of current corrections: then correct, not just start and stop 470 | not_prev_corrected_spans = [(m2, p2) for (m2, p2) in m1_curr_spans if not ( 471 | p1 + k_size in read_previously_considered_positions and p2 - 1 in read_previously_considered_positions)] 472 | set_not_prev = set(not_prev_corrected_spans) 473 | not_prev_corrected_spans2 = [(m2, p2) for (m2, p2) in m1_curr_spans if 474 | (m2, p2) not in set_not_prev and ( 475 | p1 + k_size in pos_group and p2 - 1 in pos_group and pos_group[ 476 | p1 + k_size] != pos_group[p2 - 1])] 477 | not_prev_corrected_spans += not_prev_corrected_spans2 478 | 479 | if not_prev_corrected_spans: # p1 + k_size not in read_previously_considered_positions: 480 | find_most_supported_span(r_id, m1, p1, m1_curr_spans, minimizer_combinations_database, 481 | all_intervals, k_size, delta_len) 482 | # add prev_visited_intervals to intervals to consider 483 | all_intervals.extend(prev_visited_intervals) 484 | 485 | if previously_corrected_regions[r_id]: # add previously corrected regions in to the solver 486 | 487 | all_intervals.extend(previously_corrected_regions[r_id]) 488 | del previously_corrected_regions[r_id] 489 | 490 | if not all_intervals: 491 | not_used+=1 492 | if DEBUG: 493 | eprint("Found no reads to work on") 494 | vals=reads[r_id] 495 | (acc, seq, qual) = vals 496 | skipfile.write(">{0}\n{1}\n".format(acc, seq)) 497 | continue 498 | else: 499 | all_intervals.sort(key=lambda x: x[1]) 500 | opt_indicies = solve_WIS( 501 | all_intervals) # solve Weighted Interval Scheduling here to find set of best non overlapping intervals to correct over 502 | intervals_to_correct = get_intervals_to_correct(opt_indicies[::-1], all_intervals) 503 | #if we have found intervals in our read: add it to all_intervals_for_graph and give it a graph_id (an internal id) 504 | if intervals_to_correct: 505 | all_intervals_for_graph[graph_id] = intervals_to_correct 506 | new_all_reads[graph_id] = reads[r_id] 507 | graph_id += 1 508 | #the read has no intervals in common with other reads-> we add it into skipfile 509 | else: 510 | not_used += 1 511 | if DEBUG: 512 | eprint("Found no reads to work on") 513 | vals = reads[r_id] 514 | (acc, seq, qual) = vals 515 | skipfile.write(">{0}\n{1}\n".format(acc, seq)) 516 | 517 | if not_used>0: 518 | print("Skipped ",not_used," reads due to not having high enough interval abundance") 519 | else: 520 | print("Working on all reads") 521 | print("Generating the graph") 522 | all_batch_reads_dict[batch_id] = new_all_reads 523 | read_len_dict = get_read_lengths(all_reads) 524 | #for key,value in all_intervals_for_graph.items(): 525 | # print(key,len(value)) 526 | #print(all_intervals_for_graph) 527 | 528 | #profiler = Profiler() 529 | #profiler.start() 530 | #generate the graph from the intervals 531 | #TODO: add timestamp 532 | DG, reads_for_isoforms = GraphGeneration.generateGraphfromIntervals( 533 | all_intervals_for_graph, k_size, delta_len, read_len_dict,new_all_reads) 534 | #profiler.stop() 535 | 536 | #profiler.print() 537 | #test for cyclicity of the graph - a status we cannot continue working on -> if cyclic we get an error 538 | #is_cyclic = SimplifyGraph.isCyclic(DG) 539 | #if is_cyclic: 540 | # k_size+=1 541 | # w+=1 542 | # print("The graph has a cycle - critical error") 543 | #return -1 544 | #else: 545 | # print("No cycle in graph") 546 | if DEBUG==True: 547 | print("BATCHID",batch_id) 548 | for id, value in all_batch_reads_dict.items(): 549 | for other_id,other_val in value.items(): 550 | print(id,": ",other_id,":",other_val[0],"::",other_val[1]) 551 | 552 | mode = args.slow 553 | #profiler = Profiler() 554 | #profiler.start() 555 | #the bubble popping step: We simplify the graph by linearizing all poppable bubbles 556 | SimplifyGraph.simplifyGraph(DG, new_all_reads, work_dir, k_size, delta_len, mode) 557 | #profiler.stop() 558 | 559 | #profiler.print() 560 | #TODO: add delta as user parameter possibly? 561 | delta = 0.15 562 | print("Starting to generate Isoforms") 563 | 564 | if args.parallel: 565 | batch_id = p_batch_id 566 | #profiler = Profiler() 567 | #profiler.start() 568 | #generation of isoforms from the graph structure 569 | IsoformGeneration.generate_isoforms(DG, new_all_reads, reads_for_isoforms, work_dir, outfolder, batch_id, delta, delta_len, delta_iso_len_3, delta_iso_len_5, max_seqs_to_spoa) 570 | #profiler.stop() 571 | 572 | print("Isoforms generated-Starting batch merging ") 573 | if not args.parallel: 574 | print("Merging the batches with linear strategy") 575 | #merges the predictions from different batches 576 | #batch_merging_parallel.join_back_via_batch_merging(args.outfolder, delta, args.delta_len, args.delta_iso_len_3, args.delta_iso_len_5, 577 | # args.max_seqs_to_spoa, args.iso_abundance) 578 | 579 | print("removing temporary workdir") 580 | #sys.stdout.close() 581 | shutil.rmtree(work_dir) 582 | 583 | DEBUG=False 584 | 585 | #TODO: add low_output (bool) as well as delta as user parameters and remove slow, merge_sub_isoforms_3, merge_sub_isoforms_5 586 | if __name__ == '__main__': 587 | parser = argparse.ArgumentParser(description="De novo error correction of long-read transcriptome reads", 588 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) 589 | parser.add_argument('--version', action='version', version='%(prog)s 0.3.9') 590 | parser.add_argument('--fastq', type=str, default=False, help='Path to input fastq file with reads') 591 | 592 | parser.add_argument('--k', type=int, default=20, help='Kmer size') 593 | parser.add_argument('--w', type=int, default=31, help='Window size') 594 | parser.add_argument('--xmin', type=int, default=18, help='Upper interval length') 595 | parser.add_argument('--xmax', type=int, default=80, help='Lower interval length') 596 | parser.add_argument('--T', type=float, default=0.1, help='Minimum fraction keeping substitution') 597 | parser.add_argument('--exact', action="store_true", help='Get exact solution for WIS for every read (recalculating weights for each read (much slower but slightly more accuracy,\ 598 | not to be used for clusters with over ~500 reads)') 599 | parser.add_argument('--disable_numpy', action="store_true", 600 | help='Do not require numpy to be installed, but this version is about 1.5x slower than with numpy.') 601 | parser.add_argument('--delta_len', type=int, default=5, help='Maximum length difference between two reads intervals for which they would still be merged') 602 | parser.add_argument('--max_seqs_to_spoa', type=int, default=200, help='Maximum number of seqs to spoa') 603 | parser.add_argument('--max_seqs', type=int, default=1000, 604 | help='Maximum number of seqs to correct at a time (in case of large clusters).') 605 | parser.add_argument('--exact_instance_limit', type=int, default=0, 606 | help='Activates slower exact mode for instance smaller than this limit') 607 | parser.add_argument('--set_w_dynamically', action="store_true", 608 | help='Set w = k + max(2*k, floor(cluster_size/1000)).') 609 | parser.add_argument('--verbose', action="store_true", help='Print various developer stats.') 610 | 611 | parser.add_argument('--compression', action="store_true", help='Use homopolymer compressed reads. (Deprecated, because we will have fewer \ 612 | minmimizer combinations to span regions in homopolymenr dense regions. Solution \ 613 | could be to adjust upper interval length dynamically to guarantee a certain number of spanning intervals.') 614 | parser.add_argument('--outfolder', type=str, default=None, 615 | help='The outfolder of isONform, into which the algorithm will write the results.') 616 | parser.add_argument('--iso_abundance', type=int,default=5, help='Cutoff parameter: abundance of reads that have to support an isoform to show in results') 617 | parser.add_argument('--delta_iso_len_3', type=int, default=30, 618 | help='Cutoff parameter: maximum length difference at 3prime end, for which subisoforms are still merged into longer isoforms') 619 | parser.add_argument('--delta_iso_len_5', type=int, default=50, 620 | help='Cutoff parameter: maximum length difference at 5prime end, for which subisoforms are still merged into longer isoforms') 621 | parser.add_argument('--parallel',type=bool,default=False,help='Indicates whether we run the parallelization wrapper script') 622 | parser.add_argument('--slow',action="store_true", help='EXPERIMENTAL PARAMETER: has high repercussions on run time use the slow mode for the simplification of the graph (bubble popping), slow mode: every bubble gets popped.') 623 | args = parser.parse_args() 624 | 625 | if args.xmin < 2 * args.k: 626 | args.xmin = 2 * args.k 627 | eprint("xmin set to {0}".format(args.xmin)) 628 | 629 | if len(sys.argv) == 1: 630 | parser.print_help() 631 | sys.exit() 632 | 633 | os.environ['PYTHONHASHSEED'] = '0' 634 | if args.outfolder and not os.path.exists(args.outfolder): 635 | os.makedirs(args.outfolder) 636 | 637 | if 100 < args.w or args.w < args.k: 638 | eprint('Please specify a window of size larger or equal to k, and smaller than 100.') 639 | sys.exit(1) 640 | 641 | main(args) 642 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------