Here is the modified script that calculates the log2 of (probability / 0.25) for each nucleotide at every position and saves the result as a Position Weight Matrix (PWM) in a file named sigma70-PWM.txt.
✅ Key Features of This Script
Log2 Transformation: For each nucleotide at each position, compute log2(probability / 0.25).
No Rounding: The exact log2 values are written to the file without any rounding.
File Output: The output is written to sigma70-PWM.txt in a tab-separated format.
🧠 Why log2(probability / 0.25)?
This transformation is commonly used in PWMs (Position Weight Matrices) to compare the observed nucleotide frequencies with a uniform background distribution (where each nucleotide has a 25% probability). The formula:
score=log2(0.25observed probability)
gives a log-odds score, which is useful for motif discovery and sequence analysis.
🧪 Code Implementation
python
import pandas as pd
import numpy as np
import math
# Read the CSV file with semicolon delimiter
df = pd.read_csv('sigma70-promoters-filtered.csv', delimiter=';')
# Convert sequences to lowercase
df['promoter_sequence'] = df['promoter_sequence'].str.lower()
# Get the length of sequences (assuming all are same length)
seq_length = len(df['promoter_sequence'].iloc[0])
# Initialize count matrix for A, C, G, T
counts = {
'a': np.zeros(seq_length),
'c': np.zeros(seq_length),
'g': np.zeros(seq_length),
't': np.zeros(seq_length)
}
# Count nucleotides at each position
for seq in df['promoter_sequence']:
for i, nucleotide in enumerate(seq):
counts[nucleotide][i] += 1
# Convert counts to probabilities
total_sequences = len(df)
ppm = {base: counts[base] / total_sequences for base in 'acgt'}
# Save PWM to file
with open('sigma70-PWM.txt', 'w') as f:
f.write('pos\tA\tC\tG\tT\n')
for i in range(seq_length):
a_val = ppm['a'][i]
c_val = ppm['c'][i]
g_val = ppm['g'][i]
t_val = ppm['t'][i]
# Apply log2 transformation
a_log = math.log2(a_val / 0.25)
c_log = math.log2(c_val / 0.25)
g_log = math.log2(g_val / 0.25)
t_log = math.log2(t_val / 0.25)
# Write to file (no rounding, exact values)
f.write(f"{i+1}\t{a_log}\t{c_log}\t{g_log}\t{t_log}\n")
📄 Output Format Example
The sigma70-PWM.txt file will look like this:
code
pos A C G T
1 0.0 -1.0 -1.0 1.0
2 1.0 0.0 -1.0 -1.0
3 -1.0 -1.0 1.0 0.0
...
Each row corresponds to a position in the promoter sequences, and each column contains the log2 score for the respective nucleotide.
⚠️ Important Notes
If any probability is zero, log2(0 / 0.25) will produce -inf, which is valid in scientific contexts.
The script uses math.log2() for precise log calculations.
The output is not rounded and preserves the full floating-point precision of the computed values.
🧪 Testing Tips
Ensure all promoter sequences are of the same length.
If you encounter nan (Not a Number), it may indicate a zero probability. You can handle this by adding a small value like 1e-10 to avoid division by zero.
Let me know if you'd like to add error handling or format the output differently!