using Krylov
using LinearAlgebra, Printf

m = 5
n = 8
λ = 1.0e-3
A = rand(m, n)
b = A * ones(n)
xy_exact = [A  λ*I] \ b # In Julia, this is the min-norm solution!

(x, y, stats) = craig(A, b, λ=λ, atol=0.0, rtol=1.0e-20, verbose=1)
show(stats)

# Check that we have a minimum-norm solution.
# When λ > 0 we solve min ‖(x,s)‖  s.t. Ax + λs = b, and we get s = λy.
@printf("Primal feasibility: %7.1e\n", norm(b - A * x - λ^2 * y) / norm(b))
@printf("Dual   feasibility: %7.1e\n", norm(x - A' * y) / norm(x))
@printf("Error in x: %7.1e\n", norm(x - xy_exact[1:n]) / norm(xy_exact[1:n]))
if λ > 0.0
  @printf("Error in y: %7.1e\n", norm(λ * y - xy_exact[n+1:n+m]) / norm(xy_exact[n+1:n+m]))
end
CRAIG: system of 5 equations in 8 variables
    k       ‖r‖       ‖x‖       ‖A‖      κ(A)         α        β  timer
    0  7.83e+00  0.00e+00  0.00e+00  0.00e+00   ✗ ✗ ✗ ✗  ✗ ✗ ✗ ✗  0.28s
    1  3.51e-01  2.68e+00  2.92e+00  2.92e+00   2.9e+00  1.3e-01  0.47s
    2  9.02e-02  2.73e+00  3.00e+00  4.25e+00   6.7e-01  1.7e-01  0.58s
    3  4.26e-02  2.73e+00  3.20e+00  5.57e+00   9.9e-01  4.7e-01  0.58s
    4  1.41e-02  2.73e+00  3.29e+00  6.70e+00   7.5e-01  2.5e-01  0.58s
    5  1.25e-10  2.73e+00  3.35e+00  7.65e+00   6.2e-01  5.5e-09  0.58s

SimpleStats
 niter: 5
 solved: true
 inconsistent: false
 residuals: []
 Aresiduals: []
 κ₂(A): []
 timer: 578.77ms
 status: solution good enough for the tolerances given
Primal feasibility: 1.6e-11
Dual   feasibility: 2.3e-16
Error in x: 1.6e-11
Error in y: 1.2e-11