Introducing interleaved products and amounts in Python with no overhead per cycle

I am trying to implement logically nested sums and partial products in python to build a function. The idea is to do this without explicit loops. The required output is a list (indexed by t for a given matrix J)

Formula:

formula

A short verbal description of the formula: for each t there are 3 indices i, j, k in the range 0- (N-1). The indices i, j build a matrix (or array 2d), each of whose elements is the product of some (J, t) -dependent function (it doesn’t matter) over the index k, excluding the specific value i, k. The function is just numpy.sum over the flattened matrix / array.

Now the code below works as expected:

import numpy as np 
t_output = np.arange(0,10,100)
jmat = np.random.random(N**2).reshape(N,N)

def corr_mat(i,j,t,params):
  return np.prod(np.cos(\
    2.0 * t * np.delete(jmat[:,i] + jmat[:,j],(i,j)))) + \
      np.prod(np.cos(\
        2.0 * t * np.delete(jmat[:,i] - jmat[:,j],(i,j))))

def corr_time(t, jmat):
   return np.array([corr_mat(i,j,t,jmat) for i in xrange(N)\
     for j in xrange(N)]).reshape(N,N)

result = np.array([np.sum(corr_time(t,jmat)) for t in t_output])

"corr_time" .

import numpy as np 
t_output = np.arange(0,10,100)
jmat = np.random.random(N**2).reshape(N,N)

def corr_mat(i,j,t,params):
  return np.prod(np.cos(\
    2.0 * t * np.delete(jmat[:,i] + jmat[:,j],(i,j)))) + \
      np.prod(np.cos(\
        2.0 * t * np.delete(jmat[:,i] - jmat[:,j],(i,j))))

i,j = np.meshgrid(range(0,N), range(0,N))

result = np.array([np.sum(corr_mat(i,j,t,params)) for t in t_output])

meshgrid . - , ? .

+4
1

/ jmat (45x) .

def precalc(jmat):
  JM1 = np.zeros((N,N,N))
  JM2 = np.zeros((N,N,N))
  for i in range(N):
    for j in range(N):
      for k in range(N):
        #JJ[i,j,k]=jmat[k,i]+jmat[k,j]
        if k!=i and k!=j:
          JM1[i,j,k]=jmat[k,i]+jmat[k,j]
          JM2[i,j,k]=jmat[k,i]-jmat[k,j]
  return JM1, JM2

def corr_time1(t, JM1, JM2):
    return np.prod(np.cos(2*JM1*t),axis=-1)+np.prod(np.cos(2*JM2*t),axis=-1)

JM1, JM2 = precalc(jmat)
result = np.array([np.sum(corr_time1(t,JM1,JM2)) for t in t_output])

. precalc, . , . , j, i, k .

, np.prod , t_output:

def corr_time2(t, JM1, JM2):
    return np.prod(np.cos(2*JM1[None,...]*t[:,None,None,None]),axis=-1) +\
       np.prod(np.cos(2*JM2[None,...]*t[:,None,None,None]),axis=-1)
result = np.sum(corr_time2(t_output, JM1, JM2),axis=(1,2))

, 20%. , t_output 10 . np.arange(0,100,10). precalc .


precalc 28x

def precalc1(jmat):
  # calc all the 'outer' sums/diffs, and zero the k=i,j terms
  ii = np.arange(jmat.shape[0])
  JM1 = jmat[:,:,None] + jmat[:,None,:]
  JM2 = jmat[:,:,None] - jmat[:,None,:]
  JM1[ii,ii,:] = 0
  JM2[ii,ii,:] = 0
  JM1[ii,:,ii] = 0
  JM2[ii,:,ii] = 0
  JM1 = JM1.transpose([1,2,0])
  JM2 = JM2.transpose([1,2,0])
  return JM1, JM2
+3

All Articles