Below is a Python script that accomplishes what you described. I'll first explain the key points of the script and then provide the full code.
Key Explanation:
-
Reading the Input File:
- The script reads the "sega007.fasta" file, assuming it contains a single DNA sequence in FASTA format. It extracts the sequence and converts it to uppercase for consistency.
-
Processing the Forward Strand:
- Large Windows: The script divides the sequence into large chunks (windows) of 500100 bp each, with a 100 bp overhang. Specifically:
- The first window starts at position 1 and ends at 500100 (or the end of the sequence if it's shorter).
- Each subsequent window starts at (end of previous window - 100) and extends for 500100 bp (or to the end of the sequence).
- For the last window, it will simply go to the end of the sequence without worrying about overhang.
- Small Sliding Windows Inside Each Large Window:
- For each large window (e.g., from position A to B), the script outputs smaller sliding windows of 81 bp (based on your example) with a slide of 1 bp.
- For each small window (e.g., from i to i+80), it outputs a line in the format:
>i-(i+80) followed by the subsequence.
- Files are named as
sega007-XX.fasta, where XX is a zero-padded number (e.g., 01, 02, etc.).
-
Processing the Reverse Strand:
- First, the script computes the reverse complement of the entire sequence.
- It then applies the same logic as the forward strand to the reverse complement sequence.
- To "start from the other end" as you mentioned, we process the reverse complement as a new sequence and generate large windows starting from its beginning (which corresponds to the end of the original sequence).
- File numbering continues from where the forward strand left off (e.g., if forward uses 01 to 05, reverse starts at 06).
-
Output Files:
- Each file corresponds to one large window and contains the small sliding windows within that large window.
- For the last large window in both forward and reverse, it will include as much as possible without forcing an overhang.
- Files are saved in the same directory as the script.
-
Assumptions:
- Small window size is 81 bp, as per your example. If you want a different size, you can modify the
small_window_size variable in the code.
- The sequence is 1-based in the output (as in your example).
- If the sequence is shorter than 500100 bp, it will still process what it can.
- Error handling: The script checks if the input file exists and handles basic errors.
Full Python Script:
import os
import sys
def read_fasta(file_path):
"""Read a FASTA file and return the sequence as a string."""
if not os.path.exists(file_path):
raise FileNotFoundError(f"The file {file_path} does not exist.")
with open(file_path, 'r') as f:
lines = f.readlines()
sequence = ''.join(line.strip() for line in lines if not line.startswith('>'))
return sequence.upper() # Convert to uppercase for consistency
def reverse_complement(sequence):
"""Compute the reverse complement of a DNA sequence."""
complement = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C', 'N': 'N'} # Handle 'N' as is
return ''.join(complement.get(base, base) for base in reversed(sequence))
def generate_large_windows(sequence, window_size=500100, overhang=100):
"""Generate large windows with the specified overhang."""
L = len(sequence)
windows = []
current_start = 1 # 1-based
while current_start <= L:
end = min(current_start + window_size - 1, L)
windows.append((current_start, end))
if end < L:
next_start = end - overhang # Calculate next start with overhang
if next_start >= 1:
current_start = next_start
else:
break # Can't go further
else:
break # Reached the end
return windows
def output_small_windows(sequence, start, end, small_window_size=81, slide=1, file_index):
"""Output small sliding windows for a given large window to a file."""
file_name = f"sega007-{file_index:02d}.fasta" # e.g., sega007-01.fasta
with open(file_name, 'w') as f:
for i in range(start, end - small_window_size + 2): # 1-based, up to end - small_size + 1
if i + small_window_size - 1 <= end: # Ensure it doesn't go beyond the large window
subseq = sequence[i-1:i-1 + small_window_size] # 0-based slicing
f.write(f">{i}-{(i + small_window_size - 1)}\n")
f.write(subseq + '\n') # Write the subsequence
print(f"Written to {file_name} for large window {start}-{end}")
def main():
input_file = "sega007.fasta"
try:
sequence = read_fasta(input_file)
L = len(sequence)
# Process forward strand
forward_windows = generate_large_windows(sequence)
for idx, (start, end) in enumerate(forward_windows, start=1): # Start indexing from 1
output_small_windows(sequence, start, end, file_index=idx)
num_forward_files = len(forward_windows)
# Process reverse strand
rev_sequence = reverse_complement(sequence)
reverse_windows = generate_large_windows(rev_sequence) # Generate for reverse sequence
for idx, (start_rev, end_rev) in enumerate(reverse_windows, start=num_forward_files + 1): # Continue numbering
output_small_windows(rev_sequence, start_rev, end_rev, file_index=idx)
print(f"Processing complete. Total files created: {len(forward_windows) + len(reverse_windows)}")
except Exception as e:
print(f"An error occurred: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
How to Run the Script:
- Save the script to a file, e.g.,
process_fasta.py.
- Make sure you have Python installed (Python 3.x recommended).
- Place the script in the same directory as your "sega007.fasta" file.
- Run the script from the command line:
python process_fasta.py
- Output files will be generated in the same directory, e.g.,
sega007-01.fasta, sega007-02.fasta, etc.
Example Output in a File:
For a large window from 1 to 500100 in the forward strand, the file sega007-01.fasta might look like:
>1-81
AAA...CCC # First 81 bp
>2-82
AAT...CCG # Next 81 bp, starting at position 2
>3-83
ATT...CGG # And so on...
...
>500021-500101 # Up to the end of the large window
XXX...YYY
This script should handle your requirements accurately. If you need to adjust parameters like the small window size (e.g., change small_window_size=81), just modify the code accordingly. Let me know if you have any questions!