The parse_gene_list function provided is responsible for parsing a genome file and extracting information about genes, such as their names, start and end positions, promoter positions, and gene sequences. The function has some areas where the code can be organized and improved without changing its functionality. Here is a refactored version of the parse_gene_list function:
import numpy as np # Make sure NumPy is imported at the top of the file
def parse_gene_list(reference_sequence=None, filename="additional_data/REL606.6.gbk"):
if reference_sequence is None:
reference_sequence = parse_genome()
features = {'CDS', 'gene', 'tRNA', 'rRNA', 'repeat_region'}
observed_gene_names = set()
gene_info = {
'gene_names': [],
'start_positions': [],
'end_positions': [],
'promoter_start_positions': [],
'promoter_end_positions': [],
'gene_sequences': [],
'strands': []
}
with open(filename, "r") as file:
line = file.readline()
while line != "":
items = line.split()
if not items:
line = file.readline()
continue
feature, *other_items = items
if feature not in features:
line = file.readline()
continue
feature_location = other_items[0] if other_items else ""
gene_name, locus_name, is_pseudo = "", "", False
if feature in ['CDS', 'tRNA', 'rRNA']:
while line.strip() and line.split()[0] not in features:
key, _, value = line.partition('=')
value = value.strip()[1:-1]
if key.strip().startswith('/gene'):
gene_name = value
elif key.strip().startswith('/locus_tag'):
locus_name = value
elif key.strip().startswith('/pseudo'):
is_pseudo = True
line = file.readline().strip()
gene_name = gene_name or locus_name
if is_pseudo:
gene_name = ""
if feature_location and gene_name:
update_gene_info(gene_info, feature, feature_location, gene_name, reference_sequence, observed_gene_names)
line = file.readline().strip()
# sort genes based on start position
sorted_info = sorted(zip(
gene_info['gene_names'], gene_info['start_positions'],
gene_info['end_positions'], gene_info['promoter_start_positions'],
gene_info['promoter_end_positions'], gene_info['gene_sequences'],
gene_info['strands']
), key=lambda pair: pair[1])
# unpack sorted gene information
(
gene_info['gene_names'], gene_info['start_positions'],
gene_info['end_positions'], gene_info['promoter_start_positions'],
gene_info['promoter_end_positions'], gene_info['gene_sequences'],
gene_info['strands']
) = map(list, zip(*sorted_info))
# Convert positions to NumPy arrays
gene_info['start_positions'] = np.array(gene_info['start_positions'])
gene_info['end_positions'] = np.array(gene_info['end_positions'])
gene_info['promoter_start_positions'] = np.array(gene_info['promoter_start_positions'])
gene_info['promoter_end_positions'] = np.array(gene_info['promoter_end_positions'])
return (
gene_info['gene_names'], gene_info['start_positions'],
gene_info['end_positions'], gene_info['promoter_start_positions'],
gene_info['promoter_end_positions'], gene_info['gene_sequences'],
gene_info['strands']
)
def update_gene_info(gene_info, feature, feature_location, gene_name, reference_sequence, observed_gene_names):
"""Updates the gene info dictionary with parsed feature details."""
is_reverse = feature_location.startswith('complement')
# Remove flanking symbols and split location at commas
location_str = feature_location.lstrip("complement(join(").rstrip(")")
location_strs = location_str.split(",")
for location_str in location_strs:
start, end = map(int, location_str.split(".."))
gene_sequence = reference_sequence[start - 1:end] if feature == "CDS" else ""
promoter_start, promoter_end = (start - 100, start - 1) # Forward strand by default
strand = 'forward'
if is_reverse:
strand = 'reverse'
promoter_start, promoter_end = (end + 1, end + 100)
# Ensure gene name is unique
gene_name = get_unique_gene_name(gene_name, observed_gene_names)
# Record information
gene_info['start_positions'].append(start)
gene_info['end_positions'].append(end)
gene_info['promoter_start_positions'].append(promoter_start)
gene_info['promoter_end_positions'].append(promoter_end)
gene_info['gene_names'].append(gene_name)
gene_info['gene_sequences'].append(gene_sequence)
gene_info['strands'].append(strand)
observed_gene_names.add(gene_name)
def get_unique_gene_name(gene_name, observed_gene_names):
"""Generates a unique gene name by appending a counter to duplicates."""
if gene_name not in observed_gene_names:
return gene_name
i = 1
new_gene_name = gene_name
while new_gene_name in observed_gene_names:
i += 1
new_gene_name = "{}_{}".format(gene_name, i)
return new_gene_name
# You need to have the `parse_genome` function defined somewhere in your script.
# This is the same function you would define elsewhere or import if defined in another file.
Here are the improvements made:
- Replaced the equality comparison with
None (== None) with the idiomatic is None check.
- Grouped related gene information into a
gene_info dictionary where each key correlates to a specific feature type.
- Used
with statement to automatically close the file after the end of the block.
- Added two helper functions
update_gene_info and get_unique_gene_name to break out functionality, making the code more readable, organized, and potentially reusable.
- Made use of tuple unpacking to improve readability.
- Converted gene positions lists to NumPy arrays right before returning the results.
These changes make the code cleaner, more organized, and maintainable. The functionality of the parse_gene_list function remains the same. Testing is recommended to ensure that refactoring hasn't introduced any bugs.