quala main
Quasi-Newton and other accelerators
test_solve_linear_system.py
Go to the documentation of this file.
1import quala as qa
2import numpy as np
3from typing import List
4
5A = np.array([[20, -10], [-10, 30]], dtype=np.float64)
6b = np.array([10, 20], dtype=np.float64)
7n = A.shape[1]
8
9ε = 1e-15
10
11
13 x = b.copy()
14 aa = qa.AndersonAccel({'memory': n}, n)
15 res_aa: List[float] = []
16 for i in range(1 + n + 2):
17 r = A @ x - b
18 g = r + x
19 res_aa.append(np.linalg.norm(r))
20 print(f"i: {i}")
21 print(f"x: {x}")
22 print(f"g: {g}")
23 print(f"r: {r}")
24 if i == 0:
25 aa.initialize(g, r)
26 x = g
27 else:
28 x = aa.compute(g, r)
29
30 print(f"i: final")
31 print(f"x: {x}")
32 print(f"r: {r}")
33 assert np.allclose(x, [1, 1], rtol=ε, atol=ε)
34
35
37 x = b.copy()
38 r = A @ x - b
39 lbfgs = qa.LBFGS({'memory': 2 * n}, n)
40 res_lbfgs: List[float] = []
41 for i in range(1 + 2 * n + 2):
42 res_lbfgs.append(np.linalg.norm(r))
43 print(f"i: {i}")
44 print(f"x: {x}")
45 print(f"r: {r}")
46 q = r.copy()
47 lbfgs.apply(q, -1)
48 x_new = x - q
49 r_new = A @ x_new - b
50 lbfgs.update(x, x_new, r, r_new, qa.LBFGS.Sign.Positive)
51 x = x_new
52 r = r_new
53
54 print(f"i: final")
55 print(f"x: {x}")
56 print(f"r: {r}")
57 assert np.allclose(x, [1, 1], rtol=ε, atol=ε)
58
59
61 x = b.copy()
62 r = A @ x - b
63 broyden = qa.BroydenGood({'memory': 3 * n}, n)
64 res_broyden: List[float] = []
65 for i in range(1 + 2 * n + 2):
66 res_broyden.append(np.linalg.norm(r))
67 print(f"i: {i}")
68 print(f"x: {x}")
69 print(f"r: {r}")
70 q = r.copy()
71 broyden.apply(q)
72 x_new = x - q
73 r_new = A @ x_new - b
74 broyden.update(x, x_new, r, r_new)
75 x = x_new
76 r = r_new
77
78 print(f"i: final")
79 print(f"x: {x}")
80 print(f"r: {r}")
81 assert np.allclose(x, [1, 1], rtol=ε, atol=ε)