-
Notifications
You must be signed in to change notification settings - Fork 224
feat(linalg): add generalized least squares solver #1105
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
Open
aamrindersingh
wants to merge
12
commits into
fortran-lang:master
Choose a base branch
from
aamrindersingh:1047-feat-generalized-lstsq
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 9 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
9e16d37
feat(linalg): add generalized least squares solver
aamrindersingh 82ab371
Update src/linalg/stdlib_linalg_least_squares.fypp
aamrindersingh fbb6c69
docs: clarify SPD (real) / HPD (complex) for GLS, add zero parameter
aamrindersingh 703ae17
test: remove unused tol variable in generalized_lstsq test
aamrindersingh 4764aa9
refactor(generalized_lstsq): use optval, cholesky subroutine, and do …
aamrindersingh 296727a
fix(handle_ggglm_info): expand select case with specific error messages
aamrindersingh 5a70184
Add overwrite_w, SVD-based sqrt test, improve error messages
aamrindersingh 0b5f9ad
Use eye/hermitian in tests, document Cholesky zeroing, fix error prop…
aamrindersingh 07417f8
removed where_at error handling
aamrindersingh 8c82fab
add solve_generalized_lstsq subroutine, fix docs and allocate style
aamrindersingh 34e840d
fix: address review comments for generalized_lstsq
aamrindersingh 3640093
Update src/linalg/stdlib_linalg.fypp
perazz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| ! Generalized least-squares solver with correlated errors | ||
| program example_generalized_lstsq | ||
| use stdlib_linalg_constants, only: dp | ||
| use stdlib_linalg, only: generalized_lstsq | ||
| implicit none | ||
|
|
||
| real(dp) :: A(3,2), b(3), W(3,3) | ||
|
jvdp1 marked this conversation as resolved.
Outdated
|
||
| real(dp), allocatable :: x(:) | ||
|
|
||
| ! Design matrix: intercept + slope | ||
| A(:,1) = 1.0_dp | ||
| A(:,2) = [1.0_dp, 2.0_dp, 3.0_dp] | ||
|
|
||
| ! Observations | ||
| b = [1.0_dp, 2.1_dp, 2.9_dp] | ||
|
|
||
| ! Covariance matrix (correlated errors) | ||
| W(1,:) = [1.0_dp, 0.5_dp, 0.25_dp] | ||
| W(2,:) = [0.5_dp, 1.0_dp, 0.5_dp] | ||
| W(3,:) = [0.25_dp, 0.5_dp, 1.0_dp] | ||
|
jvdp1 marked this conversation as resolved.
Outdated
|
||
|
|
||
| ! Solve generalized least-squares | ||
| x = generalized_lstsq(W, A, b) | ||
|
|
||
| print '("GLS fit: intercept = ",f8.4,", slope = ",f8.4)', x(1), x(2) | ||
| ! GLS fit: intercept = 0.0500, slope = 0.9500 | ||
|
|
||
| end program example_generalized_lstsq | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -7,10 +7,10 @@ | |||||||||||||||||
| submodule (stdlib_linalg) stdlib_linalg_least_squares | ||||||||||||||||||
| !! Least-squares solution to Ax=b | ||||||||||||||||||
| use stdlib_linalg_constants | ||||||||||||||||||
| use stdlib_linalg_lapack, only: gelsd, gglse, stdlib_ilaenv | ||||||||||||||||||
| use stdlib_linalg_lapack_aux, only: handle_gelsd_info, handle_gglse_info | ||||||||||||||||||
| use stdlib_linalg_lapack, only: gelsd, gglse, ggglm, stdlib_ilaenv | ||||||||||||||||||
| use stdlib_linalg_lapack_aux, only: handle_gelsd_info, handle_gglse_info, handle_ggglm_info | ||||||||||||||||||
| use stdlib_linalg_state, only: linalg_state_type, linalg_error_handling, LINALG_ERROR, & | ||||||||||||||||||
| LINALG_INTERNAL_ERROR, LINALG_VALUE_ERROR | ||||||||||||||||||
| LINALG_INTERNAL_ERROR, LINALG_VALUE_ERROR, LINALG_SUCCESS | ||||||||||||||||||
| implicit none | ||||||||||||||||||
|
|
||||||||||||||||||
| character(*), parameter :: this = 'lstsq' | ||||||||||||||||||
|
|
@@ -564,4 +564,139 @@ submodule (stdlib_linalg) stdlib_linalg_least_squares | |||||||||||||||||
| end function stdlib_linalg_${ri}$_constrained_lstsq | ||||||||||||||||||
| #:endfor | ||||||||||||||||||
|
|
||||||||||||||||||
| !------------------------------------------------------------- | ||||||||||||||||||
| !----- Generalized Least-Squares Solver ----- | ||||||||||||||||||
| !------------------------------------------------------------- | ||||||||||||||||||
|
|
||||||||||||||||||
| #:for rk,rt,ri in RC_KINDS_TYPES | ||||||||||||||||||
| ! Generalized least-squares: minimize (Ax-b)^T W^{-1} (Ax-b) where W is symmetric/Hermitian positive definite | ||||||||||||||||||
| module function stdlib_linalg_${ri}$_generalized_lstsq(w,a,b,prefactored_w,overwrite_a,overwrite_w,err) result(x) | ||||||||||||||||||
| !> Covariance matrix W[m,m] (symmetric/Hermitian positive definite) or its matrix square root | ||||||||||||||||||
| ${rt}$, intent(inout), target :: w(:,:) | ||||||||||||||||||
| !> Input matrix a[m,n] | ||||||||||||||||||
|
jvdp1 marked this conversation as resolved.
Outdated
|
||||||||||||||||||
| ${rt}$, intent(inout), target :: a(:,:) | ||||||||||||||||||
| !> Right hand side vector b[m] | ||||||||||||||||||
| ${rt}$, intent(in) :: b(:) | ||||||||||||||||||
| !> [optional] Is W already a matrix square root (e.g., Cholesky factor)? Default: .false. | ||||||||||||||||||
| logical(lk), optional, intent(in) :: prefactored_w | ||||||||||||||||||
| !> [optional] Can A data be overwritten and destroyed? | ||||||||||||||||||
| logical(lk), optional, intent(in) :: overwrite_a | ||||||||||||||||||
| !> [optional] Can W data be overwritten and destroyed? Default: .false. | ||||||||||||||||||
| logical(lk), optional, intent(in) :: overwrite_w | ||||||||||||||||||
| !> [optional] state return flag. On error if not requested, the code will stop | ||||||||||||||||||
| type(linalg_state_type), optional, intent(out) :: err | ||||||||||||||||||
| !> Result array x[n] | ||||||||||||||||||
| ${rt}$, allocatable :: x(:) | ||||||||||||||||||
|
jvdp1 marked this conversation as resolved.
|
||||||||||||||||||
|
|
||||||||||||||||||
| ! Local variables | ||||||||||||||||||
| type(linalg_state_type) :: err0 | ||||||||||||||||||
| integer(ilp) :: m, n, p, lda, ldb, lwork, info | ||||||||||||||||||
| logical(lk) :: copy_a, copy_w, is_prefactored | ||||||||||||||||||
| ${rt}$, pointer :: amat(:,:), lmat(:,:) | ||||||||||||||||||
| ${rt}$, allocatable, target :: amat_alloc(:,:), lmat_alloc(:,:) | ||||||||||||||||||
| ${rt}$, allocatable :: d(:), y(:), work(:) | ||||||||||||||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Two work allocations will be too expensive. let's use a static variable for work size query
Suggested change
|
||||||||||||||||||
| character(*), parameter :: this = 'generalized_lstsq' | ||||||||||||||||||
|
|
||||||||||||||||||
| m = size(a, 1, kind=ilp) | ||||||||||||||||||
| n = size(a, 2, kind=ilp) | ||||||||||||||||||
| p = m ! For GLS, B is m×m | ||||||||||||||||||
|
|
||||||||||||||||||
| ! Allocate result early (prevents segfault on error return) | ||||||||||||||||||
| allocate(x(n)) | ||||||||||||||||||
|
|
||||||||||||||||||
| ! Validate matrix dimensions | ||||||||||||||||||
| if (m < 1 .or. n < 1) then | ||||||||||||||||||
| err0 = linalg_state_type(this, LINALG_VALUE_ERROR, 'Invalid matrix size a(m, n) =', [m, n]) | ||||||||||||||||||
| call linalg_error_handling(err0, err) | ||||||||||||||||||
| return | ||||||||||||||||||
| end if | ||||||||||||||||||
|
|
||||||||||||||||||
| ! Validate sizes | ||||||||||||||||||
| if (size(w, 1, kind=ilp) /= m .or. size(w, 2, kind=ilp) /= m) then | ||||||||||||||||||
| err0 = linalg_state_type(this, LINALG_VALUE_ERROR, & | ||||||||||||||||||
| 'Covariance matrix must be square m×m:', shape(w, kind=ilp)) | ||||||||||||||||||
| call linalg_error_handling(err0, err) | ||||||||||||||||||
| return | ||||||||||||||||||
| end if | ||||||||||||||||||
|
|
||||||||||||||||||
| if (size(b, kind=ilp) /= m) then | ||||||||||||||||||
|
perazz marked this conversation as resolved.
|
||||||||||||||||||
| err0 = linalg_state_type(this, LINALG_VALUE_ERROR, & | ||||||||||||||||||
| 'Right-hand side size must match rows of A:', size(b, kind=ilp), '/=', m) | ||||||||||||||||||
| call linalg_error_handling(err0, err) | ||||||||||||||||||
| return | ||||||||||||||||||
| end if | ||||||||||||||||||
|
|
||||||||||||||||||
| if (m < n) then | ||||||||||||||||||
| err0 = linalg_state_type(this, LINALG_VALUE_ERROR, & | ||||||||||||||||||
| 'GGGLM requires m >= n (overdetermined or square):', m, '<', n) | ||||||||||||||||||
| call linalg_error_handling(err0, err) | ||||||||||||||||||
| return | ||||||||||||||||||
| end if | ||||||||||||||||||
|
|
||||||||||||||||||
| ! Process options | ||||||||||||||||||
| is_prefactored = optval(prefactored_w, .false._lk) | ||||||||||||||||||
| copy_a = .not. optval(overwrite_a, .false._lk) | ||||||||||||||||||
| copy_w = .not. optval(overwrite_w, .false._lk) | ||||||||||||||||||
|
|
||||||||||||||||||
| ! Handle A matrix | ||||||||||||||||||
| if (copy_a) then | ||||||||||||||||||
| allocate(amat_alloc(m, n), source=a) | ||||||||||||||||||
| amat => amat_alloc | ||||||||||||||||||
| else | ||||||||||||||||||
| amat => a | ||||||||||||||||||
| end if | ||||||||||||||||||
|
|
||||||||||||||||||
| ! Handle covariance/matrix square root | ||||||||||||||||||
| if (copy_w) then | ||||||||||||||||||
| allocate(lmat_alloc(m, m), source=w) | ||||||||||||||||||
| lmat => lmat_alloc | ||||||||||||||||||
| else | ||||||||||||||||||
| lmat => w | ||||||||||||||||||
| end if | ||||||||||||||||||
|
|
||||||||||||||||||
| if (.not. is_prefactored) then | ||||||||||||||||||
| ! Compute Cholesky factorization: W = L * L^T (real) or W = L * L^H (complex) | ||||||||||||||||||
| call cholesky(lmat, lower=.true._lk, other_zeroed=.true._lk, err=err0) | ||||||||||||||||||
| if (err0%error()) then | ||||||||||||||||||
| ! Cleanup before early return | ||||||||||||||||||
| if (copy_a) deallocate(amat_alloc) | ||||||||||||||||||
| if (copy_w) deallocate(lmat_alloc) | ||||||||||||||||||
| call linalg_error_handling(err0, err) | ||||||||||||||||||
| return | ||||||||||||||||||
| end if | ||||||||||||||||||
| end if | ||||||||||||||||||
| ! If prefactored_w=.true., user provides a valid matrix square root B where W = B*B^T. | ||||||||||||||||||
| ! This can be a Cholesky factor OR any other valid square root (e.g., SVD-based). | ||||||||||||||||||
| ! We do not modify the user's input. | ||||||||||||||||||
|
|
||||||||||||||||||
| ! Prepare for GGGLM | ||||||||||||||||||
| allocate(d(m), source=b) | ||||||||||||||||||
|
jvdp1 marked this conversation as resolved.
Outdated
|
||||||||||||||||||
| allocate(y(p)) | ||||||||||||||||||
|
|
||||||||||||||||||
| lda = m | ||||||||||||||||||
| ldb = m | ||||||||||||||||||
|
|
||||||||||||||||||
| ! Workspace query | ||||||||||||||||||
| allocate(work(1)) | ||||||||||||||||||
| call ggglm(m, n, p, amat, lda, lmat, ldb, d, x, y, work, -1_ilp, info) | ||||||||||||||||||
| lwork = ceiling(real(work(1), kind=${rk}$), kind=ilp) | ||||||||||||||||||
| deallocate(work) | ||||||||||||||||||
| allocate(work(lwork)) | ||||||||||||||||||
|
Comment on lines
+713
to
+717
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Avoid double allocation here
Suggested change
|
||||||||||||||||||
|
|
||||||||||||||||||
| ! Solve GLS via GGGLM | ||||||||||||||||||
| call ggglm(m, n, p, amat, lda, lmat, ldb, d, x, y, work, lwork, info) | ||||||||||||||||||
|
perazz marked this conversation as resolved.
|
||||||||||||||||||
|
|
||||||||||||||||||
| ! Handle errors | ||||||||||||||||||
| call handle_ggglm_info(this, info, m, n, p, lda, ldb, err0) | ||||||||||||||||||
|
|
||||||||||||||||||
| ! Cleanup | ||||||||||||||||||
| if (copy_a) deallocate(amat_alloc) | ||||||||||||||||||
| if (copy_w) deallocate(lmat_alloc) | ||||||||||||||||||
| deallocate(d, y, work) | ||||||||||||||||||
|
|
||||||||||||||||||
| call linalg_error_handling(err0, err) | ||||||||||||||||||
|
|
||||||||||||||||||
| end function stdlib_linalg_${ri}$_generalized_lstsq | ||||||||||||||||||
| #:endfor | ||||||||||||||||||
|
|
||||||||||||||||||
| end submodule stdlib_linalg_least_squares | ||||||||||||||||||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You could mention here that, if the Cholesky factor is used, user need to have zeroed-out the other triangular part.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why asking that to the user, and not to do it internally?
If asked to the user, should there be an internal check to ensure that it is really the case?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The Cholesky factors are not the only matrix square-root one can use. If you use
svdand take the square-root of the singular values, it'll be a valid square-root although it won't have the upper or lower triangular structure of the Cholesky factor. In order to check internally whether the upper (lower) triangular part has been zeroed-out by the user, we would need to know for sure that the pre-factoredWmatrix has been obtained with Cholesky. And even there, we would need to know whetherUorLis being used.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
OK. thank you for the explanation. Could we then add something like that to warn the user that is up to its responsability:
"It is the user's responsibility to ensure that the prefactored matrix B is valid."
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure enough !