IndexError when Computing Maximum Distances in Brain-Strand Segmentation

30 Views Asked by At

I need help with this project related to brain-strand segmentation. Im using the function bellow and console keeps sending: dist1[cont] = math.dist(p1, p2))

IndexError: list index out of range.

Please help. Here's my code

strands_selected = []
    dist1 = []
    dist2 =[]
    dist_max_d = []
    dist_max_i = []
    cont= 0
for i in strand_per_tractography:  # 100 000
        for k in strand_per_fascicle:  # 734 para el peor caso
            for p in points_of_interest:  # 3
                    p1 = tractography[i][p]
                    p2 = strand_per_fascicle[k][p]
                    p3 = strand_per_fascicle[k][p][::-1]
                    dist1[cont] = math.dist(p1, p2)
                    dist2[cont] = math.dist(p1, p3)
                    dist_max_d[cont] = max(dist1[cont], dist_max_d[cont])
                    dist_max_i[cont] = max(dist2[cont], dist_max_i[cont])
                    cont+=1
                    if cont == 2:
                     min_value = min( dist_max_d[p], dist_max_i[p])
                     if min_value < thresh:  # Verifica si la distancia es menor al umbral
                       strands_selected.append(tractography[i])
                       print (dist_max_d[cont])
                       cont = 0

I've tried changing dist_max_d and dist_max_i to this:

dist_max_d = [0] * len(points_of_interest)
dist_max_i = [0] * len(points_of_interest)

but then

dist1[cont] = math.dist(p1, p2)

IndexError: list assignment index out of range
1

There are 1 best solutions below

0
nigh_anxiety On

dist1, dist2, dist_max_d and dist_max_i are all empty lists of length 0.

When you try to assign a value to dist1[cont], that index does not exist, resulting in the IndexError.

You have two options:

  1. Preallocate your lists to the required size. I actually couldn't determine this on examining the provided code, as my first assumption was on your for loop comments, giving a size of 100000 * 734 * 3 = 220_200_000, but then I noticed you are resetting the cont variable to 0 under some conditions, and it wasn't clear if your indentation in the provided code is correct or not. As currently cont is only reset when cont == 2 and min_value < thresh
N = max_size_of_lists
dist1 = [None] * N
dist2 = [None] * N
dist_max_d = [0] * N # Use 0 due to the usage of max() when assigning values later
dist_max_i = [0] * N
  1. Alternatively, instead assigning directly to a specific index, keep the lists empty to start, and use the .append(value) method.
    dist1.append(math.dist(p1, p2))
    dist2.append(math.dist(p1, p3))

Then instead of using cont, you just need to call the .clear() method on each list. However, there seem to be several possible issues with the if blocks at the end of the loop and I couldn't quite figure out what the intentions were, especially when you use p instead of cont to access dist_max_d[p], dist_max_i[p]