]> git.rustad.me Git - nummat1/commitdiff
Refactor newton.py
authorBjørn Rustad <rustadbjornen@gmail.com>
Thu, 29 Sep 2011 08:58:05 +0000 (10:58 +0200)
committerBjørn Rustad <rustadbjornen@gmail.com>
Thu, 29 Sep 2011 08:58:05 +0000 (10:58 +0200)
newton.py

index 8ea7538d92b54eefffe609129c45a4b43db2b540..d626dbbc6dd4ccca6e51c6b7431d01f0a3d81010 100644 (file)
--- a/newton.py
+++ b/newton.py
@@ -1,3 +1,4 @@
+from enthought.mayavi import mlab
 from function import function_g, gradient_g, hessian_g
 import generate
 import surf
@@ -6,27 +7,62 @@ import matplotlib.pyplot as plt
 from numpy.linalg import norm, inv
 
 def newton_iter(x, grad_g, hess_g):
-    return x - inv(hess_g(x)).dot(grad_g(x))
+    return x - inv(hess_g).dot(grad_g)
 
-H = generate.spdmatrix(2, 3)
-b = generate.vector(2, -1, 1)
-c = generate.vector(2, -3, 3)
+def newton(xk, H, b, c, tolerance, maxiter):
+    x0_norm = norm(gradient_g(xk, H, b, c))
+    
+    relative_residual = norm(gradient_g(xk, H, b, c)) / x0_norm
+    relative_residuals = []
+    points = []
+    
+    while relative_residual > tolerance and maxiter > 0:
+        maxiter -= 1
+        xk = newton_iter(xk, gradient_g(xk, H, b, c), hessian_g(xk, H, b, c))
+        relative_residuals.append(relative_residual)
+        points.append(xk)
+        relative_residual = norm(gradient_g(xk, H, b, c)) / x0_norm
 
-alpha = 0.1
-xiter = np.array([1, 1])
-x0_norm = norm(gradient_g(xiter, H, b, c))
+    return (points, relative_residuals)
 
-tolerance = 0.0001
+def main():
+    H = generate.spdmatrix(2, 3)
+    b = generate.vector(2, -1, 1)
+    c = generate.vector(2, -3, 3)
+    
+    print H
+    print b
+    print c
 
-relative_residual = norm(gradient_g(xiter, H, b, c)) / x0_norm
-relative_residuals = [relative_residual]
+    x0 = np.array([0, 0])
+    x0_norm = norm(gradient_g(x0, H, b, c))
 
-while relative_residual > tolerance:
-    xiter = newton_iter(xiter, lambda x: gradient_g(x, H, b, c), lambda x:
-            hessian_g(x, H, b, c))
-    relative_residual = norm(gradient_g(xiter, H, b, c)) / x0_norm
-    relative_residuals.append(relative_residual)
+    points, residuals = newton(x0, H, b, c, 0.01, 100)
+    function_values = []
 
-    print xiter
+    last = points[len(points)-1]
+    for point in points:
+        print point
+        z = function_g(point, H, b, c)
+        function_values.append(z)
+        if abs(point[0]) < 3 and abs(point[1]) < 3:
+            p = mlab.points3d([point[0]], [point[1]], [z], scale_factor=0.05)
+    
+    X, Y, Z = surf.surf(H, b, c, last[0]-1, last[0]+1, last[1]-1, last[1]+1, -10, 3)
+    
+    plt.figure(1)
+    ax = plt.subplot(211)
+    plt.plot(residuals)
+    ax.set_yscale('log')
+    
+    ax = plt.subplot(212)
+    plt.plot(function_values)
+    
+    plt.show()
+    
+    surface = mlab.mesh(X, Y, Z)
+    axes = mlab.axes()
+    mlab.show()
 
-print "Cirka null: ", gradient_g(xiter, H, b, c)
+if __name__ == "__main__":
+    main()