Advertisement
Guest User

einsum example

a guest
Dec 11th, 2014
309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. import numpy as np
  2. import time
  3.  
  4. Nx = 3
  5. Ny = 4
  6. Nk = 5
  7. Nl = 6
  8. Nu = 7
  9. Nv = 8
  10. Fx = np.random.rand(Nx, Nk)
  11. Fy = np.random.rand(Ny, Nl)
  12. Fu = np.random.rand(Nu, Nk)
  13. Fv = np.random.rand(Nv, Nl)
  14. P = np.random.rand(Nx, Ny)
  15. B = np.random.rand(Nk, Nl)
  16. I1 = np.zeros([Nu, Nv])
  17. I2 = np.zeros([Nu, Nv])
  18. t = time.time()
  19. for iu in range(Nu):
  20.     for iv in range(Nv):
  21.         for ix in range(Nx):
  22.             for iy in range(Ny):
  23.                 S = 0.
  24.                 for ik in range(Nk):
  25.                     for il in range(Nl):
  26.                         S += Fu[iu,ik]*Fv[iv,il]*Fx[ix,ik]*Fy[iy,il]*P[ix,iy]*B[ik,il]
  27.                 I1[iu, iv] += S
  28.                 I2[iu, iv] += S**2.
  29. print "time for loop:", time.time() - t;
  30. t = time.time()
  31. # 0.0787379741669
  32. I1_ = np.einsum('uk, vl, xk, yl, xy, kl->uv', Fu, Fv, Fx, Fy, P, B)
  33. print "time for I1_: ", time.time() - t
  34. # 0.00049090385437
  35. print np.allclose(I1_, I1)
  36. # True
  37. # Solution by expanding the square (not ideal)
  38. t = time.time()
  39. I2_ = np.einsum('uk,vl,xk,yl,um,vn,xm,yn,kl,mn,xy->uv', Fu,Fv,Fx,Fy,Fu,Fv,Fx,Fy,B,B,P**2)
  40. print "time for I2_: ", time.time() - t
  41. # 0.0226809978485 <- faster than for loop but still much slower than I1_ einsum
  42. print np.allclose(I2_, I2)
  43. t0 = time.time()
  44. E = np.einsum('uk, vl, xk, yl, xy, kl->uvxy', Fu, Fv, Fx, Fy, P, B)
  45. E1 = np.einsum('uvxy->uv', E)
  46. E2 = np.einsum('uvxy->uv', np.square(E))
  47. t1 = time.time() - t0
  48. print "time for E1,E2:", t1
  49. print "E1 ~ I1_:", np.allclose(E1, I1_)
  50. print "E2 ~ I2_:", np.allclose(E2, I2_)
  51. # True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement