Учитывая набор интервалов, я хотел бы найти неперекрывающиеся отдельные интервалы из набора интервалов.
Например:
Ввод: [[1,10], [5,20], [6,21], [17,25], [22,23], [24,50] ,[30,55], [60,70]]
Вывод: [[1,5], [21,22], [23,24], [25,30], [50,55], [60,70]]
Как я могу это сделать?
То, что я пробовал сейчас:
gene_bounds_list = [[1,10],[5,20], [6,21],[17,25],[22,23], [24,50],[30,55],[60,70]]
overlap_list = []
nonoverlap_list = []
nonoverlap_list.append(gene_bounds_list[0])
for i in range(1, len(gene_bounds_list)):
curr_gene_bounds = gene_bounds_list[i]
prev_gene_bounds = nonoverlap_list[-1]
if curr_gene_bounds[0]<prev_gene_bounds[0]:
if curr_gene_bounds[1]<prev_gene_bounds[0]: #case1
continue
if curr_gene_bounds[1] < prev_gene_bounds[1]: #case2
nonoverlap_list[-1][0] = curr_gene_bounds[1]
if curr_gene_bounds[1]>prev_gene_bounds[1]:
# previous gene was completely overlapping within current gene,
# so replace previous gene by current (bigger) gene and put previous gene into overlap list
overlap_list.append(nonoverlap_list[-1])
new_bound = [gene_bounds_list[i][0], gene_bounds_list[i][1]]
nonoverlap_list.pop()
nonoverlap_list.append([new_bound[0], new_bound[1]])
elif curr_gene_bounds[0] > prev_gene_bounds[0] and curr_gene_bounds[1] < prev_gene_bounds[1]:
# completely within another gene
overlap_list.append([curr_gene_bounds[0], curr_gene_bounds[1]])
elif curr_gene_bounds[0] < prev_gene_bounds[1]:
# partially overlapping with another gene
new_bound = [nonoverlap_list[-1][1], curr_gene_bounds[1]]
nonoverlap_list[-1][1] = curr_gene_bounds[0]
nonoverlap_list.append([new_bound[0], new_bound[1]])
else:
# not overlapping with another gene
nonoverlap_list.append([gene_bounds_list[i][0], gene_bounds_list[i][1]])
unique_data = [list(x) for x in set(tuple(x) for x in gene_bounds_list)]
within_overlapping_intervals = []
for small in overlap_list:
for master in unique_data:
if (small[0]==master[0] and small[1]==master[1]):
continue
if (small[0]>master[0] and small[1]<master[1]):
if(small not in within_overlapping_intervals):
within_overlapping_intervals.append([small[0], small[1]])
for o in within_overlapping_intervals:
nonoverlap_list.append(o) # append the overlapping intervals
nonoverlap_list.sort(key=lambda tup: tup[0])
flat_data = sorted([x for sublist in nonoverlap_list for x in sublist])
new_gene_intervals = [flat_data[i:i + 2] for i in range(0, len(flat_data), 2)]
print(new_gene_intervals)
Однако это дает мне результат: [[1, 5], [6, 10], [17, 20], [21, 22], [23, 24], [25, 30], [50, 55], [60, 70]]
Есть идеи, как убрать нежелательные интервалы?