Allow specifying window size
- User
Allow specifying window size
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Allow specifying window size
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's modify the script to allow you to specify the window size.
We'll add a new command-line argument --window-size (or -w) which will default to 101. The script will also enforce that the window size is an odd number, as this simplifies centering (e.g., 101bp has 50bp on each side of the center).
Here's the updated script:
#!/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 --window-size 21
"""
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 a PWM centered on positions with customizable window size."
)
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)",
)
p.add_argument(
"--window-size",
"-w",
type=int,
default=101,
help="Length of the PWM window in base pairs (must be a positive odd integer, default: 101)",
)
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, window_size):
"""
For each 0-based position, extract a window of specified size.
Uses modulo so windows wrap around (circular genome).
Returns list of strings of the specified window_size.
"""
L = len(genome)
half_window = (window_size - 1) // 2 # e.g., for 101bp, half_window is 50
windows = []
if L == 0:
sys.exit("Error: Genome sequence is empty.")
if window_size > L:
sys.exit(f"Error: Window size ({window_size}) cannot be larger than genome length ({L}).")
for pos in positions:
# Build window by indexing modulo L
# i goes from -half_window to +half_window (inclusive)
win_chars = []
for i in range(-half_window, half_window + 1):
# Calculate the circular index
circular_idx = (pos + i) % L
win_chars.append(genome[circular_idx])
win = ''.join(win_chars)
if len(win) != window_size:
# This should ideally not happen if logic is correct, but as a safeguard
sys.exit(f"Internal error: Extracted window length {len(win)} does not match requested window size {window_size} for position {pos}.")
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 position within the window.
Returns a dict of lists: counts['A'][i] = count of A at column i.
"""
if not windows:
return {"A": [], "C": [], "G": [], "T": []}
npos = len(windows[0]) # This will be our window_size
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 characters
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, ...}
"""
pwm = {nt: [] for nt in "ACGT"}
if total == 0:
# If no windows were processed, return empty PWM
return pwm
# Determine the length of the PWM (which is the window_size)
if not counts or not next(iter(counts.values()), None):
return pwm # No counts, return empty
pwm_length = len(next(iter(counts.values())))
for i in range(pwm_length):
for nt in "ACGT":
freq = counts[nt][i] / total
# To avoid log(0), we use float("-inf") for zero frequencies.
val = math.log2(freq / bgfreq[nt]) if freq > 0 else float("-inf")
pwm[nt].append(val)
return pwm
def write_pwm(pwm, out_path, window_size):
"""
Write the PWM to a TSV with columns: Position, A, C, G, T.
Positions are relative to the center (e.g., -50 .. +50 for 101bp).
"""
if not pwm or not next(iter(pwm.values()), None):
print("Warning: No PWM data to write. Output file might be empty.", file=sys.stderr)
# Create an empty DataFrame with headers if no data
df = pd.DataFrame(columns=["Position", "A", "C", "G", "T"])
else:
n = len(next(iter(pwm.values()))) # This is our window_size
rows = []
half_window = (window_size - 1) // 2
for i in range(n):
pos = i - half_window # Calculate relative position
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 of size {window_size} to {out_path}")
def main():
args = parse_args()
# 1) Validate window size
if args.window_size % 2 == 0 or args.window_size <= 0:
sys.exit(f"Error: --window-size must be a positive odd integer (received: {args.window_size}).")
# 2) Load genome & positions
genome = load_genome(args.fasta)
positions = load_positions(args.positions)
# 3) Extract windows
windows = extract_windows(genome, positions, args.window_size)
print(f"Extracted {len(windows)} windows, each {args.window_size} bp long.")
# 4) Build counts
counts = build_count_matrix(windows)
# 5) 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)
# 6) Write output
write_pwm(pwm, args.out, args.window_size)
if __name__ == "__main__":
main()
Key Changes:
argparse for window_size:
--window-size (-w) argument with type=int and default=101.help string explaining the requirement for an odd integer.Window Size Validation in main:
main checks args.window_size. If it's even or non-positive, the script exits with an error.extract_windows Function Update:
window_size as an argument.half_window = (window_size - 1) // 2 internally.range(-half_window, half_window + 1) correctly generates the indices for the specified window size.if window_size > L: to prevent absurd window sizes compared to the genome.write_pwm Function Update:
window_size as an argument to correctly calculate relative positions (pos = i - half_window).Now you can run the script like this:
python build_pwm.pypython build_pwm.py --window-size 21python build_pwm.py -w 51