Debian Codegraph @

scripts/k3000/compute_pi.py

raw symbols SCIP
1 import sys
2 """
3 Given a fasta file containing n sequences having all the same length
4 Returns the pi value https://en.wikipedia.org/wiki/Nucleotide_diversity
5
6
7 1/ stores the n sequences
8 2/ computes for all i<j in [1,n] the pi_i,j value
9 3/ computes and prints the pi value
10 """
11
12
13 def stores_fasta_sequences(fasta_file_name):
14 sequences=[]
15 with open(fasta_file_name) as fasta_file:
16 while True:
17 line = fasta_file.readline()
18 if not line: break # end of the file
19 line = line.strip()
20 if line[0] == ">": continue # comment
21 sequences.append(line)
22 if len(sequences) == 0: return None
23 l = len(sequences[0])
24 for sequence in sequences:
25 if len(sequence) != l:
26 sys.stderr.write(f"File {fasta_file_name} contains sequences of distinct sizes, unable to compute pi\n")
27 sys.exit(1)
28 return sequences
29
30
31 def main():
32 if len(sys.argv) !=2:
33 sys.stderr.write(f"Usage: {sys.argv[0]} fasta_file_name\n")
34 sys.stderr.write("Given a fasta file containing n sequences having all the same length\n")
35 sys.stderr.write("Returns the pi value https://en.wikipedia.org/wiki/Nucleotide_diversity\n")
36 sys.stderr.write(" 1/ stores the n sequences\n")
37 sys.stderr.write(" 2/ computes for all i<j in [1,n] the pi_i,j value\n")
38 sys.stderr.write(" 3/ computes and prints the pi value\n")
39
40 sequences = stores_fasta_sequences(sys.argv[1])
41 if not sequences :
42 sys.stderr.write(f"File {sys.argv[1]} contains no sequence\n")
43 print (sequences)
44
45 if __name__ == '__main__':
46 main()
47