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.03e+01  0.00e+00  0.00e+00  0.00e+00   ✗ ✗ ✗ ✗  ✗ ✗ ✗ ✗  0.38s
    1  3.28e-01  2.79e+00  3.71e+00  3.71e+00   3.7e+00  1.2e-01  0.63s
    2  9.26e-02  2.80e+00  3.88e+00  5.49e+00   1.1e+00  3.1e-01  0.78s
    3  5.70e-02  2.81e+00  3.97e+00  6.93e+00   7.2e-01  4.4e-01  0.78s
    4  3.24e-02  2.82e+00  3.99e+00  8.19e+00   2.6e-01  1.5e-01  0.78s
    5  5.33e-09  2.82e+00  4.03e+00  9.40e+00   6.2e-01  1.0e-07  0.78s

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