I have a file titled "test.fa" that reads:
>Sequence 1
TCAGAACCAGTTATAAATTTATCATTTCCTTCTCCACTCCT
>Sequence 2
CCCACGCAGCCGCCCTCCTCCCCGGTCACTGACTGGTCCTG
>Sequence 3
TCGACCCTCTGGAACCTATCAGGGACCACAGTCAGCCAGGCAAG
>Sequence 4
AAAACACTTGAGGGAGCAGATAACTGGGCCAACCATGACTC
This test file only has 8 lines, but could have more. I also don't now the length of all sequences. So first I count the number of lines, and create a matrix based on the number of lines.
import numpy as np
filename = "test.fa"
with open(filename, 'r') as file:
n1 = 0
n2 = 0
for line in file.readlines():
if line[0] != '>':
m1 = 1
n1 = n1 + m1
else:
m2 = 1
n2 = n2 + m2
seq = np.chararray((n1,2),itemsize = 99)
Next, I add values to the matrix.
with open(filename, 'r') as file:
n3 = -1
n4 = -1
for line in file.readlines():
if line[0] != '>':
m3 = 1
n3 = n3 + m3
seq[n3,1] = line
else:
m4 = 1
n4 = n4 + m4
seq[n4,0] = line
If I call 'seq' I get:
chararray([[b'>Sequence 1', b'TCAGAACCAGTTATAAATTTATCATTTCCTTCTCCACTCCT'],
[b'>Sequence 2', b'CCCACGCAGCCGCCCTCCTCCCCGGTCACTGACTGGTCCTG'],
[b'>Sequence 3', b'TCGACCCTCTGGAACCTATCAGGGACCACAGTCAGCCAGGCAAG'],
[b'>Sequence 4', b'AAAACACTTGAGGGAGCAGATAACTGGGCCAACCATGACTC']], dtype='|S99')
seq[2,1]: b'TCGACCCTCTGGAACCTATCAGGGACCACAGTCAGCCAGGCAAG'
seq[2,1][0] : 84
seq[2,1][0:8] : b'TCGACCCT'
seq[2,8][8] : 67
seq[2,1][8:9] : C
This doesn’t feel like the best way manage this data (and why does [2,1][0] return 84?). I am not sure np.chararray with itemsize of 99 is the best approach.
My question is: What is a better way to organize/manage this data? I eventually need to count the occurrences of each nucleotide ( i.e. how many As, Ts, Cs, Gs), and pull substrings from each sequence. For context, this relates to Expectation Maximization and Gibbs Sampling.