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  9.55e+00  0.00e+00  0.00e+00  0.00e+00   ✗ ✗ ✗ ✗  ✗ ✗ ✗ ✗  0.00s
    1  4.98e-01  2.71e+00  3.53e+00  3.53e+00   3.5e+00  1.8e-01  0.00s
    2  2.60e-01  2.76e+00  3.68e+00  5.20e+00   9.2e-01  4.8e-01  0.00s
    3  1.32e-01  2.78e+00  3.79e+00  6.71e+00   8.3e-01  4.2e-01  0.00s
    4  9.98e-03  2.79e+00  3.83e+00  7.93e+00   5.4e-01  4.1e-02  0.00s
    5  9.00e-10  2.79e+00  3.86e+00  8.87e+00   4.7e-01  4.3e-08  0.00s

SimpleStats
 niter: 5
 solved: true
 inconsistent: false
 indefinite: false
 npcCount: 0
 residuals: []
 Aresiduals: []
 κ₂(A): []
 allocation timer: 2.40μs
 timer: 65.88μs
 status: solution good enough for the tolerances given
Primal feasibility: 9.4e-11
Dual   feasibility: 3.1e-16
Error in x: 9.1e-11
Error in y: 5.0e-11