Back to the blog

Look at Earlier Attempts to Reach the Solution Sooner: Anderson Acceleration

In a real stirred tank, the liquid does not always mix perfectly. One way to represent this is to split the tank into two zones that exchange a lot of liquid, as if they were two connected tanks. That is exercise 4.5 in Nieves and Domínguez [1, pp. 352–353].

Finding the concentration left in each zone means solving two equations that cannot be rearranged with algebra, so you guess: you propose a value, the equations hand you back a corrected one, and you repeat. With the book's method it takes 8350 attempts. With Anderson acceleration, 8 are enough, with no derivatives: it just looks at the earlier attempts.


1. Two Tanks With Recirculation

Two reactors with recirculation: 25 L/min of feed, 125 L/min from reactor 1 to 2 and 100 L/min back to 1

A feed of 25 L/min enters with 1 mol/L of reactant A, and another 100 L/min return from tank 2 to tank 1. In each tank, A turns into B at a rate that grows with its concentration raised to the power 1.8. Once the system settles, in each tank what comes in of A equals what goes out plus what reacts. With the book's data [1, p. 353], in mol/min, tank 1 satisfies

\[\underbrace{25 + 100\,C_{A2}}_{\text{in}} = \underbrace{125\,C_{A1}}_{\text{out}} + \underbrace{16\,C_{A1}^{1.8}}_{\text{reacts}}\]

and tank 2, which receives everything that leaves tank 1,

\[\underbrace{125\,C_{A1}}_{\text{in}} = \underbrace{125\,C_{A2}}_{\text{out}} + \underbrace{4\,C_{A2}^{1.8}}_{\text{reacts}}\]

(\(C_{A1}\) and \(C_{A2}\) are the concentrations of A in each tank, in mol/L.) The exponent 1.8 does not let you solve them by rearranging. The book gives the solution: 0.6493 and 0.6352 mol/L.


2. The Book's Method: 8350 Attempts

The guessing is called the fixed-point method, and Nieves applies it to several equations by solving each one for a different unknown [1, p. 295]. Here the natural choice is to take \(C_{A1}\) from the "out" term of the first balance, and \(C_{A2}\) from the second:

\[C_{A1} \leftarrow \frac{25 + 100\,C_{A2} - 16\,C_{A1}^{1.8}}{125}, \qquad C_{A2} \leftarrow C_{A1} - \frac{4\,C_{A2}^{1.8}}{125}\]

The values of the previous attempt go on the right; the next one ends up on the left. That rule is \(g\), and the solution is the point that \(g\) leaves in place. To know when to stop, you look at the residual, \(g(x) - x\), which says how far \(g\) would move the current attempt; here the iteration stops when it drops below \(10^{-8}\).

Starting from 1 mol/L in both tanks, the attempts zigzag: \(C_{A1}\) goes down, up and down again, and \(C_{A2}\) does the same, out of step. They close in on the solution, but after 40 attempts the residual has barely halved. Reaching \(10^{-8}\) takes 8350 attempts.

Why so slow? Near the solution, each attempt multiplies what is left by a fixed number, like the amplification factor in the article on Euler. Here there are two directions, with two factors: the eigenvalues of the Jacobian of \(g\) at the solution. In one, it is 0.795, and that part of the error dies out quickly. In the other it is −0.998: the minus sign is the zigzag, and each attempt trims less than 0.2 % of that part. The book already warns that the fixed-point method may converge slowly [1, p. 298].

Nieves suggests a trick: compute \(C_{A2}\) with the \(C_{A1}\) just computed. That is successive displacements, as opposed to the simultaneous ones above, and it cuts the count to 32 attempts. But it depends on finding a good rearrangement, which the book itself admits is hard [1, p. 298]. Can you speed up the rearrangement you already have?


3. Anderson Looks at Earlier Attempts

The fixed-point method has the memory of a goldfish: it looks only at the last attempt and throws away everything it learned before. In 1965, Donald Anderson proposed not throwing it away [2]. His idea fits in one question: which mix of the latest attempts would have the smallest residual?

Each attempt \(x_i\) left two pieces of data behind: where \(g\) sent it, and its residual, \(r_i = g(x_i) - x_i\). If you mix attempts with weights that add up to 1, the residual of the mix is, to a first approximation, the same mix of their residuals (if \(g\) were linear, it would be exact). So it is enough to choose the weights that make it as small as possible and jump to the same mix of the \(g(x_i)\):

\[x_{\text{new}} = \sum_i \alpha_i\, g(x_i), \qquad \text{with the } \alpha_i \text{ that minimize } \Big\lVert \sum_i \alpha_i\, r_i \Big\rVert \text{ and add up to } 1\]

It is a tiny least-squares problem. With memory \(m\), Anderson keeps the last \(m + 1\) attempts. The code uses an equivalent form, with the changes between consecutive attempts, which leaves the least-squares problem without constraints:

import numpy as np

def anderson(g, x0, m, tol=1e-8, max_iter=20000):
    """Anderson acceleration with memory m: remembers the last m + 1 attempts."""
    x = np.asarray(x0, dtype=float)
    G, R = [], []                          # latest g(x) and residuals g(x) - x
    for attempt in range(1, max_iter + 1):
        gx = g(x)
        r = gx - x
        if np.max(np.abs(r)) < tol:
            return gx, attempt
        G, R = (G + [gx])[-(m + 1):], (R + [r])[-(m + 1):]
        if len(R) == 1:                    # no history (or m = 0): fixed-point step
            x = gx
            continue
        dG = np.diff(G, axis=0).T          # columns: changes between consecutive attempts
        dR = np.diff(R, axis=0).T
        gamma = np.linalg.lstsq(dR, r, rcond=None)[0]
        x = gx - dG @ gamma                # the combination with the smallest residual
    raise RuntimeError("did not converge in max_iter attempts")

Each attempt costs the same as a fixed-point one, a single evaluation of \(g\), plus that least-squares problem in \(m\) unknowns. These are the attempts needed to reach \(10^{-8}\):

Memory Simultaneous Successive
\(m = 0\) (fixed point) 8350 32
\(m = 1\) 30 9
\(m = 2\) 8 7
\(m = 3\) 8 7

With \(m = 2\), the book's slow rearrangement goes from 8350 attempts down to 8, almost as fast as Anderson on the good rearrangement, which needs 7: there was no need to look for another rearrangement. And \(m = 3\) no longer helps: with two unknowns, two remembered changes cover every direction.

Residual versus attempt: the fixed point barely drops and Anderson with m = 2 gets there in 8


4. Try It Yourself

How many attempts can you save while reaching the same solution? Every option starts at 1 mol/L in both tanks and reaches the same concentrations.

Start on Simultaneous with m = 0 (without Anderson), then switch to m = 2: the count drops from 8350 to 8. The tabs change how the concentrations are updated; the memory sets how many earlier attempts Anderson can use.

Path of the attempts: the fixed point zigzags and Anderson with m = 2 gets there in 8

Interactive demo (requires JavaScript). The figure shows the zigzag of the fixed point and the 8 attempts of Anderson with m = 2.


5. Wegstein Is Anderson With Memory 1

A process simulator solves a recycle loop by cutting the recirculation: it assumes its value, computes the units one after another and compares. In the two tanks that leaves a single unknown, \(C_{A2}\), and the fixed-point method takes 41 attempts. To speed up that loop, the Aspen Plus manual (version 10.1) gives Wegstein's method, from 1958, as the default [3], [4, pp. 17-5, 17-9], and it gets there in 6.

In a single variable, Anderson with \(m = 1\) is exactly Wegstein (Aspen bounds the Wegstein factor, but here it never reaches those bounds): both evaluate \(g\) at the same 6 points, because both are the secant method applied to \(g(x) - x = 0\). The difference shows up with several variables. Aspen Plus computes the Wegstein factor for each one separately, and its manual warns that this does not work well when they are strongly coupled [4, pp. 17-9, 17-10]. Anderson chooses its weights by looking at the whole vector, so the interactions come in on their own.


6. When It Helps

Anderson usually speeds up iterations that converge linearly, like the fixed-point method. When \(g\) always brings any two points closer (it is a contraction), Evans and colleagues proved that it improves the convergence rate, to first order, by a factor equal to what the least-squares problem gains at each attempt; but it does not usually speed up Newton, which already converges quadratically [5]. Here Newton-Raphson gets there in 5 iterations, but it needs the derivatives of the balances; Anderson only evaluates \(g\), and that matters when \(g\) is a black box, such as an entire flowsheet. You do not need to code it either: SciPy ships scipy.optimize.anderson [6].


7. In Short

  1. The fixed-point method crawls when one of its factors is close to 1: here, 8350 attempts.
  2. Anderson looks at the earlier attempts and jumps to the mix with the smallest residual. With no derivatives and with the same rearrangement, it gets there in 8.
  3. In one variable and with memory 1, it is the Wegstein method of process simulators; with several variables, it also takes advantage of their interactions.

Related topics: explicit and implicit Euler and Newton-Raphson with SymPy.


References

[1] A. Nieves Hurtado, F.C. Domínguez Sánchez, Métodos numéricos aplicados a la ingeniería, fourth ed., Grupo Editorial Patria, Mexico City, 2014.

[2] D.G. Anderson, Iterative procedures for nonlinear integral equations, J. ACM 12 (1965) 547–560. https://doi.org/10.1145/321296.321305.

[3] J.H. Wegstein, Accelerating convergence of iterative processes, Commun. ACM 1 (6) (1958) 9–13. https://doi.org/10.1145/368861.368871.

[4] Aspen Technology, Aspen Plus User Guide, vol. 2, version 10.1, Aspen Technology, Inc., 1999.

[5] C. Evans, S. Pollock, L.G. Rebholz, M. Xiao, A proof that Anderson acceleration improves the convergence rate in linearly converging fixed-point methods (but not in those converging quadratically), SIAM J. Numer. Anal. 58 (2020) 788–810. https://doi.org/10.1137/19M1245384.

[6] P. Virtanen, et al., SciPy 1.0: fundamental algorithms for scientific computing in Python, Nat. Methods 17 (2020) 261–272. https://doi.org/10.1038/s41592-019-0686-2.

Back to the blog