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  8.36e+00  0.00e+00  0.00e+00  0.00e+00   ✗ ✗ ✗ ✗  ✗ ✗ ✗ ✗  0.49s
    1  2.25e-01  2.79e+00  3.00e+00  3.00e+00   3.0e+00  8.0e-02  0.91s
    2  1.13e-01  2.81e+00  3.13e+00  4.43e+00   8.2e-01  4.1e-01  1.09s
    3  3.80e-02  2.81e+00  3.26e+00  5.76e+00   8.6e-01  2.9e-01  1.09s
    4  9.36e-02  2.81e+00  3.46e+00  7.09e+00   4.4e-01  1.1e+00  1.09s
    5  3.90e-10  2.82e+00  3.48e+00  9.21e+00   3.3e-01  1.4e-09  1.09s

SimpleStats
 niter: 5
 solved: true
 inconsistent: false
 indefinite: false
 npcCount: 0
 residuals: []
 Aresiduals: []
 κ₂(A): []
 timer: 1.09s
 status: solution good enough for the tolerances given
Primal feasibility: 4.7e-11
Dual   feasibility: 3.1e-16
Error in x: 4.6e-11
Error in y: 1.5e-11