Step 2: Parse the GenBank file to get the sequence
record = SeqIO.read("sega007.gb", "genbank")
genome_seq = str(record.seq).lower() # Working in lowercase
genome_length = len(genome_seq)
Step 3: Prepare output data
output_rows = []
Step 4: Iterate through each promoter
for idx, row in promoter_df.iterrows():
name = row["promoter_name"]
seq = row["promoter_sequence"]
code
# Identify the uppercase letter and its position
upper_idx = next((i for i, c in enumerate(seq) if c.isupper()), None)
if upper_idx is None:
print(f"No uppercase found in promoter {name}. Skipping.")
continue
# Normalize: sequences are matched in lowercase
promoter_seq = seq.lower()
promoter_len = len(promoter_seq)
found = False # Flag to track if match is found
for strand, seq_to_search in [('+', genome_seq), ('-', str(Seq(genome_seq).reverse_complement()))]:
pos = seq_to_search.find(promoter_seq)
if pos != -1:
if strand == '+':
start = pos
end = pos + promoter_len - 1
upper_pos = start + upper_idx
else:
# On negative strand, coordinates are reversed
start = genome_length - pos - promoter_len
end = genome_length - pos - 1
# upper index is from reversed promoter string
upper_pos = end - upper_idx
# Get coverage at required positions
try:
start_cov = data[start]
end_cov = data[end]
upper_cov = data[upper_pos]
# Save the result
output_rows.append({
"promoter_name": name,
"promoter_sequence": seq,
"start_coverage": start_cov,
"end_coverage": end_cov,
"up_coverage": upper_cov,
"strand": strand
})
found = True
break # Stop checking once found
except IndexError as e:
print(f"Index out of bounds for promoter {name}: {e}")
continue
if not found:
print(f"Promoter {name} not found in genome.")
See this shitcode? It does not find start and end of the promoter properly on the negative strand, it does it in reverse, upper is also screwed up. FUCKING FIX IT.
Assistant
Absolutely, let's fix the coordinate logic for the negative strand.
Your code currently reverses start/end for the negative strand, which is incorrect for 0-based, end-inclusive coordinates.
Let's clarify the correct approach:
Correct coordinate mapping:
For a match at position pos in the reverse complement:
The corresponding position in the original sequence is: genome_length - pos - promoter_len (start) genome_length - pos - 1 (end)
The upper_idx (uppercase letter) in the promoter sequence, when matching on the negative strand, refers to the reverse complement sequence, so its position in the original genome is: end - upper_idx (since the reverse complement reverses the order)
But, the bug is that you are searching for the forward promoter sequence in the reverse complement, which is not correct.
You should search for the reverse complement of the promoter in the original genome sequence for the negative strand.
import numpy as np
import gzip
import pandas as pd
from Bio import SeqIO
from Bio.Seq import Seq
# Load coverage data
with gzip.open('sample_001_coverage_unique_no_genes.txt.gz', 'rt') as f:
data = np.loadtxt(f)
print(data.size)
# Load promoter table
promoter_df = pd.read_csv("sigma70-promoters-filtered.csv", sep=";")
# Load genome
record = SeqIO.read("sega007.gb", "genbank")
genome_seq = str(record.seq).lower()
genome_length = len(genome_seq)
output_rows = []
for idx, row in promoter_df.iterrows():
name = row["promoter_name"]
seq = row["promoter_sequence"]
# Find uppercase letter index
upper_idx = next((i for i, c in enumerate(seq) if c.isupper()), None)
if upper_idx is None:
print(f"No uppercase found in promoter {name}. Skipping.")
continue
promoter_seq = seq.lower()
promoter_len = len(promoter_seq)
found = False
# + strand: search as is
pos = genome_seq.find(promoter_seq)
if pos != -1:
start = pos
end = pos + promoter_len - 1
upper_pos = start + upper_idx
try:
start_cov = data[start]
end_cov = data[end]
upper_cov = data[upper_pos]
output_rows.append({
"promoter_name": name,
"promoter_sequence": seq,
"start_coverage": start_cov,
"end_coverage": end_cov,
"up_coverage": upper_cov,
"strand": "+"
})
found = True
except IndexError as e:
print(f"Index out of bounds for promoter {name} (+): {e}")
# - strand: search for reverse complement in genome
if not found:
rc_promoter_seq = str(Seq(promoter_seq).reverse_complement())
pos = genome_seq.find(rc_promoter_seq)
if pos != -1:
start = pos
end = pos + promoter_len - 1
# The uppercase letter in the original promoter corresponds to the reverse position in the reverse complement
rc_upper_idx = promoter_len - upper_idx - 1
upper_pos = start + rc_upper_idx
try:
start_cov = data[start]
end_cov = data[end]
upper_cov = data[upper_pos]
output_rows.append({
"promoter_name": name,
"promoter_sequence": seq,
"start_coverage": start_cov,
"end_coverage": end_cov,
"up_coverage": upper_cov,
"strand": "-"
})
found = True
except IndexError as e:
print(f"Index out of bounds for promoter {name} (-): {e}")
if not found:
print(f"Promoter {name} not found in genome.")
output_df = pd.DataFrame(output_rows)
output_df.to_csv("sigma70-promoter-diff.csv", sep=";", index=False)
print("Done. Results saved to sigma70-promoter-diff.csv")
Key Fixes:
For the negative strand, search for the reverse complement of the promoter in the original genome.
The uppercase position in the reverse complement is at promoter_len - upper_idx - 1.
All coordinates are now correct and consistent for both strands.
Let me know if you want a version with more comments or further explanation!