pythonlistnumpystructgenetic-algorithm

Error invalid index to scalar variable how to solve when using shape function


I am trying to use the following function to make mutation step in agametic algorithm. Unfortunately, I have got an error as follows:

IndexError                                Traceback (most recent call last)
<ipython-input-20-35511e994420> in <cell line: 2>()
      1 #Run the GA algorithm.
----> 2 out_1 = myGA_pv.run_ga_pv_simulation(problem, params)
      3 #out_2 = myGA_wind.run_ga_simulation(problem, params)
      4 

1 frames
/content/myGA_pv.py in mutate(x, mu, sigma)
    151     flag = np.random.rand(np.int(np.nan_to_num(x.position))) <= mu
    152     ind = np.argwhere(flag)
--> 153     y.position[ind] += sigma*(np.random.rand(ind.any().shape))
    154     return y
    155 

IndexError: invalid index to scalar variable.

The code of this function is like follows:

def mutate(x, mu, sigma):
    y = x.deepcopy() 
    flag = np.random.rand(np.int(np.nan_to_num(x.position))) <= mu
    ind = np.argwhere(flag)
    y.position[ind] += sigma*(np.random.rand(ind.shape))
    return y

How to overcome such error ?


Solution

  • If your x.position was a scalar variables, i.e. a np.float64 constructed like:

    In [101]: y=np.array([15.,20.])[0]; y
    Out[101]: 15.0
    

    argwhere works with an int of that, and produces a (n,1) array:

    In [102]: ind=np.argwhere(np.random.rand(int(y))<.15)
    
    In [103]: ind
    Out[103]: 
    array([[ 0],
           [11]], dtype=int64)
    

    Using that as index to y produces your error:

    In [104]: y[ind]
    ---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    Cell In[104], line 1
    ----> 1 y[ind]
    
    IndexError: invalid index to scalar variable.
    

    Any attempt to index that scalar variable produces this error.

    I don't know what of this is your code, and what's copied from somewhere elese (without much understanding?), but the key thing is look at the indexing operation in the problem line. What are the variables, the position and the ind.

    y.position[ind]
    

    I can't propose any fix because I don't have the big picture or any of your data. But the first step of any fix is to understand the error