Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. A = np.array([[2,-1,0,0,0,0,0,0,0,0],
  2.               [-1,2,-1,0,0,0,0,0,0,0],
  3.               [0,-1,2,-1,0,0,0,0,0,0],
  4.               [0,0,-1,2,-1,0,0,0,0,0],
  5.               [0,0,0,-1,2,-1,0,0,0,0],
  6.               [0,0,0,0,-1,2,-1,0,0,0],
  7.               [0,0,0,0,0,-1,2,-1,0,0],
  8.               [0,0,0,0,0,0,-1,2,-1,0],
  9.               [0,0,0,0,0,0,0,-1,2,-1],
  10.               [0,0,0,0,0,0,0,0,-1,2]])
  11.  
  12.  
  13. B = np.array([[1 if j <= i else 0 for j in range(10)] for i in range(10)])
  14. q = np.array([1 for i in range(10)]).reshape((10,1))
  15. d = np.array([i + 1 for i in range(10)]).reshape((10,1))
  16.  
  17.  
  18.  
  19. def get_x(l):
  20.     return np.linalg.inv(A) @ (q - B @ l) / 2
  21.  
  22.  
  23. def get_l(x, l, r):
  24.     l = l + r * (B @ x - d)
  25. #     print(np.maximum(np.zeros((10, 1)), l).shape)
  26. #     print(l.shape)
  27.     return np.maximum(np.zeros((10, 1)), l)
  28.  
  29.  
  30. def f(x):
  31.     print(B @ x - d)
  32.     return (x.T @ A) @ x - q.T @ x
  33.    
  34.  
  35. def ADMM(r=1, eps=0.01):
  36.     x = np.random.random(size=(10,1))
  37.     l = np.random.random(size=(10,1))
  38.     stopper = 0
  39.     while True:
  40.         if stopper > 10:
  41.             print('Stopped in %d iteration' % stopper)
  42.             break
  43.         l = get_l(x, l, r)
  44.         x_next = get_x(x)
  45.         if np.linalg.norm(x - x_next) < eps:
  46.             print('Stopped in %d iteration' % stopper)
  47.             break
  48.         x = x_next
  49.         stopper += 1
  50.         if stopper % 5 == 0:
  51.             print('%d iter f(x) = %f' % (stopper, f(x)))
  52.            
  53.     return x
  54.  
  55. ADMM(r=1, eps=0.1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement