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  1.00e+01  0.00e+00  0.00e+00  0.00e+00   ✗ ✗ ✗ ✗  ✗ ✗ ✗ ✗  0.38s
    1  1.18e-01  2.77e+00  3.61e+00  3.61e+00   3.6e+00  4.3e-02  0.77s
    2  3.85e-02  2.77e+00  3.69e+00  5.22e+00   7.3e-01  2.4e-01  0.91s
    3  1.42e-02  2.78e+00  3.72e+00  6.50e+00   4.2e-01  1.6e-01  0.91s
    4  7.11e-03  2.78e+00  3.78e+00  7.67e+00   5.8e-01  2.9e-01  0.91s
    5  2.93e-09  2.78e+00  3.86e+00  8.85e+00   7.9e-01  3.3e-07  0.91s

SimpleStats
 niter: 5
 solved: true
 inconsistent: false
 residuals: []
 Aresiduals: []
 κ₂(A): []
 timer: 908.36ms
 status: solution good enough for the tolerances given
Primal feasibility: 2.9e-10
Dual   feasibility: 1.3e-16
Error in x: 2.9e-10
Error in y: 2.6e-10