"""Kaczmarz's algorithm for the solution of a system of linear equations,
Ax = b, with plots of the paths of its approximate solutions for systems of two
unknowns: a consistent system in cyclic and random order, a fan of lines
through one point, and the first system with errors in b."""

import matplotlib.pyplot as plt
import numpy as np

# Four equations in two unknowns, whose lines meet at (x, y) = (1, 2).
A = np.array([[-4, 1], [2, 0.5], [3, 1.5], [0, 1]])
b = np.array([-2, 3, 6, 2])
SOLUTION = np.array([1, 2])
# Errors in b that make the system inconsistent.
ERRORS = np.array([0.3, -0.2, 0.25, -0.15])
SEED = 1907  # for the random orders, so that every run gives the same results


def kaczmarz(A, b, order="cyclic", tol=1e-6, max_steps=10000, rng=None):
    """Solve Ax = b by Kaczmarz's algorithm, starting from x = 0.

    The rows of A are taken in turn (order="cyclic"), at random with
    probabilities proportional to their squared norms (order="random"), or in
    a new random order in each pass through them (order="shuffled"); rng is a
    NumPy random Generator, or a seed for one. The iteration stops when x is
    closer than tol to the hyperplane of every equation, a_i . x = b_i, or
    after max_steps steps. Returns the array of approximate solutions x_0,
    x_1, ..., of which the last is the solution.
    """
    m, n = A.shape
    rng = np.random.default_rng(rng)
    norms2 = np.sum(A**2, axis=1)  # the squared norm of each row
    norms = np.sqrt(norms2)
    x = np.zeros(n)
    xs = [x]
    for k in range(max_steps):
        if order == "cyclic":
            i = k % m
        elif order == "random":
            i = rng.choice(m, p=norms2 / norms2.sum())
        elif order == "shuffled":
            if k % m == 0:
                rows = rng.permutation(m)
            i = rows[k % m]
        else:
            raise ValueError(f"Unknown order: {order}")
        x = x + (b[i] - A[i] @ x) / norms2[i] * A[i]
        xs.append(x)
        # The distances from the hyperplanes. Checking them costs as much as
        # m steps: a program for large systems would check once in each pass.
        if np.max(np.abs(A @ x - b) / norms) < tol:
            break
    return np.array(xs)


def fan(m, point):
    """Return A and b for a system of m equations whose lines pass through
    point, at angles that increase by pi/m from one equation to the next."""
    theta = np.pi * np.arange(m) / m
    A = np.column_stack((np.cos(theta), np.sin(theta)))
    return A, A @ point


def errors(A, b, solution, order, n_steps, n_runs=1, rng=None):
    """Return the distances from solution of the approximations x_0, x_1, ...,
    x_{n_steps} in each of n_runs runs of Kaczmarz's algorithm, as an array
    with one row for each run."""
    rng = np.random.default_rng(rng)
    return np.array([np.linalg.norm(kaczmarz(A, b, order, tol=0,
                                             max_steps=n_steps, rng=rng)
                                    - solution, axis=1)
                     for _ in range(n_runs)])


def plot_system(ax, A, b, xs, lims):
    """Plot the line a_i . x = b_i of each equation of a system of two
    unknowns, and the path xs of Kaczmarz's algorithm, with equal scales on
    the axes, so that the steps meet the lines at right angles, and with the
    limits lims = (x0, x1, y0, y1)."""
    for ai, bi in zip(A, b):
        p = bi / (ai @ ai) * ai  # the point of the line nearest the origin
        ax.axline(p, p + (-ai[1], ai[0]), c="C0", lw=1)
    ax.plot(*xs.T, "o-", c="k", ms=3, lw=1)
    ax.set_aspect("equal")
    ax.axis(lims)
    ax.set_xlabel("$x$")
    ax.set_ylabel("$y$")


if __name__ == "__main__":
    # The paths of the cyclic and random orders.
    fig, axes = plt.subplots(ncols=2, figsize=(10, 5), layout="constrained")
    for ax, order in zip(axes, ("cyclic", "random")):
        xs = kaczmarz(A, b, order, rng=SEED)
        print(f"{order}: {len(xs) - 1} steps to x = {xs[-1]}")
        plot_system(ax, A, b, xs, (-0.5, 2.5, -0.5, 2.5))
        ax.set_title(f"{order.capitalize()} order")

    # The error of the cyclic order, the median errors of 1000 runs of each
    # random order (the random order of the system with each equation divided
    # by the norm of its row chooses the rows with equal probabilities), and
    # Strohmer and Vershynin's bound on the root-mean-square error of the
    # random order.
    n_steps = 30
    k = np.arange(n_steps + 1)
    w = 1 / np.linalg.norm(A, axis=1)
    fig, ax = plt.subplots(layout="constrained")
    for label, AA, bb, order, n_runs in (
            ("cyclic", A, b, "cyclic", 1),
            ("random", A, b, "random", 1000),
            ("equal probabilities", A * w[:, None], b * w, "random", 1000),
            ("shuffled", A, b, "shuffled", 1000)):
        e = errors(AA, bb, SOLUTION, order, n_steps, n_runs, rng=SEED)
        ax.plot(k, np.median(e, axis=0), label=label)
    sigma = np.linalg.svd(A, compute_uv=False)  # the singular values of A
    kappa = np.linalg.norm(A) / sigma[-1]
    print(f"kappa = {kappa:.2f}")
    ax.plot(k, np.linalg.norm(SOLUTION) * (1 - 1 / kappa**2)**(k / 2), "k--",
            label="bound")
    ax.set_yscale("log")
    ax.set_ylim(1e-9, 10)
    ax.set_xlabel("Step, $k$")
    ax.set_ylabel(r"Error, $\Vert\mathbf{x}_k - \mathbf{x}\Vert$")
    ax.legend()

    # A fan of 13 lines through (1, 2), in cyclic order (its first five
    # passes) and in random order.
    F, g = fan(13, SOLUTION)
    fig, axes = plt.subplots(ncols=2, figsize=(10, 5), layout="constrained")
    for ax, order in zip(axes, ("cyclic", "random")):
        xs = kaczmarz(F, g, order, rng=SEED)
        print(f"Fan, {order}: {len(xs) - 1} steps")
        plot_system(ax, F, g, xs[:66], (-1.4, 3.4, -0.4, 4.4))
        ax.set_title(f"{order.capitalize()} order")

    # The system with errors in b: the last pass of the cyclic order, 2000
    # steps of the random order, and the least-squares solutions of the
    # system (x) and of the system with each equation divided by the norm of
    # its row (+).
    be = b + ERRORS
    x_ls = np.linalg.lstsq(A, be)[0]
    x_wls = np.linalg.lstsq(A * w[:, None], be * w)[0]
    print(f"Least-squares solution: {x_ls}; weighted: {x_wls}")
    fig, ax = plt.subplots(layout="constrained")
    plot_system(ax, A, be, kaczmarz(A, be, tol=0, max_steps=400)[-5:],
                (0.6, 1.4, 1.6, 2.4))
    xs = kaczmarz(A, be, "random", tol=0, max_steps=2000, rng=SEED)
    ax.plot(*xs.T, ".", c="0.5", ms=2, zorder=0)
    ax.plot(*x_ls, "kx", ms=10)
    ax.plot(*x_wls, "k+", ms=10)
    plt.show()
