I'm working on an implementation of an Evolutionary Algorithm in Pandas using Numpy. The code is based around an implementation found on MathWorks. It works and produces logical results, however it is incredibely slow.
The 'Pythonized' version of this code looks something like this:
# Initialize
xm = np.zeros((n, nlambda))
sigmam, alpham = list(np.ones(nlambda) * np.nan), list(np.ones(nlambda) * np.nan)
sigmam: List[np.ndarray] # list of NUMBER OF OFFSPRINGS np arrays 264x264
alpham: List[np.ndarray] # list of NUMBER OF OFFSPRINGS np arrays 264x264
for i in population_size:
### Some code ###
alpham[i] = np.where(alpham[i] > math.pi, alpham[i] - 2 * math.pi, alpham[i])
alpham[i] = np.where(alpham[i] < -math.pi, alpham[i] + 2 * math.pi, alpham[i])
R = np.eye(n)
for m in range(n - 1):
for q in range(m + 1, n):
T = np.eye(n)
T[np.ix_([m, q], [m, q])] = [[np.cos(alpham[i][m,m]), -np.sin(alpham[i][m,q])], [np.sin(alpham[i][q,m]), np.cos(alpham[i][q,q])]]
R[:, [m, q]] = np.dot(R, T[:, [m,q]])
### Some code ###
We are looking for methods to optimize this code, by making more clever use of numpy arrays/vectorization. What would be ways to optimize this?