Here’s a standalone script that
- Reads your PPM from “sigma70-PPM.txt”
- Reads a list of sequences (one per line) from “sequences.txt”
- Computes for each sequence the PPM‐based probability (i.e. ∏ₗ PPM[l][base])
- Writes out a two‐column file “sequence_probabilities.txt”
import pandas as pd
import sys
def load_ppm(ppm_file: str) -> pd.DataFrame:
"""
Load a PPM file with header:
pos A C G T
Returns a DataFrame indexed 0..L-1, columns ['A','C','G','T'].
"""
df = pd.read_csv(ppm_file, sep='\t')
df = df.set_index('pos')
# Make sure index is 1..L; we'll shift it to 0..L-1 for zero‐based lookup
df.index = df.index - 1
return df[['A','C','G','T']]
def load_sequences(seq_file: str) -> list:
"""
Load sequences from a text file, one sequence per line.
Strips whitespace and lowercases them.
"""
with open(seq_file, 'r') as f:
seqs = [line.strip().lower() for line in f if line.strip()]
return seqs
def calc_sequence_probability(seq: str, ppm: pd.DataFrame) -> float:
"""
Compute P(seq) = product over i of PPM[i][base].
If seq length ≠ ppm length or an invalid base appears, returns 0.0.
"""
L = ppm.shape[0]
if len(seq) != L:
# length mismatch
return 0.0
p = 1.0
for i, b in enumerate(seq):
b = b.upper()
if b not in ppm.columns:
# unknown base → zero the probability
return 0.0
p *= ppm.at[i, b]
# early exit if probability is zero
if p == 0.0:
return 0.0
return p
def main(ppm_file='sigma70-PPM.txt',
seq_file='sequences.txt',
out_file='sequence_probabilities.txt'):
# Load PPM
ppm = load_ppm(ppm_file)
L = ppm.shape[0]
print(f"Loaded PPM of length {L} positions.")
# Load sequences
seqs = load_sequences(seq_file)
print(f"Loaded {len(seqs)} sequences from {seq_file}.")
# Compute probabilities
results = []
for seq in seqs:
prob = calc_sequence_probability(seq, ppm)
results.append((seq, prob))
# Write output
with open(out_file, 'w') as f:
f.write("sequence\tprobability\n")
for seq, prob in results:
f.write(f"{seq}\t{prob}\n")
print(f"Wrote probabilities to {out_file}.")
if __name__ == "__main__":
# You can also pass custom file‐names via command‐line:
# python seq_prob.py ppm.txt seqs.txt out.txt
if len(sys.argv) == 4:
_, ppm_file, seq_file, out_file = sys.argv
main(ppm_file, seq_file, out_file)
else:
main()
Save this as, e.g., seq_prob.py, make sure you have:
sigma70-PPM.txt (tab‐delimited, pos A C G T header)
sequences.txt (one raw sequence per line)
Then run:
python seq_prob.py
Or with custom file names:
python seq_prob.py myPPM.txt mySeqs.txt myOutput.txt
That’s it! You’ll end up with sequence_probabilities.txt listing each sequence and its PPM‐based probability.