Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

KrylovJL solvers returning incorrect answer when u0 is a SubArray #347

Closed
vpuri3 opened this issue Jul 25, 2023 · 1 comment · Fixed by #348
Closed

KrylovJL solvers returning incorrect answer when u0 is a SubArray #347

vpuri3 opened this issue Jul 25, 2023 · 1 comment · Fixed by #348

Comments

@vpuri3
Copy link
Member

vpuri3 commented Jul 25, 2023

julia> using LinearSolve, IterativeSolvers

julia> A = rand(4, 4); b = rand(4); u0 = zeros(4);

julia> lp = LinearProblem(A, b; u0 = view(u0, :));

julia> solve(lp, KrylovJL_GMRES()) # broken
u: 4-element view(::Vector{Float64}, :) with eltype Float64:
 0.0
 0.0
 0.0
 0.0

julia> solve(lp, IterativeSolversJL_GMRES())
u: 4-element view(::Vector{Float64}, :) with eltype Float64:
  1.4228823954515826
 -1.3845427042881076
  3.1810595009865623
 -1.512734087737276

julia> solve(lp, LUFactorization())
u: 4-element view(::Vector{Float64}, :) with eltype Float64:
  1.4228823954515823
 -1.3845427042881064
  3.1810595009865623
 -1.512734087737277
@fredrikekre
Copy link
Contributor

This is caused by

. Because the RHS is ::Vector then the solver struct enforces the same type also for x, and thus u0 will be converted to Vector in the line above. A potential fix is:

diff --git a/src/iterative_wrappers.jl b/src/iterative_wrappers.jl
index b471065..6de56a9 100644
--- a/src/iterative_wrappers.jl
+++ b/src/iterative_wrappers.jl
@@ -282,6 +282,11 @@ function SciMLBase.solve!(cache::LinearCache, alg::KrylovJL; kwargs...)
         ReturnCode.Success
     end

+    # Copy the solution to the allocated output vector
+    if cache.u !== cache.cacheval.x
+        cache.u .= cache.cacheval.x
+    end
+
     return SciMLBase.build_linear_solution(alg, cache.u, resid, cache;
         iters = stats.niter)
 end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants