import numpy as np import gzip with gzip.open('sample001coverageuniquenogenes.txt.gz',…
- User
import numpy as np import gzip
with gzip.open('sample_001_coverage_unique_no_genes.txt.gz', 'rt') as f:
data = np.loadtxt(f) print(data.size)import pandas as pd from Bio import SeqIO from Bio.Seq import Seq import numpy as np
Load the data (don't recreate, just assume it's available)
data = np.load(...) # <- Already available per your instructions
Step 1: Read the promoter CSV file
promoter_df = pd.read_csv("sigma70-promoters-filtered.csv", sep=";")
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"]
# 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.")Step 5: Write the output to CSV
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")
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. In particulat the part with the coverage. FUCKING FIX IT.
- Assistant
Absolutely, let's fix the negative strand coordinate logic and make the code robust and clear.
The main issues in your code are:- Negative strand coordinate calculation is wrong:
When you search for the promoter sequence on the reverse complement, the position you get (pos) is relative to the reverse complement, not the original genome. - Uppercase position (
upper_idx):
On the negative strand, the "uppercase" base in the original sequence corresponds to a different position in the reverse complement.
Let's fix these issues step by step.
Corrected Code
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) # Read promoter CSV promoter_df = pd.read_csv("sigma70-promoters-filtered.csv", sep=";") # Parse GenBank file to get the sequence 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 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 promoter_seq = seq.lower() promoter_len = len(promoter_seq) found = False # Search both strands for strand in ['+', '-']: if strand == '+': pos = genome_seq.find(promoter_seq) if pos != -1: start = pos end = pos + promoter_len - 1 upper_pos = start + upper_idx else: # For negative strand, search reverse complement in original genome rc_promoter_seq = str(Seq(promoter_seq).reverse_complement()) pos = genome_seq.find(rc_promoter_seq) if pos != -1: # On negative strand, the match starts at 'pos' in the original genome start = pos end = pos + promoter_len - 1 # The uppercase base in the original sequence is at (promoter_len - 1 - upper_idx) in the reverse complement upper_pos = start + (promoter_len - 1 - upper_idx) if pos != -1: 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": strand }) found = True break 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.") 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 Explained
-
Negative strand search:
- Search for the reverse complement of the promoter sequence in the original genome.
- The match position (
pos) is the start in the original genome. - The uppercase base in the original sequence is at position
(promoter_len - 1 - upper_idx)in the reverse complement, so its genomic coordinate isstart + (promoter_len - 1 - upper_idx).
-
Coverage extraction:
- For both strands,
start,end, andupper_posare always genome coordinates.
- For both strands,
-
No more weird coordinate flipping:
- All coordinates are now consistent and correct.
Summary Table
Strand Search Sequence Found at pos start end upper_pos + promoter_seq pos pos pos+len-1 pos+upper_idx - reverse_complement(seq) pos pos pos+len-1 pos+(len-1-upper_idx)
This will fix your coverage extraction and strand logic.
If you need to handle multiple matches per promoter, let me know! - Negative strand coordinate calculation is wrong:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.