hi!
- User
hi!
- Assistant
Hello! How can I assist you today?
- User
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
hi!
Hello! How can I assist you today?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
digest this code:
def search_for_insertions( line: pd.DataFrame, chains: dict, sequences: dict, chromsizes: dict, species: list, wd: str, ): gps = defaultdict(dict) chroms = {} reachedEnd = []
# Added definitions in pisco pipe
reference = species[0]
species = species[1:]
geneName = line.loc[0, "gene"]
evidence = f"{wd}/logs/evidence/"
negatives = f"{wd}/logs/negatives/"
msa_dir = f"{wd}/logs/seqs/{geneName}"
msa_file_name = f"{msa_dir}/{geneName}.indels"
sites = [
list(line.values[0][:4])
+ list(line.values[0][range(4, len(line.values[0]), 2)])
] # this will mimic the original 'sites' ([[str]]) format just to make the code work
similarityThreshold = Const.MIN_SIMILARITY
windowSize = Const.WINDOW_SIZE
minimumSize = Const.MIN_SIZE
os.makedirs(evidence, exist_ok=True)
os.makedirs(negatives, exist_ok=True)
os.makedirs(msa_dir, exist_ok=True)
log_file = open(f"{wd}/logs/genes/{geneName}.log", "a")
sys.stdout = log_file
sys.stderr = log_file
# insertions/deletions considered/accepted
IC, IA = 0, 0
DC, DA = 0, 0
site_to_seqs = {}
with open(f"{evidence}/{geneName}.txt", "w") as ev:
with open(f"{negatives}/{geneName}.txt", "w") as negs:
inIntron = False
reachedEndOfAllChains = False
nextIntron = 0
usableInsertions, usableDeletions = [], []
# Initialize chain locations [ We already dealt with this in job.py ]
chroms[reference] = line.loc[0, "chr"]
# print(sites[0])
# sequences[reference] = load_sequence(reference, chroms[reference], treeDir, geneName)
for s in species:
if s not in chains:
print("Skipping species {} because it is not in chains".format(s))
continue
gps[s] = {
"rc": int(
chains[s][0][5]
), # start coord of alignment in reference species (update to become current coord)
"qc": int(
chains[s][0][10]
), # start coord of alignment in query species (update to become current coord)
"strand": chains[s][0][9], # query sequence strand
"lineNum": 1, # which line are we reading from in the chain file
"col": 0, # which column we are in
"bpLeft": int(
chains[s][1][0]
), # how many bp are left in this column before we have to change column
}
print(
"{}: {}".format(
s, ", ".join([k + ": " + str(gps[s][k]) for k in gps[s].keys()])
)
)
chroms[s] = chains[s][0][
7
] # totally unnecesary but since its inside the logic...
start_coords = [gps[s]["rc"] for s in species if s in chains]
if len(start_coords) == 0:
return
rcc = min(start_coords)
if s not in gps:
print("keys in chains: {}".format(" ".join(list(chains.keys()))))
print("\nProceeding with search.")
aggregate_insertions = []
# Search until we have searched all introns
while nextIntron < len(sites):
if reachedEndOfAllChains:
break
indels = []
rcc += Const.STEP_SIZE
# Check if we're in an intron
if (
int(sites[nextIntron][2]) <= rcc <= int(sites[nextIntron][3])
and inIntron is False
):
print(
"\n------- Entering range: region {} out of {}. -------".format(
nextIntron + 1, len(sites)
)
)
inIntron = True
if inIntron is True and rcc >= int(sites[nextIntron][3]):
print("------- Leaving range. --------")
inIntron = False
nextIntron += 1
while nextIntron < len(sites) and int(sites[nextIntron][3]) <= rcc:
nextIntron += 1
# Update positions in all chains
# In each species we take a step
for s in gps.keys():
if s in reachedEnd:
print("Reached end of {} chain. Skipping.".format(s))
if (
len(reachedEnd) == len(list(chains.keys()))
and len(chains[s][gps[s]["lineNum"]]) < 3
):
print("Reached end of all chains!")
reachedEndOfAllChains = True
break
continue
if len(chains[s][gps[s]["lineNum"]]) < 3:
print(f"Appending {s} to reachedEnd...", reachedEnd)
reachedEnd.append(s)
if len(reachedEnd) == len(list(chains.keys())):
print("Reached end of all chains!")
reachedEndOfAllChains = True
break
continue
prev = gps[s]["rc"]
gps[s]["rc"] = max(gps[s]["rc"], rcc)
if (
gps[s]["rc"] == rcc and prev != rcc - Const.STEP_SIZE
): # detects when we enter the chain
gps[s]["qc"] = gps[s]["qc"] + (rcc - prev)
print("We've entered the range of the {} chain.".format(s))
# If we've reached the start of this chain, update properties
# NOTE: do we need to add prev != rcc - Const.STEP_SIZE in the if statement here as well
if gps[s]["rc"] == rcc:
increment = gps[s]["bpLeft"]
gps[s]["bpLeft"] = gps[s]["bpLeft"] - Const.STEP_SIZE
changedLine = False
# If we are still in an ungapped aligment, we have taken 10 bp step in the ref coord
# we need to mirror that step in the query coord and take 10 bp
if gps[s]["col"] == 0 and gps[s]["bpLeft"] > 0:
gps[s]["qc"] += Const.STEP_SIZE
# Have to enter next col/line if we run out of ungapped alignment
while gps[s]["bpLeft"] <= 0:
if gps[s]["col"] == 0:
gps[s]["col"] = 1
gps[s]["qc"] += increment
# If we were in a query gap and there are no bp left, then we change lines and are
# back into an ungapped alignment
elif gps[s]["col"] == 1:
gps[s]["col"] = 0
gps[s]["lineNum"] += 1
changedLine = True
# This is important because we will want to check to see if those gaps were indels
# Update qc to account to rgap
gps[s]["qc"] += int(chains[s][gps[s]["lineNum"] - 1][2])
# Takes into account the fact that we stepped into the next ungapped alignment for some distance
# Note: put in print states to figure out which object is throwing the error
# len(chains[s]) <= gps[s]['lineNum']
# This checks to see if we are at the end of a chain file
if len(chains[s][gps[s]["lineNum"]]) < 3:
reachedEnd.append(s)
print(
"Reached end of {} chain!!!!!!!! Skipping.".format(
s
)
)
break
# print("Length of chains[s]: {}".format(len(chains[s])))
# print("gps[s][linenum]: {}".format(gps[s]['lineNum']))
# print("gps[s][col]: {}".format(gps[s]['col']))
# print("chains[s][gps[s]['lineNum']]: {}".format(chains[s][gps[s]['lineNum']]))
newBpLeft = (
int(chains[s][gps[s]["lineNum"]][gps[s]["col"]])
+ gps[s]["bpLeft"]
)
increment = newBpLeft - gps[s]["bpLeft"]
gps[s]["bpLeft"] = newBpLeft
if gps[s]["col"] == 0 and gps[s]["bpLeft"] > 0:
gps[s]["qc"] += (
int(chains[s][gps[s]["lineNum"]][0])
- gps[s]["bpLeft"]
)
# Check for insertion
if (
changedLine is True
and inIntron is True
and int(chains[s][gps[s]["lineNum"] - 1][1]) == 0
and int(chains[s][gps[s]["lineNum"] - 1][2]) >= minimumSize
):
insertionSize, overstep = (
int(chains[s][gps[s]["lineNum"] - 1][2]),
int(chains[s][gps[s]["lineNum"]][0]) - gps[s]["bpLeft"],
)
rip, qchrom, qis, qie, qstrand = (
rcc - overstep,
chroms[s],
gps[s]["qc"] - overstep - insertionSize,
gps[s]["qc"] - overstep,
gps[s]["strand"],
)
insertionSeq = get_seq_from_browser_coords(
qis, qie, qstrand, chromsizes[s][qchrom], sequences[s]
)
indels.append(
[
"insertion",
s,
str(insertionSize),
chroms[reference],
str(rip),
str(rip),
qchrom,
str(qis),
str(qie),
qstrand,
]
)
# aggregate_insertions.append([s, str(insertionSize), chroms[reference], str(rip), qchrom, str(qis), str(qie), qstrand])
# Check for shared deletion
if (
changedLine is True
and inIntron is True
and int(chains[s][gps[s]["lineNum"] - 1][2]) == 0
and int(chains[s][gps[s]["lineNum"] - 1][1]) >= minimumSize
):
deletionSize, overstep = (
int(chains[s][gps[s]["lineNum"] - 1][1]),
int(chains[s][gps[s]["lineNum"]][0]) - gps[s]["bpLeft"],
)
ris, rie, qchrom, qip, qstrand = (
rcc - overstep - deletionSize,
rcc - overstep,
chroms[s],
gps[s]["qc"] - overstep,
gps[s]["strand"],
)
deletionSeq = get_seq_from_browser_coords(
ris, rie, "+", -1, sequences[reference]
)
# print("Deletion seq: {}".format(deletionSeq))
indels.append(
[
"deletion",
s,
str(deletionSize),
chroms[reference],
str(ris),
str(rie),
qchrom,
str(qip),
str(qip),
qstrand,
]
)
# aggregate_insertions.append([s, str(insertionSize), chroms[reference], str(rip), qchrom, str(qis), str(qie), qstrand])
# We actually search every indel that we find: we filter them later
for indel in indels:
# If in debug mode, only search the desired site
if not DEBUG or (DEBUG and CASE in indel):
if int(indel[2]) > Const.MAX_SIZE:
print(
"----- Skipping {} of size {} at hg38 coordinates {}... -----".format(
indel[0], indel[2], " ".join(indel[3:6])
)
)
print("*--------------------------------------------*")
continue
print(
"*----- Verifying {} of size {} at hg38 coordinates {}... -----*".format(
indel[0], indel[2], " ".join(indel[3:6])
)
)
# --- Print out reference window if insertion --- #
if indel[0] == "insertion":
IC += 1
rip = int(indel[4])
if int(indel[4]) != int(indel[5]):
print("THERE's A BUG")
rprewindow = str(
sequences[reference][rip - windowSize : rip].seq
).lower()
rpostwindow = str(
sequences[reference][rip : rip + windowSize].seq
).lower()
print("OUTGROUP PREWINDOW: {}".format(rprewindow))
print("OUTGROUP POSTWINDOW: {}".format(rpostwindow))
else:
DC += 1
# # INSERTION WINDOW BOOSTING: THIS IS TRIAL, a
# if indel[0] == 'insertion':
# adjustedWindowSize = windowSize + 50
# else:
# adjustedWindowSize = windowSize
adjustedWindowSize = Const.WINDOW_SIZE
keep, status, seqs = verify_indel(
indel,
species,
chains,
sequences,
chromsizes,
similarityThreshold,
adjustedWindowSize,
reference,
)
if not keep:
continue
print("\nSTATUS: \n{}\n".format(" ".join(status)))
isValidEvidence = is_valid(status, reference)
# NOTE: We only write insertion sequences to pickled dict
print("isValidEvidence: ", isValidEvidence)
if isValidEvidence:
if indel[0] == "insertion":
# Add query1 window sequence to dictionary
q1 = indel[1]
q1chrom, q1s, q1e, q1strand = indel[6:]
q1s, q1e = int(q1s), int(q1e)
q1_prewindow = get_seq_from_browser_coords(
q1s - adjustedWindowSize,
q1s,
q1strand,
chromsizes[q1][q1chrom],
sequences[q1],
)
insertionSeq = get_seq_from_browser_coords(
q1s,
q1e,
q1strand,
chromsizes[q1][q1chrom],
sequences[q1],
)
q1_postwindow = get_seq_from_browser_coords(
q1e,
q1e + adjustedWindowSize,
q1strand,
chromsizes[q1][q1chrom],
sequences[q1],
)
seqs[q1] = q1_prewindow + insertionSeq + q1_postwindow
site_to_seqs[" ".join(status)] = seqs
usableInsertions.append(status)
IA += 1
else:
# Add query1 window sequence to dictionary
q1 = indel[1]
q1chrom, q1s, q1e, q1strand = indel[6:]
qip = int(q1s)
q1_prewindow = get_seq_from_browser_coords(
qip - adjustedWindowSize,
qip,
q1strand,
chromsizes[q1][q1chrom],
sequences[q1],
)
q1_postwindow = get_seq_from_browser_coords(
qip,
qip + adjustedWindowSize,
q1strand,
chromsizes[q1][q1chrom],
sequences[q1],
)
seqs[q1] = q1_prewindow + q1_postwindow
site_to_seqs[" ".join(status)] = seqs
usableDeletions.append(status)
DA += 1
# write status + seqs to a file and perform MSA
tmp = "tmp" + "_".join(status[:4]) + ".fa"
cmd = f"{Const.CLUSTAL} -i {msa_dir}/{tmp}"
with open(f"{msa_dir}/{tmp}", "w") as align_file:
# align_file.write("#" + " ".join(status) + "\n")
for s in seqs:
align_file.write(f">{s}\n")
align_file.write(f"{seqs[s]}\n")
process = subprocess.Popen(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.communicate()
with open(msa_file_name, "a") as msa_file:
msa_file.write("# " + " ".join(status) + "\n\n")
msa_file.write(stdout.decode("utf-8") + "\n")
os.remove(f"{msa_dir}/{tmp}")
else:
negs.write(" ".join(status) + "\n")
print("*--------------------------------------------*")
if DEBUG:
return
# Filter out duplicates
# Sort on chromosome, then start position
usableInsertions = clusterNearbyIndels(
sorted(usableInsertions, key=lambda x: (x[2][3:], int(x[3])))
)
usableDeletions = clusterNearbyIndels(
sorted(usableDeletions, key=lambda x: (x[2][3:], int(x[3])))
)
for status in usableInsertions + usableDeletions:
ev.write(" ".join(status) + "\n")
print(
"\nIC vs. IA: (insertions considered/accepted): {}/{} -> {}.".format(
IC, IA, round(IA / (IC + 1), 2)
)
)
print(
"DC vs. DA: (deletions considered/accepted): {}/{} -> {}.".format(
DC, DA, round(DA / (DC + 1), 2)
)
)
print("Search completed.")
return
I am running this with 33 species and ~100 genes are having super long times (>2 days). Seeing this code, could explain me when this scenario is possible? What would be the worst case and why?
The function search_for_insertions processes genomic data to identify and verify insertion and deletion events among different species within a specified gene. Given its complexity, several factors can contribute to significantly long runtimes, especially when dealing with 33 species and around 100 genes.
Loop Over Genes: The function is repeatedly called for each gene, and each call involves nested loops and extensive data processing.
Species Loop: The outermost loop processes each species, which means the workload scales linearly with the number of species. The more species you have, the longer it takes per gene.
Chain Processing: The inner processing involves updating chain positions and verifying insertions/deletions. If the chain data are very long, this can involve significant computation:
while nextIntron < len(sites):
...
for s in gps.keys():
...
while gps[s]["bpLeft"] <= 0:
...
Indel Verification and MSA: Each identified indel (insertion or deletion) must be verified and aligned using multiple sequence alignment (MSA). MSA is computationally intensive, especially if there are many indels to verify:
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
External Command Execution: The calls to external tools (e.g., Clustal for MSA) may introduce delays, especially if these tools are invoked many times.
I/O Operations: Writing to and reading from files, as well as making directories:
os.makedirs(evidence, exist_ok=True)
os.makedirs(negatives, exist_ok=True)
os.makedirs(msa_dir, exist_ok=True)
Frequent I/O can slow down the program significantly, especially on systems with slow disk access.
Cluster Nearby Indels: Post-processing to filter and cluster nearby indels can be expensive depending on the number of indels:
usableInsertions = clusterNearbyIndels(sorted(usableInsertions, key=lambda x: (x[2][3:], int(x[3]))))
usableDeletions = clusterNearbyIndels(sorted(usableDeletions, key=lambda x: (x[2][3:], int(x[3]))))
The worst-case scenario occurs when each gene:
By addressing these points, the runtime can be significantly reduced, especially in scenarios involving large datasets and complex genomic analyses.
Not yet included in a published release.