Here's the modified script that converts the PPM (Position Probability Matrix) to a PWM (Position Weight Matrix) using log-odds scoring with the formula:
[
\text{PWM}(i, b) = \log_2 \left( \frac{m(b, i)}{0.25} \right)
]
where:
- ( m(b, i) ) is the probability of base ( b ) at position ( i ),
- ( 0.25 ) is the background probability (assuming uniform distribution of A, C, G, T).
Modified Code:
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'}
# Compute PWM (log-odds scores)
pwm = {}
background = 0.25 # Uniform background probability
for base in 'acgt':
pwm[base] = np.log2(ppm[base] / background)
# 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):
f.write(f'{i+1}\t{pwm["a"][i]:.6f}\t{pwm["c"][i]:.6f}\t{pwm["g"][i]:.6f}\t{pwm["t"][i]:.6f}\n')
Key Changes:
- Added
math.log2() to compute the log-odds score for each base probability.
- Background probability = 0.25 (assuming uniform distribution of A, C, G, T).
- Stored as
sigma70-PWM.txt (Position Weight Matrix).
- Used
:.6f formatting (6 decimal places) for readability (adjust if needed).
Interpretation of PWM Values:
- Positive values → The base is more frequent than expected by chance.
- Negative values → The base is less frequent than expected by chance.
- Zero → The base occurs at background frequency (0.25).
Example Output:
pos A C G T
1 -0.415037 0.321928 -1.000000 1.584963
2 0.000000 -0.415037 1.321928 -0.321928
...
This PWM can now be used for scoring new sequences to predict whether they are sigma70 promoters.
Would you like any modifications (e.g., handling zero probabilities, different background frequencies)?