Write a python script that accepts a fasta file(default sega007.fasta) and tsv(default positions.tsv) as input. In column "Positions" are 0-indexed postitions stored. Make 101bp long PWM scoring matrix centered at those positions.
Reads a TSV of 0‐indexed positions (default positions.tsv, column named “Positions”)
Extracts a 101 bp window (±50 bp) around each position
Builds a PWM (counts → freqs → log₂‐odds vs. background)
Writes the resulting 101×4 matrix to matrix.tsv
Save this as, e.g., build_pwm.py and run with python build_pwm.py or customize names with flags.
python
#!/usr/bin/env python3
"""
build_pwm.py
Usage:
python build_pwm.py
python build_pwm.py --fasta myseqs.fasta --positions mypos.tsv --out pwm.tsv
"""
import argparse
import math
import sys
from collections import Counter, defaultdict
import pandas as pd
from Bio import SeqIO
def parse_args():
p = argparse.ArgumentParser(description="Build 101bp‐wide PWM centered on positions")
p.add_argument(
"--fasta",
"-f",
default="sega007.fasta",
help="Input FASTA (default: sega007.fasta)",
)
p.add_argument(
"--positions",
"-p",
default="positions.tsv",
help="TSV of 0‐indexed positions with a column named 'Positions'",
)
p.add_argument(
"--out",
"-o",
default="matrix.tsv",
help="Output PWM TSV (default: matrix.tsv)",
)
return p.parse_args()
def load_genome(fasta_path):
"""
Return the concatenated sequence of the *first* record in the FASTA.
"""
try:
rec = next(SeqIO.parse(fasta_path, "fasta"))
except StopIteration:
sys.exit(f"Error: no sequences found in {fasta_path}")
return str(rec.seq).upper()
def load_positions(tsv_path):
"""
Read positions.tsv into a pandas.DataFrame and verify column "Positions".
"""
df = pd.read_csv(tsv_path, sep="\t", comment="#")
if "Positions" not in df.columns:
sys.exit(f"Error: no 'Positions' column found in {tsv_path}")
return df["Positions"].astype(int).tolist()
def extract_windows(genome, positions, half=50):
"""
For each 0-based position, extract [pos-half .. pos+half] (inclusive).
Returns list of 101‐bp strings. Skips windows that fall off the ends.
"""
L = len(genome)
windows = []
for pos in positions:
start = pos - half
end = pos + half # inclusive
if start < 0 or end >= L:
# skip out‐of‐bounds
continue
win = genome[start : end + 1]
if len(win) == 2 * half + 1:
windows.append(win)
if not windows:
sys.exit("Error: no valid windows extracted (check your positions and genome length).")
return windows
def build_count_matrix(windows):
"""
Count A/C/G/T at each of the 101 columns.
Returns a dict of lists: counts['A'][i] = count of A at column i.
"""
npos = len(windows[0])
counts = {nt: [0]*npos for nt in "ACGT"}
for w in windows:
for i, ch in enumerate(w):
if ch in counts:
counts[ch][i] += 1
# else ignore Ns or other ambiguous
return counts
def counts_to_log_odds(counts, total, bgfreq):
"""
Convert counts -> frequency -> log2 odds vs. bgfreq.
bgfreq: dict of background freqs, e.g. {'A':0.246, ...}
"""
import math
pwm = {nt: [] for nt in "ACGT"}
for i in range(len(next(iter(counts.values())))):
for nt in "ACGT":
freq = counts[nt][i] / total
# to avoid log(0), we can add a small pseudocount if desired.
if freq == 0:
val = float("-inf")
else:
val = math.log2(freq / bgfreq[nt])
pwm[nt].append(val)
return pwm
def write_pwm(pwm, out_path):
"""
Write a 101×4 TSV with columns: Position A C G T
Positions are -50 .. +50
"""
n = len(next(iter(pwm.values())))
rows = []
for i in range(n):
pos = i - (n // 2)
row = {
"Position": pos,
"A": pwm["A"][i],
"C": pwm["C"][i],
"G": pwm["G"][i],
"T": pwm["T"][i],
}
rows.append(row)
df = pd.DataFrame(rows)
df.to_csv(out_path, sep="\t", index=False, float_format="%.4f")
print(f"Wrote PWM to {out_path} ({n} positions)")
def main():
args = parse_args()
# 1) load genome & positions
genome = load_genome(args.fasta)
positions = load_positions(args.positions)
# 2) extract windows
windows = extract_windows(genome, positions, half=50)
print(f"Extracted {len(windows)} windows of length {len(windows[0])}")
# 3) build counts
counts = build_count_matrix(windows)
# 4) convert to log-odds PWM
bgfreq = {"A": 0.246, "C": 0.254, "G": 0.254, "T": 0.246}
pwm = counts_to_log_odds(counts, total=len(windows), bgfreq=bgfreq)
# 5) write output
write_pwm(pwm, args.out)
if __name__ == "__main__":
main()
How it works
Argparse
You can override defaults with --fasta, --positions or --out.
FASTA parsing
We pick the first record (you can easily extend to multiple).
Position TSV
Expects a header with “Positions” holding 0‐based indices.
Window extraction
Grabs 101 bp centered (±50). Skips any that run off‐the‐end.
Counting & PWM
Builds A/C/G/T counts per column, divides by number of windows → freq
Applies log₂(freq / background) with bg freqs {A:0.246, C:0.254, G:0.254, T:0.246}
Output
A TSV with columns Position, A, C, G, T (positions −50 … +50).
You can add pseudocounts (e.g. +1) to avoid −inf if any column has zero count for a base. Let me know if you need that! 😊
User
Allow wraparound
Assistant
Below is the minimal change you need to allow circular “wrap‐around” extraction of your 101 bp windows. Instead of skipping windows that run off either end of the chromosome, we now index modulo the genome length.
diff
--- a/build_pwm.py
+++ b/build_pwm.py
@@ -42,21 +42,23 @@ def load_positions(tsv_path):
def extract_windows(genome, positions, half=50):
"""
For each 0-based position, extract [pos-half .. pos+half] (inclusive).
- Skips windows that fall off the ends.
+ Uses modulo so windows wrap around (circular genome).
Returns list of 101‐bp strings.
"""
L = len(genome)
windows = []
for pos in positions:
- start = pos - half
- end = pos + half # inclusive
- if start < 0 or end >= L:
- # skip out‐of‐bounds
- continue
- win = genome[start : end + 1]
- if len(win) == 2 * half + 1:
- windows.append(win)
+ # build window by indexing modulo L
+ # i goes from -half .. +half
+ win = ''.join(genome[(pos + i) % L] for i in range(-half, half + 1))
+ if len(win) == 2*half + 1:
+ windows.append(win)
if not windows:
sys.exit("Error: no windows extracted (check your inputs).")
return windows
Full context (with the updated function) for clarity:
#!/usr/bin/env python3
import argparse, math, sys
import pandas as pd
from collections import Counter
from Bio import SeqIO
def parse_args():
p = argparse.ArgumentParser()
p.add_argument("-f", "--fasta", default="sega007.fasta")
p.add_argument("-p", "--positions", default="positions.tsv")
p.add_argument("-o", "--out", default="matrix.tsv")
return p.parse_args()
def load_genome(fasta_path):
rec = next(SeqIO.parse(fasta_path, "fasta"), None)
if not rec: sys.exit(f"No seq in {fasta_path}")
return str(rec.seq).upper()
def load_positions(tsv_path):
df = pd.read_csv(tsv_path, sep="\t")
if "Positions" not in df:
sys.exit("Need a 'Positions' column")
return df["Positions"].astype(int).tolist()
def extract_windows(genome, positions, half=50):
"""
Circular extraction of 101bp windows around each 0-based position.
"""
L = len(genome)
windows = []
for pos in positions:
win = ''.join(genome[(pos + i) % L] for i in range(-half, half + 1))
if len(win) == 2*half + 1:
windows.append(win)
if not windows:
sys.exit("Error: no windows extracted (check your inputs).")
return windows
def build_count_matrix(windows):
npos = len(windows[0])
counts = {nt: [0]*npos for nt in "ACGT"}
for w in windows:
for i,ch in enumerate(w):
if ch in counts:
counts[ch][i] += 1
return counts
def counts_to_log_odds(counts, total, bg={'A':.246,'C':.254,'G':.254,'T':.246}):
pwm = {nt: [] for nt in "ACGT"}
for i in range(len(next(iter(counts.values())))):
for nt in "ACGT":
freq = counts[nt][i] / total
val = math.log2(freq/bg[nt]) if freq>0 else float("-inf")
pwm[nt].append(val)
return pwm
def write_pwm(pwm, out_path):
n = len(next(iter(pwm.values())))
rows = []
for i in range(n):
pos = i - (n//2)
rows.append({
"Position": pos,
"A": pwm["A"][i],
"C": pwm["C"][i],
"G": pwm["G"][i],
"T": pwm["T"][i]
})
pd.DataFrame(rows).to_csv(out_path, sep="\t", index=False, float_format="%.4f")
print(f"Wrote PWM to {out_path}")
def main():
args = parse_args()
genome = load_genome(args.fasta)
positions = load_positions(args.positions)
windows = extract_windows(genome, positions, half=50)
print(f"Extracted {len(windows)} windows")
counts = build_count_matrix(windows)
pwm = counts_to_log_odds(counts, total=len(windows))
write_pwm(pwm, args.out)
if __name__=="__main__":
main()
Now every 101 bp window is fetched in a circular fashion—no more end‐skipping! 🎉