Debian Codegraph @

plink2_matrix.h

raw
1 #ifndef __PLINK2_MATRIX_H__
2 #define __PLINK2_MATRIX_H__
3
4 // This file is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
5 // Christopher Chang.
6 //
7 // This program is free software: you can redistribute it and/or modify it
8 // under the terms of the GNU General Public License as published by the Free
9 // Software Foundation, either version 3 of the License, or (at your option)
10 // any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but WITHOUT
13 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 // more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
21 // Wrappers for frequent LAPACK calls (sometimes with no-LAPACK fallbacks).
22 // Now supports MKL backend.
23
24 // todo: allow this to take advantage of 64-bit integer LAPACK. As of this
25 // writing, it's available on Amazon EC2 64-bit Linux instances, but I can't
26 // find it for Windows. (And even if OS X vecLib adds it soon, we can't use it
27 // there anytime soon because static linking is not an option.)
28
29 // #include "plink2_cmdline.h"
30 #include "include/plink2_bits.h"
31
32 #ifdef NOLAPACK
33 typedef double MatrixInvertBuf1;
34 CONSTI32(kMatrixInvertBuf1ElemAlloc, 2 * sizeof(double));
35 CONSTI32(kMatrixInvertBuf1CheckedAlloc, 2 * sizeof(double));
36 # define __CLPK_integer int
37
38 #else // not NOLAPACK
39
40 # ifdef __APPLE__
41 // Make -DLAPACK_ILP64 and -DACCELERATE_LAPACK_ILP64 have the same effect.
42 # if defined(LAPACK_ILP64) && !defined(ACCELERATE_LAPACK_ILP64)
43 # define ACCELERATE_LAPACK_ILP64
44 # endif
45 # if defined(ACCELERATE_LAPACK_ILP64) && !defined(LAPACK_ILP64)
46 # define LAPACK_ILP64
47 # endif
48 # endif
49
50 # ifdef DYNAMIC_MKL
51 # define USE_MKL
52 # endif
53
54 # ifdef USE_MKL
55 # ifdef __APPLE__
56 # error "plink2 cannot currently use MKL on OS X."
57 # endif
58 # ifdef LAPACK_ILP64
59 # define MKL_ILP64
60 # endif
61 # ifdef DYNAMIC_MKL
62 # include <mkl_service.h>
63 # else
64 // If this isn't initially found, use the compiler's -I option to specify the
65 // appropriate include-file directory. A common location is
66 // /opt/intel/mkl/include .
67 // If this isn't installed at all on your system but you want/need to change
68 // that, see the instructions at
69 // https://software.intel.com/en-us/articles/installing-intel-free-libs-and-python-apt-repo
70 # include "mkl_service.h"
71 # endif
72 # define USE_MTBLAS
73 // this technically doesn't have to be a macro, but it's surrounded by other
74 // things which do have to be macros, so changing this to a namespaced function
75 // arguably *decreases* overall readability...
76 # define BLAS_SET_NUM_THREADS mkl_set_num_threads
77 # else
78 # ifdef USE_OPENBLAS
79 # ifdef __cplusplus
80 extern "C" {
81 # endif
82 void openblas_set_num_threads(int num_threads);
83 # ifdef __cplusplus
84 } // extern "C"
85 # endif
86 # define USE_MTBLAS
87 # define BLAS_SET_NUM_THREADS openblas_set_num_threads
88 # else
89 # ifndef ACCELERATE_NEW_LAPACK
90 # define BLAS_SET_NUM_THREADS(num)
91 # endif
92 # endif
93 # endif
94
95 # ifdef __APPLE__
96 # ifdef ACCELERATE_NEW_LAPACK
97 # ifdef LAPACK_ILP64
98 // unfortunately, compiler complains about incompatible pointer types if we
99 // use the less-ambiguous "long long" or "int64_t" here
100 typedef long __CLPK_integer;
101 static_assert(sizeof(long) == 8, "Unexpected 'long' type size.");
102 # else
103 typedef int32_t __CLPK_integer;
104 # endif
105 # else // !ACCELERATE_NEW_LAPACK
106 # ifdef LAPACK_ILP64
107 # error "LAPACK_ILP64 requires ACCELERATE_NEW_LAPACK on macOS"
108 # endif
109 # endif
110 # include <Accelerate/Accelerate.h>
111 # define USE_CBLAS_XGEMM
112 # if defined(ACCELERATE_NEW_LAPACK) && !defined(USE_OPENBLAS)
113 HEADER_INLINE void BLAS_SET_NUM_THREADS(__attribute__((unused)) int num_threads) {
114 if (__builtin_available(macOS 15.0, *)) {
115 if (num_threads > 1) {
116 BLASSetThreading(BLAS_THREADING_MULTI_THREADED);
117 } else {
118 BLASSetThreading(BLAS_THREADING_SINGLE_THREADED);
119 }
120 }
121 }
122 # endif
123 # elif defined(USE_AOCL)
124 # define USE_CBLAS_XGEMM
125 # endif
126
127 # ifndef __APPLE__
128
129 # ifdef __cplusplus
130 extern "C" {
131 # endif
132 typedef double __CLPK_doublereal;
133 # ifdef __LP64__
134 # ifdef LAPACK_ILP64
135 typedef long long __CLPK_integer;
136 # else
137 typedef int32_t __CLPK_integer;
138 # endif
139 # else
140 # ifdef LAPACK_ILP64
141 # error "Invalid compile flags."
142 # else
143 # ifdef _WIN32
144 // probably don't need this?
145 typedef int32_t __CLPK_integer;
146 # else
147 typedef long int __CLPK_integer;
148 # endif
149 # endif
150 # endif // !__LP64__
151
152 # ifdef _WIN32
153 // openblas is easy enough to set up on Windows nowadays.
154 // not worth the trouble of ripping out vector extensions, etc. just so we
155 // can compile with Visual Studio and gain access to MKL
156 # ifndef USE_OPENBLAS
157 # error "Windows build currently requires OpenBLAS's LAPACK."
158 # endif
159 # define HAVE_LAPACK_CONFIG_H
160 # define LAPACK_COMPLEX_STRUCTURE
161 # include "lapacke.h"
162
163 __CLPK_doublereal ddot_(__CLPK_integer* n, __CLPK_doublereal* dx,
164 __CLPK_integer* incx, __CLPK_doublereal* dy,
165 __CLPK_integer* incy);
166 __CLPK_doublereal sdot_(__CLPK_integer* n, float* sx, __CLPK_integer* incx,
167 float* sy, __CLPK_integer* incy);
168 # else // Linux
169 # ifdef USE_MKL
170 # define USE_CBLAS_XGEMM
171 # ifdef DYNAMIC_MKL
172 # include <mkl_cblas.h>
173 # include <mkl_lapack.h>
174 # else
175 # include "mkl_cblas.h"
176 # include "mkl_lapack.h"
177 # endif
178 static_assert(sizeof(MKL_INT) == 8, "Unexpected MKL_INT size.");
179 # else
180 // If you want 64-bit index support, but not MKL (e.g. you're targeting an
181 // AMD processor), modify the Makefile to link to a LAPACK library recompiled
182 // with -fdefault-integer-8.
183
184 # ifdef USE_CBLAS_XGEMM
185 # include <cblas.h>
186 int dpotri_(char* uplo, __CLPK_integer* n, __CLPK_doublereal* a,
187 __CLPK_integer* lda, __CLPK_integer* info);
188 # else
189 // ARGH
190 // cmake on Ubuntu 14 seems to require use of cblas_f77.h instead of
191 // cblas.h. Conversely, cblas_f77.h does not seem to be available on
192 // the Scientific Linux ATLAS/LAPACK install, and right now that's my
193 // only option for producing 32-bit static builds...
194 // So. Default include is cblas.h. To play well with cmake + Ubuntu
195 // 14 and 16 simultaneously, there is a CBLAS_F77_ON_OLD_GCC mode
196 // which picks cblas_f77.h on Ubuntu 14 and cblas.h on 16.
197 # ifdef FORCE_CBLAS_F77
198 # include <cblas_f77.h>
199 # elif !defined(CBLAS_F77_ON_OLD_GCC)
200 # include <cblas.h>
201 # else
202 # if (__GNUC__ == 4)
203 # include <cblas_f77.h>
204 # else
205 # if __has_include(<cblas.h>)
206 # include <cblas.h>
207 # else
208 # include <cblas_f77.h>
209 # endif
210 # endif
211 # endif
212 __CLPK_doublereal ddot_(__CLPK_integer* n, __CLPK_doublereal* dx,
213 __CLPK_integer* incx, __CLPK_doublereal* dy,
214 __CLPK_integer* incy);
215
216 __CLPK_doublereal sdot_(__CLPK_integer* n, float* sx, __CLPK_integer* incx,
217 float* sy, __CLPK_integer* incy);
218 int dpotri_(char* uplo, __CLPK_integer* n, __CLPK_doublereal* a,
219 __CLPK_integer* lda, __CLPK_integer* info);
220 # endif
221 # endif // !USE_MKL
222 # ifdef USE_CUDA
223 # include "cuda/plink2_matrix_cuda.h"
224 # endif
225 # endif
226
227 void xerbla_(void);
228 # ifdef __cplusplus
229 } // extern "C"
230 # endif
231
232 # endif // !__APPLE__
233
234 typedef __CLPK_integer MatrixInvertBuf1;
235 // need to be careful about >= 2^32?
236 CONSTI32(kMatrixInvertBuf1ElemAlloc, sizeof(__CLPK_integer));
237 // invert_matrix_checked() usually requires a larger buffer
238 CONSTI32(kMatrixInvertBuf1CheckedAlloc, 2 * sizeof(__CLPK_integer));
239
240 #endif // !NOLAPACK
241
242 #ifdef __cplusplus
243 namespace plink2 {
244 #endif
245
246 static const double kMatrixSingularRcond = 1e-14;
247
248 // Returns -1 if no inf/nan found.
249 // May move this to a more central location if there are other users.
250 intptr_t FirstInfOrNan(const double* vec, uintptr_t size);
251
252 uint32_t LowerTriangularFirstInfOrNan(const double* matrix, uintptr_t dim, uintptr_t* row_idx_ptr, uintptr_t* col_idx_ptr);
253
254 // Copies (C-order) lower-left to upper right.
255 void ReflectMatrix(uint32_t dim, double* matrix);
256
257 void ReflectStridedMatrix(uint32_t dim, uint32_t stride, double* matrix);
258
259 void ReflectFmatrix(uint32_t dim, uint32_t stride, float* matrix);
260
261 // If dim < stride, this zeroes out the trailing elements of each row.
262 void ReflectStridedMatrix0(uint32_t dim, uint32_t stride, double* matrix);
263
264 void ReflectFmatrix0(uint32_t dim, uint32_t stride, float* matrix);
265
266 // AddDVec and AddFVec execute main += arg, under the assumption that both
267 // vectors have been zero-padded.
268 // "ctav" is the float-length of both vectors, rounded up to a vector boundary.
269 // (With the current implementation, it's harmless to just pass in ct instead,
270 // but ctav is better practice since it indicates awareness of what this
271 // function is actually doing.)
272 HEADER_INLINE void AddDVec(const double* arg, uintptr_t ctav, double* main) {
273 // LEA instruction supports multiply by 4 or 8, but *not* by 16 or 32, so
274 // this awkward loop tends to generate slightly better code than the more
275 // natural vector-based loop.
276 for (uintptr_t ulii = 0; ulii < ctav; ulii += kDoublePerDVec) {
277 *R_CAST(VecD*, &(main[ulii])) += *R_CAST(const VecD*, &(arg[ulii]));
278 }
279 }
280
281 HEADER_INLINE void AddFVec(const float* arg, uintptr_t ctav, float* main) {
282 for (uintptr_t ulii = 0; ulii < ctav; ulii += kFloatPerFVec) {
283 *R_CAST(VecF*, &(main[ulii])) += *R_CAST(const VecF*, &(arg[ulii]));
284 }
285 }
286
287 #ifdef __LP64__
288 // FillDVec sets all elements of dst to dxx, and zero-fills any trailing
289 // elements (w.r.t. vector boundaries).
290 // bugfix (21 Nov 2023): forgot about trailing zero-fill.
291 HEADER_INLINE void FillDVec(uintptr_t ct, double dxx, double* dst) {
292 for (uintptr_t ulii = 0; ulii != ct; ++ulii) {
293 dst[ulii] = dxx;
294 }
295 const uintptr_t remainder = ct % kDoublePerDVec;
296 if (remainder) {
297 const uintptr_t ctav = ct + kDoublePerDVec - remainder;
298 for (uintptr_t ulii = ct; ulii != ctav; ++ulii) {
299 dst[ulii] = 0.0;
300 }
301 }
302 }
303 #else
304 HEADER_INLINE void FillDVec(uintptr_t ct, double dxx, double* dst) {
305 for (uintptr_t ulii = 0; ulii != ct; ++ulii) {
306 dst[ulii] = dxx;
307 }
308 }
309 #endif
310
311 #ifdef __LP64__
312 // FillFVec sets all elements of dst to fxx, and zero-fills any trailing
313 // elements (w.r.t. vector boundaries).
314 HEADER_INLINE void FillFVec(uintptr_t ct, float fxx, float* dst) {
315 const uintptr_t fullvec_ct = ct / kFloatPerFVec;
316 const VecF vfill = VCONST_F(fxx);
317 VecF* dst_alias = R_CAST(VecF*, dst);
318 for (uintptr_t ulii = 0; ulii != fullvec_ct; ++ulii) {
319 dst_alias[ulii] = vfill;
320 }
321 const uintptr_t trailing_start_idx = fullvec_ct * kFloatPerFVec;
322 if (trailing_start_idx != ct) {
323 for (uintptr_t ulii = trailing_start_idx; ulii != ct; ++ulii) {
324 dst[ulii] = fxx;
325 }
326 const uintptr_t trailing_stop_idx = trailing_start_idx + kFloatPerFVec;
327 for (uintptr_t ulii = ct; ulii != trailing_stop_idx; ++ulii) {
328 dst[ulii] = S_CAST(float, 0.0);
329 }
330 }
331 }
332 #else
333 HEADER_INLINE void FillFVec(uintptr_t ct, float fxx, float* dst) {
334 for (uintptr_t ulii = 0; ulii != ct; ++ulii) {
335 dst[ulii] = fxx;
336 }
337 }
338 #endif
339
340 HEADER_INLINE double DotprodDShort(const double* vec1, const double* vec2, uint32_t ct) {
341 double dotprod = 0.0;
342 for (uint32_t uii = 0; uii != ct; ++uii) {
343 dotprod += vec1[uii] * vec2[uii];
344 }
345 return dotprod;
346 }
347
348 HEADER_INLINE float DotprodFShort(const float* vec1, const float* vec2, uint32_t ct) {
349 float dotprod = 0.0;
350 for (uint32_t uii = 0; uii != ct; ++uii) {
351 dotprod += vec1[uii] * vec2[uii];
352 }
353 return dotprod;
354 }
355
356 // todo: benchmark again after Spectre/Meltdown mitigation is deployed
357 CONSTI32(kDotprodDThresh, 17);
358 CONSTI32(kDotprodFThresh, 15);
359
360 #ifdef NOLAPACK
361 HEADER_INLINE double DotprodD(const double* vec1, const double* vec2, uint32_t ct) {
362 return DotprodDShort(vec1, vec2, ct);
363 }
364
365 HEADER_INLINE double DotprodxD(const double* vec1, const double* vec2, uint32_t ct) {
366 return DotprodDShort(vec1, vec2, ct);
367 }
368
369 HEADER_INLINE float DotprodF(const float* vec1, const float* vec2, uint32_t ct) {
370 return DotprodFShort(vec1, vec2, ct);
371 }
372
373 BoolErr InvertMatrix(int32_t dim, double* matrix, MatrixInvertBuf1* dbl_1d_buf, double* dbl_2d_buf);
374
375 HEADER_INLINE BoolErr InvertMatrixChecked(int32_t dim, double* matrix, MatrixInvertBuf1* dbl_1d_buf, double* dbl_2d_buf) {
376 return InvertMatrix(dim, matrix, dbl_1d_buf, dbl_2d_buf);
377 }
378
379 HEADER_INLINE BoolErr InvertSymmdefMatrix(int32_t dim, double* matrix, MatrixInvertBuf1* dbl_1d_buf, double* dbl_2d_buf) {
380 ReflectMatrix(dim, matrix);
381 return InvertMatrix(dim, matrix, dbl_1d_buf, dbl_2d_buf);
382 }
383
384 HEADER_INLINE BoolErr InvertSymmdefMatrixChecked(int32_t dim, double* matrix, MatrixInvertBuf1* dbl_1d_buf, double* dbl_2d_buf) {
385 ReflectMatrix(dim, matrix);
386 return InvertMatrix(dim, matrix, dbl_1d_buf, dbl_2d_buf);
387 }
388
389 // first half computes either LU or singular value decomposition, and
390 // determinant
391 // second half actually inverts matrix, assuming 1d_buf and 2d_buf have results
392 // from first half
393 BoolErr InvertStridedMatrixFirstHalf(int32_t dim, int32_t stride, double* matrix, MatrixInvertBuf1* dbl_1d_buf, double* dbl_2d_buf);
394
395 HEADER_INLINE BoolErr InvertSymmdefMatrixFirstHalf(int32_t dim, int32_t stride, double* matrix, MatrixInvertBuf1* dbl_1d_buf, double* dbl_2d_buf) {
396 ReflectStridedMatrix(dim, stride, matrix);
397 return InvertStridedMatrixFirstHalf(dim, stride, matrix, dbl_1d_buf, dbl_2d_buf);
398 }
399
400 BoolErr InvertFmatrixFirstHalf(int32_t dim, uint32_t stride, const float* matrix, double* half_inverted, MatrixInvertBuf1* dbl_1d_buf, double* dbl_2d_buf);
401
402 HEADER_INLINE BoolErr InvertSymmdefFmatrixFirstHalf(int32_t dim, uint32_t stride, float* matrix, double* half_inverted, MatrixInvertBuf1* dbl_1d_buf, double* dbl_2d_buf) {
403 ReflectFmatrix(dim, stride, matrix);
404 return InvertFmatrixFirstHalf(dim, stride, matrix, half_inverted, dbl_1d_buf, dbl_2d_buf);
405 }
406
407 HEADER_INLINE double HalfInvertedDet(__maybe_unused const double* half_inverted_iter, __maybe_unused const MatrixInvertBuf1* dbl_1d_buf, uint32_t dim) {
408 // singular values in dbl_1d_buf
409 double det_u = dbl_1d_buf[0];
410 for (uint32_t uii = 1; uii != dim; ++uii) {
411 det_u *= dbl_1d_buf[uii];
412 }
413 return fabs(det_u);
414 }
415
416 HEADER_INLINE double HalfSymmInvertedDet(__maybe_unused const double* half_inverted_iter, __maybe_unused const MatrixInvertBuf1* dbl_1d_buf, uint32_t dim, __maybe_unused uint32_t stride) {
417 return HalfInvertedDet(half_inverted_iter, dbl_1d_buf, dim);
418 }
419
420 void InvertStridedMatrixSecondHalf(__CLPK_integer dim, __CLPK_integer stride, double* inverted_result, MatrixInvertBuf1* dbl_1d_buf, double* dbl_2d_buf);
421
422 HEADER_INLINE void InvertSymmdefMatrixSecondHalf(__CLPK_integer dim, __CLPK_integer stride, double* inverted_result, __maybe_unused MatrixInvertBuf1* dbl_1d_buf, __maybe_unused double* dbl_2d_buf) {
423 InvertStridedMatrixSecondHalf(dim, stride, inverted_result, dbl_1d_buf, dbl_2d_buf);
424 }
425
426 void InvertFmatrixSecondHalf(__CLPK_integer dim, uint32_t stride, double* half_inverted, float* inverted_result, MatrixInvertBuf1* dbl_1d_buf, double* dbl_2d_buf);
427
428 HEADER_INLINE void InvertSymmdefFmatrixSecondHalf(__CLPK_integer dim, uint32_t stride, double* half_inverted, float* inverted_result, MatrixInvertBuf1* dbl_1d_buf, double* dbl_2d_buf) {
429 InvertFmatrixSecondHalf(dim, stride, half_inverted, inverted_result, dbl_1d_buf, dbl_2d_buf);
430 }
431
432 HEADER_INLINE BoolErr InvertSymmdefStridedMatrix(__CLPK_integer dim, __CLPK_integer stride, double* matrix, MatrixInvertBuf1* dbl_1d_buf, double* dbl_2d_buf) {
433 if (InvertSymmdefMatrixFirstHalf(dim, stride, matrix, dbl_1d_buf, dbl_2d_buf)) {
434 return 1;
435 }
436 InvertSymmdefMatrixSecondHalf(dim, stride, matrix, dbl_1d_buf, dbl_2d_buf);
437 return 0;
438 }
439
440 #else // !NOLAPACK
441 HEADER_INLINE double DotprodD(const double* vec1, const double* vec2, uint32_t ct) {
442 # ifndef USE_CBLAS_XGEMM
443 __CLPK_integer cti = ct;
444 __CLPK_integer incxy = 1;
445 return ddot_(&cti, K_CAST(double*, vec1), &incxy, K_CAST(double*, vec2), &incxy);
446 # else
447 return cblas_ddot(ct, vec1, 1, vec2, 1);
448 # endif
449 }
450
451 HEADER_INLINE double DotprodxD(const double* vec1, const double* vec2, uint32_t ct) {
452 if (ct > kDotprodDThresh) {
453 // best threshold is machine-dependent; this is what I got on my MacBook
454 return DotprodD(vec1, vec2, ct);
455 }
456 return DotprodDShort(vec1, vec2, ct);
457 }
458
459 // not worthwhile for ct < 16.
460 HEADER_INLINE float DotprodF(const float* vec1, const float* vec2, uint32_t ct) {
461 # ifndef USE_CBLAS_XGEMM
462 __CLPK_integer cti = ct;
463 __CLPK_integer incxy = 1;
464 return S_CAST(float, sdot_(&cti, K_CAST(float*, vec1), &incxy, K_CAST(float*, vec2), &incxy));
465 # else
466 return cblas_sdot(ct, vec1, 1, vec2, 1);
467 # endif
468 }
469
470 // extra if-statement in DotprodxF() seems disproportionally expensive in
471 // test?... guess I won't have auto-branch for now.
472
473 BoolErr InvertMatrix(__CLPK_integer dim, double* matrix, MatrixInvertBuf1* int_1d_buf, double* dbl_2d_buf);
474
475 BoolErr InvertMatrixChecked(__CLPK_integer dim, double* matrix, MatrixInvertBuf1* int_1d_buf, double* dbl_2d_buf);
476
477
478 // InvertSymmdef... functions only assume (C-order) lower left of matrix is
479 // filled, and only the lower left of the return matrix is valid.
480 BoolErr InvertSymmdefMatrix(__CLPK_integer dim, double* matrix, MatrixInvertBuf1* int_1d_buf, double* dbl_2d_buf);
481
482 BoolErr InvertSymmdefStridedMatrix(__CLPK_integer dim, __CLPK_integer stride, double* matrix, MatrixInvertBuf1* int_1d_buf, double* dbl_2d_buf);
483
484 // dbl_2d_buf must have room for at least max(dim, 3) * dim elements.
485 BoolErr InvertSymmdefMatrixChecked(__CLPK_integer dim, double* matrix, MatrixInvertBuf1* int_1d_buf, double* dbl_2d_buf);
486
487 BoolErr InvertSymmdefMatrixFirstHalf(__CLPK_integer dim, __CLPK_integer stride, double* matrix, MatrixInvertBuf1* int_1d_buf, double* dbl_2d_buf);
488
489
490 BoolErr InvertFmatrixFirstHalf(__CLPK_integer dim, uint32_t stride, const float* matrix, double* half_inverted, MatrixInvertBuf1* int_1d_buf, double* dbl_2d_buf);
491
492 BoolErr InvertSymmdefFmatrixFirstHalf(__CLPK_integer dim, uint32_t stride, float* matrix, double* half_inverted, MatrixInvertBuf1* int_1d_buf, double* dbl_2d_buf);
493
494 /*
495 HEADER_INLINE double HalfInvertedDet(__maybe_unused const double* half_inverted_iter, __maybe_unused const MatrixInvertBuf1* int_1d_buf, uint32_t dim) {
496 uint32_t dim_p1 = dim + 1;
497 double det_u = *half_inverted_iter;
498 for (uint32_t uii = 1; uii != dim; ++uii) {
499 half_inverted_iter = &(half_inverted_iter[dim_p1]);
500 det_u *= (*half_inverted_iter);
501 }
502 return fabs(det_u);
503 }
504 */
505
506 HEADER_INLINE double HalfSymmInvertedDet(__maybe_unused const double* half_inverted_iter, __maybe_unused const MatrixInvertBuf1* int_1d_buf, uint32_t dim, uint32_t stride) {
507 uint32_t stride_p1 = stride + 1;
508 double sqrt_det_u = *half_inverted_iter;
509 for (uint32_t uii = 1; uii != dim; ++uii) {
510 half_inverted_iter = &(half_inverted_iter[stride_p1]);
511 sqrt_det_u *= (*half_inverted_iter);
512 }
513 return sqrt_det_u * sqrt_det_u;
514 }
515
516 HEADER_INLINE void InvertSymmdefMatrixSecondHalf(__CLPK_integer dim, __CLPK_integer stride, double* matrix, __maybe_unused MatrixInvertBuf1* int_1d_buf, __maybe_unused double* dbl_2d_buf) {
517 char uplo = 'U';
518 __CLPK_integer info;
519 dpotri_(&uplo, &dim, matrix, &stride, &info);
520 }
521
522 void InvertFmatrixSecondHalf(__CLPK_integer dim, uint32_t stride, double* half_inverted, float* inverted_result, MatrixInvertBuf1* int_1d_buf, double* dbl_2d_buf);
523
524 void InvertSymmdefFmatrixSecondHalf(__CLPK_integer dim, uint32_t stride, double* half_inverted, float* inverted_result, MatrixInvertBuf1* int_1d_buf, double* dbl_2d_buf);
525 #endif // !NOLAPACK
526
527 void ColMajorMatrixMultiply(const double* inmatrix1, const double* inmatrix2, __CLPK_integer row1_ct, __CLPK_integer col2_ct, __CLPK_integer common_ct, double* outmatrix);
528
529 HEADER_INLINE void RowMajorMatrixMultiply(const double* inmatrix1, const double* inmatrix2, __CLPK_integer row1_ct, __CLPK_integer col2_ct, __CLPK_integer common_ct, double* outmatrix) {
530 return ColMajorMatrixMultiply(inmatrix2, inmatrix1, col2_ct, row1_ct, common_ct, outmatrix);
531 }
532
533 // this is essentially a full-blown dgemm wrapper, only missing the alpha
534 // parameter now
535 void ColMajorMatrixMultiplyStridedAddassign(const double* inmatrix1, const double* inmatrix2, __CLPK_integer row1_ct, __CLPK_integer stride1, __CLPK_integer col2_ct, __CLPK_integer stride2, __CLPK_integer common_ct, __CLPK_integer stride3, double beta, double* outmatrix);
536
537 HEADER_INLINE void ColMajorMatrixMultiplyStrided(const double* inmatrix1, const double* inmatrix2, __CLPK_integer row1_ct, __CLPK_integer stride1, __CLPK_integer col2_ct, __CLPK_integer stride2, __CLPK_integer common_ct, __CLPK_integer stride3, double* outmatrix) {
538 ColMajorMatrixMultiplyStridedAddassign(inmatrix1, inmatrix2, row1_ct, stride1, col2_ct, stride2, common_ct, stride3, 0.0, outmatrix);
539 }
540
541 HEADER_INLINE void RowMajorMatrixMultiplyIncr(const double* inmatrix1, const double* inmatrix2, __CLPK_integer row1_ct, __CLPK_integer col2_ct, __CLPK_integer common_ct, double* outmatrix) {
542 return ColMajorMatrixMultiplyStridedAddassign(inmatrix2, inmatrix1, col2_ct, col2_ct, row1_ct, common_ct, common_ct, col2_ct, 1.0, outmatrix);
543 }
544
545 HEADER_INLINE void RowMajorMatrixMultiplyStrided(const double* inmatrix1, const double* inmatrix2, __CLPK_integer row1_ct, __CLPK_integer stride1, __CLPK_integer col2_ct, __CLPK_integer stride2, __CLPK_integer common_ct, __CLPK_integer stride3, double* outmatrix) {
546 // stride1 should be close to common_ct
547 // stride2 should be close to col2_ct
548 // output matrix uses stride3, which should be close to col2_ct
549 return ColMajorMatrixMultiplyStridedAddassign(inmatrix2, inmatrix1, col2_ct, stride2, row1_ct, stride1, common_ct, stride3, 0.0, outmatrix);
550 }
551
552 HEADER_INLINE void RowMajorMatrixMultiplyStridedIncr(const double* inmatrix1, const double* inmatrix2, __CLPK_integer row1_ct, __CLPK_integer stride1, __CLPK_integer col2_ct, __CLPK_integer stride2, __CLPK_integer common_ct, __CLPK_integer stride3, double* outmatrix) {
553 return ColMajorMatrixMultiplyStridedAddassign(inmatrix2, inmatrix1, col2_ct, stride2, row1_ct, stride1, common_ct, stride3, 1.0, outmatrix);
554 }
555
556 // out^T := V^T * M
557 // out := M^T * V
558 void ColMajorVectorMatrixMultiplyStrided(const double* in_dvec1, const double* inmatrix2, __CLPK_integer common_ct, __CLPK_integer stride2, __CLPK_integer col2_ct, double* out_dvec);
559
560 // out := M * V
561 void ColMajorMatrixVectorMultiplyStrided(const double* inmatrix1, const double* in_dvec2, __CLPK_integer row1_ct, __CLPK_integer stride1, __CLPK_integer common_ct, double* out_dvec);
562
563 void ColMajorFmatrixMultiplyStrided(const float* inmatrix1, const float* inmatrix2, __CLPK_integer row1_ct, __CLPK_integer stride1, __CLPK_integer col2_ct, __CLPK_integer stride2, __CLPK_integer common_ct, __CLPK_integer stride3, float* outmatrix);
564
565 HEADER_INLINE void RowMajorFmatrixMultiply(const float* inmatrix1, const float* inmatrix2, __CLPK_integer row1_ct, __CLPK_integer col2_ct, __CLPK_integer common_ct, float* outmatrix) {
566 ColMajorFmatrixMultiplyStrided(inmatrix2, inmatrix1, col2_ct, col2_ct, row1_ct, common_ct, common_ct, col2_ct, outmatrix);
567 }
568
569 // out := M * V
570 void ColMajorFmatrixVectorMultiplyStrided(const float* inmatrix1, const float* in_fvec2, __CLPK_integer row1_ct, __CLPK_integer stride1, __CLPK_integer common_ct, float* out_fvec);
571
572 // out^T := V^T * M
573 // out := M^T * V
574 void ColMajorFvectorMatrixMultiplyStrided(const float* in_fvec1, const float* inmatrix2, __CLPK_integer common_ct, __CLPK_integer stride2, __CLPK_integer col2_ct, float* out_fvec);
575
576 void MatrixTransposeCopy(const double* old_matrix, uint32_t old_maj, uint32_t new_maj, double* new_matrix_iter);
577
578 void FmatrixTransposeCopy(const float* old_matrix, uint32_t old_maj, uint32_t new_maj, uint32_t new_maj_max, float* new_matrix_iter);
579
580
581 // A(A^T), where A is row-major; result is dim x dim
582 // ONLY UPDATES LOWER TRIANGLE OF result[].
583 void MultiplySelfTranspose(const double* input_matrix, uint32_t dim, uint32_t col_ct, double* result);
584
585 void MultiplySelfTransposeStrided(const double* input_matrix, uint32_t dim, uint32_t col_ct, uint32_t stride, double* result);
586
587 void MultiplySelfTransposeStridedF(const float* input_matrix, uint32_t dim, uint32_t col_ct, uint32_t stride, float* result);
588
589
590 // (A^T)A
591 void TransposeMultiplySelfIncr(double* input_part, uint32_t dim, uint32_t partial_row_ct, double* result);
592
593 #ifndef NOLAPACK
594 BoolErr GetSvdRectLwork(uint32_t major_ct, uint32_t minor_ct, __CLPK_integer* lwork_ptr);
595
596 // currently a wrapper for dgesvd_().
597 IntErr SvdRect(uint32_t major_ct, uint32_t minor_ct, __CLPK_integer lwork, double* matrix, double* ss, double* vv, unsigned char* svd_rect_wkspace);
598
599 HEADER_INLINE IntErr SvdRectFused(uint32_t major_ct, uint32_t minor_ct, __CLPK_integer lwork, double* matrix, double* ss, unsigned char* svd_rect_wkspace) {
600 double* work = R_CAST(double*, svd_rect_wkspace);
601 double* vv_buf = &(work[lwork]);
602 return SvdRect(major_ct, minor_ct, lwork, matrix, ss, vv_buf, svd_rect_wkspace);
603 }
604
605 BoolErr GetExtractEigvecsLworks(uint32_t dim, uint32_t pc_ct, __CLPK_integer* lwork_ptr, __CLPK_integer* liwork_ptr, uintptr_t* wkspace_byte_ct_ptr);
606
607 // currently a wrapper for dsyevr_(). Matrix is expected to be
608 // lower-triangular from C's perspective.
609 // reverse_eigvecs is eigenvector-major, but the vectors are in order of
610 // *increasing* eigenvalue.
611 BoolErr ExtractEigvecs(uint32_t dim, uint32_t pc_ct, __CLPK_integer lwork, __CLPK_integer liwork, double* matrix, double* eigvals, double* reverse_eigvecs, unsigned char* extract_eigvecs_wkspace);
612 #endif
613
614 // Computes inverse of
615 // [ A b^T ]
616 // [ b c ]
617 // given precomputed A^{-1} (must be fully filled out, not just lower left).
618 // See e.g.
619 // https://en.wikipedia.org/wiki/Invertible_matrix#Blockwise_inversion .
620 // Only fills lower left of outmatrix.
621 // insert_idx specifies the zero-based row/column number of b/c in outmatrix.
622 BoolErr InvertRank1Symm(const double* a_inv, const double* bb, __CLPK_integer orig_dim, uint32_t insert_idx, double cc, double* __restrict outmatrix, double* __restrict ainv_b_buf);
623
624 // When you only need the diagonal from InvertRank1Symm(). insert_idx
625 // assumed to be orig_dim.
626 BoolErr InvertRank1SymmDiag(const double* a_inv, const double* bb, __CLPK_integer orig_dim, double cc, double* __restrict outdiag, double* __restrict ainv_b_buf);
627
628 // [ A B^T ]
629 // [ B D ]
630 // B is row-major.
631 BoolErr InvertRank2Symm(const double* a_inv, const double* bb, __CLPK_integer orig_dim, __CLPK_integer b_stride, uint32_t insert_idx, double d11, double d12, double d22, double* __restrict outmatrix, double* __restrict b_ainv_buf, double* __restrict s_b_ainv_buf);
632
633 BoolErr InvertRank2SymmDiag(const double* a_inv, const double* bb, __CLPK_integer orig_dim, double d11, double d12, double d22, double* __restrict outdiag, double* __restrict b_ainv_buf, double* __restrict s_b_ainv_buf);
634
635 #ifdef NOLAPACK
636 BoolErr LinearRegressionInvMain(const double* xt_y_phenomaj, uint32_t predictor_ct, uint32_t pheno_ct, double* xtx_inv, double* fitted_coefs_phenomaj, MatrixInvertBuf1* mi_buf, double* dbl_2d_buf);
637 #else
638 BoolErr LinearRegressionInvMain(const double* xt_y_phenomaj, uint32_t predictor_ct, __CLPK_integer pheno_ct, double* xtx_inv, double* fitted_coefs_phenomaj);
639 #endif
640
641 // now assumes xtx_inv is predictors_pmaj * transpose on input
642 HEADER_INLINE BoolErr LinearRegressionInv(const double* pheno_d_pmaj, const double* predictors_pmaj, uint32_t predictor_ct, uint32_t sample_ct, uint32_t pheno_ct, double* xtx_inv, double* fitted_coefs_phenomaj, double* xt_y_phenomaj, __maybe_unused MatrixInvertBuf1* mi_buf, __maybe_unused double* dbl_2d_buf) {
643 // MultiplySelfTranspose(predictors_pmaj, predictor_ct, sample_ct,
644 // xtx_inv);
645 // categorical optimization possible here
646 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
647 RowMajorMatrixMultiply(predictors_pmaj, &(pheno_d_pmaj[pheno_idx * sample_ct]), predictor_ct, 1, sample_ct, &(xt_y_phenomaj[pheno_idx * predictor_ct]));
648 }
649 #ifdef NOLAPACK
650 return LinearRegressionInvMain(xt_y_phenomaj, predictor_ct, pheno_ct, xtx_inv, fitted_coefs_phenomaj, mi_buf, dbl_2d_buf);
651 #else
652 return LinearRegressionInvMain(xt_y_phenomaj, predictor_ct, pheno_ct, xtx_inv, fitted_coefs_phenomaj);
653 #endif
654 }
655
656 HEADER_INLINE BoolErr LinearRegressionDVec(const double* pheno_d, const double* predictors_pmaj, uint32_t predictor_ct, uint32_t sample_ct, double* fitted_coefs, double* xtx_inv_buf, double* xt_y_buf, __maybe_unused MatrixInvertBuf1* mi_buf, __maybe_unused double* dbl_2d_buf) {
657 // categorical optimization possible here
658 const uint32_t sample_ctav = RoundUpPow2(sample_ct, kDoublePerDVec);
659 ColMajorVectorMatrixMultiplyStrided(pheno_d, predictors_pmaj, sample_ct, sample_ctav, predictor_ct, xt_y_buf);
660 MultiplySelfTransposeStrided(predictors_pmaj, predictor_ct, sample_ct, sample_ctav, xtx_inv_buf);
661 #ifdef NOLAPACK
662 return LinearRegressionInvMain(xt_y_buf, predictor_ct, 1, xtx_inv_buf, fitted_coefs, mi_buf, dbl_2d_buf);
663 #else
664 return LinearRegressionInvMain(xt_y_buf, predictor_ct, 1, xtx_inv_buf, fitted_coefs);
665 #endif
666 }
667
668 // just for debugging
669 HEADER_INLINE void PrintVector(const double* vec, uintptr_t ct) {
670 printf("%g", vec[0]);
671 for (uintptr_t ulii = 1; ulii != ct; ++ulii) {
672 printf(" %g", vec[ulii]);
673 }
674 printf("\n");
675 }
676
677 HEADER_INLINE void PrintFvector(const float* vec, uintptr_t ct) {
678 printf("%g", S_CAST(double, vec[0]));
679 for (uintptr_t ulii = 1; ulii != ct; ++ulii) {
680 printf(" %g", S_CAST(double, vec[ulii]));
681 }
682 printf("\n");
683 }
684
685 HEADER_INLINE void PrintSymmMatrix(const double* matrix, uint32_t dim) {
686 for (uint32_t uii = 0; uii != dim; ++uii) {
687 printf("%g", matrix[uii * dim]);
688 for (uint32_t ujj = 1; ujj <= uii; ++ujj) {
689 printf(" %g", matrix[uii * dim + ujj]);
690 }
691 printf("\n");
692 }
693 }
694
695 HEADER_INLINE void PrintSymmFmatrix(const float* matrix, uint32_t dim) {
696 for (uint32_t uii = 0; uii != dim; ++uii) {
697 printf("%g", S_CAST(double, matrix[uii * dim]));
698 for (uint32_t ujj = 1; ujj <= uii; ++ujj) {
699 printf(" %g", S_CAST(double, matrix[uii * dim + ujj]));
700 }
701 printf("\n");
702 }
703 }
704
705 HEADER_INLINE void PrintMatrix(const double* matrix, uintptr_t row_ct, uintptr_t col_ct) {
706 for (uintptr_t ulii = 0; ulii != row_ct; ++ulii) {
707 printf("%g", matrix[ulii * col_ct]);
708 for (uintptr_t uljj = 1; uljj != col_ct; ++uljj) {
709 printf(" %g", matrix[ulii * col_ct + uljj]);
710 }
711 printf("\n");
712 }
713 }
714
715 HEADER_INLINE void PrintStridedMatrix(const double* matrix, uintptr_t row_ct, uintptr_t col_ct, uintptr_t stride) {
716 for (uintptr_t ulii = 0; ulii != row_ct; ++ulii) {
717 printf("%g", matrix[ulii * stride]);
718 for (uintptr_t uljj = 1; uljj != col_ct; ++uljj) {
719 printf(" %g", matrix[ulii * stride + uljj]);
720 }
721 printf("\n");
722 }
723 }
724
725 HEADER_INLINE void PrintFmatrix(const float* matrix, uintptr_t row_ct, uintptr_t col_ct, uintptr_t stride) {
726 for (uintptr_t ulii = 0; ulii != row_ct; ++ulii) {
727 printf("%g", S_CAST(double, matrix[ulii * stride]));
728 for (uintptr_t uljj = 1; uljj != col_ct; ++uljj) {
729 printf(" %g", S_CAST(double, matrix[ulii * stride + uljj]));
730 }
731 printf("\n");
732 }
733 }
734
735 #ifdef __cplusplus
736 } // namespace plink2
737 #endif
738
739 #endif // __PLINK2_MATRIX_H__