upstream-extended/community/tools/find_subsequences/find_subsequences.py
1#!/usr/bin/env python
2
3import argparse
4import re
5
6from Bio import SeqIO
7from Bio.Alphabet import generic_dna
8from Bio.Seq import Seq
9from Bio.SeqUtils import nt_search
10
11choices = [
12 "embl",
13 "fasta",
14 "fastq-sanger",
15 "fastq",
16 "fastq-solexa",
17 "fastq-illumina",
18 "genbank",
19 "gb",
20]
21
22
23def find_pattern(seqs, pattern, outfile_path, strand):
24 """
25 Finds all occurrences of a pattern in the a given sequence.
26 Outputs sequence ID, start and end postion of the pattern.
27 """
28 pattern = pattern.upper()
29 rev_compl = Seq(pattern, generic_dna).complement()
30 search_func = simple_pattern_search
31 if set(pattern).difference(set("ATCG")):
32 search_func = complex_pattern_search
33
34 with open(outfile_path, "w+") as outfile:
35 for seq in seqs:
36 if strand in ["both", "forward"]:
37 search_func(seq, pattern, outfile)
38 if strand in ["both", "reverse"]:
39 search_func(seq, rev_compl, outfile, "-")
40
41
42def simple_pattern_search(sequence, pattern, outfile, strand="+"):
43 """
44 Simple regular expression search. This is way faster than the complex search.
45 """
46 bed_template = "%s\t%s\t%s\t%s\t%s\t%s\n"
47 for match in re.finditer(str(pattern), str(sequence.seq), re.IGNORECASE):
48 outfile.write(
49 bed_template
50 % (
51 sequence.id,
52 match.start(),
53 match.end(),
54 sequence.description,
55 "",
56 strand,
57 )
58 )
59
60
61def complex_pattern_search(sequence, pattern, outfile, strand="+"):
62 """
63 Searching for pattern with biopyhon's nt_search().
64 This allows for ambiguous values, like N = A or T or C or G, R = A or G ...
65 """
66 pattern_length = len(pattern)
67 matches = nt_search(str(sequence.seq), pattern)
68 bed_template = "%s\t%s\t%s\t%s\t%s\t%s\n"
69 for match in matches[1:]:
70 outfile.write(
71 bed_template
72 % (sequence.id, match, match + pattern_length, sequence.description, "", strand)
73 )
74
75
76if __name__ == "__main__":
77 parser = argparse.ArgumentParser()
78 parser.add_argument("-i", "--input", required=True)
79 parser.add_argument("-o", "--output", required=True)
80 parser.add_argument("-p", "--pattern", required=True)
81 parser.add_argument(
82 "--strand", choices=["both", "forward", "reverse"], default="both"
83 )
84 parser.add_argument("-f", "--format", default="fasta", choices=choices)
85 args = parser.parse_args()
86
87 with open(args.input) as handle:
88 find_pattern(
89 SeqIO.parse(handle, args.format), args.pattern, args.output, args.strand
90 )