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)         α        β
    0  8.77e+00  0.00e+00  0.00e+00  0.00e+00
    1  4.20e-01  2.70e+00  3.25e+00  3.25e+00   3.2e+00  1.6e-01
    2  1.44e-01  2.73e+00  3.42e+00  4.84e+00   1.0e+00  3.4e-01
    3  7.60e-02  2.74e+00  3.51e+00  6.13e+00   6.7e-01  3.5e-01
    4  1.89e-02  2.74e+00  3.59e+00  7.35e+00   7.4e-01  1.8e-01
    5  6.01e-11  2.74e+00  3.63e+00  8.30e+00   5.3e-01  1.7e-09

SimpleStats
 niter: 5
 solved: true
 inconsistent: false
 residuals: []
 Aresiduals: []
 κ₂(A): []
 status: solution good enough for the tolerances given
Primal feasibility: 6.8e-12
Dual   feasibility: 1.6e-16
Error in x: 6.7e-12
Error in y: 5.1e-12