| 1 |
#! /usr/bin/env python3 |
| 2 |
# Author: Martin C. Frith 2021 |
| 3 |
|
| 4 |
# xxx This is inefficient: ok for smallish data |
| 5 |
|
| 6 |
from __future__ import print_function |
| 7 |
|
| 8 |
import collections |
| 9 |
import gzip |
| 10 |
import itertools |
| 11 |
import optparse |
| 12 |
import signal |
| 13 |
import sys |
| 14 |
|
| 15 |
def openFile(fileName): |
| 16 |
if fileName == "-": |
| 17 |
return sys.stdin |
| 18 |
if fileName.endswith(".gz"): |
| 19 |
return gzip.open(fileName, "rt") |
| 20 |
return open(fileName) |
| 21 |
|
| 22 |
def fastaInput(fileNames): |
| 23 |
for f in fileNames: |
| 24 |
head = None |
| 25 |
for line in openFile(f): |
| 26 |
if line[0] == ">": |
| 27 |
if head: |
| 28 |
yield head, "".join(body) |
| 29 |
head = line |
| 30 |
body = [] |
| 31 |
else: |
| 32 |
body.append(line.rstrip().upper()) |
| 33 |
if head: |
| 34 |
yield head, "".join(body) |
| 35 |
|
| 36 |
def sortKey(seqRecord): |
| 37 |
name, seq = seqRecord |
| 38 |
return -len(seq), seq |
| 39 |
|
| 40 |
def nonContainedSeqRecords(seqRecords): |
| 41 |
maxPowerOfTwo = 3 # xxx ??? |
| 42 |
minSeqLen = min(len(seq) for name, seq in seqRecords if seq) |
| 43 |
for minPowerOfTwo in range(maxPowerOfTwo + 1): |
| 44 |
wordLen = 2 ** minPowerOfTwo |
| 45 |
if wordLen * 2 > minSeqLen: |
| 46 |
break |
| 47 |
wordLengths = [2 ** i for i in range(minPowerOfTwo, maxPowerOfTwo + 1)] |
| 48 |
index = collections.defaultdict(list) |
| 49 |
for record in seqRecords: |
| 50 |
name, seq = record |
| 51 |
if not seq: |
| 52 |
break |
| 53 |
seqLen = len(seq) |
| 54 |
wordLengths = [i for i in wordLengths if i <= seqLen] |
| 55 |
wordLen = wordLengths[-1] |
| 56 |
word = seq[:wordLen] |
| 57 |
if all(seq not in oldSeq for oldSeq in index[word]): |
| 58 |
for wordLen in wordLengths: |
| 59 |
words = set(seq[i-wordLen:i] for i in range(wordLen, seqLen)) |
| 60 |
for word in words: |
| 61 |
index[word].append(seq) |
| 62 |
yield record |
| 63 |
|
| 64 |
def main(opts, args): |
| 65 |
if not args: |
| 66 |
args = ["-"] |
| 67 |
records = sorted(fastaInput(args), key=sortKey) |
| 68 |
records = [next(v) for k, v in itertools.groupby(records, sortKey)] |
| 69 |
if opts.s: |
| 70 |
records = list(nonContainedSeqRecords(records)) |
| 71 |
for i, x in records: |
| 72 |
print(i, x, sep="") |
| 73 |
|
| 74 |
if __name__ == "__main__": |
| 75 |
signal.signal(signal.SIGPIPE, signal.SIG_DFL) # avoid silly error message |
| 76 |
usage = "%prog [options] seqs.fasta" |
| 77 |
descr = "Keep the first of identical sequences (after converting them to uppercase)." |
| 78 |
op = optparse.OptionParser(usage=usage, description=descr) |
| 79 |
op.add_option("-s", action="store_true", help= |
| 80 |
"omit any sequence that is a shorter substring of another") |
| 81 |
opts, args = op.parse_args() |
| 82 |
main(opts, args) |