Guest User

Untitled

a guest
Nov 8th, 2019
64
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import numpy
  2. import math
  3. from pylab import *
  4. from sympy import *
  5. from scipy.optimize import minimize_scalar
  6. import matplotlib.pyplot as plt
  7. from matplotlib import cm
  8. from mpl_toolkits.mplot3d import axes3d, Axes3D
  9.  
  10. z_str = '(a[1] - a[0]) ** 2 + 100 * (1 - a[0]) ** 2'
  11.  
  12. exec 'z = lambda a: ' + z_str
  13.  
  14. z_str = z_str.replace('a[0]', 'x')
  15. z_str = z_str.replace('a[1]', 'y')
  16.  
  17. def z_grad(a):
  18. x = Symbol('x')
  19. y = Symbol('y')
  20.  
  21. exec 'z_d = ' + z_str
  22.  
  23. yprime = z_d.diff(y)
  24. dif_y=str(yprime).replace('y', str(a[1]))
  25. dif_y=dif_y.replace('x', str(a[0]))
  26.  
  27. yprime = z_d.diff(x)
  28. dif_x=str(yprime).replace('y', str(a[1]))
  29. dif_x=dif_x.replace('x', str(a[0]))
  30.  
  31. return numpy.array([eval(dif_y), eval(dif_x)])
  32.  
  33. def mininize(a):
  34. l_min = minimize_scalar(lambda l: z(a - l * z_grad(a))).x
  35. return a - l_min * z_grad(a)
  36.  
  37. def norm(a):
  38. return math.sqrt(a[0] ** 2 + a[1] ** 2)
  39.  
  40. def grad_step(dot):
  41. return mininize(dot)
  42.  
  43. dot = [numpy.array([-150.0, 150.0])]
  44. dot.append(grad_step(dot[0]))
  45.  
  46. eps = 0.0001
  47.  
  48. while norm(dot[-2] - dot[-1]) > eps: dot.append(grad_step(dot[-1]))
  49. def makeData ():
  50. x = numpy.arange (-200, 200, 1.0)
  51. y = numpy.arange (-200, 200, 1.0)
  52. xgrid, ygrid = numpy.meshgrid(x, y)
  53. zgrid = z([xgrid, ygrid])
  54. return xgrid, ygrid, zgrid
  55.  
  56. xt, yt, zt = makeData()
  57.  
  58. fig = plt.figure()
  59. ax = plt.axes(projection='3d')
  60.  
  61. ax.plot_surface(xt, yt, zt, cmap=cm.hot)
  62. ax.plot([x[0] for x in dot], [x[1] for x in dot], [z(x) for x in dot], color='b')
  63.  
  64. plt.show()
RAW Paste Data