├── external ├── Eigen │ ├── Eigen │ ├── src │ │ ├── Core │ │ │ ├── util │ │ │ │ ├── NonMPL2.h │ │ │ │ ├── ReenableStupidWarnings.h │ │ │ │ └── ReshapedHelper.h │ │ │ ├── functors │ │ │ │ └── TernaryFunctors.h │ │ │ ├── arch │ │ │ │ ├── HIP │ │ │ │ │ └── hcc │ │ │ │ │ │ └── math_constants.h │ │ │ │ ├── SVE │ │ │ │ │ ├── MathFunctions.h │ │ │ │ │ └── TypeCasting.h │ │ │ │ ├── Default │ │ │ │ │ └── Settings.h │ │ │ │ ├── AVX512 │ │ │ │ │ └── TypeCasting.h │ │ │ │ ├── GPU │ │ │ │ │ └── TypeCasting.h │ │ │ │ ├── AltiVec │ │ │ │ │ └── MathFunctions.h │ │ │ │ └── SYCL │ │ │ │ │ └── TypeCasting.h │ │ │ ├── DiagonalProduct.h │ │ │ ├── SelfCwiseBinaryOp.h │ │ │ ├── NestByValue.h │ │ │ ├── Swap.h │ │ │ └── Assign.h │ │ ├── misc │ │ │ ├── lapacke_mangling.h │ │ │ ├── RealSvd2x2.h │ │ │ └── Kernel.h │ │ ├── SparseCore │ │ │ ├── SparseFuzzy.h │ │ │ ├── SparseRedux.h │ │ │ └── MappedSparseMatrix.h │ │ ├── SparseLU │ │ │ └── SparseLU_Utils.h │ │ └── StlSupport │ │ │ └── details.h │ ├── Dense │ ├── StdList │ ├── StdDeque │ ├── StdVector │ ├── Householder │ ├── Jacobi │ ├── Sparse │ ├── QtAlignedMalloc │ ├── MetisSupport │ ├── PardisoSupport │ ├── SPQRSupport │ ├── SparseQR │ ├── Cholesky │ ├── SparseCholesky │ ├── LU │ ├── QR │ ├── UmfPackSupport │ ├── KLUSupport │ ├── SVD │ ├── PaStiXSupport │ ├── SparseLU │ ├── Eigenvalues │ ├── CholmodSupport │ ├── Geometry │ ├── IterativeLinearSolvers │ ├── SuperLUSupport │ ├── SparseCore │ └── OrderingMethods ├── zstd │ ├── lib │ │ ├── .gitignore │ │ ├── libzstd.pc.in │ │ ├── common │ │ │ ├── xxhash.c │ │ │ ├── debug.c │ │ │ ├── allocations.h │ │ │ ├── zstd_common.c │ │ │ └── pool.h │ │ ├── dll │ │ │ └── example │ │ │ │ ├── build_package.bat │ │ │ │ ├── fullbench-dll.sln │ │ │ │ └── Makefile │ │ ├── module.modulemap │ │ ├── deprecated │ │ │ ├── zbuff_common.c │ │ │ └── zbuff_decompress.c │ │ ├── compress │ │ │ ├── zstd_fast.h │ │ │ ├── zstd_compress_superblock.h │ │ │ ├── zstd_preSplit.h │ │ │ ├── zstd_compress_literals.h │ │ │ ├── zstd_double_fast.h │ │ │ └── zstd_compress_sequences.h │ │ ├── decompress │ │ │ ├── zstd_ddict.h │ │ │ └── zstd_decompress_block.h │ │ └── dictBuilder │ │ │ └── divsufsort.h │ └── LICENSE ├── bgen │ ├── samples.h │ ├── Makefile │ ├── utils.h │ ├── header.h │ ├── reader.h │ ├── variant.h │ ├── header.cpp │ ├── genotypes.h │ ├── writer.h │ └── samples.cpp ├── Spectra │ ├── Util │ │ ├── Version.h │ │ ├── GEigsMode.h │ │ ├── CompInfo.h │ │ └── TypeTraits.h │ └── MatOp │ │ └── internal │ │ ├── SymGEigsRegInvOp.h │ │ ├── SymGEigsCholeskyOp.h │ │ ├── SymGEigsBucklingOp.h │ │ └── SymGEigsShiftInvertOp.h └── popl │ └── LICENSE ├── PCAone.pdf ├── misc ├── architecture.png └── architecture.org ├── .gitmodules ├── .clang-format ├── src ├── Projection.hpp ├── Arnoldi.hpp ├── Inbreeding.hpp ├── FileBinary.hpp ├── FileUSV.hpp ├── FileUSV.cpp ├── FileBgen.hpp ├── FileBinary.cpp ├── Timer.hpp ├── FileCsv.hpp ├── FileBeagle.hpp ├── FilePlink.hpp ├── Projection.cpp ├── Data.hpp ├── Halko.hpp ├── LD.hpp ├── FileBeagle.cpp ├── Cmd.hpp └── kfunc.h ├── .gitignore ├── .github └── workflows │ ├── mac.yml │ ├── linux.yml │ └── linux_aarch64.yml ├── publish.sh └── scripts ├── common.R ├── calc_decay_bin.R ├── parse_ld_matrix.R ├── summarise_ld_r2bin.cpp └── plot-loadings.R /external/Eigen/Eigen: -------------------------------------------------------------------------------- 1 | #include "Dense" 2 | #include "Sparse" 3 | -------------------------------------------------------------------------------- /PCAone.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zilong-Li/PCAone/HEAD/PCAone.pdf -------------------------------------------------------------------------------- /external/zstd/lib/.gitignore: -------------------------------------------------------------------------------- 1 | # make install artefact 2 | libzstd.pc 3 | libzstd-nomt 4 | -------------------------------------------------------------------------------- /misc/architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zilong-Li/PCAone/HEAD/misc/architecture.png -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "PCAoneR"] 2 | path = PCAoneR 3 | url = https://github.com/Zilong-Li/PCAoneR 4 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/util/NonMPL2.h: -------------------------------------------------------------------------------- 1 | #ifdef EIGEN_MPL2_ONLY 2 | #error Including non-MPL2 code in EIGEN_MPL2_ONLY mode 3 | #endif 4 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | Language: Cpp 2 | Standard: Cpp11 3 | BasedOnStyle: Google 4 | ColumnLimit: 110 -------------------------------------------------------------------------------- /external/Eigen/Dense: -------------------------------------------------------------------------------- 1 | #include "Core" 2 | #include "LU" 3 | #include "Cholesky" 4 | #include "QR" 5 | #include "SVD" 6 | #include "Geometry" 7 | #include "Eigenvalues" 8 | -------------------------------------------------------------------------------- /src/Projection.hpp: -------------------------------------------------------------------------------- 1 | #ifndef PCAone_Projecction_ 2 | #define PCAone_Projecction_ 3 | 4 | #include "Cmd.hpp" 5 | #include "Data.hpp" 6 | 7 | void run_projection(Data* data, const Param& params); 8 | 9 | #endif // PCAone_Projecction_ 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | t.* 2 | example* 3 | *TAGS 4 | GRTAGS 5 | GPATH 6 | .RData 7 | .Rhistory 8 | *.o 9 | *.makefile 10 | external/*/*.a 11 | *.dylib 12 | /external/zstd/lib/*.a 13 | /external/zstd/lib/*.so* 14 | /external/zstd/lib/obj/ 15 | compile_commands.json 16 | .ccls-cache 17 | .cache 18 | log 19 | *tmp 20 | .DS_Store 21 | lib*.a 22 | out.* 23 | test* 24 | run.sh 25 | tutorial 26 | .ccls 27 | plink* 28 | pcaone.* 29 | releases 30 | *.bin 31 | PCAone 32 | adj* 33 | Rplots.pdf 34 | -------------------------------------------------------------------------------- /external/bgen/samples.h: -------------------------------------------------------------------------------- 1 | #ifndef BGEN_SAMPLES_H_ 2 | #define BGEN_SAMPLES_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | namespace bgen { 9 | 10 | class Samples { 11 | public: 12 | Samples(std::ifstream & handle, int n_samples); 13 | Samples(std::string path, int n_samples); 14 | Samples(int n_samples); 15 | Samples() {} 16 | std::vector samples; 17 | }; 18 | 19 | } // namespace bgen 20 | 21 | #endif // BGEN_SAMPLES_H_ 22 | -------------------------------------------------------------------------------- /external/bgen/Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # Makefile to compile bgen library 3 | # 4 | # CXX ?= g++ 5 | 6 | # Platform := $(shell uname -s) 7 | # AVX = 1 8 | # ifeq ($(Platform), Darwin) 9 | # CXXFLAGS += -march=native 10 | # else 11 | # CXXFLAGS += -mavx -mavx2 12 | # endif 13 | 14 | OBJECTS = $(patsubst %.cpp,%.o,$(wildcard *.cpp)) 15 | INC = -I../zstd/lib 16 | 17 | bgenlib.a: $(OBJECTS) 18 | ar -rcs $@ $^ 19 | 20 | %.o: %.cpp 21 | $(CXX) $(CFLAGS) $(CXXFLAGS) -o $@ -c $< $(INC) $(CPPFLAGS) $(LDFLAGS) 22 | 23 | clean: 24 | rm -f *.o *.a 25 | -------------------------------------------------------------------------------- /external/zstd/lib/libzstd.pc.in: -------------------------------------------------------------------------------- 1 | # ZSTD - standard compression algorithm 2 | # Copyright (c) Meta Platforms, Inc. and affiliates. 3 | # BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php) 4 | 5 | prefix=@PREFIX@ 6 | exec_prefix=@EXEC_PREFIX@ 7 | includedir=@INCLUDEDIR@ 8 | libdir=@LIBDIR@ 9 | 10 | Name: zstd 11 | Description: fast lossless compression algorithm library 12 | URL: https://facebook.github.io/zstd/ 13 | Version: @VERSION@ 14 | Libs: -L${libdir} -lzstd @LIBS_MT@ 15 | Libs.private: @LIBS_PRIVATE@ 16 | Cflags: -I${includedir} @LIBS_MT@ 17 | -------------------------------------------------------------------------------- /external/Eigen/src/misc/lapacke_mangling.h: -------------------------------------------------------------------------------- 1 | #ifndef LAPACK_HEADER_INCLUDED 2 | #define LAPACK_HEADER_INCLUDED 3 | 4 | #ifndef LAPACK_GLOBAL 5 | #if defined(LAPACK_GLOBAL_PATTERN_LC) || defined(ADD_) 6 | #define LAPACK_GLOBAL(lcname,UCNAME) lcname##_ 7 | #elif defined(LAPACK_GLOBAL_PATTERN_UC) || defined(UPPER) 8 | #define LAPACK_GLOBAL(lcname,UCNAME) UCNAME 9 | #elif defined(LAPACK_GLOBAL_PATTERN_MC) || defined(NOCHANGE) 10 | #define LAPACK_GLOBAL(lcname,UCNAME) lcname 11 | #else 12 | #define LAPACK_GLOBAL(lcname,UCNAME) lcname##_ 13 | #endif 14 | #endif 15 | 16 | #endif 17 | 18 | -------------------------------------------------------------------------------- /.github/workflows/mac.yml: -------------------------------------------------------------------------------- 1 | name: MacOS 2 | 3 | on: 4 | push: 5 | branches: [ main, dev ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: macOS-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v3 16 | 17 | - name: install dependency 18 | run: brew install libomp wget 19 | 20 | - name: make 21 | run: | 22 | export LDFLAGS="-L"$(brew --prefix libomp)/lib 23 | export CPPFLAGS="-I"$(brew --prefix libomp)/include 24 | make -j4 25 | 26 | - name: test 27 | run: | 28 | make test_full 29 | -------------------------------------------------------------------------------- /external/Spectra/Util/Version.h: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2020-2022 Yixuan Qiu 2 | // 3 | // This Source Code Form is subject to the terms of the Mozilla 4 | // Public License v. 2.0. If a copy of the MPL was not distributed 5 | // with this file, You can obtain one at https://mozilla.org/MPL/2.0/. 6 | 7 | #ifndef SPECTRA_VERSION_H 8 | #define SPECTRA_VERSION_H 9 | 10 | #define SPECTRA_MAJOR_VERSION 1 11 | #define SPECTRA_MINOR_VERSION 0 12 | #define SPECTRA_PATCH_VERSION 1 13 | 14 | #define SPECTRA_VERSION (SPECTRA_MAJOR_VERSION * 10000 + SPECTRA_MINOR_VERSION * 100 + SPECTRA_PATCH_VERSION) 15 | 16 | #endif // SPECTRA_VERSION_H 17 | -------------------------------------------------------------------------------- /.github/workflows/linux.yml: -------------------------------------------------------------------------------- 1 | name: Linux (x86_64) 2 | 3 | on: 4 | push: 5 | branches: [ main, dev] 6 | pull_request: 7 | branches: [ main ] 8 | workflow_dispatch: 9 | 10 | jobs: 11 | build: 12 | name: Build on Linux (x86_64) 13 | runs-on: ubuntu-22.04 14 | 15 | steps: 16 | - name: Checkout repository 17 | uses: actions/checkout@v4 18 | 19 | - name: Install dependencies 20 | run: | 21 | sudo apt-get update 22 | sudo apt-get -y install build-essential libzstd-dev wget 23 | 24 | - name: Build and run full test suite 25 | run: | 26 | make -j4 27 | make test_full 28 | -------------------------------------------------------------------------------- /.github/workflows/linux_aarch64.yml: -------------------------------------------------------------------------------- 1 | name: Linux (AArch64) 2 | 3 | on: 4 | push: 5 | branches: [ main, dev] 6 | pull_request: 7 | branches: [ main ] 8 | workflow_dispatch: 9 | 10 | jobs: 11 | build-aarch64: 12 | name: Build on Linux (AArch64) 13 | runs-on: ubuntu-22.04-arm 14 | steps: 15 | - name: Checkout repository 16 | uses: actions/checkout@v4 17 | 18 | - name: Install dependencies 19 | run: | 20 | sudo apt-get update 21 | sudo apt-get -y install build-essential libzstd-dev zlib1g-dev wget 22 | 23 | - name: Build and run test suite 24 | run: | 25 | make -j4 26 | make test_aarch64 27 | -------------------------------------------------------------------------------- /external/bgen/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef BGEN_UTILS_H_ 2 | #define BGEN_UTILS_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | namespace bgen { 14 | 15 | struct Range { 16 | std::uint8_t _min; 17 | std::uint8_t _max; 18 | }; 19 | 20 | std::uint32_t n_choose_k(int n, int k); 21 | bool minor_certain(double freq, int n_checked, double z); 22 | std::uint64_t fast_ploidy_sum(std::uint8_t * x, std::uint32_t & size); 23 | Range fast_range(std::uint8_t * x, std::uint32_t & size); 24 | 25 | } // namespace bgen 26 | 27 | #endif // BGEN_UTILS_H_ 28 | -------------------------------------------------------------------------------- /external/bgen/header.h: -------------------------------------------------------------------------------- 1 | #ifndef BGEN_HEADER_H_ 2 | #define BGEN_HEADER_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "utils.h" 12 | 13 | namespace bgen { 14 | 15 | class Header { 16 | std::uint32_t header_length; 17 | std::string magic; 18 | public: 19 | Header(std::ifstream & handle); 20 | Header() {} 21 | std::uint32_t offset; 22 | std::uint32_t nvariants; 23 | std::uint32_t nsamples = 5; 24 | int compression; 25 | int layout; 26 | bool has_sample_ids; 27 | std::string extra; 28 | }; 29 | 30 | } // namespace bgen 31 | 32 | #endif // BGEN_HEADER_H_ 33 | -------------------------------------------------------------------------------- /external/zstd/lib/common/xxhash.c: -------------------------------------------------------------------------------- 1 | /* 2 | * xxHash - Extremely Fast Hash algorithm 3 | * Copyright (c) Yann Collet - Meta Platforms, Inc 4 | * 5 | * This source code is licensed under both the BSD-style license (found in the 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | * in the COPYING file in the root directory of this source tree). 8 | * You may select, at your option, one of the above-listed licenses. 9 | */ 10 | 11 | /* 12 | * xxhash.c instantiates functions defined in xxhash.h 13 | */ 14 | 15 | #define XXH_STATIC_LINKING_ONLY /* access advanced declarations */ 16 | #define XXH_IMPLEMENTATION /* access definitions */ 17 | 18 | #include "xxhash.h" 19 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/functors/TernaryFunctors.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2016 Eugene Brevdo 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | #ifndef EIGEN_TERNARY_FUNCTORS_H 11 | #define EIGEN_TERNARY_FUNCTORS_H 12 | 13 | namespace Eigen { 14 | 15 | namespace internal { 16 | 17 | //---------- associative ternary functors ---------- 18 | 19 | 20 | 21 | } // end namespace internal 22 | 23 | } // end namespace Eigen 24 | 25 | #endif // EIGEN_TERNARY_FUNCTORS_H 26 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/arch/HIP/hcc/math_constants.h: -------------------------------------------------------------------------------- 1 | /* 2 | * math_constants.h - 3 | * HIP equivalent of the CUDA header of the same name 4 | */ 5 | 6 | #ifndef __MATH_CONSTANTS_H__ 7 | #define __MATH_CONSTANTS_H__ 8 | 9 | /* single precision constants */ 10 | 11 | #define HIPRT_INF_F __int_as_float(0x7f800000) 12 | #define HIPRT_NAN_F __int_as_float(0x7fffffff) 13 | #define HIPRT_MIN_DENORM_F __int_as_float(0x00000001) 14 | #define HIPRT_MAX_NORMAL_F __int_as_float(0x7f7fffff) 15 | #define HIPRT_NEG_ZERO_F __int_as_float(0x80000000) 16 | #define HIPRT_ZERO_F 0.0f 17 | #define HIPRT_ONE_F 1.0f 18 | 19 | /* double precision constants */ 20 | #define HIPRT_INF __hiloint2double(0x7ff00000, 0x00000000) 21 | #define HIPRT_NAN __hiloint2double(0xfff80000, 0x00000000) 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /external/Eigen/StdList: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2009 Hauke Heibel 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | #ifndef EIGEN_STDLIST_MODULE_H 11 | #define EIGEN_STDLIST_MODULE_H 12 | 13 | #include "Core" 14 | #include 15 | 16 | #if EIGEN_COMP_MSVC && EIGEN_OS_WIN64 && (EIGEN_MAX_STATIC_ALIGN_BYTES<=16) /* MSVC auto aligns up to 16 bytes in 64 bit builds */ 17 | 18 | #define EIGEN_DEFINE_STL_LIST_SPECIALIZATION(...) 19 | 20 | #else 21 | 22 | #include "src/StlSupport/StdList.h" 23 | 24 | #endif 25 | 26 | #endif // EIGEN_STDLIST_MODULE_H 27 | -------------------------------------------------------------------------------- /external/zstd/lib/dll/example/build_package.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | MKDIR bin\dll bin\static bin\example bin\include 3 | COPY tests\fullbench.c bin\example\ 4 | COPY programs\datagen.c bin\example\ 5 | COPY programs\datagen.h bin\example\ 6 | COPY programs\util.h bin\example\ 7 | COPY programs\platform.h bin\example\ 8 | COPY lib\common\mem.h bin\example\ 9 | COPY lib\common\zstd_internal.h bin\example\ 10 | COPY lib\common\error_private.h bin\example\ 11 | COPY lib\common\xxhash.h bin\example\ 12 | COPY lib\libzstd.a bin\static\libzstd_static.lib 13 | COPY lib\dll\libzstd.* bin\dll\ 14 | COPY lib\dll\example\Makefile bin\example\ 15 | COPY lib\dll\example\fullbench-dll.* bin\example\ 16 | COPY lib\dll\example\README.md bin\ 17 | COPY lib\zstd.h bin\include\ 18 | COPY lib\common\zstd_errors.h bin\include\ 19 | COPY lib\dictBuilder\zdict.h bin\include\ 20 | COPY programs\zstd.exe bin\zstd.exe 21 | -------------------------------------------------------------------------------- /external/Eigen/StdDeque: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2009 Gael Guennebaud 5 | // Copyright (C) 2009 Hauke Heibel 6 | // 7 | // This Source Code Form is subject to the terms of the Mozilla 8 | // Public License v. 2.0. If a copy of the MPL was not distributed 9 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 10 | 11 | #ifndef EIGEN_STDDEQUE_MODULE_H 12 | #define EIGEN_STDDEQUE_MODULE_H 13 | 14 | #include "Core" 15 | #include 16 | 17 | #if EIGEN_COMP_MSVC && EIGEN_OS_WIN64 && (EIGEN_MAX_STATIC_ALIGN_BYTES<=16) /* MSVC auto aligns up to 16 bytes in 64 bit builds */ 18 | 19 | #define EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(...) 20 | 21 | #else 22 | 23 | #include "src/StlSupport/StdDeque.h" 24 | 25 | #endif 26 | 27 | #endif // EIGEN_STDDEQUE_MODULE_H 28 | -------------------------------------------------------------------------------- /external/Eigen/StdVector: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2009 Gael Guennebaud 5 | // Copyright (C) 2009 Hauke Heibel 6 | // 7 | // This Source Code Form is subject to the terms of the Mozilla 8 | // Public License v. 2.0. If a copy of the MPL was not distributed 9 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 10 | 11 | #ifndef EIGEN_STDVECTOR_MODULE_H 12 | #define EIGEN_STDVECTOR_MODULE_H 13 | 14 | #include "Core" 15 | #include 16 | 17 | #if EIGEN_COMP_MSVC && EIGEN_OS_WIN64 && (EIGEN_MAX_STATIC_ALIGN_BYTES<=16) /* MSVC auto aligns up to 16 bytes in 64 bit builds */ 18 | 19 | #define EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(...) 20 | 21 | #else 22 | 23 | #include "src/StlSupport/StdVector.h" 24 | 25 | #endif 26 | 27 | #endif // EIGEN_STDVECTOR_MODULE_H 28 | -------------------------------------------------------------------------------- /publish.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # exit immediately if errors 4 | set -e 5 | 6 | version=v`grep "^VERSION" Makefile|cut -c 9-` 7 | 8 | dir=releases/$version 9 | mkdir -p $dir 10 | 11 | platform=$(uname -s) 12 | 13 | if [ $platform == "Darwin" ];then 14 | 15 | echo "Publishing releases on MacOS Silicon"; 16 | export LDFLAGS="-L"$(brew --prefix libomp)/lib 17 | export CPPFLAGS="-I"$(brew --prefix libomp)/include 18 | make clean && make -j6 STATIC=1 && zip PCAone-Mac.zip PCAone PCAone.pdf && mv PCAone-Mac.zip $dir && echo "Publishing PCAone-Mac.zip done"; 19 | 20 | elif [ $platform == "Linux" ];then 21 | 22 | echo "Publishing releases on Linux "; 23 | make clean && make -j6 MKLROOT=/opt/intel/oneapi/mkl/latest ONEAPI_COMPILER=/opt/intel/oneapi/compiler/latest STATIC=1 AVX=1 && zip PCAone-Linux.zip PCAone PCAone.pdf && mv PCAone-Linux.zip $dir && echo "Publishing PCAone-Linux.zip done"; 24 | 25 | fi 26 | 27 | -------------------------------------------------------------------------------- /src/Arnoldi.hpp: -------------------------------------------------------------------------------- 1 | #ifndef PCAONE_ARNOLDI_ 2 | #define PCAONE_ARNOLDI_ 3 | 4 | #include "Data.hpp" 5 | 6 | class ArnoldiOpData { 7 | public: 8 | ArnoldiOpData(Data* data_) : data(data_), n(data_->nsamples) { data->nops = 1; } 9 | 10 | ~ArnoldiOpData() {} 11 | 12 | // The line below is new for spectra v1.0.0 13 | using Scalar = double; 14 | 15 | inline uint64 rows() const { return n; } 16 | inline uint64 cols() const { return n; } 17 | // y = G * G' * x ; data.G is n x m; 18 | void perform_op(const double* x_in, double* y_out) const; 19 | inline void setFlags(bool is_update, bool is_standardize) { 20 | update = is_update; 21 | standardize = is_standardize; 22 | } 23 | 24 | Mat2D U, VT; 25 | Mat1D S; 26 | 27 | private: 28 | Data* data; 29 | const uint64 n; 30 | bool update = false, standardize = false; 31 | }; 32 | 33 | void run_pca_with_arnoldi(Data* data, const Param& params); 34 | 35 | #endif // PCAONE_ARNOLDI_ 36 | -------------------------------------------------------------------------------- /external/Eigen/Householder: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_HOUSEHOLDER_MODULE_H 9 | #define EIGEN_HOUSEHOLDER_MODULE_H 10 | 11 | #include "Core" 12 | 13 | #include "src/Core/util/DisableStupidWarnings.h" 14 | 15 | /** \defgroup Householder_Module Householder module 16 | * This module provides Householder transformations. 17 | * 18 | * \code 19 | * #include 20 | * \endcode 21 | */ 22 | 23 | #include "src/Householder/Householder.h" 24 | #include "src/Householder/HouseholderSequence.h" 25 | #include "src/Householder/BlockHouseholder.h" 26 | 27 | #include "src/Core/util/ReenableStupidWarnings.h" 28 | 29 | #endif // EIGEN_HOUSEHOLDER_MODULE_H 30 | -------------------------------------------------------------------------------- /external/Eigen/Jacobi: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_JACOBI_MODULE_H 9 | #define EIGEN_JACOBI_MODULE_H 10 | 11 | #include "Core" 12 | 13 | #include "src/Core/util/DisableStupidWarnings.h" 14 | 15 | /** \defgroup Jacobi_Module Jacobi module 16 | * This module provides Jacobi and Givens rotations. 17 | * 18 | * \code 19 | * #include 20 | * \endcode 21 | * 22 | * In addition to listed classes, it defines the two following MatrixBase methods to apply a Jacobi or Givens rotation: 23 | * - MatrixBase::applyOnTheLeft() 24 | * - MatrixBase::applyOnTheRight(). 25 | */ 26 | 27 | #include "src/Jacobi/Jacobi.h" 28 | 29 | #include "src/Core/util/ReenableStupidWarnings.h" 30 | 31 | #endif // EIGEN_JACOBI_MODULE_H 32 | 33 | -------------------------------------------------------------------------------- /external/Eigen/Sparse: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_SPARSE_MODULE_H 9 | #define EIGEN_SPARSE_MODULE_H 10 | 11 | /** \defgroup Sparse_Module Sparse meta-module 12 | * 13 | * Meta-module including all related modules: 14 | * - \ref SparseCore_Module 15 | * - \ref OrderingMethods_Module 16 | * - \ref SparseCholesky_Module 17 | * - \ref SparseLU_Module 18 | * - \ref SparseQR_Module 19 | * - \ref IterativeLinearSolvers_Module 20 | * 21 | \code 22 | #include 23 | \endcode 24 | */ 25 | 26 | #include "SparseCore" 27 | #include "OrderingMethods" 28 | #include "SparseCholesky" 29 | #include "SparseLU" 30 | #include "SparseQR" 31 | #include "IterativeLinearSolvers" 32 | 33 | #endif // EIGEN_SPARSE_MODULE_H 34 | 35 | -------------------------------------------------------------------------------- /external/bgen/reader.h: -------------------------------------------------------------------------------- 1 | #ifndef BGEN_READER_H_ 2 | #define BGEN_READER_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include "header.h" 9 | #include "samples.h" 10 | #include "variant.h" 11 | 12 | namespace bgen { 13 | 14 | class CppBgenReader { 15 | public: 16 | CppBgenReader(std::string path, std::string sample_path = "", bool delay_parsing = false); 17 | void parse_all_variants(); 18 | Variant next_var(); 19 | void drop_variants(std::vector indices); 20 | std::vector varids(); 21 | std::vector rsids(); 22 | std::vector chroms(); 23 | std::vector positions(); 24 | Variant & operator[](std::size_t idx) { return variants[idx]; } 25 | Variant & get(std::size_t idx) { return variants[idx]; } 26 | std::vector variants; 27 | Header header; 28 | Samples samples; 29 | std::uint64_t offset; 30 | std::uint64_t fsize; 31 | std::ifstream handle; 32 | }; 33 | 34 | } // namespace bgen 35 | 36 | #endif // BGEN_READER_H_ 37 | -------------------------------------------------------------------------------- /external/zstd/lib/module.modulemap: -------------------------------------------------------------------------------- 1 | module libzstd [extern_c] { 2 | header "zstd.h" 3 | export * 4 | config_macros [exhaustive] \ 5 | /* zstd.h */ \ 6 | ZSTD_STATIC_LINKING_ONLY, \ 7 | ZSTDLIB_VISIBILITY, \ 8 | ZSTDLIB_VISIBLE, \ 9 | ZSTDLIB_HIDDEN, \ 10 | ZSTD_DLL_EXPORT, \ 11 | ZSTDLIB_STATIC_API, \ 12 | ZSTD_DISABLE_DEPRECATE_WARNINGS, \ 13 | ZSTD_CLEVEL_DEFAULT, \ 14 | /* zdict.h */ \ 15 | ZDICT_STATIC_LINKING_ONLY, \ 16 | ZDICTLIB_VISIBLE, \ 17 | ZDICTLIB_HIDDEN, \ 18 | ZDICTLIB_VISIBILITY, \ 19 | ZDICTLIB_STATIC_API, \ 20 | ZDICT_DISABLE_DEPRECATE_WARNINGS, \ 21 | /* zstd_errors.h */ \ 22 | ZSTDERRORLIB_VISIBLE, \ 23 | ZSTDERRORLIB_HIDDEN, \ 24 | ZSTDERRORLIB_VISIBILITY 25 | 26 | module dictbuilder [extern_c] { 27 | header "zdict.h" 28 | export * 29 | } 30 | 31 | module errors [extern_c] { 32 | header "zstd_errors.h" 33 | export * 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /external/Eigen/QtAlignedMalloc: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_QTMALLOC_MODULE_H 9 | #define EIGEN_QTMALLOC_MODULE_H 10 | 11 | #include "Core" 12 | 13 | #if (!EIGEN_MALLOC_ALREADY_ALIGNED) 14 | 15 | #include "src/Core/util/DisableStupidWarnings.h" 16 | 17 | void *qMalloc(std::size_t size) 18 | { 19 | return Eigen::internal::aligned_malloc(size); 20 | } 21 | 22 | void qFree(void *ptr) 23 | { 24 | Eigen::internal::aligned_free(ptr); 25 | } 26 | 27 | void *qRealloc(void *ptr, std::size_t size) 28 | { 29 | void* newPtr = Eigen::internal::aligned_malloc(size); 30 | std::memcpy(newPtr, ptr, size); 31 | Eigen::internal::aligned_free(ptr); 32 | return newPtr; 33 | } 34 | 35 | #include "src/Core/util/ReenableStupidWarnings.h" 36 | 37 | #endif 38 | 39 | #endif // EIGEN_QTMALLOC_MODULE_H 40 | -------------------------------------------------------------------------------- /external/Spectra/Util/GEigsMode.h: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2016-2022 Yixuan Qiu 2 | // 3 | // This Source Code Form is subject to the terms of the Mozilla 4 | // Public License v. 2.0. If a copy of the MPL was not distributed 5 | // with this file, You can obtain one at https://mozilla.org/MPL/2.0/. 6 | 7 | #ifndef SPECTRA_GEIGS_MODE_H 8 | #define SPECTRA_GEIGS_MODE_H 9 | 10 | namespace Spectra { 11 | 12 | /// 13 | /// \ingroup Enumerations 14 | /// 15 | /// The enumeration to specify the mode of generalized eigenvalue solver. 16 | /// 17 | enum class GEigsMode 18 | { 19 | Cholesky, ///< Using Cholesky decomposition to solve generalized eigenvalues. 20 | RegularInverse, ///< Regular inverse mode for generalized eigenvalue solver. 21 | ShiftInvert, ///< Shift-and-invert mode for generalized eigenvalue solver. 22 | Buckling, ///< Buckling mode for generalized eigenvalue solver. 23 | Cayley ///< Cayley transformation mode for generalized eigenvalue solver. 24 | }; 25 | 26 | } // namespace Spectra 27 | 28 | #endif // SPECTRA_GEIGS_MODE_H 29 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/DiagonalProduct.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2008 Gael Guennebaud 5 | // Copyright (C) 2007-2009 Benoit Jacob 6 | // 7 | // This Source Code Form is subject to the terms of the Mozilla 8 | // Public License v. 2.0. If a copy of the MPL was not distributed 9 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 10 | 11 | #ifndef EIGEN_DIAGONALPRODUCT_H 12 | #define EIGEN_DIAGONALPRODUCT_H 13 | 14 | namespace Eigen { 15 | 16 | /** \returns the diagonal matrix product of \c *this by the diagonal matrix \a diagonal. 17 | */ 18 | template 19 | template 20 | EIGEN_DEVICE_FUNC inline const Product 21 | MatrixBase::operator*(const DiagonalBase &a_diagonal) const 22 | { 23 | return Product(derived(),a_diagonal.derived()); 24 | } 25 | 26 | } // end namespace Eigen 27 | 28 | #endif // EIGEN_DIAGONALPRODUCT_H 29 | -------------------------------------------------------------------------------- /external/zstd/lib/deprecated/zbuff_common.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under both the BSD-style license (found in the 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | * in the COPYING file in the root directory of this source tree). 8 | * You may select, at your option, one of the above-listed licenses. 9 | */ 10 | 11 | /*-************************************* 12 | * Dependencies 13 | ***************************************/ 14 | #include "../common/error_private.h" 15 | #include "zbuff.h" 16 | 17 | /*-**************************************** 18 | * ZBUFF Error Management (deprecated) 19 | ******************************************/ 20 | 21 | /*! ZBUFF_isError() : 22 | * tells if a return value is an error code */ 23 | unsigned ZBUFF_isError(size_t errorCode) { return ERR_isError(errorCode); } 24 | /*! ZBUFF_getErrorName() : 25 | * provides error code string from function result (useful for debugging) */ 26 | const char* ZBUFF_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); } 27 | -------------------------------------------------------------------------------- /external/Eigen/MetisSupport: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_METISSUPPORT_MODULE_H 9 | #define EIGEN_METISSUPPORT_MODULE_H 10 | 11 | #include "SparseCore" 12 | 13 | #include "src/Core/util/DisableStupidWarnings.h" 14 | 15 | extern "C" { 16 | #include 17 | } 18 | 19 | 20 | /** \ingroup Support_modules 21 | * \defgroup MetisSupport_Module MetisSupport module 22 | * 23 | * \code 24 | * #include 25 | * \endcode 26 | * This module defines an interface to the METIS reordering package (http://glaros.dtc.umn.edu/gkhome/views/metis). 27 | * It can be used just as any other built-in method as explained in \link OrderingMethods_Module here. \endlink 28 | */ 29 | 30 | 31 | #include "src/MetisSupport/MetisSupport.h" 32 | 33 | #include "src/Core/util/ReenableStupidWarnings.h" 34 | 35 | #endif // EIGEN_METISSUPPORT_MODULE_H 36 | -------------------------------------------------------------------------------- /external/popl/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2015-2016 Johannes Pohl 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /src/Inbreeding.hpp: -------------------------------------------------------------------------------- 1 | #ifndef PCAONE_INBREEDING_ 2 | #define PCAONE_INBREEDING_ 3 | 4 | #include "Cmd.hpp" 5 | #include "Data.hpp" 6 | 7 | // PI is N x M 8 | // GL is (N x 2) x M 9 | // D is Fnew-F 10 | // F is updated as Fnew in-place 11 | void calc_inbreed_coef(Mat1D& D, Mat1D& F, const Mat2D& PI, const Mat2D& GL, const int type, const int size, 12 | const uint start); 13 | 14 | // out of core version 15 | void calc_inbreed_coef_outofcore(Mat1D& D1, Mat1D& F, Data* data, Data* Pi, const Param& params); 16 | 17 | // log-likelihoods test per site 18 | // F is the estimated inbreeding coef 19 | // T is output 20 | void calc_inbreed_site_lrt(Mat1D& T, const Mat1D& F, const Mat2D& PI, const Mat2D& GL, const int type, 21 | const int size, const uint start); 22 | 23 | void write_hwe_per_site(const std::string& fout, const std::string& fbim, const Mat1D& hwe, const Mat1D& lrt, 24 | const Mat1D& coef); 25 | 26 | void run_inbreeding_em(int type, const Mat2D& GL, const Mat2D& PI, const Param& params); 27 | 28 | void run_inbreeding(Data* Pi, const Param& params); 29 | 30 | #endif // PCAONE_INBREEDING_ 31 | -------------------------------------------------------------------------------- /external/bgen/variant.h: -------------------------------------------------------------------------------- 1 | #ifndef BGEN_VARIANT_H_ 2 | #define BGEN_VARIANT_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "genotypes.h" 12 | #include "utils.h" 13 | 14 | namespace bgen { 15 | 16 | class Variant { 17 | Genotypes geno; 18 | std::ifstream * handle; 19 | public: 20 | Variant(std::ifstream * _handle, std::uint64_t & varoffset, int layout, int compression, int expected_n, std::uint64_t fsize); 21 | Variant() {} 22 | int probs_per_sample(); 23 | void alt_dosage(float * dosage); 24 | void minor_allele_dosage(float * dosage); 25 | void probs_1d(float * probs); 26 | bool phased(); 27 | std::uint8_t * ploidy(); 28 | std::vector copy_data(); 29 | std::string minor_allele; 30 | 31 | std::uint64_t offset; 32 | std::uint32_t n_samples; 33 | std::string varid; 34 | std::string rsid; 35 | std::string chrom; 36 | std::uint32_t pos; 37 | std::uint16_t n_alleles; 38 | std::vector alleles; 39 | std::uint64_t next_variant_offset; 40 | }; 41 | 42 | } // namespace bgen 43 | 44 | #endif // BGEN_VARIANT_H_ 45 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/util/ReenableStupidWarnings.h: -------------------------------------------------------------------------------- 1 | #ifdef EIGEN_WARNINGS_DISABLED_2 2 | // "DisableStupidWarnings.h" was included twice recursively: Do not reenable warnings yet! 3 | # undef EIGEN_WARNINGS_DISABLED_2 4 | 5 | #elif defined(EIGEN_WARNINGS_DISABLED) 6 | #undef EIGEN_WARNINGS_DISABLED 7 | 8 | #ifndef EIGEN_PERMANENTLY_DISABLE_STUPID_WARNINGS 9 | #ifdef _MSC_VER 10 | #pragma warning( pop ) 11 | #elif defined __INTEL_COMPILER 12 | #pragma warning pop 13 | #elif defined __clang__ 14 | #pragma clang diagnostic pop 15 | #elif defined __GNUC__ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) 16 | #pragma GCC diagnostic pop 17 | #endif 18 | 19 | #if defined __NVCC__ 20 | // Don't reenable the diagnostic messages, as it turns out these messages need 21 | // to be disabled at the point of the template instantiation (i.e the user code) 22 | // otherwise they'll be triggered by nvcc. 23 | // #pragma diag_default code_is_unreachable 24 | // #pragma diag_default initialization_not_reachable 25 | // #pragma diag_default 2651 26 | // #pragma diag_default 2653 27 | #endif 28 | 29 | #endif 30 | 31 | #endif // EIGEN_WARNINGS_DISABLED 32 | -------------------------------------------------------------------------------- /external/zstd/lib/common/debug.c: -------------------------------------------------------------------------------- 1 | /* ****************************************************************** 2 | * debug 3 | * Part of FSE library 4 | * Copyright (c) Meta Platforms, Inc. and affiliates. 5 | * 6 | * You can contact the author at : 7 | * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy 8 | * 9 | * This source code is licensed under both the BSD-style license (found in the 10 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 11 | * in the COPYING file in the root directory of this source tree). 12 | * You may select, at your option, one of the above-listed licenses. 13 | ****************************************************************** */ 14 | 15 | 16 | /* 17 | * This module only hosts one global variable 18 | * which can be used to dynamically influence the verbosity of traces, 19 | * such as DEBUGLOG and RAWLOG 20 | */ 21 | 22 | #include "debug.h" 23 | 24 | #if !defined(ZSTD_LINUX_KERNEL) || (DEBUGLEVEL>=2) 25 | /* We only use this when DEBUGLEVEL>=2, but we get -Werror=pedantic errors if a 26 | * translation unit is empty. So remove this from Linux kernel builds, but 27 | * otherwise just leave it in. 28 | */ 29 | int g_debuglevel = DEBUGLEVEL; 30 | #endif 31 | -------------------------------------------------------------------------------- /external/Eigen/src/SparseCore/SparseFuzzy.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2008-2014 Gael Guennebaud 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | #ifndef EIGEN_SPARSE_FUZZY_H 11 | #define EIGEN_SPARSE_FUZZY_H 12 | 13 | namespace Eigen { 14 | 15 | template 16 | template 17 | bool SparseMatrixBase::isApprox(const SparseMatrixBase& other, const RealScalar &prec) const 18 | { 19 | const typename internal::nested_eval::type actualA(derived()); 20 | typename internal::conditional::type, 22 | const PlainObject>::type actualB(other.derived()); 23 | 24 | return (actualA - actualB).squaredNorm() <= prec * prec * numext::mini(actualA.squaredNorm(), actualB.squaredNorm()); 25 | } 26 | 27 | } // end namespace Eigen 28 | 29 | #endif // EIGEN_SPARSE_FUZZY_H 30 | -------------------------------------------------------------------------------- /external/Eigen/PardisoSupport: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_PARDISOSUPPORT_MODULE_H 9 | #define EIGEN_PARDISOSUPPORT_MODULE_H 10 | 11 | #include "SparseCore" 12 | 13 | #include "src/Core/util/DisableStupidWarnings.h" 14 | 15 | #include 16 | 17 | /** \ingroup Support_modules 18 | * \defgroup PardisoSupport_Module PardisoSupport module 19 | * 20 | * This module brings support for the Intel(R) MKL PARDISO direct sparse solvers. 21 | * 22 | * \code 23 | * #include 24 | * \endcode 25 | * 26 | * In order to use this module, the MKL headers must be accessible from the include paths, and your binary must be linked to the MKL library and its dependencies. 27 | * See this \ref TopicUsingIntelMKL "page" for more information on MKL-Eigen integration. 28 | * 29 | */ 30 | 31 | #include "src/PardisoSupport/PardisoSupport.h" 32 | 33 | #include "src/Core/util/ReenableStupidWarnings.h" 34 | 35 | #endif // EIGEN_PARDISOSUPPORT_MODULE_H 36 | -------------------------------------------------------------------------------- /src/FileBinary.hpp: -------------------------------------------------------------------------------- 1 | #ifndef FILEBINARY_H_ 2 | #define FILEBINARY_H_ 3 | 4 | #include "Data.hpp" 5 | 6 | class FileBin : public Data { 7 | public: 8 | FileBin(Param ¶ms_) : Data(params_) { 9 | cao.print(tick.date(), "start parsing binary format"); 10 | ifs_bin.open(params.filein, std::ios::in | std::ios::binary); 11 | is_zstd = isZstdCompressed(params.filein.c_str()); 12 | if (is_zstd) { 13 | cao.error("does not support parsing zstd compressed binary fille yet"); 14 | } else { 15 | ifs_bin.read((char *)&nsnps, ibyte); 16 | ifs_bin.read((char *)&nsamples, ibyte); 17 | cao.print(tick.date(), "shape of input matrix (features x samples) is", nsnps, "x", nsamples); 18 | bytes_per_snp = nsamples * ibyte; 19 | } 20 | } 21 | 22 | ~FileBin() override = default; 23 | 24 | void read_all() final; 25 | 26 | // for blockwise 27 | void check_file_offset_first_var() final; 28 | 29 | void read_block_initial(uint64, uint64, bool) final; 30 | 31 | void read_block_update(uint64, uint64, const Mat2D &, const Mat1D &, const Mat2D &, bool) final {} 32 | 33 | private: 34 | std::ifstream ifs_bin; 35 | const uint ibyte = 4; 36 | uint64 bytes_per_snp; 37 | bool is_zstd = false; 38 | }; 39 | 40 | #endif // FILEBINARY_H_ 41 | -------------------------------------------------------------------------------- /external/Eigen/SPQRSupport: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_SPQRSUPPORT_MODULE_H 9 | #define EIGEN_SPQRSUPPORT_MODULE_H 10 | 11 | #include "SparseCore" 12 | 13 | #include "src/Core/util/DisableStupidWarnings.h" 14 | 15 | #include "SuiteSparseQR.hpp" 16 | 17 | /** \ingroup Support_modules 18 | * \defgroup SPQRSupport_Module SuiteSparseQR module 19 | * 20 | * This module provides an interface to the SPQR library, which is part of the suitesparse package. 21 | * 22 | * \code 23 | * #include 24 | * \endcode 25 | * 26 | * In order to use this module, the SPQR headers must be accessible from the include paths, and your binary must be linked to the SPQR library and its dependencies (Cholmod, AMD, COLAMD,...). 27 | * For a cmake based project, you can use our FindSPQR.cmake and FindCholmod.Cmake modules 28 | * 29 | */ 30 | 31 | #include "src/CholmodSupport/CholmodSupport.h" 32 | #include "src/SPQRSupport/SuiteSparseQRSupport.h" 33 | 34 | #endif 35 | -------------------------------------------------------------------------------- /external/zstd/lib/compress/zstd_fast.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under both the BSD-style license (found in the 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | * in the COPYING file in the root directory of this source tree). 8 | * You may select, at your option, one of the above-listed licenses. 9 | */ 10 | 11 | #ifndef ZSTD_FAST_H 12 | #define ZSTD_FAST_H 13 | 14 | #include "../common/mem.h" /* U32 */ 15 | #include "zstd_compress_internal.h" 16 | 17 | void ZSTD_fillHashTable(ZSTD_MatchState_t* ms, 18 | void const* end, ZSTD_dictTableLoadMethod_e dtlm, 19 | ZSTD_tableFillPurpose_e tfp); 20 | size_t ZSTD_compressBlock_fast( 21 | ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], 22 | void const* src, size_t srcSize); 23 | size_t ZSTD_compressBlock_fast_dictMatchState( 24 | ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], 25 | void const* src, size_t srcSize); 26 | size_t ZSTD_compressBlock_fast_extDict( 27 | ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], 28 | void const* src, size_t srcSize); 29 | 30 | #endif /* ZSTD_FAST_H */ 31 | -------------------------------------------------------------------------------- /external/zstd/lib/compress/zstd_compress_superblock.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under both the BSD-style license (found in the 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | * in the COPYING file in the root directory of this source tree). 8 | * You may select, at your option, one of the above-listed licenses. 9 | */ 10 | 11 | #ifndef ZSTD_COMPRESS_ADVANCED_H 12 | #define ZSTD_COMPRESS_ADVANCED_H 13 | 14 | /*-************************************* 15 | * Dependencies 16 | ***************************************/ 17 | 18 | #include "../zstd.h" /* ZSTD_CCtx */ 19 | 20 | /*-************************************* 21 | * Target Compressed Block Size 22 | ***************************************/ 23 | 24 | /* ZSTD_compressSuperBlock() : 25 | * Used to compress a super block when targetCBlockSize is being used. 26 | * The given block will be compressed into multiple sub blocks that are around targetCBlockSize. */ 27 | size_t ZSTD_compressSuperBlock(ZSTD_CCtx* zc, 28 | void* dst, size_t dstCapacity, 29 | void const* src, size_t srcSize, 30 | unsigned lastBlock); 31 | 32 | #endif /* ZSTD_COMPRESS_ADVANCED_H */ 33 | -------------------------------------------------------------------------------- /external/zstd/lib/compress/zstd_preSplit.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under both the BSD-style license (found in the 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | * in the COPYING file in the root directory of this source tree). 8 | * You may select, at your option, one of the above-listed licenses. 9 | */ 10 | 11 | #ifndef ZSTD_PRESPLIT_H 12 | #define ZSTD_PRESPLIT_H 13 | 14 | #include /* size_t */ 15 | 16 | #define ZSTD_SLIPBLOCK_WORKSPACESIZE 8208 17 | 18 | /* ZSTD_splitBlock(): 19 | * @level must be a value between 0 and 4. 20 | * higher levels spend more energy to detect block boundaries. 21 | * @workspace must be aligned for size_t. 22 | * @wkspSize must be at least >= ZSTD_SLIPBLOCK_WORKSPACESIZE 23 | * note: 24 | * For the time being, this function only accepts full 128 KB blocks. 25 | * Therefore, @blockSize must be == 128 KB. 26 | * While this could be extended to smaller sizes in the future, 27 | * it is not yet clear if this would be useful. TBD. 28 | */ 29 | size_t ZSTD_splitBlock(const void* blockStart, size_t blockSize, 30 | int level, 31 | void* workspace, size_t wkspSize); 32 | 33 | #endif /* ZSTD_PRESPLIT_H */ 34 | -------------------------------------------------------------------------------- /external/Eigen/SparseQR: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_SPARSEQR_MODULE_H 9 | #define EIGEN_SPARSEQR_MODULE_H 10 | 11 | #include "SparseCore" 12 | #include "OrderingMethods" 13 | #include "src/Core/util/DisableStupidWarnings.h" 14 | 15 | /** \defgroup SparseQR_Module SparseQR module 16 | * \brief Provides QR decomposition for sparse matrices 17 | * 18 | * This module provides a simplicial version of the left-looking Sparse QR decomposition. 19 | * The columns of the input matrix should be reordered to limit the fill-in during the 20 | * decomposition. Built-in methods (COLAMD, AMD) or external methods (METIS) can be used to this end. 21 | * See the \link OrderingMethods_Module OrderingMethods\endlink module for the list 22 | * of built-in and external ordering methods. 23 | * 24 | * \code 25 | * #include 26 | * \endcode 27 | * 28 | * 29 | */ 30 | 31 | #include "src/SparseCore/SparseColEtree.h" 32 | #include "src/SparseQR/SparseQR.h" 33 | 34 | #include "src/Core/util/ReenableStupidWarnings.h" 35 | 36 | #endif 37 | -------------------------------------------------------------------------------- /external/Eigen/Cholesky: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_CHOLESKY_MODULE_H 9 | #define EIGEN_CHOLESKY_MODULE_H 10 | 11 | #include "Core" 12 | #include "Jacobi" 13 | 14 | #include "src/Core/util/DisableStupidWarnings.h" 15 | 16 | /** \defgroup Cholesky_Module Cholesky module 17 | * 18 | * 19 | * 20 | * This module provides two variants of the Cholesky decomposition for selfadjoint (hermitian) matrices. 21 | * Those decompositions are also accessible via the following methods: 22 | * - MatrixBase::llt() 23 | * - MatrixBase::ldlt() 24 | * - SelfAdjointView::llt() 25 | * - SelfAdjointView::ldlt() 26 | * 27 | * \code 28 | * #include 29 | * \endcode 30 | */ 31 | 32 | #include "src/Cholesky/LLT.h" 33 | #include "src/Cholesky/LDLT.h" 34 | #ifdef EIGEN_USE_LAPACKE 35 | #ifdef EIGEN_USE_MKL 36 | #include "mkl_lapacke.h" 37 | #else 38 | #include "src/misc/lapacke.h" 39 | #endif 40 | #include "src/Cholesky/LLT_LAPACKE.h" 41 | #endif 42 | 43 | #include "src/Core/util/ReenableStupidWarnings.h" 44 | 45 | #endif // EIGEN_CHOLESKY_MODULE_H 46 | -------------------------------------------------------------------------------- /external/Spectra/Util/CompInfo.h: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2016-2022 Yixuan Qiu 2 | // 3 | // This Source Code Form is subject to the terms of the Mozilla 4 | // Public License v. 2.0. If a copy of the MPL was not distributed 5 | // with this file, You can obtain one at https://mozilla.org/MPL/2.0/. 6 | 7 | #ifndef SPECTRA_COMP_INFO_H 8 | #define SPECTRA_COMP_INFO_H 9 | 10 | namespace Spectra { 11 | 12 | /// 13 | /// \ingroup Enumerations 14 | /// 15 | /// The enumeration to report the status of computation. 16 | /// 17 | enum class CompInfo 18 | { 19 | Successful, ///< Computation was successful. 20 | 21 | NotComputed, ///< Used in eigen solvers, indicating that computation 22 | ///< has not been conducted. Users should call 23 | ///< the `compute()` member function of solvers. 24 | 25 | NotConverging, ///< Used in eigen solvers, indicating that some eigenvalues 26 | ///< did not converge. The `compute()` 27 | ///< function returns the number of converged eigenvalues. 28 | 29 | NumericalIssue ///< Used in various matrix factorization classes, for example in 30 | ///< Cholesky decomposition it indicates that the 31 | ///< matrix is not positive definite. 32 | }; 33 | 34 | } // namespace Spectra 35 | 36 | #endif // SPECTRA_COMP_INFO_H 37 | -------------------------------------------------------------------------------- /external/zstd/lib/dll/example/fullbench-dll.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 12.00 2 | # Visual Studio Express 2012 for Windows Desktop 3 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench-dll", "fullbench-dll.vcxproj", "{13992FD2-077E-4954-B065-A428198201A9}" 4 | EndProject 5 | Global 6 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 7 | Debug|Win32 = Debug|Win32 8 | Debug|x64 = Debug|x64 9 | Release|Win32 = Release|Win32 10 | Release|x64 = Release|x64 11 | EndGlobalSection 12 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 13 | {13992FD2-077E-4954-B065-A428198201A9}.Debug|Win32.ActiveCfg = Debug|Win32 14 | {13992FD2-077E-4954-B065-A428198201A9}.Debug|Win32.Build.0 = Debug|Win32 15 | {13992FD2-077E-4954-B065-A428198201A9}.Debug|x64.ActiveCfg = Debug|x64 16 | {13992FD2-077E-4954-B065-A428198201A9}.Debug|x64.Build.0 = Debug|x64 17 | {13992FD2-077E-4954-B065-A428198201A9}.Release|Win32.ActiveCfg = Release|Win32 18 | {13992FD2-077E-4954-B065-A428198201A9}.Release|Win32.Build.0 = Release|Win32 19 | {13992FD2-077E-4954-B065-A428198201A9}.Release|x64.ActiveCfg = Release|x64 20 | {13992FD2-077E-4954-B065-A428198201A9}.Release|x64.Build.0 = Release|x64 21 | EndGlobalSection 22 | GlobalSection(SolutionProperties) = preSolution 23 | HideSolutionNode = FALSE 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /external/Eigen/SparseCholesky: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2008-2013 Gael Guennebaud 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | #ifndef EIGEN_SPARSECHOLESKY_MODULE_H 11 | #define EIGEN_SPARSECHOLESKY_MODULE_H 12 | 13 | #include "SparseCore" 14 | #include "OrderingMethods" 15 | 16 | #include "src/Core/util/DisableStupidWarnings.h" 17 | 18 | /** 19 | * \defgroup SparseCholesky_Module SparseCholesky module 20 | * 21 | * This module currently provides two variants of the direct sparse Cholesky decomposition for selfadjoint (hermitian) matrices. 22 | * Those decompositions are accessible via the following classes: 23 | * - SimplicialLLt, 24 | * - SimplicialLDLt 25 | * 26 | * Such problems can also be solved using the ConjugateGradient solver from the IterativeLinearSolvers module. 27 | * 28 | * \code 29 | * #include 30 | * \endcode 31 | */ 32 | 33 | #include "src/SparseCholesky/SimplicialCholesky.h" 34 | #include "src/SparseCholesky/SimplicialCholesky_impl.h" 35 | #include "src/Core/util/ReenableStupidWarnings.h" 36 | 37 | #endif // EIGEN_SPARSECHOLESKY_MODULE_H 38 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/arch/SVE/MathFunctions.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2020, Arm Limited and Contributors 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | #ifndef EIGEN_MATH_FUNCTIONS_SVE_H 11 | #define EIGEN_MATH_FUNCTIONS_SVE_H 12 | 13 | namespace Eigen { 14 | namespace internal { 15 | 16 | template <> 17 | EIGEN_STRONG_INLINE EIGEN_UNUSED PacketXf pexp(const PacketXf& x) { 18 | return pexp_float(x); 19 | } 20 | 21 | template <> 22 | EIGEN_STRONG_INLINE EIGEN_UNUSED PacketXf plog(const PacketXf& x) { 23 | return plog_float(x); 24 | } 25 | 26 | template <> 27 | EIGEN_STRONG_INLINE EIGEN_UNUSED PacketXf psin(const PacketXf& x) { 28 | return psin_float(x); 29 | } 30 | 31 | template <> 32 | EIGEN_STRONG_INLINE EIGEN_UNUSED PacketXf pcos(const PacketXf& x) { 33 | return pcos_float(x); 34 | } 35 | 36 | // Hyperbolic Tangent function. 37 | template <> 38 | EIGEN_STRONG_INLINE EIGEN_UNUSED PacketXf ptanh(const PacketXf& x) { 39 | return internal::generic_fast_tanh_float(x); 40 | } 41 | } // end namespace internal 42 | } // end namespace Eigen 43 | 44 | #endif // EIGEN_MATH_FUNCTIONS_SVE_H 45 | -------------------------------------------------------------------------------- /src/FileUSV.hpp: -------------------------------------------------------------------------------- 1 | #ifndef PCAONE_FILEUSV 2 | #define PCAONE_FILEUSV 3 | 4 | #include "Data.hpp" 5 | 6 | // To get \Pi mainly 7 | class FileUSV : public Data { 8 | public: 9 | FileUSV(const Param ¶ms_) : Data(params_) { 10 | cao.print(tick.date(), "start parsing U:", params.fileU, ", S:", params.fileS, ", V:", params.fileV); 11 | read_sigvals(params.fileS, nsamples, nsnps, S); // could not structual bindings 12 | if (S.size() != params.k) cao.warn("the value of -k not equal the number of rows in " + params.fileS); 13 | K = fmin(S.size(), params.k); 14 | cao.print(tick.date(), "start parsing mbim and read allele frequency of SNPs from", params.filebim); 15 | F = read_frq(params.filebim); 16 | if (F.size() != nsnps) cao.error("the number of sites in mbim not matching the header line of .sigvals"); 17 | cao.print(tick.date(), "N (# samples):", nsamples, ", M (# SNPs):", nsnps); 18 | V = read_eigvecs(params.fileV, nsnps, K); 19 | U = read_eigvecs(params.fileU, nsamples, K); 20 | } 21 | 22 | ~FileUSV() override = default; 23 | 24 | void read_all() final; 25 | 26 | // for blockwise 27 | void check_file_offset_first_var() final {} 28 | 29 | void read_block_initial(uint64, uint64, bool) final; 30 | 31 | void read_block_update(uint64, uint64, const Mat2D &, const Mat1D &, const Mat2D &, bool) final {} 32 | 33 | private: 34 | int K; 35 | Mat1D S; 36 | Mat2D U, V; 37 | }; 38 | 39 | #endif // PCAONE_FILEUSV 40 | -------------------------------------------------------------------------------- /external/Eigen/LU: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_LU_MODULE_H 9 | #define EIGEN_LU_MODULE_H 10 | 11 | #include "Core" 12 | 13 | #include "src/Core/util/DisableStupidWarnings.h" 14 | 15 | /** \defgroup LU_Module LU module 16 | * This module includes %LU decomposition and related notions such as matrix inversion and determinant. 17 | * This module defines the following MatrixBase methods: 18 | * - MatrixBase::inverse() 19 | * - MatrixBase::determinant() 20 | * 21 | * \code 22 | * #include 23 | * \endcode 24 | */ 25 | 26 | #include "src/misc/Kernel.h" 27 | #include "src/misc/Image.h" 28 | #include "src/LU/FullPivLU.h" 29 | #include "src/LU/PartialPivLU.h" 30 | #ifdef EIGEN_USE_LAPACKE 31 | #ifdef EIGEN_USE_MKL 32 | #include "mkl_lapacke.h" 33 | #else 34 | #include "src/misc/lapacke.h" 35 | #endif 36 | #include "src/LU/PartialPivLU_LAPACKE.h" 37 | #endif 38 | #include "src/LU/Determinant.h" 39 | #include "src/LU/InverseImpl.h" 40 | 41 | #if defined EIGEN_VECTORIZE_SSE || defined EIGEN_VECTORIZE_NEON 42 | #include "src/LU/arch/InverseSize4.h" 43 | #endif 44 | 45 | #include "src/Core/util/ReenableStupidWarnings.h" 46 | 47 | #endif // EIGEN_LU_MODULE_H 48 | -------------------------------------------------------------------------------- /external/Eigen/QR: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_QR_MODULE_H 9 | #define EIGEN_QR_MODULE_H 10 | 11 | #include "Core" 12 | 13 | #include "Cholesky" 14 | #include "Jacobi" 15 | #include "Householder" 16 | 17 | #include "src/Core/util/DisableStupidWarnings.h" 18 | 19 | /** \defgroup QR_Module QR module 20 | * 21 | * 22 | * 23 | * This module provides various QR decompositions 24 | * This module also provides some MatrixBase methods, including: 25 | * - MatrixBase::householderQr() 26 | * - MatrixBase::colPivHouseholderQr() 27 | * - MatrixBase::fullPivHouseholderQr() 28 | * 29 | * \code 30 | * #include 31 | * \endcode 32 | */ 33 | 34 | #include "src/QR/HouseholderQR.h" 35 | #include "src/QR/FullPivHouseholderQR.h" 36 | #include "src/QR/ColPivHouseholderQR.h" 37 | #include "src/QR/CompleteOrthogonalDecomposition.h" 38 | #ifdef EIGEN_USE_LAPACKE 39 | #ifdef EIGEN_USE_MKL 40 | #include "mkl_lapacke.h" 41 | #else 42 | #include "src/misc/lapacke.h" 43 | #endif 44 | #include "src/QR/HouseholderQR_LAPACKE.h" 45 | #include "src/QR/ColPivHouseholderQR_LAPACKE.h" 46 | #endif 47 | 48 | #include "src/Core/util/ReenableStupidWarnings.h" 49 | 50 | #endif // EIGEN_QR_MODULE_H 51 | -------------------------------------------------------------------------------- /external/bgen/header.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "header.h" 8 | 9 | namespace bgen { 10 | 11 | Header::Header(std::ifstream & handle) { 12 | handle.seekg(0); 13 | char buff[20]; 14 | handle.read(&buff[0], 20); 15 | 16 | offset = *reinterpret_cast(&buff[0]); 17 | header_length = *reinterpret_cast(&buff[4]); 18 | nvariants = *reinterpret_cast(&buff[8]); 19 | nsamples = *reinterpret_cast(&buff[12]); 20 | magic = std::string(&buff[16], 4); 21 | 22 | // make sure we are reading a bgen file 23 | if ((magic != "bgen") && ((int) (magic[0] & magic[1] & magic[2] & magic[3]) != 0)) { 24 | throw std::invalid_argument("doesn't appear to be a bgen file"); 25 | } 26 | 27 | // read any extra data contained in the header 28 | int size = header_length - 20; 29 | if (size > 0) { 30 | extra.resize(size); 31 | handle.read(&extra[0], size); 32 | } 33 | 34 | // read flags data 35 | std::bitset<32> flags; 36 | handle.read(reinterpret_cast(&flags), sizeof(std::uint32_t)); 37 | 38 | std::bitset<32> compr_mask(0b000000000000000000000000000011); 39 | std::bitset<32> layout_mask(0b000000000000000000000000111100); 40 | compression = (int) (flags & compr_mask).to_ulong(); 41 | layout = (int) ((flags & layout_mask) >> 2).to_ulong(); 42 | has_sample_ids = flags[31]; 43 | } 44 | 45 | } // namespace bgen 46 | -------------------------------------------------------------------------------- /external/zstd/lib/decompress/zstd_ddict.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under both the BSD-style license (found in the 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | * in the COPYING file in the root directory of this source tree). 8 | * You may select, at your option, one of the above-listed licenses. 9 | */ 10 | 11 | 12 | #ifndef ZSTD_DDICT_H 13 | #define ZSTD_DDICT_H 14 | 15 | /*-******************************************************* 16 | * Dependencies 17 | *********************************************************/ 18 | #include "../common/zstd_deps.h" /* size_t */ 19 | #include "../zstd.h" /* ZSTD_DDict, and several public functions */ 20 | 21 | 22 | /*-******************************************************* 23 | * Interface 24 | *********************************************************/ 25 | 26 | /* note: several prototypes are already published in `zstd.h` : 27 | * ZSTD_createDDict() 28 | * ZSTD_createDDict_byReference() 29 | * ZSTD_createDDict_advanced() 30 | * ZSTD_freeDDict() 31 | * ZSTD_initStaticDDict() 32 | * ZSTD_sizeof_DDict() 33 | * ZSTD_estimateDDictSize() 34 | * ZSTD_getDictID_fromDict() 35 | */ 36 | 37 | const void* ZSTD_DDict_dictContent(const ZSTD_DDict* ddict); 38 | size_t ZSTD_DDict_dictSize(const ZSTD_DDict* ddict); 39 | 40 | void ZSTD_copyDDictParameters(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); 41 | 42 | 43 | 44 | #endif /* ZSTD_DDICT_H */ 45 | -------------------------------------------------------------------------------- /external/Eigen/UmfPackSupport: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_UMFPACKSUPPORT_MODULE_H 9 | #define EIGEN_UMFPACKSUPPORT_MODULE_H 10 | 11 | #include "SparseCore" 12 | 13 | #include "src/Core/util/DisableStupidWarnings.h" 14 | 15 | extern "C" { 16 | #include 17 | } 18 | 19 | /** \ingroup Support_modules 20 | * \defgroup UmfPackSupport_Module UmfPackSupport module 21 | * 22 | * This module provides an interface to the UmfPack library which is part of the suitesparse package. 23 | * It provides the following factorization class: 24 | * - class UmfPackLU: a multifrontal sequential LU factorization. 25 | * 26 | * \code 27 | * #include 28 | * \endcode 29 | * 30 | * In order to use this module, the umfpack headers must be accessible from the include paths, and your binary must be linked to the umfpack library and its dependencies. 31 | * The dependencies depend on how umfpack has been compiled. 32 | * For a cmake based project, you can use our FindUmfPack.cmake module to help you in this task. 33 | * 34 | */ 35 | 36 | #include "src/UmfPackSupport/UmfPackSupport.h" 37 | 38 | #include "src/Core/util/ReenableStupidWarnings.h" 39 | 40 | #endif // EIGEN_UMFPACKSUPPORT_MODULE_H 41 | -------------------------------------------------------------------------------- /external/Eigen/KLUSupport: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_KLUSUPPORT_MODULE_H 9 | #define EIGEN_KLUSUPPORT_MODULE_H 10 | 11 | #include 12 | 13 | #include 14 | 15 | extern "C" { 16 | #include 17 | #include 18 | } 19 | 20 | /** \ingroup Support_modules 21 | * \defgroup KLUSupport_Module KLUSupport module 22 | * 23 | * This module provides an interface to the KLU library which is part of the suitesparse package. 24 | * It provides the following factorization class: 25 | * - class KLU: a sparse LU factorization, well-suited for circuit simulation. 26 | * 27 | * \code 28 | * #include 29 | * \endcode 30 | * 31 | * In order to use this module, the klu and btf headers must be accessible from the include paths, and your binary must be linked to the klu library and its dependencies. 32 | * The dependencies depend on how umfpack has been compiled. 33 | * For a cmake based project, you can use our FindKLU.cmake module to help you in this task. 34 | * 35 | */ 36 | 37 | #include "src/KLUSupport/KLUSupport.h" 38 | 39 | #include 40 | 41 | #endif // EIGEN_KLUSUPPORT_MODULE_H 42 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/arch/SVE/TypeCasting.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2020, Arm Limited and Contributors 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | #ifndef EIGEN_TYPE_CASTING_SVE_H 11 | #define EIGEN_TYPE_CASTING_SVE_H 12 | 13 | namespace Eigen { 14 | namespace internal { 15 | 16 | template <> 17 | struct type_casting_traits { 18 | enum { VectorizedCast = 1, SrcCoeffRatio = 1, TgtCoeffRatio = 1 }; 19 | }; 20 | 21 | template <> 22 | struct type_casting_traits { 23 | enum { VectorizedCast = 1, SrcCoeffRatio = 1, TgtCoeffRatio = 1 }; 24 | }; 25 | 26 | template <> 27 | EIGEN_STRONG_INLINE PacketXf pcast(const PacketXi& a) { 28 | return svcvt_f32_s32_z(svptrue_b32(), a); 29 | } 30 | 31 | template <> 32 | EIGEN_STRONG_INLINE PacketXi pcast(const PacketXf& a) { 33 | return svcvt_s32_f32_z(svptrue_b32(), a); 34 | } 35 | 36 | template <> 37 | EIGEN_STRONG_INLINE PacketXf preinterpret(const PacketXi& a) { 38 | return svreinterpret_f32_s32(a); 39 | } 40 | 41 | template <> 42 | EIGEN_STRONG_INLINE PacketXi preinterpret(const PacketXf& a) { 43 | return svreinterpret_s32_f32(a); 44 | } 45 | 46 | } // namespace internal 47 | } // namespace Eigen 48 | 49 | #endif // EIGEN_TYPE_CASTING_SVE_H 50 | -------------------------------------------------------------------------------- /external/zstd/LICENSE: -------------------------------------------------------------------------------- 1 | BSD License 2 | 3 | For Zstandard software 4 | 5 | Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. 6 | 7 | Redistribution and use in source and binary forms, with or without modification, 8 | are permitted provided that the following conditions are met: 9 | 10 | * Redistributions of source code must retain the above copyright notice, this 11 | list of conditions and the following disclaimer. 12 | 13 | * Redistributions in binary form must reproduce the above copyright notice, 14 | this list of conditions and the following disclaimer in the documentation 15 | and/or other materials provided with the distribution. 16 | 17 | * Neither the name Facebook, nor Meta, nor the names of its contributors may 18 | be used to endorse or promote products derived from this software without 19 | specific prior written permission. 20 | 21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 22 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 23 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 24 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 25 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 26 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 27 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 28 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 30 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/util/ReshapedHelper.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2017 Gael Guennebaud 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | 11 | #ifndef EIGEN_RESHAPED_HELPER_H 12 | #define EIGEN_RESHAPED_HELPER_H 13 | 14 | namespace Eigen { 15 | 16 | enum AutoSize_t { AutoSize }; 17 | const int AutoOrder = 2; 18 | 19 | namespace internal { 20 | 21 | template 22 | struct get_compiletime_reshape_size { 23 | enum { value = get_fixed_value::value }; 24 | }; 25 | 26 | template 27 | Index get_runtime_reshape_size(SizeType size, Index /*other*/, Index /*total*/) { 28 | return internal::get_runtime_value(size); 29 | } 30 | 31 | template 32 | struct get_compiletime_reshape_size { 33 | enum { 34 | other_size = get_fixed_value::value, 35 | value = (TotalSize==Dynamic || other_size==Dynamic) ? Dynamic : TotalSize / other_size }; 36 | }; 37 | 38 | inline Index get_runtime_reshape_size(AutoSize_t /*size*/, Index other, Index total) { 39 | return total/other; 40 | } 41 | 42 | template 43 | struct get_compiletime_reshape_order { 44 | enum { value = Order == AutoOrder ? Flags & RowMajorBit : Order }; 45 | }; 46 | 47 | } 48 | 49 | } // end namespace Eigen 50 | 51 | #endif // EIGEN_RESHAPED_HELPER_H 52 | -------------------------------------------------------------------------------- /external/zstd/lib/dll/example/Makefile: -------------------------------------------------------------------------------- 1 | # ################################################################ 2 | # Copyright (c) Meta Platforms, Inc. and affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under both the BSD-style license (found in the 6 | # LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | # in the COPYING file in the root directory of this source tree). 8 | # You may select, at your option, one of the above-listed licenses. 9 | # ################################################################ 10 | 11 | VOID := /dev/null 12 | ZSTDDIR := ../include 13 | LIBDIR := ../static 14 | DLLDIR := ../dll 15 | 16 | CFLAGS ?= -O3 # can select custom flags. For example : CFLAGS="-O2 -g" make 17 | CFLAGS += -Wall -Wextra -Wundef -Wcast-qual -Wcast-align -Wshadow -Wswitch-enum \ 18 | -Wdeclaration-after-statement -Wstrict-prototypes \ 19 | -Wpointer-arith -Wstrict-aliasing=1 20 | CFLAGS += $(MOREFLAGS) 21 | CPPFLAGS:= -I$(ZSTDDIR) -DXXH_NAMESPACE=ZSTD_ 22 | FLAGS := $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) 23 | 24 | 25 | # Define *.exe as extension for Windows systems 26 | ifneq (,$(filter Windows%,$(OS))) 27 | EXT =.exe 28 | else 29 | EXT = 30 | endif 31 | 32 | .PHONY: default fullbench-dll fullbench-lib 33 | 34 | 35 | default: all 36 | 37 | all: fullbench-dll fullbench-lib 38 | 39 | 40 | fullbench-lib: fullbench.c datagen.c 41 | $(CC) $(FLAGS) $^ -o $@$(EXT) $(LIBDIR)/libzstd_static.lib 42 | 43 | fullbench-dll: fullbench.c datagen.c 44 | $(CC) $(FLAGS) $^ -o $@$(EXT) -DZSTD_DLL_IMPORT=1 $(DLLDIR)/libzstd.dll 45 | 46 | clean: 47 | @$(RM) fullbench-dll$(EXT) fullbench-lib$(EXT) \ 48 | @echo Cleaning completed 49 | -------------------------------------------------------------------------------- /misc/architecture.org: -------------------------------------------------------------------------------- 1 | #+title: Overview 2 | 3 | * Test fonts 4 | 5 | #+begin_src plantuml :file font.png 6 | @startuml 7 | listfonts 8 | @enduml 9 | #+end_src 10 | 11 | #+RESULTS: 12 | [[file:font.png]] 13 | 14 | * UML 15 | 16 | generated by plantuml-1.2024.4.jar 17 | 18 | #+begin_src plantuml :file architecture.png 19 | skinparam dpi 300 20 | skinparam defaultFontName FiraCode Nerd Font Med 21 | skinparam groupInheritance 2 22 | skinparam packageStyle rectangle 23 | hide empty fields 24 | hide empty members 25 | abstract class Data { 26 | -Matrix A 27 | +void {abstract} read_all() 28 | +void {abstract} read_block() 29 | } 30 | Data <|-- FilePlink 31 | Data <|-- FileBeagle 32 | Data <|-- FileBgen 33 | Data <|-- FileCSV 34 | Data <|-- OtherFormats 35 | class FilePlink { 36 | +normalization() 37 | } 38 | class FileBeagle { 39 | +normalization() 40 | } 41 | class FileBgen { 42 | +normalization() 43 | } 44 | class FileCSV { 45 | +normalization() 46 | } 47 | class OtherFormats { 48 | +normalization() 49 | } 50 | package "PCA methods" as PCA { 51 | class PCAone { 52 | +InCore 53 | +OutOfCore 54 | } 55 | class IRAM { 56 | +InCore 57 | +OutOfCore 58 | } 59 | class RSVD { 60 | +InCore 61 | +OutOfCore 62 | } 63 | class FullSVD { 64 | +InCore 65 | } 66 | } 67 | 68 | class "PCA Related" as PCAem { 69 | +EMU 70 | +PCAngsd 71 | +Projection 72 | +LD 73 | +HWE 74 | } 75 | FullSVD <-- Data: <:astonished:> 76 | IRAM <-- Data: <:smile:> 77 | RSVD <-- Data: <:nerd_face:> 78 | PCAone <-- Data: <:sunglasses:> 79 | PCA -left-> PCAem 80 | Data -left[dashed]-> PCAem: <:boom:> 81 | #+end_src 82 | 83 | #+RESULTS: 84 | [[file:architecture.png]] 85 | 86 | 87 | -------------------------------------------------------------------------------- /src/FileUSV.cpp: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * @file https://github.com/Zilong-Li/PCAone/src/FileUSV.cpp 3 | * @author Zilong Li 4 | * Copyright (C) 2024. Use of this code is governed by the LICENSE file. 5 | ******************************************************************************/ 6 | 7 | #include "FileUSV.hpp" 8 | 9 | using namespace std; 10 | 11 | void FileUSV::read_all() { 12 | G = U * S.asDiagonal() * V.transpose(); 13 | if (params.inbreed) { 14 | // get \PI and store it in G 15 | #pragma omp parallel for 16 | for (int i = 0; i < G.cols(); i++) { 17 | for (int j = 0; j < G.rows(); j++) { 18 | G(j, i) = (G(j, i) + 2.0 * F(i)) * 0.5; 19 | G(j, i) = fmin(fmax(G(j, i), 1e-4), 1.0 - 1e-4); 20 | } 21 | } 22 | } 23 | } 24 | 25 | // get a block 26 | // NOTE: sanity check if blocks are continuous 27 | void FileUSV::read_block_initial(uint64 start_idx, uint64 stop_idx, bool standardize) { 28 | uint actual_block_size = stop_idx - start_idx + 1; 29 | if (G.cols() < blocksize || (actual_block_size < blocksize)) { 30 | G = Mat2D::Zero(nsamples, actual_block_size); 31 | } 32 | #pragma omp parallel for 33 | for (uint i = 0; i < actual_block_size; ++i) { 34 | uint64 snp_idx = start_idx + i; 35 | for (uint j = 0; j < nsamples; j++) { 36 | G(j, i) = 0.0; 37 | for (int k = 0; k < K; ++k) { 38 | G(j, i) += U(j, k) * S(k) * V(snp_idx, k); 39 | } 40 | if (params.inbreed) { 41 | // map to domain 42 | G(j, i) = (G(j, i) + 2.0 * F(snp_idx)) * 0.5; 43 | G(j, i) = fmin(fmax(G(j, i), 1e-4), 1.0 - 1e-4); 44 | } 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/FileBgen.hpp: -------------------------------------------------------------------------------- 1 | #ifndef PCAONE_FILEBGEN_ 2 | #define PCAONE_FILEBGEN_ 3 | 4 | #include "Data.hpp" 5 | #include "bgen/reader.h" 6 | #include "bgen/writer.h" 7 | 8 | // const double GENOTYPE_THRESHOLD = 0.9; 9 | // const double BGEN_MISSING_VALUE = -9; 10 | // const double BGEN2GENO[4] = {0, 0.5, 1, BGEN_MISSING_VALUE}; 11 | 12 | 13 | class FileBgen : public Data { 14 | public: 15 | // using Data::Data; 16 | FileBgen(const Param& params_) : Data(params_) { 17 | cao.print(tick.date(), "start parsing BGEN format"); 18 | bg = new bgen::CppBgenReader(params.filein, "", true); 19 | nsamples = bg->header.nsamples; 20 | nsnps = bg->header.nvariants; 21 | dosages.resize(nsamples); 22 | F = Mat1D::Zero(nsnps); // initial F 23 | cao.print(tick.date(), "N(#samples) =", nsamples, ", M(#SNPs) =", nsnps); 24 | cao.print(tick.date(), "the layout is", bg->header.layout, ", compressed by", 25 | bg->header.compression == 2 ? "zstd" : "zlib"); 26 | } 27 | 28 | ~FileBgen() override { delete bg; } 29 | 30 | void read_all() final; 31 | 32 | // for blockwise 33 | void check_file_offset_first_var() final { bg->offset = bg->header.offset + 4; } 34 | 35 | void read_block_initial(uint64, uint64, bool) final; 36 | 37 | void read_block_update(uint64, uint64, const Mat2D &, const Mat1D &, const Mat2D &, bool) final {} 38 | 39 | private: 40 | bgen::CppBgenReader* bg; 41 | std::vector dosages, probs1d; 42 | bool frequency_was_estimated = false; 43 | }; 44 | 45 | void permute_bgen_thread(std::vector idx, std::string fin, std::string fout, int ithread); 46 | 47 | PermMat permute_bgen(std::string& fin, std::string fout, int nthreads); 48 | 49 | #endif // PCAONE_FILEBGEN_ 50 | -------------------------------------------------------------------------------- /src/FileBinary.cpp: -------------------------------------------------------------------------------- 1 | #include "FileBinary.hpp" 2 | 3 | using namespace std; 4 | 5 | void FileBin::check_file_offset_first_var() { 6 | setlocale(LC_ALL, "C"); 7 | ios_base::sync_with_stdio(false); 8 | // magic += missing_points.size() * sizeof(uint64); 9 | long long offset = ibyte * 2 + nsnps * bytes_per_snp; 10 | if (ifs_bin.tellg() == offset) { 11 | // reach the end of bed, reset the position to the first variant; 12 | ifs_bin.seekg(ibyte * 2, std::ios_base::beg); 13 | } else if (ifs_bin.tellg() == ibyte * 2) { 14 | ; 15 | } else { 16 | ifs_bin.seekg(ibyte * 2, std::ios_base::beg); 17 | if (params.verbose) cao.warn("confirm you are running the window-based RSVD (algorithm2)"); 18 | } 19 | } 20 | 21 | void FileBin::read_all() { 22 | check_file_offset_first_var(); 23 | G = Mat2D::Zero(nsamples, nsnps); 24 | Eigen::VectorXf fg(nsamples); 25 | for (Eigen::Index i = 0; i < G.cols(); i++) { 26 | ifs_bin.read((char *)fg.data(), bytes_per_snp); 27 | G.col(i) = fg.cast(); 28 | G.col(i).array() -= G.col(i).mean(); 29 | } 30 | } 31 | 32 | // TODO : can standardize 33 | void FileBin::read_block_initial(uint64 start_idx, uint64 stop_idx, bool standardize) { 34 | // magic += missing_points.size() * sizeof(uint64); 35 | // check where we are 36 | long long offset = ibyte * 2 + start_idx * bytes_per_snp; 37 | if (ifs_bin.tellg() != offset) cao.error("something wrong with read_snp_block!\n"); 38 | uint actual_block_size = stop_idx - start_idx + 1; 39 | G = Mat2D(nsamples, actual_block_size); 40 | Eigen::VectorXf fg(nsamples); 41 | for (Eigen::Index i = 0; i < G.cols(); i++) { 42 | ifs_bin.read((char *)fg.data(), bytes_per_snp); 43 | G.col(i) = fg.cast(); 44 | G.col(i).array() -= G.col(i).mean(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /external/Eigen/SVD: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_SVD_MODULE_H 9 | #define EIGEN_SVD_MODULE_H 10 | 11 | #include "QR" 12 | #include "Householder" 13 | #include "Jacobi" 14 | 15 | #include "src/Core/util/DisableStupidWarnings.h" 16 | 17 | /** \defgroup SVD_Module SVD module 18 | * 19 | * 20 | * 21 | * This module provides SVD decomposition for matrices (both real and complex). 22 | * Two decomposition algorithms are provided: 23 | * - JacobiSVD implementing two-sided Jacobi iterations is numerically very accurate, fast for small matrices, but very slow for larger ones. 24 | * - BDCSVD implementing a recursive divide & conquer strategy on top of an upper-bidiagonalization which remains fast for large problems. 25 | * These decompositions are accessible via the respective classes and following MatrixBase methods: 26 | * - MatrixBase::jacobiSvd() 27 | * - MatrixBase::bdcSvd() 28 | * 29 | * \code 30 | * #include 31 | * \endcode 32 | */ 33 | 34 | #include "src/misc/RealSvd2x2.h" 35 | #include "src/SVD/UpperBidiagonalization.h" 36 | #include "src/SVD/SVDBase.h" 37 | #include "src/SVD/JacobiSVD.h" 38 | #include "src/SVD/BDCSVD.h" 39 | #if defined(EIGEN_USE_LAPACKE) && !defined(EIGEN_USE_LAPACKE_STRICT) 40 | #ifdef EIGEN_USE_MKL 41 | #include "mkl_lapacke.h" 42 | #else 43 | #include "src/misc/lapacke.h" 44 | #endif 45 | #include "src/SVD/JacobiSVD_LAPACKE.h" 46 | #endif 47 | 48 | #include "src/Core/util/ReenableStupidWarnings.h" 49 | 50 | #endif // EIGEN_SVD_MODULE_H 51 | -------------------------------------------------------------------------------- /external/zstd/lib/compress/zstd_compress_literals.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under both the BSD-style license (found in the 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | * in the COPYING file in the root directory of this source tree). 8 | * You may select, at your option, one of the above-listed licenses. 9 | */ 10 | 11 | #ifndef ZSTD_COMPRESS_LITERALS_H 12 | #define ZSTD_COMPRESS_LITERALS_H 13 | 14 | #include "zstd_compress_internal.h" /* ZSTD_hufCTables_t, ZSTD_minGain() */ 15 | 16 | 17 | size_t ZSTD_noCompressLiterals (void* dst, size_t dstCapacity, const void* src, size_t srcSize); 18 | 19 | /* ZSTD_compressRleLiteralsBlock() : 20 | * Conditions : 21 | * - All bytes in @src are identical 22 | * - dstCapacity >= 4 */ 23 | size_t ZSTD_compressRleLiteralsBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize); 24 | 25 | /* ZSTD_compressLiterals(): 26 | * @entropyWorkspace: must be aligned on 4-bytes boundaries 27 | * @entropyWorkspaceSize : must be >= HUF_WORKSPACE_SIZE 28 | * @suspectUncompressible: sampling checks, to potentially skip huffman coding 29 | */ 30 | size_t ZSTD_compressLiterals (void* dst, size_t dstCapacity, 31 | const void* src, size_t srcSize, 32 | void* entropyWorkspace, size_t entropyWorkspaceSize, 33 | const ZSTD_hufCTables_t* prevHuf, 34 | ZSTD_hufCTables_t* nextHuf, 35 | ZSTD_strategy strategy, int disableLiteralCompression, 36 | int suspectUncompressible, 37 | int bmi2); 38 | 39 | #endif /* ZSTD_COMPRESS_LITERALS_H */ 40 | -------------------------------------------------------------------------------- /src/Timer.hpp: -------------------------------------------------------------------------------- 1 | #ifndef TIMER_H_ 2 | #define TIMER_H_ 3 | 4 | #include 5 | #include 6 | #include // put_time 7 | #include 8 | 9 | class Timer { 10 | protected: 11 | std::chrono::time_point start_clock, prev_clock; 12 | 13 | public: 14 | Timer(); 15 | ~Timer(); 16 | void clock(); 17 | std::string date(); 18 | std::string intime(); 19 | double reltime(); 20 | double abstime(); 21 | }; 22 | 23 | inline Timer::Timer() { start_clock = std::chrono::high_resolution_clock::now(); } 24 | 25 | inline Timer::~Timer() {} 26 | 27 | inline void Timer::clock() { prev_clock = std::chrono::high_resolution_clock::now(); } 28 | 29 | inline double Timer::reltime() { 30 | return std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - 31 | prev_clock) 32 | .count() / 33 | 1e3; 34 | } 35 | 36 | inline double Timer::abstime() { 37 | return std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - 38 | start_clock) 39 | .count() / 40 | 1e3; 41 | } 42 | 43 | inline std::string Timer::date() { 44 | auto now = std::chrono::system_clock::now(); 45 | auto in_time_t = std::chrono::system_clock::to_time_t(now); 46 | std::stringstream ss; 47 | ss << std::put_time(std::localtime(&in_time_t), "[%d/%m/%Y-%X]"); 48 | return ss.str(); 49 | } 50 | 51 | inline std::string Timer::intime() { 52 | auto now = std::chrono::system_clock::now(); 53 | auto in_time_t = std::chrono::system_clock::to_time_t(now); 54 | std::stringstream ss; 55 | ss << in_time_t; 56 | return ss.str(); 57 | } 58 | 59 | #endif // TIMER_H_ 60 | -------------------------------------------------------------------------------- /scripts/common.R: -------------------------------------------------------------------------------- 1 | 2 | library(data.table) 3 | 4 | ## sample size correction 5 | bs <- function(x,n) x-(1-x)/(n-2) 6 | 7 | parse_ld_bins <- function(fn, n=NULL){ 8 | nbin <- 500 9 | all <- read.table(fn, head=T) 10 | chrs <- unique(all$chr) 11 | num <- sapply(chrs, function(c) all[all$chr==c, "num"][1:nbin]) 12 | 13 | weight <- num / rowSums(num) 14 | 15 | r2chr <- sapply(chrs, function(c) all[all$chr==c,"avg_R2"][1:nbin]) 16 | r2all <- rowSums(r2chr*weight) 17 | 18 | dist <- all[all$chr==1,"distance"][1:nbin] 19 | r2 <- r2all 20 | if(!is.null(n)) r2 <- bs(r2all,n) 21 | dat <- cbind(dist=dist, r2=r2) 22 | as.data.frame(dat) 23 | } 24 | 25 | plot_ld_curve <- function(dat, ...){ 26 | ymax <- min(c(max(dat$r2), 0.4)) 27 | ymax <- 0.3 28 | bins <- c("5Kb"=5e3, "10Kb"=1e4, "50Kb"=5e4, "100Kb"=1e5, "500Kb"=5e5, "1Mb"=1e6, "5Mb"=5e6) 29 | plot(dat$dist, dat$r2, ylim = c(0, ymax), type = "l", log = "x", axes = F, xlab = "", ylab="", ...) 30 | axis(1, at=bins, labels = NA) 31 | mtext(names(bins),side=1,line=1:2*0.9,at=bins) 32 | ylabr2 <- expression(paste(mean~tilde(r)^2)) 33 | mtext(ylabr2,2,line=2,cex=2) 34 | mtext("Distance",side=1,line=4,cex=2) 35 | axis(2,at=0:(as.integer(ymax*10))/10) 36 | } 37 | 38 | ## https://logfc.wordpress.com/2017/03/15/adding-figure-labels-a-b-c-in-the-top-left-corner-of-the-plotting-region/ 39 | addlabel <- function(label, adj=0, padj=0, font=1){ 40 | par(xpd=NA) 41 | di <- dev.size("in") 42 | x <- grconvertX(c(0, di[1]), from="in", to="user") 43 | y <- grconvertY(c(0, di[2]), from="in", to="user") 44 | 45 | fig <- par("fig") 46 | x <- x[1] + (x[2] - x[1]) * fig[1:2] 47 | y <- y[1] + (y[2] - y[1]) * fig[3:4] 48 | 49 | ax <- x[1] + strwidth(label, cex=3) / 2 50 | ay <- y[2] - strheight(label, cex=3) / 2 51 | text(ax-adj, ay-padj, label, cex=3, font=font) 52 | } 53 | 54 | 55 | -------------------------------------------------------------------------------- /external/zstd/lib/common/allocations.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under both the BSD-style license (found in the 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | * in the COPYING file in the root directory of this source tree). 8 | * You may select, at your option, one of the above-listed licenses. 9 | */ 10 | 11 | /* This file provides custom allocation primitives 12 | */ 13 | 14 | #define ZSTD_DEPS_NEED_MALLOC 15 | #include "zstd_deps.h" /* ZSTD_malloc, ZSTD_calloc, ZSTD_free, ZSTD_memset */ 16 | 17 | #include "compiler.h" /* MEM_STATIC */ 18 | #define ZSTD_STATIC_LINKING_ONLY 19 | #include "../zstd.h" /* ZSTD_customMem */ 20 | 21 | #ifndef ZSTD_ALLOCATIONS_H 22 | #define ZSTD_ALLOCATIONS_H 23 | 24 | /* custom memory allocation functions */ 25 | 26 | MEM_STATIC void* ZSTD_customMalloc(size_t size, ZSTD_customMem customMem) 27 | { 28 | if (customMem.customAlloc) 29 | return customMem.customAlloc(customMem.opaque, size); 30 | return ZSTD_malloc(size); 31 | } 32 | 33 | MEM_STATIC void* ZSTD_customCalloc(size_t size, ZSTD_customMem customMem) 34 | { 35 | if (customMem.customAlloc) { 36 | /* calloc implemented as malloc+memset; 37 | * not as efficient as calloc, but next best guess for custom malloc */ 38 | void* const ptr = customMem.customAlloc(customMem.opaque, size); 39 | ZSTD_memset(ptr, 0, size); 40 | return ptr; 41 | } 42 | return ZSTD_calloc(1, size); 43 | } 44 | 45 | MEM_STATIC void ZSTD_customFree(void* ptr, ZSTD_customMem customMem) 46 | { 47 | if (ptr!=NULL) { 48 | if (customMem.customFree) 49 | customMem.customFree(customMem.opaque, ptr); 50 | else 51 | ZSTD_free(ptr); 52 | } 53 | } 54 | 55 | #endif /* ZSTD_ALLOCATIONS_H */ 56 | -------------------------------------------------------------------------------- /external/zstd/lib/common/zstd_common.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under both the BSD-style license (found in the 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | * in the COPYING file in the root directory of this source tree). 8 | * You may select, at your option, one of the above-listed licenses. 9 | */ 10 | 11 | 12 | 13 | /*-************************************* 14 | * Dependencies 15 | ***************************************/ 16 | #define ZSTD_DEPS_NEED_MALLOC 17 | #include "error_private.h" 18 | #include "zstd_internal.h" 19 | 20 | 21 | /*-**************************************** 22 | * Version 23 | ******************************************/ 24 | unsigned ZSTD_versionNumber(void) { return ZSTD_VERSION_NUMBER; } 25 | 26 | const char* ZSTD_versionString(void) { return ZSTD_VERSION_STRING; } 27 | 28 | 29 | /*-**************************************** 30 | * ZSTD Error Management 31 | ******************************************/ 32 | #undef ZSTD_isError /* defined within zstd_internal.h */ 33 | /*! ZSTD_isError() : 34 | * tells if a return value is an error code 35 | * symbol is required for external callers */ 36 | unsigned ZSTD_isError(size_t code) { return ERR_isError(code); } 37 | 38 | /*! ZSTD_getErrorName() : 39 | * provides error code string from function result (useful for debugging) */ 40 | const char* ZSTD_getErrorName(size_t code) { return ERR_getErrorName(code); } 41 | 42 | /*! ZSTD_getError() : 43 | * convert a `size_t` function result into a proper ZSTD_errorCode enum */ 44 | ZSTD_ErrorCode ZSTD_getErrorCode(size_t code) { return ERR_getErrorCode(code); } 45 | 46 | /*! ZSTD_getErrorString() : 47 | * provides error code string from enum */ 48 | const char* ZSTD_getErrorString(ZSTD_ErrorCode code) { return ERR_getErrorString(code); } 49 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/SelfCwiseBinaryOp.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2009-2010 Gael Guennebaud 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | #ifndef EIGEN_SELFCWISEBINARYOP_H 11 | #define EIGEN_SELFCWISEBINARYOP_H 12 | 13 | namespace Eigen { 14 | 15 | // TODO generalize the scalar type of 'other' 16 | 17 | template 18 | EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::operator*=(const Scalar& other) 19 | { 20 | internal::call_assignment(this->derived(), PlainObject::Constant(rows(),cols(),other), internal::mul_assign_op()); 21 | return derived(); 22 | } 23 | 24 | template 25 | EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& ArrayBase::operator+=(const Scalar& other) 26 | { 27 | internal::call_assignment(this->derived(), PlainObject::Constant(rows(),cols(),other), internal::add_assign_op()); 28 | return derived(); 29 | } 30 | 31 | template 32 | EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& ArrayBase::operator-=(const Scalar& other) 33 | { 34 | internal::call_assignment(this->derived(), PlainObject::Constant(rows(),cols(),other), internal::sub_assign_op()); 35 | return derived(); 36 | } 37 | 38 | template 39 | EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::operator/=(const Scalar& other) 40 | { 41 | internal::call_assignment(this->derived(), PlainObject::Constant(rows(),cols(),other), internal::div_assign_op()); 42 | return derived(); 43 | } 44 | 45 | } // end namespace Eigen 46 | 47 | #endif // EIGEN_SELFCWISEBINARYOP_H 48 | -------------------------------------------------------------------------------- /external/Eigen/src/SparseCore/SparseRedux.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2008-2014 Gael Guennebaud 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | #ifndef EIGEN_SPARSEREDUX_H 11 | #define EIGEN_SPARSEREDUX_H 12 | 13 | namespace Eigen { 14 | 15 | template 16 | typename internal::traits::Scalar 17 | SparseMatrixBase::sum() const 18 | { 19 | eigen_assert(rows()>0 && cols()>0 && "you are using a non initialized matrix"); 20 | Scalar res(0); 21 | internal::evaluator thisEval(derived()); 22 | for (Index j=0; j::InnerIterator iter(thisEval,j); iter; ++iter) 24 | res += iter.value(); 25 | return res; 26 | } 27 | 28 | template 29 | typename internal::traits >::Scalar 30 | SparseMatrix<_Scalar,_Options,_Index>::sum() const 31 | { 32 | eigen_assert(rows()>0 && cols()>0 && "you are using a non initialized matrix"); 33 | if(this->isCompressed()) 34 | return Matrix::Map(m_data.valuePtr(), m_data.size()).sum(); 35 | else 36 | return Base::sum(); 37 | } 38 | 39 | template 40 | typename internal::traits >::Scalar 41 | SparseVector<_Scalar,_Options,_Index>::sum() const 42 | { 43 | eigen_assert(rows()>0 && cols()>0 && "you are using a non initialized matrix"); 44 | return Matrix::Map(m_data.valuePtr(), m_data.size()).sum(); 45 | } 46 | 47 | } // end namespace Eigen 48 | 49 | #endif // EIGEN_SPARSEREDUX_H 50 | -------------------------------------------------------------------------------- /scripts/calc_decay_bin.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | suppressPackageStartupMessages({ 4 | library(argparser) 5 | library(dplyr) 6 | library(data.table) 7 | }) 8 | 9 | # Create a parser 10 | p <- arg_parser("calculate the LD R2 for making the decay curve plot") 11 | 12 | # Add command line arguments 13 | p <- add_argument(p, "input", help="the ld.gz file for pairwise R2 generated by PCAone or plink") 14 | p <- add_argument(p, "output", help="output file path, a tab-separated plain text file") 15 | p <- add_argument(p, "--window", help="the window size in base pair used by PCAone or plink", default = 1000000L) 16 | p <- add_argument(p, "--bins", help="the number of bins to split the R2 into", default = 100L) 17 | 18 | # Parse the command line arguments 19 | args <- parse_args(p) 20 | 21 | ## args <- commandArgs(trailingOnly = T) 22 | 23 | fn <- args$input 24 | fout <- args$output 25 | window <- args$window 26 | nbins <- args$bins 27 | 28 | 29 | d <- fread(fn, sep = "\t", select= c("CHR_A", "BP_A", "BP_B", "R2"), data.table=F, nrows = 1000000000L) 30 | 31 | ## library(vroom) 32 | ## d <- vroom(fn, delim = "\t", show_col_types = FALSE, col_select = c(CHR_A, BP_A, BP_B, R2), altrep = c("chr", "int", "num"), n_max = 1000000000L) 33 | ## d <- vroom(fn, delim = "\t", show_col_types = FALSE, col_select = c(CHR_A, BP_A, BP_B, R2), n_max = 1000000000L) 34 | message("done reading") 35 | 36 | chrs <- unique(d$CHR_A) 37 | 38 | res <- lapply(chrs, function(c){ 39 | m <- d %>% filter(CHR_A==c) %>% transmute(Dist=BP_B - BP_A, R2) %>% arrange(Dist) %>% 40 | mutate(bin=ntile(Dist, nbins)) %>% group_by(bin) %>% summarise(num = n(),avg_R2 = mean(R2), std = sd(R2)) 41 | m <- cbind(c, m) 42 | m 43 | }) 44 | 45 | res <- do.call(rbind.data.frame, res) 46 | res$bin <- res$bin * (window / nbins) 47 | colnames(res) <- c("chr", "distance", "num", "avg_R2", "std") 48 | 49 | write.table(res, fout, sep = "\t", row.names = F, quote = F) 50 | 51 | -------------------------------------------------------------------------------- /external/zstd/lib/compress/zstd_double_fast.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under both the BSD-style license (found in the 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | * in the COPYING file in the root directory of this source tree). 8 | * You may select, at your option, one of the above-listed licenses. 9 | */ 10 | 11 | #ifndef ZSTD_DOUBLE_FAST_H 12 | #define ZSTD_DOUBLE_FAST_H 13 | 14 | #include "../common/mem.h" /* U32 */ 15 | #include "zstd_compress_internal.h" /* ZSTD_CCtx, size_t */ 16 | 17 | #ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR 18 | 19 | void ZSTD_fillDoubleHashTable(ZSTD_MatchState_t* ms, 20 | void const* end, ZSTD_dictTableLoadMethod_e dtlm, 21 | ZSTD_tableFillPurpose_e tfp); 22 | 23 | size_t ZSTD_compressBlock_doubleFast( 24 | ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], 25 | void const* src, size_t srcSize); 26 | size_t ZSTD_compressBlock_doubleFast_dictMatchState( 27 | ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], 28 | void const* src, size_t srcSize); 29 | size_t ZSTD_compressBlock_doubleFast_extDict( 30 | ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], 31 | void const* src, size_t srcSize); 32 | 33 | #define ZSTD_COMPRESSBLOCK_DOUBLEFAST ZSTD_compressBlock_doubleFast 34 | #define ZSTD_COMPRESSBLOCK_DOUBLEFAST_DICTMATCHSTATE ZSTD_compressBlock_doubleFast_dictMatchState 35 | #define ZSTD_COMPRESSBLOCK_DOUBLEFAST_EXTDICT ZSTD_compressBlock_doubleFast_extDict 36 | #else 37 | #define ZSTD_COMPRESSBLOCK_DOUBLEFAST NULL 38 | #define ZSTD_COMPRESSBLOCK_DOUBLEFAST_DICTMATCHSTATE NULL 39 | #define ZSTD_COMPRESSBLOCK_DOUBLEFAST_EXTDICT NULL 40 | #endif /* ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR */ 41 | 42 | #endif /* ZSTD_DOUBLE_FAST_H */ 43 | -------------------------------------------------------------------------------- /external/Eigen/PaStiXSupport: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_PASTIXSUPPORT_MODULE_H 9 | #define EIGEN_PASTIXSUPPORT_MODULE_H 10 | 11 | #include "SparseCore" 12 | 13 | #include "src/Core/util/DisableStupidWarnings.h" 14 | 15 | extern "C" { 16 | #include 17 | #include 18 | } 19 | 20 | #ifdef complex 21 | #undef complex 22 | #endif 23 | 24 | /** \ingroup Support_modules 25 | * \defgroup PaStiXSupport_Module PaStiXSupport module 26 | * 27 | * This module provides an interface to the PaSTiX library. 28 | * PaSTiX is a general \b supernodal, \b parallel and \b opensource sparse solver. 29 | * It provides the two following main factorization classes: 30 | * - class PastixLLT : a supernodal, parallel LLt Cholesky factorization. 31 | * - class PastixLDLT: a supernodal, parallel LDLt Cholesky factorization. 32 | * - class PastixLU : a supernodal, parallel LU factorization (optimized for a symmetric pattern). 33 | * 34 | * \code 35 | * #include 36 | * \endcode 37 | * 38 | * In order to use this module, the PaSTiX headers must be accessible from the include paths, and your binary must be linked to the PaSTiX library and its dependencies. 39 | * This wrapper resuires PaStiX version 5.x compiled without MPI support. 40 | * The dependencies depend on how PaSTiX has been compiled. 41 | * For a cmake based project, you can use our FindPaSTiX.cmake module to help you in this task. 42 | * 43 | */ 44 | 45 | #include "src/PaStiXSupport/PaStiXSupport.h" 46 | 47 | #include "src/Core/util/ReenableStupidWarnings.h" 48 | 49 | #endif // EIGEN_PASTIXSUPPORT_MODULE_H 50 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/arch/Default/Settings.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2008-2010 Gael Guennebaud 5 | // Copyright (C) 2006-2008 Benoit Jacob 6 | // 7 | // This Source Code Form is subject to the terms of the Mozilla 8 | // Public License v. 2.0. If a copy of the MPL was not distributed 9 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 10 | 11 | 12 | /* All the parameters defined in this file can be specialized in the 13 | * architecture specific files, and/or by the user. 14 | * More to come... */ 15 | 16 | #ifndef EIGEN_DEFAULT_SETTINGS_H 17 | #define EIGEN_DEFAULT_SETTINGS_H 18 | 19 | /** Defines the maximal loop size to enable meta unrolling of loops. 20 | * Note that the value here is expressed in Eigen's own notion of "number of FLOPS", 21 | * it does not correspond to the number of iterations or the number of instructions 22 | */ 23 | #ifndef EIGEN_UNROLLING_LIMIT 24 | #define EIGEN_UNROLLING_LIMIT 110 25 | #endif 26 | 27 | /** Defines the threshold between a "small" and a "large" matrix. 28 | * This threshold is mainly used to select the proper product implementation. 29 | */ 30 | #ifndef EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD 31 | #define EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD 8 32 | #endif 33 | 34 | /** Defines the maximal width of the blocks used in the triangular product and solver 35 | * for vectors (level 2 blas xTRMV and xTRSV). The default is 8. 36 | */ 37 | #ifndef EIGEN_TUNE_TRIANGULAR_PANEL_WIDTH 38 | #define EIGEN_TUNE_TRIANGULAR_PANEL_WIDTH 8 39 | #endif 40 | 41 | 42 | /** Defines the default number of registers available for that architecture. 43 | * Currently it must be 8 or 16. Other values will fail. 44 | */ 45 | #ifndef EIGEN_ARCH_DEFAULT_NUMBER_OF_REGISTERS 46 | #define EIGEN_ARCH_DEFAULT_NUMBER_OF_REGISTERS 8 47 | #endif 48 | 49 | #endif // EIGEN_DEFAULT_SETTINGS_H 50 | -------------------------------------------------------------------------------- /external/Eigen/src/misc/RealSvd2x2.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2009-2010 Benoit Jacob 5 | // Copyright (C) 2013-2016 Gael Guennebaud 6 | // 7 | // This Source Code Form is subject to the terms of the Mozilla 8 | // Public License v. 2.0. If a copy of the MPL was not distributed 9 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 10 | 11 | #ifndef EIGEN_REALSVD2X2_H 12 | #define EIGEN_REALSVD2X2_H 13 | 14 | namespace Eigen { 15 | 16 | namespace internal { 17 | 18 | template 19 | void real_2x2_jacobi_svd(const MatrixType& matrix, Index p, Index q, 20 | JacobiRotation *j_left, 21 | JacobiRotation *j_right) 22 | { 23 | using std::sqrt; 24 | using std::abs; 25 | Matrix m; 26 | m << numext::real(matrix.coeff(p,p)), numext::real(matrix.coeff(p,q)), 27 | numext::real(matrix.coeff(q,p)), numext::real(matrix.coeff(q,q)); 28 | JacobiRotation rot1; 29 | RealScalar t = m.coeff(0,0) + m.coeff(1,1); 30 | RealScalar d = m.coeff(1,0) - m.coeff(0,1); 31 | 32 | if(abs(d) < (std::numeric_limits::min)()) 33 | { 34 | rot1.s() = RealScalar(0); 35 | rot1.c() = RealScalar(1); 36 | } 37 | else 38 | { 39 | // If d!=0, then t/d cannot overflow because the magnitude of the 40 | // entries forming d are not too small compared to the ones forming t. 41 | RealScalar u = t / d; 42 | RealScalar tmp = sqrt(RealScalar(1) + numext::abs2(u)); 43 | rot1.s() = RealScalar(1) / tmp; 44 | rot1.c() = u / tmp; 45 | } 46 | m.applyOnTheLeft(0,1,rot1); 47 | j_right->makeJacobi(m,0,1); 48 | *j_left = rot1 * j_right->transpose(); 49 | } 50 | 51 | } // end namespace internal 52 | 53 | } // end namespace Eigen 54 | 55 | #endif // EIGEN_REALSVD2X2_H 56 | -------------------------------------------------------------------------------- /src/FileCsv.hpp: -------------------------------------------------------------------------------- 1 | #ifndef PCAONE_FILECSV_ 2 | #define PCAONE_FILECSV_ 3 | 4 | #include "Data.hpp" 5 | 6 | void parse_csvzstd(ZstdDS& zbuf, uint& nsamples, uint& nsnps, uint scale, std::vector& libsize, 7 | std::vector& tidx, double& median_libsize); 8 | 9 | void read_csvzstd_block(ZstdDS& zbuf, std::string& buffCur, uint blocksize, uint64 start_idx, uint64 stop_idx, 10 | Mat2D& G, uint nsamples, std::vector& libsize, std::vector& tidx, 11 | double median_libsize, uint scale, double scaleFactor); 12 | 13 | PermMat shuffle_csvzstd_to_bin(std::string& fin, std::string fout, uint gb, uint scale, double scaleFactor); 14 | 15 | // for other types, assume data is already noralized only do centering 16 | class FileCsv : public Data { 17 | public: 18 | FileCsv(const Param& params_) : Data(params_) { 19 | cao.print(tick.date(), "start parsing CSV format compressed by ZSTD"); 20 | 21 | if (params.nsnps > 0 && params.nsamples > 0 && !params.cpmed) { 22 | cao.print(tick.date(), "use nsamples and nsnps given by user."); 23 | nsamples = params.nsamples; 24 | nsnps = params.nsnps; 25 | } else { 26 | zbuf.fin = fopenOrDie(params.filein.c_str(), "rb"); 27 | parse_csvzstd(zbuf, nsamples, nsnps, params.scale, libsize, tidx, median_libsize); 28 | } 29 | cao.print(tick.date(), "shape of input matrix (features x samples) is", nsnps, " x", nsamples); 30 | } 31 | 32 | ~FileCsv() override = default; 33 | 34 | void read_all() final; 35 | // for blockwise 36 | void check_file_offset_first_var() final; 37 | 38 | void read_block_initial(uint64, uint64, bool) final; 39 | 40 | void read_block_update(uint64, uint64, const Mat2D&, const Mat1D&, const Mat2D&, bool) final {} 41 | 42 | private: 43 | ZstdDS zbuf; 44 | std::vector tidx; 45 | std::vector libsize; 46 | double median_libsize; 47 | std::string buffCur{""}; 48 | }; 49 | 50 | #endif // PCAONE_FILECSV_ 51 | -------------------------------------------------------------------------------- /external/Eigen/SparseLU: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2012 Désiré Nuentsa-Wakam 5 | // Copyright (C) 2012 Gael Guennebaud 6 | // 7 | // This Source Code Form is subject to the terms of the Mozilla 8 | // Public License v. 2.0. If a copy of the MPL was not distributed 9 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 10 | 11 | #ifndef EIGEN_SPARSELU_MODULE_H 12 | #define EIGEN_SPARSELU_MODULE_H 13 | 14 | #include "SparseCore" 15 | 16 | /** 17 | * \defgroup SparseLU_Module SparseLU module 18 | * This module defines a supernodal factorization of general sparse matrices. 19 | * The code is fully optimized for supernode-panel updates with specialized kernels. 20 | * Please, see the documentation of the SparseLU class for more details. 21 | */ 22 | 23 | // Ordering interface 24 | #include "OrderingMethods" 25 | 26 | #include "src/Core/util/DisableStupidWarnings.h" 27 | 28 | #include "src/SparseLU/SparseLU_gemm_kernel.h" 29 | 30 | #include "src/SparseLU/SparseLU_Structs.h" 31 | #include "src/SparseLU/SparseLU_SupernodalMatrix.h" 32 | #include "src/SparseLU/SparseLUImpl.h" 33 | #include "src/SparseCore/SparseColEtree.h" 34 | #include "src/SparseLU/SparseLU_Memory.h" 35 | #include "src/SparseLU/SparseLU_heap_relax_snode.h" 36 | #include "src/SparseLU/SparseLU_relax_snode.h" 37 | #include "src/SparseLU/SparseLU_pivotL.h" 38 | #include "src/SparseLU/SparseLU_panel_dfs.h" 39 | #include "src/SparseLU/SparseLU_kernel_bmod.h" 40 | #include "src/SparseLU/SparseLU_panel_bmod.h" 41 | #include "src/SparseLU/SparseLU_column_dfs.h" 42 | #include "src/SparseLU/SparseLU_column_bmod.h" 43 | #include "src/SparseLU/SparseLU_copy_to_ucol.h" 44 | #include "src/SparseLU/SparseLU_pruneL.h" 45 | #include "src/SparseLU/SparseLU_Utils.h" 46 | #include "src/SparseLU/SparseLU.h" 47 | 48 | #include "src/Core/util/ReenableStupidWarnings.h" 49 | 50 | #endif // EIGEN_SPARSELU_MODULE_H 51 | -------------------------------------------------------------------------------- /external/Eigen/Eigenvalues: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_EIGENVALUES_MODULE_H 9 | #define EIGEN_EIGENVALUES_MODULE_H 10 | 11 | #include "Core" 12 | 13 | #include "Cholesky" 14 | #include "Jacobi" 15 | #include "Householder" 16 | #include "LU" 17 | #include "Geometry" 18 | 19 | #include "src/Core/util/DisableStupidWarnings.h" 20 | 21 | /** \defgroup Eigenvalues_Module Eigenvalues module 22 | * 23 | * 24 | * 25 | * This module mainly provides various eigenvalue solvers. 26 | * This module also provides some MatrixBase methods, including: 27 | * - MatrixBase::eigenvalues(), 28 | * - MatrixBase::operatorNorm() 29 | * 30 | * \code 31 | * #include 32 | * \endcode 33 | */ 34 | 35 | #include "src/misc/RealSvd2x2.h" 36 | #include "src/Eigenvalues/Tridiagonalization.h" 37 | #include "src/Eigenvalues/RealSchur.h" 38 | #include "src/Eigenvalues/EigenSolver.h" 39 | #include "src/Eigenvalues/SelfAdjointEigenSolver.h" 40 | #include "src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h" 41 | #include "src/Eigenvalues/HessenbergDecomposition.h" 42 | #include "src/Eigenvalues/ComplexSchur.h" 43 | #include "src/Eigenvalues/ComplexEigenSolver.h" 44 | #include "src/Eigenvalues/RealQZ.h" 45 | #include "src/Eigenvalues/GeneralizedEigenSolver.h" 46 | #include "src/Eigenvalues/MatrixBaseEigenvalues.h" 47 | #ifdef EIGEN_USE_LAPACKE 48 | #ifdef EIGEN_USE_MKL 49 | #include "mkl_lapacke.h" 50 | #else 51 | #include "src/misc/lapacke.h" 52 | #endif 53 | #include "src/Eigenvalues/RealSchur_LAPACKE.h" 54 | #include "src/Eigenvalues/ComplexSchur_LAPACKE.h" 55 | #include "src/Eigenvalues/SelfAdjointEigenSolver_LAPACKE.h" 56 | #endif 57 | 58 | #include "src/Core/util/ReenableStupidWarnings.h" 59 | 60 | #endif // EIGEN_EIGENVALUES_MODULE_H 61 | -------------------------------------------------------------------------------- /scripts/parse_ld_matrix.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | ## this script calculates the adjusted LD (r2). 4 | ## the input is the binary file with suffix .residuals outputted by PCAone 5 | 6 | args <- commandArgs(trailingOnly = T) 7 | 8 | library(Rcpp) 9 | library(RcppEigen) 10 | 11 | sourceCpp("misc/ld-scores.cpp") 12 | 13 | cppFunction('List ld_curve_cpp(Eigen::MatrixXd m, IntegerVector pos, IntegerVector bins){ 14 | int nsnps = m.cols(), nb = bins.size(), winsize = max(bins); 15 | NumericVector r_sum(nb), r2_sum(nb); 16 | IntegerVector counts(nb); 17 | const int df = m.rows() - 1; // N-1 18 | Eigen::VectorXd sds = (m.array().square().colwise().sum() / df).sqrt(); 19 | int i, j, b, dist; 20 | for(i = 0; i < nsnps; i++) { 21 | b = 0; 22 | for(j = i + 1; j < nsnps; j++) { 23 | dist = pos(j) - pos(i); 24 | if(dist > winsize) break; 25 | if(dist > bins[b]) b = b + 1; 26 | double r = (m.col(j).array() * m.col(i).array() / (sds(j) * sds(i))).sum() / df; 27 | r_sum[b] += r; 28 | r2_sum[b] += r * r; 29 | counts[b] += 1; 30 | } 31 | } 32 | return List::create(Named("bin") = bins, Named("counts") = counts, 33 | Named("r_sum") = r_sum, Named("r2_sum") = r2_sum); 34 | }', depends = c("RcppEigen"), rebuild = TRUE) 35 | 36 | resfile <- "pcaone.residuals" 37 | 38 | bimfile <- "example/plink.bim" 39 | 40 | bim <- data.table::fread(bimfile, h =F, data.table = F) 41 | 42 | fed(bim) 43 | 44 | chr1 <- bim[bim[,1]==1,] 45 | 46 | con <- file(resfile, "rb") 47 | dims <- readBin(con, integer(), n = 2) 48 | nsnps <- dims[1] 49 | nsamples <- dims[2] 50 | 51 | snps <- nsnps / 10 52 | snps <- nrow(chr1) 53 | m <- matrix(readBin(con, numeric(), n = nsamples * snps, size = 4), ncol = snps) 54 | 55 | pos <- chr1[,4] 56 | 57 | bins <- c(1000, 5000, 10000, 50000, 100000, 500000, 1e6, 5e6) 58 | 59 | system.time(d <- ld_curve_cpp(m, pos, bins)) 60 | 61 | str(d) 62 | plot(d[["r2_sum"]]/d[["counts"]]) 63 | 64 | dev.off() 65 | gc() 66 | 67 | 68 | close(con) 69 | 70 | 71 | cummean <- function(x) cumsum(x)/1:length(x) 72 | 73 | plot(o) 74 | 75 | dev.off() 76 | 77 | -------------------------------------------------------------------------------- /external/Eigen/CholmodSupport: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_CHOLMODSUPPORT_MODULE_H 9 | #define EIGEN_CHOLMODSUPPORT_MODULE_H 10 | 11 | #include "SparseCore" 12 | 13 | #include "src/Core/util/DisableStupidWarnings.h" 14 | 15 | extern "C" { 16 | #include 17 | } 18 | 19 | /** \ingroup Support_modules 20 | * \defgroup CholmodSupport_Module CholmodSupport module 21 | * 22 | * This module provides an interface to the Cholmod library which is part of the suitesparse package. 23 | * It provides the two following main factorization classes: 24 | * - class CholmodSupernodalLLT: a supernodal LLT Cholesky factorization. 25 | * - class CholmodDecomposiiton: a general L(D)LT Cholesky factorization with automatic or explicit runtime selection of the underlying factorization method (supernodal or simplicial). 26 | * 27 | * For the sake of completeness, this module also propose the two following classes: 28 | * - class CholmodSimplicialLLT 29 | * - class CholmodSimplicialLDLT 30 | * Note that these classes does not bring any particular advantage compared to the built-in 31 | * SimplicialLLT and SimplicialLDLT factorization classes. 32 | * 33 | * \code 34 | * #include 35 | * \endcode 36 | * 37 | * In order to use this module, the cholmod headers must be accessible from the include paths, and your binary must be linked to the cholmod library and its dependencies. 38 | * The dependencies depend on how cholmod has been compiled. 39 | * For a cmake based project, you can use our FindCholmod.cmake module to help you in this task. 40 | * 41 | */ 42 | 43 | #include "src/CholmodSupport/CholmodSupport.h" 44 | 45 | #include "src/Core/util/ReenableStupidWarnings.h" 46 | 47 | #endif // EIGEN_CHOLMODSUPPORT_MODULE_H 48 | 49 | -------------------------------------------------------------------------------- /src/FileBeagle.hpp: -------------------------------------------------------------------------------- 1 | #ifndef PCAONE_FILEBEAGLE_ 2 | #define PCAONE_FILEBEAGLE_ 3 | 4 | #include "Data.hpp" 5 | 6 | class FileBeagle : public Data { 7 | public: 8 | FileBeagle(const Param ¶ms_) : Data(params_) { 9 | cao.print(tick.date(), "start parsing BEAGLE format"); 10 | // TODO: ask user to use --pcangsd explicitly 11 | impute = true; // always imputing imcomplete information 12 | original = buffer = (char *)calloc(bufsize, sizeof(char)); 13 | if (params.nsnps > 0 && params.nsamples > 0) { 14 | cao.print(tick.date(), "use nsamples and nsnps given by user"); 15 | nsamples = params.nsamples; 16 | nsnps = params.nsnps; 17 | } else { 18 | fp = gzopen(params.filein.c_str(), "r"); 19 | tgets(fp, &buffer, &bufsize); 20 | int nCol = 1; 21 | if (buffer != original) original = buffer; 22 | const char *delims = "\t \n"; 23 | strtok_r(buffer, delims, &buffer); 24 | while (strtok_r(NULL, delims, &buffer)) nCol++; 25 | if (nCol % 3) cao.error("Number of columns should be a multiple of 3."); 26 | nsamples = nCol / 3 - 1; 27 | // NOTE: assume the columns are alignd. maybe check it first. 28 | buffer = original; 29 | nsnps = 0; 30 | // continue getting the number of sites 31 | while (tgets(fp, &buffer, &bufsize)) { 32 | nsnps++; 33 | } 34 | } 35 | 36 | if (params.pca) { // initial F 37 | F = Mat1D::Zero(nsnps); 38 | } 39 | cao.print(tick.date(), "N (# samples):", nsamples, ", M (# SNPs):", nsnps); 40 | } 41 | 42 | ~FileBeagle() override { 43 | free(buffer); 44 | if (fp) gzclose(fp); 45 | } 46 | 47 | void read_all() final; 48 | 49 | // below are for blockwise 50 | void check_file_offset_first_var() final; 51 | 52 | void read_block_initial(uint64, uint64, bool) final; 53 | 54 | void read_block_update(uint64, uint64, const Mat2D &, const Mat1D &, const Mat2D &, bool) final {} 55 | 56 | private: 57 | gzFile fp = nullptr; 58 | char *original, *buffer; 59 | uint64 bufsize = (uint64)128 * 1024 * 1024; 60 | }; 61 | 62 | #endif // PCAONE_FILEBEAGLE_ 63 | -------------------------------------------------------------------------------- /src/FilePlink.hpp: -------------------------------------------------------------------------------- 1 | #ifndef PCAONE_FILEPLINK_ 2 | #define PCAONE_FILEPLINK_ 3 | 4 | #include "Data.hpp" 5 | #include "Utils.hpp" 6 | 7 | class FileBed : public Data { 8 | public: 9 | // 10 | FileBed(const Param ¶ms_) : Data(params_) { 11 | cao.print(tick.date(), "start parsing PLINK format"); 12 | std::string fbim = params.filein + ".bim"; 13 | std::string ffam = params.filein + ".fam"; 14 | nsamples = count_lines(ffam); 15 | nsnps = count_lines(fbim); 16 | cao.print(tick.date(), "N (# samples):", nsamples, ", M (# SNPs):", nsnps); 17 | snpmajor = true; 18 | bed_bytes_per_snp = (nsamples + 3) >> 2; 19 | std::string fbed = params.filein + ".bed"; 20 | bed_ifstream.open(fbed, std::ios::in | std::ios::binary); 21 | if (!bed_ifstream.is_open()) cao.error("Cannot open bed file."); 22 | // check magic number of bed file 23 | uchar header[3]; 24 | bed_ifstream.read(reinterpret_cast(&header[0]), 3); 25 | if ((header[0] != 0x6c) || (header[1] != 0x1b) || (header[2] != 0x01)) 26 | cao.error("Incorrect magic number in plink bed file."); 27 | if (params.center) { 28 | centered_geno_lookup = Arr2D::Zero(4, nsnps); 29 | F = Mat1D::Zero(nsnps); 30 | } 31 | if (params.project > 0) { 32 | // read frq from original set 33 | cao.print(tick.date(), "read frequency of SNPs from the extended bim (.mbim)"); 34 | F = read_frq(params.filebim); 35 | if (F.size() != nsnps) cao.error("the number of sites doesn't match each other"); 36 | } 37 | } 38 | 39 | ~FileBed() override = default; 40 | 41 | void read_all() final; 42 | // for blockwise 43 | void check_file_offset_first_var() final; 44 | 45 | void read_block_initial(uint64, uint64, bool) final; 46 | 47 | void read_block_update(uint64, uint64, const Mat2D &, const Mat1D &, const Mat2D &, bool) final; 48 | 49 | private: 50 | std::ifstream bed_ifstream; 51 | uint64 bed_bytes_per_snp; 52 | bool frequency_was_estimated = false; 53 | std::vector inbed; 54 | }; 55 | 56 | PermMat permute_plink(std::string &fin, const std::string &fout, uint gb, uint nbands); 57 | 58 | #endif // PCAONE_FILEPLINK_ 59 | -------------------------------------------------------------------------------- /external/Eigen/Geometry: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_GEOMETRY_MODULE_H 9 | #define EIGEN_GEOMETRY_MODULE_H 10 | 11 | #include "Core" 12 | 13 | #include "SVD" 14 | #include "LU" 15 | #include 16 | 17 | #include "src/Core/util/DisableStupidWarnings.h" 18 | 19 | /** \defgroup Geometry_Module Geometry module 20 | * 21 | * This module provides support for: 22 | * - fixed-size homogeneous transformations 23 | * - translation, scaling, 2D and 3D rotations 24 | * - \link Quaternion quaternions \endlink 25 | * - cross products (\ref MatrixBase::cross, \ref MatrixBase::cross3) 26 | * - orthognal vector generation (\ref MatrixBase::unitOrthogonal) 27 | * - some linear components: \link ParametrizedLine parametrized-lines \endlink and \link Hyperplane hyperplanes \endlink 28 | * - \link AlignedBox axis aligned bounding boxes \endlink 29 | * - \link umeyama least-square transformation fitting \endlink 30 | * 31 | * \code 32 | * #include 33 | * \endcode 34 | */ 35 | 36 | #include "src/Geometry/OrthoMethods.h" 37 | #include "src/Geometry/EulerAngles.h" 38 | 39 | #include "src/Geometry/Homogeneous.h" 40 | #include "src/Geometry/RotationBase.h" 41 | #include "src/Geometry/Rotation2D.h" 42 | #include "src/Geometry/Quaternion.h" 43 | #include "src/Geometry/AngleAxis.h" 44 | #include "src/Geometry/Transform.h" 45 | #include "src/Geometry/Translation.h" 46 | #include "src/Geometry/Scaling.h" 47 | #include "src/Geometry/Hyperplane.h" 48 | #include "src/Geometry/ParametrizedLine.h" 49 | #include "src/Geometry/AlignedBox.h" 50 | #include "src/Geometry/Umeyama.h" 51 | 52 | // Use the SSE optimized version whenever possible. 53 | #if (defined EIGEN_VECTORIZE_SSE) || (defined EIGEN_VECTORIZE_NEON) 54 | #include "src/Geometry/arch/Geometry_SIMD.h" 55 | #endif 56 | 57 | #include "src/Core/util/ReenableStupidWarnings.h" 58 | 59 | #endif // EIGEN_GEOMETRY_MODULE_H 60 | -------------------------------------------------------------------------------- /external/bgen/genotypes.h: -------------------------------------------------------------------------------- 1 | #ifndef BGEN_GENOTYPES_H_ 2 | #define BGEN_GENOTYPES_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | namespace bgen { 12 | 13 | class Genotypes { 14 | public: 15 | Genotypes(std::ifstream* _handle, int lay, int compr, int _n_alleles, std::uint32_t _n_samples, std::uint64_t _offset, std::uint32_t _length) : 16 | handle(_handle), layout(lay), compression(compr), n_alleles(_n_alleles), n_samples(_n_samples), file_offset(_offset), length(_length) {} 17 | Genotypes() {} 18 | ~Genotypes() { clear_probs(); } 19 | void load_data_and_parse_header(); 20 | void probabilities(float * probs); 21 | void get_allele_dosage(float * dose, bool use_alt=true, bool use_minor=false); 22 | bool phased=false; 23 | std::uint32_t max_probs=0; 24 | int min_ploidy=0; 25 | int max_ploidy=0; 26 | int minor_idx=0; 27 | std::uint8_t * ploidy={}; 28 | private: 29 | void decompress(); 30 | void parse_ploidy(); 31 | void probabilities_layout1(char * uncompressed, std::uint32_t idx, float * probs, std::uint32_t & nrows); 32 | void probabilities_layout2(char * uncompressed, std::uint32_t idx, float * probs, std::uint32_t & nrows); 33 | void fast_haplotype_probs(char * uncompressed, std::uint32_t idx, float * probs, std::uint32_t & nrows); 34 | void ref_dosage_fast(char * uncompressed, std::uint32_t idx, float * dose, std::uint32_t nrows); 35 | void ref_dosage_slow(char * uncompressed, std::uint32_t idx, float * dose, std::uint32_t nrows); 36 | void swap_allele_dosage(float * dose); 37 | int find_minor_allele(float * dose); 38 | void clear_probs(); 39 | std::ifstream* handle; 40 | int layout; 41 | int compression; 42 | int n_alleles; 43 | std::uint32_t n_samples; 44 | std::uint64_t file_offset; 45 | std::uint32_t length; 46 | std::uint32_t bit_depth=0; 47 | std::uint32_t idx=0; 48 | char * uncompressed={}; 49 | bool is_decompressed = false; 50 | bool constant_ploidy=true; 51 | bool has_ploidy = false; 52 | std::vector missing; 53 | }; 54 | 55 | std::uint32_t get_max_probs(int &max_ploidy, int &n_alleles, bool &phased); 56 | 57 | } // namespace bgen 58 | 59 | #endif // BGEN_GENOTYPES_H_ 60 | -------------------------------------------------------------------------------- /external/Eigen/IterativeLinearSolvers: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_ITERATIVELINEARSOLVERS_MODULE_H 9 | #define EIGEN_ITERATIVELINEARSOLVERS_MODULE_H 10 | 11 | #include "SparseCore" 12 | #include "OrderingMethods" 13 | 14 | #include "src/Core/util/DisableStupidWarnings.h" 15 | 16 | /** 17 | * \defgroup IterativeLinearSolvers_Module IterativeLinearSolvers module 18 | * 19 | * This module currently provides iterative methods to solve problems of the form \c A \c x = \c b, where \c A is a squared matrix, usually very large and sparse. 20 | * Those solvers are accessible via the following classes: 21 | * - ConjugateGradient for selfadjoint (hermitian) matrices, 22 | * - LeastSquaresConjugateGradient for rectangular least-square problems, 23 | * - BiCGSTAB for general square matrices. 24 | * 25 | * These iterative solvers are associated with some preconditioners: 26 | * - IdentityPreconditioner - not really useful 27 | * - DiagonalPreconditioner - also called Jacobi preconditioner, work very well on diagonal dominant matrices. 28 | * - IncompleteLUT - incomplete LU factorization with dual thresholding 29 | * 30 | * Such problems can also be solved using the direct sparse decomposition modules: SparseCholesky, CholmodSupport, UmfPackSupport, SuperLUSupport. 31 | * 32 | \code 33 | #include 34 | \endcode 35 | */ 36 | 37 | #include "src/IterativeLinearSolvers/SolveWithGuess.h" 38 | #include "src/IterativeLinearSolvers/IterativeSolverBase.h" 39 | #include "src/IterativeLinearSolvers/BasicPreconditioners.h" 40 | #include "src/IterativeLinearSolvers/ConjugateGradient.h" 41 | #include "src/IterativeLinearSolvers/LeastSquareConjugateGradient.h" 42 | #include "src/IterativeLinearSolvers/BiCGSTAB.h" 43 | #include "src/IterativeLinearSolvers/IncompleteLUT.h" 44 | #include "src/IterativeLinearSolvers/IncompleteCholesky.h" 45 | 46 | #include "src/Core/util/ReenableStupidWarnings.h" 47 | 48 | #endif // EIGEN_ITERATIVELINEARSOLVERS_MODULE_H 49 | -------------------------------------------------------------------------------- /external/Eigen/src/SparseLU/SparseLU_Utils.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2012 Désiré Nuentsa-Wakam 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | 11 | #ifndef EIGEN_SPARSELU_UTILS_H 12 | #define EIGEN_SPARSELU_UTILS_H 13 | 14 | namespace Eigen { 15 | namespace internal { 16 | 17 | /** 18 | * \brief Count Nonzero elements in the factors 19 | */ 20 | template 21 | void SparseLUImpl::countnz(const Index n, Index& nnzL, Index& nnzU, GlobalLU_t& glu) 22 | { 23 | nnzL = 0; 24 | nnzU = (glu.xusub)(n); 25 | Index nsuper = (glu.supno)(n); 26 | Index jlen; 27 | Index i, j, fsupc; 28 | if (n <= 0 ) return; 29 | // For each supernode 30 | for (i = 0; i <= nsuper; i++) 31 | { 32 | fsupc = glu.xsup(i); 33 | jlen = glu.xlsub(fsupc+1) - glu.xlsub(fsupc); 34 | 35 | for (j = fsupc; j < glu.xsup(i+1); j++) 36 | { 37 | nnzL += jlen; 38 | nnzU += j - fsupc + 1; 39 | jlen--; 40 | } 41 | } 42 | } 43 | 44 | /** 45 | * \brief Fix up the data storage lsub for L-subscripts. 46 | * 47 | * It removes the subscripts sets for structural pruning, 48 | * and applies permutation to the remaining subscripts 49 | * 50 | */ 51 | template 52 | void SparseLUImpl::fixupL(const Index n, const IndexVector& perm_r, GlobalLU_t& glu) 53 | { 54 | Index fsupc, i, j, k, jstart; 55 | 56 | StorageIndex nextl = 0; 57 | Index nsuper = (glu.supno)(n); 58 | 59 | // For each supernode 60 | for (i = 0; i <= nsuper; i++) 61 | { 62 | fsupc = glu.xsup(i); 63 | jstart = glu.xlsub(fsupc); 64 | glu.xlsub(fsupc) = nextl; 65 | for (j = jstart; j < glu.xlsub(fsupc + 1); j++) 66 | { 67 | glu.lsub(nextl) = perm_r(glu.lsub(j)); // Now indexed into P*A 68 | nextl++; 69 | } 70 | for (k = fsupc+1; k < glu.xsup(i+1); k++) 71 | glu.xlsub(k) = nextl; // other columns in supernode i 72 | } 73 | 74 | glu.xlsub(n) = nextl; 75 | } 76 | 77 | } // end namespace internal 78 | 79 | } // end namespace Eigen 80 | #endif // EIGEN_SPARSELU_UTILS_H 81 | -------------------------------------------------------------------------------- /external/zstd/lib/deprecated/zbuff_decompress.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under both the BSD-style license (found in the 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | * in the COPYING file in the root directory of this source tree). 8 | * You may select, at your option, one of the above-listed licenses. 9 | */ 10 | 11 | 12 | 13 | /* ************************************* 14 | * Dependencies 15 | ***************************************/ 16 | #define ZSTD_DISABLE_DEPRECATE_WARNINGS /* suppress warning on ZSTD_initDStream_usingDict */ 17 | #include "../zstd.h" /* ZSTD_CStream, ZSTD_DStream, ZSTDLIB_API */ 18 | #define ZBUFF_STATIC_LINKING_ONLY 19 | #include "zbuff.h" 20 | 21 | 22 | ZBUFF_DCtx* ZBUFF_createDCtx(void) 23 | { 24 | return ZSTD_createDStream(); 25 | } 26 | 27 | ZBUFF_DCtx* ZBUFF_createDCtx_advanced(ZSTD_customMem customMem) 28 | { 29 | return ZSTD_createDStream_advanced(customMem); 30 | } 31 | 32 | size_t ZBUFF_freeDCtx(ZBUFF_DCtx* zbd) 33 | { 34 | return ZSTD_freeDStream(zbd); 35 | } 36 | 37 | 38 | /* *** Initialization *** */ 39 | 40 | size_t ZBUFF_decompressInitDictionary(ZBUFF_DCtx* zbd, const void* dict, size_t dictSize) 41 | { 42 | return ZSTD_initDStream_usingDict(zbd, dict, dictSize); 43 | } 44 | 45 | size_t ZBUFF_decompressInit(ZBUFF_DCtx* zbd) 46 | { 47 | return ZSTD_initDStream(zbd); 48 | } 49 | 50 | 51 | /* *** Decompression *** */ 52 | 53 | size_t ZBUFF_decompressContinue(ZBUFF_DCtx* zbd, 54 | void* dst, size_t* dstCapacityPtr, 55 | const void* src, size_t* srcSizePtr) 56 | { 57 | ZSTD_outBuffer outBuff; 58 | ZSTD_inBuffer inBuff; 59 | size_t result; 60 | outBuff.dst = dst; 61 | outBuff.pos = 0; 62 | outBuff.size = *dstCapacityPtr; 63 | inBuff.src = src; 64 | inBuff.pos = 0; 65 | inBuff.size = *srcSizePtr; 66 | result = ZSTD_decompressStream(zbd, &outBuff, &inBuff); 67 | *dstCapacityPtr = outBuff.pos; 68 | *srcSizePtr = inBuff.pos; 69 | return result; 70 | } 71 | 72 | 73 | /* ************************************* 74 | * Tool functions 75 | ***************************************/ 76 | size_t ZBUFF_recommendedDInSize(void) { return ZSTD_DStreamInSize(); } 77 | size_t ZBUFF_recommendedDOutSize(void) { return ZSTD_DStreamOutSize(); } 78 | -------------------------------------------------------------------------------- /src/Projection.cpp: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * @file https://github.com/Zilong-Li/PCAone/src/Projection.cpp 3 | * @author Zilong Li 4 | * Copyright (C) 2024. Use of this code is governed by the LICENSE file. 5 | ******************************************************************************/ 6 | 7 | #include "Projection.hpp" 8 | 9 | #include "Utils.hpp" 10 | 11 | /** 12 | * options: 13 | * 1: simple, assume no missingness 14 | * 2: like smartPCA, solving g=Vx, can take missing genotypes 15 | * 3: OADP, laser2, can take missing genotypes 16 | */ 17 | void run_projection(Data* data, const Param& params) { 18 | check_bim_vs_mbim(params.filein + ".bim", params.filebim); 19 | cao.print(tick.date(), "run projection"); 20 | 21 | data->prepare(); 22 | data->standardize_E(); 23 | double p_miss = (double)data->C.count() / (double)data->C.size(); 24 | // Singular = sqrt(Eigen * M) 25 | Mat1D S = (read_eigvals(params.fileS) * data->nsnps / params.ploidy).array().sqrt(); 26 | const int pcs = S.size(); 27 | Mat2D V = read_eigvecs(params.fileV, data->nsnps, pcs); // M x K 28 | Mat2D U(data->nsamples, pcs); 29 | 30 | if (params.project == 1) { 31 | if (p_miss > 0) cao.warn("there are missing genotypes. recommend using --project 2 or 3."); 32 | // get 1 / Singular = sqrt(Eigen * M) 33 | V = V * (S.array().inverse().matrix().asDiagonal()); 34 | // G V = U D 35 | U = data->G * V; 36 | } else if (params.project == 2) { 37 | V = V * S.asDiagonal(); 38 | if (p_miss == 0.0) { 39 | cao.warn("there is no missing genotypes"); 40 | Eigen::ColPivHouseholderQR qr(V); 41 | #pragma omp parallel for 42 | for (uint i = 0; i < data->nsamples; i++) { 43 | // Vx = g 44 | U.row(i) = qr.solve(data->G.row(i).transpose()); 45 | } 46 | } else { 47 | #pragma omp parallel for 48 | for (uint i = 0; i < data->nsamples; i++) { 49 | // find non-missing snps for sample i 50 | Int1D idx; 51 | for (int j = 0; j < V.rows(); j++) { 52 | if (!data->C(j * data->nsamples + i)) idx.push_back(j); 53 | } 54 | // Vx = g 55 | U.row(i) = V(idx, Eigen::all).colPivHouseholderQr().solve(data->G(i, idx).transpose()); 56 | } 57 | } 58 | } else { 59 | cao.error("have not implemented yet"); 60 | } 61 | 62 | data->write_eigs_files(S.array().square() / data->nsnps, S, U, V); 63 | } 64 | -------------------------------------------------------------------------------- /external/zstd/lib/compress/zstd_compress_sequences.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under both the BSD-style license (found in the 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | * in the COPYING file in the root directory of this source tree). 8 | * You may select, at your option, one of the above-listed licenses. 9 | */ 10 | 11 | #ifndef ZSTD_COMPRESS_SEQUENCES_H 12 | #define ZSTD_COMPRESS_SEQUENCES_H 13 | 14 | #include "zstd_compress_internal.h" /* SeqDef */ 15 | #include "../common/fse.h" /* FSE_repeat, FSE_CTable */ 16 | #include "../common/zstd_internal.h" /* SymbolEncodingType_e, ZSTD_strategy */ 17 | 18 | typedef enum { 19 | ZSTD_defaultDisallowed = 0, 20 | ZSTD_defaultAllowed = 1 21 | } ZSTD_DefaultPolicy_e; 22 | 23 | SymbolEncodingType_e 24 | ZSTD_selectEncodingType( 25 | FSE_repeat* repeatMode, unsigned const* count, unsigned const max, 26 | size_t const mostFrequent, size_t nbSeq, unsigned const FSELog, 27 | FSE_CTable const* prevCTable, 28 | short const* defaultNorm, U32 defaultNormLog, 29 | ZSTD_DefaultPolicy_e const isDefaultAllowed, 30 | ZSTD_strategy const strategy); 31 | 32 | size_t 33 | ZSTD_buildCTable(void* dst, size_t dstCapacity, 34 | FSE_CTable* nextCTable, U32 FSELog, SymbolEncodingType_e type, 35 | unsigned* count, U32 max, 36 | const BYTE* codeTable, size_t nbSeq, 37 | const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax, 38 | const FSE_CTable* prevCTable, size_t prevCTableSize, 39 | void* entropyWorkspace, size_t entropyWorkspaceSize); 40 | 41 | size_t ZSTD_encodeSequences( 42 | void* dst, size_t dstCapacity, 43 | FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, 44 | FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, 45 | FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, 46 | SeqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2); 47 | 48 | size_t ZSTD_fseBitCost( 49 | FSE_CTable const* ctable, 50 | unsigned const* count, 51 | unsigned const max); 52 | 53 | size_t ZSTD_crossEntropyCost(short const* norm, unsigned accuracyLog, 54 | unsigned const* count, unsigned const max); 55 | #endif /* ZSTD_COMPRESS_SEQUENCES_H */ 56 | -------------------------------------------------------------------------------- /external/Eigen/src/SparseCore/MappedSparseMatrix.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2008-2014 Gael Guennebaud 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | #ifndef EIGEN_MAPPED_SPARSEMATRIX_H 11 | #define EIGEN_MAPPED_SPARSEMATRIX_H 12 | 13 | namespace Eigen { 14 | 15 | /** \deprecated Use Map > 16 | * \class MappedSparseMatrix 17 | * 18 | * \brief Sparse matrix 19 | * 20 | * \param _Scalar the scalar type, i.e. the type of the coefficients 21 | * 22 | * See http://www.netlib.org/linalg/html_templates/node91.html for details on the storage scheme. 23 | * 24 | */ 25 | namespace internal { 26 | template 27 | struct traits > : traits > 28 | {}; 29 | } // end namespace internal 30 | 31 | template 32 | class MappedSparseMatrix 33 | : public Map > 34 | { 35 | typedef Map > Base; 36 | 37 | public: 38 | 39 | typedef typename Base::StorageIndex StorageIndex; 40 | typedef typename Base::Scalar Scalar; 41 | 42 | inline MappedSparseMatrix(Index rows, Index cols, Index nnz, StorageIndex* outerIndexPtr, StorageIndex* innerIndexPtr, Scalar* valuePtr, StorageIndex* innerNonZeroPtr = 0) 43 | : Base(rows, cols, nnz, outerIndexPtr, innerIndexPtr, valuePtr, innerNonZeroPtr) 44 | {} 45 | 46 | /** Empty destructor */ 47 | inline ~MappedSparseMatrix() {} 48 | }; 49 | 50 | namespace internal { 51 | 52 | template 53 | struct evaluator > 54 | : evaluator > > 55 | { 56 | typedef MappedSparseMatrix<_Scalar,_Options,_StorageIndex> XprType; 57 | typedef evaluator > Base; 58 | 59 | evaluator() : Base() {} 60 | explicit evaluator(const XprType &mat) : Base(mat) {} 61 | }; 62 | 63 | } 64 | 65 | } // end namespace Eigen 66 | 67 | #endif // EIGEN_MAPPED_SPARSEMATRIX_H 68 | -------------------------------------------------------------------------------- /external/Eigen/SuperLUSupport: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_SUPERLUSUPPORT_MODULE_H 9 | #define EIGEN_SUPERLUSUPPORT_MODULE_H 10 | 11 | #include "SparseCore" 12 | 13 | #include "src/Core/util/DisableStupidWarnings.h" 14 | 15 | #ifdef EMPTY 16 | #define EIGEN_EMPTY_WAS_ALREADY_DEFINED 17 | #endif 18 | 19 | typedef int int_t; 20 | #include 21 | #include 22 | #include 23 | 24 | // slu_util.h defines a preprocessor token named EMPTY which is really polluting, 25 | // so we remove it in favor of a SUPERLU_EMPTY token. 26 | // If EMPTY was already defined then we don't undef it. 27 | 28 | #if defined(EIGEN_EMPTY_WAS_ALREADY_DEFINED) 29 | # undef EIGEN_EMPTY_WAS_ALREADY_DEFINED 30 | #elif defined(EMPTY) 31 | # undef EMPTY 32 | #endif 33 | 34 | #define SUPERLU_EMPTY (-1) 35 | 36 | namespace Eigen { struct SluMatrix; } 37 | 38 | /** \ingroup Support_modules 39 | * \defgroup SuperLUSupport_Module SuperLUSupport module 40 | * 41 | * This module provides an interface to the SuperLU library. 42 | * It provides the following factorization class: 43 | * - class SuperLU: a supernodal sequential LU factorization. 44 | * - class SuperILU: a supernodal sequential incomplete LU factorization (to be used as a preconditioner for iterative methods). 45 | * 46 | * \warning This wrapper requires at least versions 4.0 of SuperLU. The 3.x versions are not supported. 47 | * 48 | * \warning When including this module, you have to use SUPERLU_EMPTY instead of EMPTY which is no longer defined because it is too polluting. 49 | * 50 | * \code 51 | * #include 52 | * \endcode 53 | * 54 | * In order to use this module, the superlu headers must be accessible from the include paths, and your binary must be linked to the superlu library and its dependencies. 55 | * The dependencies depend on how superlu has been compiled. 56 | * For a cmake based project, you can use our FindSuperLU.cmake module to help you in this task. 57 | * 58 | */ 59 | 60 | #include "src/SuperLUSupport/SuperLUSupport.h" 61 | 62 | #include "src/Core/util/ReenableStupidWarnings.h" 63 | 64 | #endif // EIGEN_SUPERLUSUPPORT_MODULE_H 65 | -------------------------------------------------------------------------------- /external/Eigen/SparseCore: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_SPARSECORE_MODULE_H 9 | #define EIGEN_SPARSECORE_MODULE_H 10 | 11 | #include "Core" 12 | 13 | #include "src/Core/util/DisableStupidWarnings.h" 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | /** 22 | * \defgroup SparseCore_Module SparseCore module 23 | * 24 | * This module provides a sparse matrix representation, and basic associated matrix manipulations 25 | * and operations. 26 | * 27 | * See the \ref TutorialSparse "Sparse tutorial" 28 | * 29 | * \code 30 | * #include 31 | * \endcode 32 | * 33 | * This module depends on: Core. 34 | */ 35 | 36 | #include "src/SparseCore/SparseUtil.h" 37 | #include "src/SparseCore/SparseMatrixBase.h" 38 | #include "src/SparseCore/SparseAssign.h" 39 | #include "src/SparseCore/CompressedStorage.h" 40 | #include "src/SparseCore/AmbiVector.h" 41 | #include "src/SparseCore/SparseCompressedBase.h" 42 | #include "src/SparseCore/SparseMatrix.h" 43 | #include "src/SparseCore/SparseMap.h" 44 | #include "src/SparseCore/MappedSparseMatrix.h" 45 | #include "src/SparseCore/SparseVector.h" 46 | #include "src/SparseCore/SparseRef.h" 47 | #include "src/SparseCore/SparseCwiseUnaryOp.h" 48 | #include "src/SparseCore/SparseCwiseBinaryOp.h" 49 | #include "src/SparseCore/SparseTranspose.h" 50 | #include "src/SparseCore/SparseBlock.h" 51 | #include "src/SparseCore/SparseDot.h" 52 | #include "src/SparseCore/SparseRedux.h" 53 | #include "src/SparseCore/SparseView.h" 54 | #include "src/SparseCore/SparseDiagonalProduct.h" 55 | #include "src/SparseCore/ConservativeSparseSparseProduct.h" 56 | #include "src/SparseCore/SparseSparseProductWithPruning.h" 57 | #include "src/SparseCore/SparseProduct.h" 58 | #include "src/SparseCore/SparseDenseProduct.h" 59 | #include "src/SparseCore/SparseSelfAdjointView.h" 60 | #include "src/SparseCore/SparseTriangularView.h" 61 | #include "src/SparseCore/TriangularSolver.h" 62 | #include "src/SparseCore/SparsePermutation.h" 63 | #include "src/SparseCore/SparseFuzzy.h" 64 | #include "src/SparseCore/SparseSolverBase.h" 65 | 66 | #include "src/Core/util/ReenableStupidWarnings.h" 67 | 68 | #endif // EIGEN_SPARSECORE_MODULE_H 69 | 70 | -------------------------------------------------------------------------------- /external/zstd/lib/dictBuilder/divsufsort.h: -------------------------------------------------------------------------------- 1 | /* 2 | * divsufsort.h for libdivsufsort-lite 3 | * Copyright (c) 2003-2008 Yuta Mori All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person 6 | * obtaining a copy of this software and associated documentation 7 | * files (the "Software"), to deal in the Software without 8 | * restriction, including without limitation the rights to use, 9 | * copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the 11 | * Software is furnished to do so, subject to the following 12 | * conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be 15 | * included in all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 18 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 19 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 20 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 21 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 22 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 23 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 24 | * OTHER DEALINGS IN THE SOFTWARE. 25 | */ 26 | 27 | #ifndef _DIVSUFSORT_H 28 | #define _DIVSUFSORT_H 1 29 | 30 | /*- Prototypes -*/ 31 | 32 | /** 33 | * Constructs the suffix array of a given string. 34 | * @param T [0..n-1] The input string. 35 | * @param SA [0..n-1] The output array of suffixes. 36 | * @param n The length of the given string. 37 | * @param openMP enables OpenMP optimization. 38 | * @return 0 if no error occurred, -1 or -2 otherwise. 39 | */ 40 | int 41 | divsufsort(const unsigned char *T, int *SA, int n, int openMP); 42 | 43 | /** 44 | * Constructs the burrows-wheeler transformed string of a given string. 45 | * @param T [0..n-1] The input string. 46 | * @param U [0..n-1] The output string. (can be T) 47 | * @param A [0..n-1] The temporary array. (can be NULL) 48 | * @param n The length of the given string. 49 | * @param num_indexes The length of secondary indexes array. (can be NULL) 50 | * @param indexes The secondary indexes array. (can be NULL) 51 | * @param openMP enables OpenMP optimization. 52 | * @return The primary index if no error occurred, -1 or -2 otherwise. 53 | */ 54 | int 55 | divbwt(const unsigned char *T, unsigned char *U, int *A, int n, unsigned char * num_indexes, int * indexes, int openMP); 56 | 57 | #endif /* _DIVSUFSORT_H */ 58 | -------------------------------------------------------------------------------- /scripts/summarise_ld_r2bin.cpp: -------------------------------------------------------------------------------- 1 | // -*- compile-command: "g++ summarise_ld_r2bin.cpp -o summarise_ld_r2bin -O3 -std=c++17 -lz"; -*- 2 | #include 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | static bool parseGzipLineByLine(const std::string& filename, 11 | std::function callback) { 12 | gzFile file = gzopen(filename.c_str(), "rb"); 13 | if (!file) { 14 | return false; 15 | } 16 | 17 | char buffer[1024]; // should be enough 18 | std::string line; 19 | 20 | while (gzgets(file, buffer, sizeof(buffer))) { 21 | line = buffer; 22 | 23 | // Remove trailing newline if present 24 | if (!line.empty() && line.back() == '\n') { 25 | line.pop_back(); 26 | } 27 | 28 | callback(line); 29 | } 30 | 31 | bool success = !gzeof(file) || gzerror(file, nullptr) == Z_OK; 32 | gzclose(file); 33 | return success; 34 | } 35 | 36 | int main(int argc, char** argv) { 37 | std::vector args(argv + 1, argv + argc); 38 | if (argc <= 1 || args[0] == "-h" || args[0] == "-help" || args[0] == "--help") { 39 | std::cout << "-i input file .ld.gz from pcaone or plink\n"; 40 | return 1; 41 | } 42 | 43 | std::string in; 44 | for (size_t i = 0; i < args.size(); i++) { 45 | if (args[i] == "-i") in = args[++i]; 46 | } 47 | 48 | std::map> iChr; 49 | std::vector>> res; 50 | 51 | int dA{0}, dB{0}, d{0}, num{0}; 52 | double r2{0}; 53 | int n = 0; // the n-th line 54 | std::istringstream iss; 55 | std::string chr, chrA, chrB, idA, idB; 56 | 57 | parseGzipLineByLine(in, [&](const std::string& line) { 58 | n++; 59 | if (n == 1) return; 60 | iss.clear(); 61 | iss.str(line); 62 | iss >> chrA >> dA >> idA >> chrB >> dB >> idB >> r2; 63 | if (chr.empty()) { 64 | chr = chrA; 65 | } else { 66 | if (chr != chrA) { 67 | res.push_back(iChr); 68 | iChr.clear(); 69 | chr = chrA; 70 | } 71 | } 72 | d = dB - dA; 73 | iChr[d].first += r2; 74 | iChr[d].second += 1; 75 | }); 76 | res.push_back(iChr); 77 | iChr.clear(); 78 | 79 | std::cout << "Chrom\tDistance\tR2Total\tnumPairs\n"; 80 | for (size_t i = 0; i < res.size(); i++) { 81 | for (const auto& [k, v] : res[i]) { 82 | std::cout << i + 1 << "\t" << k << "\t" << v.first << "\t" << v.second << "\n"; 83 | } 84 | } 85 | 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/arch/AVX512/TypeCasting.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2019 Rasmus Munk Larsen 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | #ifndef EIGEN_TYPE_CASTING_AVX512_H 11 | #define EIGEN_TYPE_CASTING_AVX512_H 12 | 13 | namespace Eigen { 14 | 15 | namespace internal { 16 | 17 | template<> EIGEN_STRONG_INLINE Packet16i pcast(const Packet16f& a) { 18 | return _mm512_cvttps_epi32(a); 19 | } 20 | 21 | template<> EIGEN_STRONG_INLINE Packet16f pcast(const Packet16i& a) { 22 | return _mm512_cvtepi32_ps(a); 23 | } 24 | 25 | template<> EIGEN_STRONG_INLINE Packet16i preinterpret(const Packet16f& a) { 26 | return _mm512_castps_si512(a); 27 | } 28 | 29 | template<> EIGEN_STRONG_INLINE Packet16f preinterpret(const Packet16i& a) { 30 | return _mm512_castsi512_ps(a); 31 | } 32 | 33 | template <> 34 | struct type_casting_traits { 35 | enum { 36 | VectorizedCast = 1, 37 | SrcCoeffRatio = 1, 38 | TgtCoeffRatio = 1 39 | }; 40 | }; 41 | 42 | template<> EIGEN_STRONG_INLINE Packet16f pcast(const Packet16h& a) { 43 | return half2float(a); 44 | } 45 | 46 | template <> 47 | struct type_casting_traits { 48 | enum { 49 | VectorizedCast = 1, 50 | SrcCoeffRatio = 1, 51 | TgtCoeffRatio = 1 52 | }; 53 | }; 54 | 55 | template<> EIGEN_STRONG_INLINE Packet16h pcast(const Packet16f& a) { 56 | return float2half(a); 57 | } 58 | 59 | template <> 60 | struct type_casting_traits { 61 | enum { 62 | VectorizedCast = 1, 63 | SrcCoeffRatio = 1, 64 | TgtCoeffRatio = 1 65 | }; 66 | }; 67 | 68 | template<> EIGEN_STRONG_INLINE Packet16f pcast(const Packet16bf& a) { 69 | return Bf16ToF32(a); 70 | } 71 | 72 | template <> 73 | struct type_casting_traits { 74 | enum { 75 | VectorizedCast = 1, 76 | SrcCoeffRatio = 1, 77 | TgtCoeffRatio = 1 78 | }; 79 | }; 80 | 81 | template<> EIGEN_STRONG_INLINE Packet16bf pcast(const Packet16f& a) { 82 | return F32ToBf16(a); 83 | } 84 | 85 | } // end namespace internal 86 | 87 | } // end namespace Eigen 88 | 89 | #endif // EIGEN_TYPE_CASTING_AVX512_H 90 | -------------------------------------------------------------------------------- /src/Data.hpp: -------------------------------------------------------------------------------- 1 | #ifndef PCAONE_DATA_ 2 | #define PCAONE_DATA_ 3 | 4 | #include "Cmd.hpp" 5 | #include "Utils.hpp" 6 | 7 | const double VAR_TOL = 1e-9; 8 | 9 | class Data { 10 | public: 11 | Data(const Param& params_) : params(params_) {} 12 | 13 | virtual ~Data() = default; 14 | 15 | virtual void read_all() = 0; 16 | // for blockwise 17 | virtual void check_file_offset_first_var() = 0; 18 | virtual void read_block_initial(uint64 start_idx, uint64 stop_idx, bool standardize) = 0; 19 | virtual void read_block_update(uint64 start_idx, uint64 stop_idx, const Mat2D& U, const Mat1D& svals, 20 | const Mat2D& VT, bool standardize) = 0; 21 | 22 | void prepare(); 23 | void standardize_E(); 24 | void filter_snps_resize_F(); 25 | void save_snps_in_bim(); 26 | void pcangsd_standardize_E(const Mat2D& U, const Mat1D& svals, const Mat2D& VT); 27 | void fit_with_pi(const Mat2D& U, const Mat1D& svals, const Mat2D& VT); 28 | void write_eigs_files(const Mat1D& E, const Mat1D& S, const Mat2D& U, const Mat2D& V); 29 | void write_residuals(const Mat1D& S, const Mat2D& U, const Mat2D& VT); 30 | // for blockwise 31 | // void fit_with_pi_block(const Mat2D& U, const Mat1D& svals, const Mat2D& VT); 32 | void calcu_vt_initial(const Mat2D& T, Mat2D& VT, bool standardize); 33 | void calcu_vt_update(const Mat2D& T, const Mat2D& U, const Mat1D& svals, Mat2D& VT, bool standardize); 34 | // given PCs, predict the missing values, then update in place by block 35 | void predict_missing_E(const Mat2D& U,uint64 start_idx, uint64 stop_idx); 36 | 37 | const Param& params; 38 | 39 | double readtime = 0; 40 | bool snpmajor = true; 41 | bool nsamples_ge_nsnps = false; // if nsamples greater than or equal to nsnps 42 | bool impute = false; // true if emu is enabled and there are missing values 43 | uint blocksize = 0, nsamples = 0, nsnps = 0; 44 | uint nblocks = 1; 45 | uint bandFactor = 1; 46 | uint nops = 0; 47 | std::vector start, stop; 48 | PermMat perm; // permuation order of SNPs 49 | Mat2D G; // genotype matrix, can be initial E or centered E, which is nsamples x nsnps; 50 | Mat2D P; // normalized genotype likelihoods, (nsamples x 2) x nsnps. 51 | Mat1D F; // observed or estimated population allele frequency 52 | Mat1D Dc; // diagnal vector of covariance matrix 53 | ArrBool C; // nsnps x nsample, if there is missing value 54 | Arr2D centered_geno_lookup; 55 | std::vector keepSNPs; // store index of SNPs to keep 56 | }; 57 | 58 | #endif // PCAONE_DATA_ 59 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/arch/GPU/TypeCasting.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2016 Benoit Steiner 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | #ifndef EIGEN_TYPE_CASTING_GPU_H 11 | #define EIGEN_TYPE_CASTING_GPU_H 12 | 13 | namespace Eigen { 14 | 15 | namespace internal { 16 | 17 | #if (defined(EIGEN_HAS_CUDA_FP16) && defined(EIGEN_CUDA_ARCH) && EIGEN_CUDA_ARCH >= 300) || \ 18 | (defined(EIGEN_HAS_HIP_FP16) && defined(EIGEN_HIP_DEVICE_COMPILE)) 19 | 20 | 21 | template <> 22 | struct type_casting_traits { 23 | enum { 24 | VectorizedCast = 1, 25 | SrcCoeffRatio = 1, 26 | TgtCoeffRatio = 2 27 | }; 28 | }; 29 | 30 | template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pcast(const half2& a, const half2& b) { 31 | float2 r1 = __half22float2(a); 32 | float2 r2 = __half22float2(b); 33 | return make_float4(r1.x, r1.y, r2.x, r2.y); 34 | } 35 | 36 | 37 | template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet4h2 pcast(const float4& a, const float4& b) { 38 | Packet4h2 r; 39 | half2* r_alias=reinterpret_cast(&r); 40 | r_alias[0]=__floats2half2_rn(a.x,a.y); 41 | r_alias[1]=__floats2half2_rn(a.z,a.w); 42 | r_alias[2]=__floats2half2_rn(b.x,b.y); 43 | r_alias[3]=__floats2half2_rn(b.z,b.w); 44 | return r; 45 | } 46 | 47 | template <> 48 | struct type_casting_traits { 49 | enum { 50 | VectorizedCast = 1, 51 | SrcCoeffRatio = 2, 52 | TgtCoeffRatio = 1 53 | }; 54 | }; 55 | 56 | template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pcast(const Packet4h2& a) { 57 | // Simply discard the second half of the input 58 | float4 r; 59 | const half2* a_alias=reinterpret_cast(&a); 60 | float2 r1 = __half22float2(a_alias[0]); 61 | float2 r2 = __half22float2(a_alias[1]); 62 | r.x=static_cast(r1.x); 63 | r.y=static_cast(r1.y); 64 | r.z=static_cast(r2.x); 65 | r.w=static_cast(r2.y); 66 | return r; 67 | } 68 | 69 | template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE half2 pcast(const float4& a) { 70 | // Simply discard the second half of the input 71 | return __floats2half2_rn(a.x, a.y); 72 | } 73 | 74 | #endif 75 | 76 | } // end namespace internal 77 | 78 | } // end namespace Eigen 79 | 80 | #endif // EIGEN_TYPE_CASTING_GPU_H 81 | -------------------------------------------------------------------------------- /external/bgen/writer.h: -------------------------------------------------------------------------------- 1 | #ifndef BGEN_BGEN_H_ 2 | #define BGEN_BGEN_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | namespace bgen { 10 | 11 | class CppBgenWriter { 12 | public: 13 | std::ofstream handle; 14 | std::uint32_t n_samples; 15 | std::uint32_t compression; 16 | std::uint32_t layout; 17 | std::uint32_t n_variants=0; 18 | std::uint32_t nvars_offset=8; 19 | std::uint32_t variant_data_offset=0; 20 | public: 21 | CppBgenWriter(std::string &path, 22 | std::uint32_t _n_samples, 23 | std::string &free_data, 24 | uint32_t _compression, 25 | uint32_t _layout, 26 | std::vector &samples) : n_samples(_n_samples), 27 | compression(_compression), 28 | layout(_layout) 29 | { 30 | handle.open(path, std::ios::out | std::ios::binary); 31 | write_header(free_data, samples); 32 | add_samples(samples); 33 | } 34 | CppBgenWriter() {} 35 | ~CppBgenWriter(); 36 | void write_header(std::string &free_data, 37 | std::vector &samples); 38 | void add_samples(std::vector &samples); 39 | std::uint64_t write_variant_header(std::string &varid, 40 | std::string &rsid, 41 | std::string &chrom, 42 | std::uint32_t &pos, 43 | std::vector &alleles, 44 | std::uint32_t _n_samples); 45 | std::uint64_t write_variant_direct(std::vector & data); 46 | std::uint64_t add_genotype_data(std::uint16_t n_alleles, 47 | double *genotypes, 48 | std::uint32_t geno_len, 49 | std::uint8_t ploidy = 2, 50 | bool phased = 0, 51 | std::uint8_t bit_depth = 8); 52 | std::uint64_t add_genotype_data(std::uint16_t n_alleles, 53 | double *genotypes, 54 | std::uint32_t geno_len, 55 | uint8_t *ploidy, 56 | std::uint8_t min_ploidy = 2, 57 | std::uint8_t max_ploidy = 2, 58 | bool phased = 0, 59 | std::uint8_t bit_depth = 8); 60 | }; 61 | 62 | } // namespace bgen 63 | 64 | #endif // BGEN_BGEN_H_ 65 | -------------------------------------------------------------------------------- /external/bgen/samples.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "samples.h" 8 | #include "utils.h" 9 | 10 | namespace bgen { 11 | 12 | Samples::Samples(std::ifstream & handle, int n_samples) { 13 | /* initialize sample list if present in the bgen file 14 | */ 15 | std::uint32_t sample_header_length; 16 | handle.read(reinterpret_cast(&sample_header_length), sizeof(std::uint32_t)); 17 | 18 | std::uint32_t sample_n_check; 19 | handle.read(reinterpret_cast(&sample_n_check), sizeof(std::uint32_t)); 20 | if (n_samples != (int) sample_n_check) { 21 | throw std::invalid_argument("inconsistent number of samples"); 22 | } 23 | 24 | samples.resize(n_samples); 25 | std::uint16_t id_len; 26 | for (int i=0; i(&id_len), sizeof(id_len)); 28 | std::string sample_id; 29 | std::copy_n(std::istream_iterator(handle), id_len, std::back_inserter(sample_id)); 30 | samples[i] = sample_id; 31 | } 32 | } 33 | 34 | Samples::Samples(std::string path, int n_samples) { 35 | /* initialize from external sample file 36 | */ 37 | std::ifstream handle(path, std::ios::in); 38 | if (!handle) { 39 | throw std::invalid_argument("error with sample file: '" + path + "'"); 40 | } 41 | 42 | std::string header; 43 | std::getline(handle, header); 44 | std::string types; 45 | std::getline(handle, types); 46 | 47 | // find the file length post header, then read it all in to memory 48 | auto pos = handle.tellg(); 49 | handle.seekg(0, std::ios::end); 50 | auto fsize = (std::uint64_t) handle.tellg() - pos; 51 | std::string lines(fsize, '\0'); 52 | handle.seekg(pos); 53 | handle.read(&lines[0], fsize); 54 | 55 | samples.resize(n_samples); 56 | std::string sample_id; 57 | std::istringstream iss(lines); 58 | 59 | // run through all lines and gte the first column as sample_id 60 | int idx = 0; 61 | std::string line; 62 | while (std::getline(iss, line, '\n')) { 63 | samples[idx] = line.substr(0, line.find(' ')); 64 | idx += 1; 65 | } 66 | 67 | if (idx != n_samples) { 68 | throw std::invalid_argument("inconsistent number of samples"); 69 | } 70 | 71 | if (n_samples != (int)samples.size()) { 72 | throw std::invalid_argument("inconsistent number of samples"); 73 | } 74 | } 75 | 76 | Samples::Samples(int n_samples) { 77 | /* initialize with integer IDs if no sample list available 78 | */ 79 | samples.resize(n_samples); 80 | for (int i=0; insnps; } // for snpmajor input 57 | Index cols() const { return data->nsamples; } 58 | Index ranks() const { return nk; } 59 | Index oversamples() const { return os; } 60 | 61 | void computeGandH(Mat2D& G, Mat2D& H, int pi = 0); 62 | }; 63 | 64 | class FancyRsvdOpData : public RsvdOpData { 65 | private: 66 | const Index nk, os, size; 67 | uint64 bandsize, blocksize, actual_block_size, start_idx, stop_idx; 68 | Mat2D H1, H2; 69 | 70 | public: 71 | FancyRsvdOpData(Data* data_, int k_, int os_ = 10) : RsvdOpData(data_), nk(k_), os(os_), size(k_ + os_) { 72 | initOmg(); 73 | H1 = Mat2D::Zero(cols(), size); 74 | H2 = Mat2D::Zero(cols(), size); 75 | } 76 | 77 | ~FancyRsvdOpData() {} 78 | 79 | Index rows() const { return data->nsnps; } 80 | Index cols() const { return data->nsamples; } 81 | Index ranks() const { return nk; } 82 | Index oversamples() const { return os; } 83 | 84 | void computeGandH(Mat2D& G, Mat2D& H, int pi = 0); 85 | }; 86 | 87 | void run_pca_with_halko(Data* data, const Param& params); 88 | 89 | #endif // PCAONE_HALKO_ 90 | -------------------------------------------------------------------------------- /external/Spectra/MatOp/internal/SymGEigsRegInvOp.h: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2017-2022 Yixuan Qiu 2 | // 3 | // This Source Code Form is subject to the terms of the Mozilla 4 | // Public License v. 2.0. If a copy of the MPL was not distributed 5 | // with this file, You can obtain one at https://mozilla.org/MPL/2.0/. 6 | 7 | #ifndef SPECTRA_SYM_GEIGS_REG_INV_OP_H 8 | #define SPECTRA_SYM_GEIGS_REG_INV_OP_H 9 | 10 | #include 11 | 12 | #include "../SparseSymMatProd.h" 13 | #include "../SparseRegularInverse.h" 14 | 15 | namespace Spectra { 16 | 17 | /// 18 | /// \ingroup Operators 19 | /// 20 | /// This class defines the matrix operation for generalized eigen solver in the 21 | /// regular inverse mode. This class is intended for internal use. 22 | /// 23 | template , 24 | typename BOpType = SparseRegularInverse> 25 | class SymGEigsRegInvOp 26 | { 27 | public: 28 | using Scalar = typename OpType::Scalar; 29 | 30 | private: 31 | using Index = Eigen::Index; 32 | using Vector = Eigen::Matrix; 33 | 34 | const OpType& m_op; 35 | const BOpType& m_Bop; 36 | mutable Vector m_cache; // temporary working space 37 | 38 | public: 39 | /// 40 | /// Constructor to create the matrix operation object. 41 | /// 42 | /// \param op The \f$A\f$ matrix operation object. 43 | /// \param Bop The \f$B\f$ matrix operation object. 44 | /// 45 | SymGEigsRegInvOp(const OpType& op, const BOpType& Bop) : 46 | m_op(op), m_Bop(Bop), m_cache(op.rows()) 47 | {} 48 | 49 | /// 50 | /// Move constructor. 51 | /// 52 | SymGEigsRegInvOp(SymGEigsRegInvOp&& other) : 53 | m_op(other.m_op), m_Bop(other.m_Bop) 54 | { 55 | // We emulate the move constructor for Vector using Vector::swap() 56 | m_cache.swap(other.m_cache); 57 | } 58 | 59 | /// 60 | /// Return the number of rows of the underlying matrix. 61 | /// 62 | Index rows() const { return m_Bop.rows(); } 63 | /// 64 | /// Return the number of columns of the underlying matrix. 65 | /// 66 | Index cols() const { return m_Bop.rows(); } 67 | 68 | /// 69 | /// Perform the matrix operation \f$y=B^{-1}Ax\f$. 70 | /// 71 | /// \param x_in Pointer to the \f$x\f$ vector. 72 | /// \param y_out Pointer to the \f$y\f$ vector. 73 | /// 74 | // y_out = inv(B) * A * x_in 75 | void perform_op(const Scalar* x_in, Scalar* y_out) const 76 | { 77 | m_op.perform_op(x_in, m_cache.data()); 78 | m_Bop.solve(m_cache.data(), y_out); 79 | } 80 | }; 81 | 82 | } // namespace Spectra 83 | 84 | #endif // SPECTRA_SYM_GEIGS_REG_INV_OP_H 85 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/arch/AltiVec/MathFunctions.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2007 Julien Pommier 5 | // Copyright (C) 2009 Gael Guennebaud 6 | // Copyright (C) 2016 Konstantinos Margaritis 7 | // 8 | // This Source Code Form is subject to the terms of the Mozilla 9 | // Public License v. 2.0. If a copy of the MPL was not distributed 10 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | 12 | #ifndef EIGEN_MATH_FUNCTIONS_ALTIVEC_H 13 | #define EIGEN_MATH_FUNCTIONS_ALTIVEC_H 14 | 15 | namespace Eigen { 16 | 17 | namespace internal { 18 | 19 | template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED 20 | Packet4f plog(const Packet4f& _x) 21 | { 22 | return plog_float(_x); 23 | } 24 | 25 | template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED 26 | Packet4f pexp(const Packet4f& _x) 27 | { 28 | return pexp_float(_x); 29 | } 30 | 31 | template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED 32 | Packet4f psin(const Packet4f& _x) 33 | { 34 | return psin_float(_x); 35 | } 36 | 37 | template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED 38 | Packet4f pcos(const Packet4f& _x) 39 | { 40 | return pcos_float(_x); 41 | } 42 | 43 | #ifndef EIGEN_COMP_CLANG 44 | template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED 45 | Packet4f prsqrt(const Packet4f& x) 46 | { 47 | return vec_rsqrt(x); 48 | } 49 | #endif 50 | 51 | #ifdef __VSX__ 52 | #ifndef EIGEN_COMP_CLANG 53 | template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED 54 | Packet2d prsqrt(const Packet2d& x) 55 | { 56 | return vec_rsqrt(x); 57 | } 58 | #endif 59 | 60 | template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED 61 | Packet4f psqrt(const Packet4f& x) 62 | { 63 | return vec_sqrt(x); 64 | } 65 | 66 | template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED 67 | Packet2d psqrt(const Packet2d& x) 68 | { 69 | return vec_sqrt(x); 70 | } 71 | 72 | template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED 73 | Packet2d pexp(const Packet2d& _x) 74 | { 75 | return pexp_double(_x); 76 | } 77 | #endif 78 | 79 | // Hyperbolic Tangent function. 80 | template <> 81 | EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet4f 82 | ptanh(const Packet4f& x) { 83 | return internal::generic_fast_tanh_float(x); 84 | } 85 | 86 | } // end namespace internal 87 | 88 | } // end namespace Eigen 89 | 90 | #endif // EIGEN_MATH_FUNCTIONS_ALTIVEC_H 91 | -------------------------------------------------------------------------------- /external/Eigen/OrderingMethods: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // This Source Code Form is subject to the terms of the Mozilla 5 | // Public License v. 2.0. If a copy of the MPL was not distributed 6 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | 8 | #ifndef EIGEN_ORDERINGMETHODS_MODULE_H 9 | #define EIGEN_ORDERINGMETHODS_MODULE_H 10 | 11 | #include "SparseCore" 12 | 13 | #include "src/Core/util/DisableStupidWarnings.h" 14 | 15 | /** 16 | * \defgroup OrderingMethods_Module OrderingMethods module 17 | * 18 | * This module is currently for internal use only 19 | * 20 | * It defines various built-in and external ordering methods for sparse matrices. 21 | * They are typically used to reduce the number of elements during 22 | * the sparse matrix decomposition (LLT, LU, QR). 23 | * Precisely, in a preprocessing step, a permutation matrix P is computed using 24 | * those ordering methods and applied to the columns of the matrix. 25 | * Using for instance the sparse Cholesky decomposition, it is expected that 26 | * the nonzeros elements in LLT(A*P) will be much smaller than that in LLT(A). 27 | * 28 | * 29 | * Usage : 30 | * \code 31 | * #include 32 | * \endcode 33 | * 34 | * A simple usage is as a template parameter in the sparse decomposition classes : 35 | * 36 | * \code 37 | * SparseLU > solver; 38 | * \endcode 39 | * 40 | * \code 41 | * SparseQR > solver; 42 | * \endcode 43 | * 44 | * It is possible as well to call directly a particular ordering method for your own purpose, 45 | * \code 46 | * AMDOrdering ordering; 47 | * PermutationMatrix perm; 48 | * SparseMatrix A; 49 | * //Fill the matrix ... 50 | * 51 | * ordering(A, perm); // Call AMD 52 | * \endcode 53 | * 54 | * \note Some of these methods (like AMD or METIS), need the sparsity pattern 55 | * of the input matrix to be symmetric. When the matrix is structurally unsymmetric, 56 | * Eigen computes internally the pattern of \f$A^T*A\f$ before calling the method. 57 | * If your matrix is already symmetric (at leat in structure), you can avoid that 58 | * by calling the method with a SelfAdjointView type. 59 | * 60 | * \code 61 | * // Call the ordering on the pattern of the lower triangular matrix A 62 | * ordering(A.selfadjointView(), perm); 63 | * \endcode 64 | */ 65 | 66 | #include "src/OrderingMethods/Amd.h" 67 | #include "src/OrderingMethods/Ordering.h" 68 | #include "src/Core/util/ReenableStupidWarnings.h" 69 | 70 | #endif // EIGEN_ORDERINGMETHODS_MODULE_H 71 | -------------------------------------------------------------------------------- /src/LD.hpp: -------------------------------------------------------------------------------- 1 | #ifndef PCAONE_LD_ 2 | #define PCAONE_LD_ 3 | 4 | #include "Cmd.hpp" 5 | #include "Data.hpp" 6 | #include "Utils.hpp" 7 | 8 | struct SNPld { 9 | std::vector pos; // pos of each SNP 10 | std::vector end_pos; // 0-based index for last snp pos 11 | std::vector chr; // chr sequences 12 | Double1D af; // allele frequency 13 | std::vector ws; // the snp index, i.e the index for lead SNP 14 | std::vector we; // the number of SNPs (including lead SNP) in a window 15 | }; 16 | 17 | // get the chr, bp, id 18 | struct BIM { 19 | std::string data; 20 | operator std::string const &() const { return data; } 21 | friend std::istream& operator>>(std::istream& is, BIM& BIM) { 22 | std::getline(is, BIM.data); 23 | if (BIM.data.empty()) return is; 24 | auto token = split_string(BIM.data, " \t"); 25 | BIM.data = token[0] + "\t" + token[3] + "\t" + token[1]; 26 | return is; 27 | } 28 | }; 29 | 30 | Arr1D calc_sds(const Mat2D& X); 31 | 32 | double calc_cor(const Mat1D& x, const Mat1D& y, const double df); 33 | 34 | std::string get_snp_pos_bim(SNPld& snp, const std::string& filebim, bool header = false, 35 | Int1D idx = Int1D{0, 3}); 36 | 37 | std::tuple get_target_snp_idx(const SNPld& snp_t, const SNPld& snp); 38 | 39 | void divide_pos_by_window(SNPld& snp, const int ld_window_bp); 40 | 41 | void ld_prune_small(Data* data, const std::string& fileout, const std::string& filebim, const SNPld& snp, 42 | const double r2_tol); 43 | 44 | void ld_prune_big(const Mat2D& G, const SNPld& snp, double r2_tol, const std::string& fileout, 45 | const std::string& filebim); 46 | 47 | void ld_clump_single_pheno(const std::string& fileout, const std::string& head, const int clump_bp, 48 | const double clump_r2, const double clump_p1, const double clump_p2, 49 | const Mat2D& G, const Int2D& idx_per_chr, const Int2D& bp_per_chr, 50 | const std::vector& pvals_per_chr); 51 | 52 | Int1D valid_assoc_file(const std::string& fileassoc, const std::string& colnames); 53 | 54 | std::vector map_index_snps(const std::string& fileassoc, const Int1D& colidx, double clump_p2); 55 | 56 | std::vector map_assoc_file(const std::string& fileassoc, const Int1D& colidx); 57 | 58 | void ld_r2_big(const Mat2D& G, const SNPld& snp, const std::string& filebim, const std::string& fileout); 59 | 60 | void ld_r2_small(Data* data, const SNPld& snp, const std::string& filebim, const std::string& fileout); 61 | 62 | void run_ld_stuff(Data* data, const Param& params); 63 | 64 | #endif // PCAONE_LD_ 65 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/NestByValue.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2008 Gael Guennebaud 5 | // Copyright (C) 2006-2008 Benoit Jacob 6 | // 7 | // This Source Code Form is subject to the terms of the Mozilla 8 | // Public License v. 2.0. If a copy of the MPL was not distributed 9 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 10 | 11 | #ifndef EIGEN_NESTBYVALUE_H 12 | #define EIGEN_NESTBYVALUE_H 13 | 14 | namespace Eigen { 15 | 16 | namespace internal { 17 | template 18 | struct traits > : public traits 19 | { 20 | enum { 21 | Flags = traits::Flags & ~NestByRefBit 22 | }; 23 | }; 24 | } 25 | 26 | /** \class NestByValue 27 | * \ingroup Core_Module 28 | * 29 | * \brief Expression which must be nested by value 30 | * 31 | * \tparam ExpressionType the type of the object of which we are requiring nesting-by-value 32 | * 33 | * This class is the return type of MatrixBase::nestByValue() 34 | * and most of the time this is the only way it is used. 35 | * 36 | * \sa MatrixBase::nestByValue() 37 | */ 38 | template class NestByValue 39 | : public internal::dense_xpr_base< NestByValue >::type 40 | { 41 | public: 42 | 43 | typedef typename internal::dense_xpr_base::type Base; 44 | EIGEN_DENSE_PUBLIC_INTERFACE(NestByValue) 45 | 46 | EIGEN_DEVICE_FUNC explicit inline NestByValue(const ExpressionType& matrix) : m_expression(matrix) {} 47 | 48 | EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const EIGEN_NOEXCEPT { return m_expression.rows(); } 49 | EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const EIGEN_NOEXCEPT { return m_expression.cols(); } 50 | 51 | EIGEN_DEVICE_FUNC operator const ExpressionType&() const { return m_expression; } 52 | 53 | EIGEN_DEVICE_FUNC const ExpressionType& nestedExpression() const { return m_expression; } 54 | 55 | protected: 56 | const ExpressionType m_expression; 57 | }; 58 | 59 | /** \returns an expression of the temporary version of *this. 60 | */ 61 | template 62 | EIGEN_DEVICE_FUNC inline const NestByValue 63 | DenseBase::nestByValue() const 64 | { 65 | return NestByValue(derived()); 66 | } 67 | 68 | namespace internal { 69 | 70 | // Evaluator of Solve -> eval into a temporary 71 | template 72 | struct evaluator > 73 | : public evaluator 74 | { 75 | typedef evaluator Base; 76 | 77 | EIGEN_DEVICE_FUNC explicit evaluator(const NestByValue& xpr) 78 | : Base(xpr.nestedExpression()) 79 | {} 80 | }; 81 | } 82 | 83 | } // end namespace Eigen 84 | 85 | #endif // EIGEN_NESTBYVALUE_H 86 | -------------------------------------------------------------------------------- /external/Spectra/Util/TypeTraits.h: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018-2022 Yixuan Qiu 2 | // 3 | // This Source Code Form is subject to the terms of the Mozilla 4 | // Public License v. 2.0. If a copy of the MPL was not distributed 5 | // with this file, You can obtain one at https://mozilla.org/MPL/2.0/. 6 | 7 | #ifndef SPECTRA_TYPE_TRAITS_H 8 | #define SPECTRA_TYPE_TRAITS_H 9 | 10 | #include 11 | #include 12 | 13 | /// \cond 14 | 15 | // Clang-Format will have unintended effects: 16 | // static constexpr Scalar(min)() 17 | // So we turn it off here 18 | // 19 | // clang-format off 20 | 21 | namespace Spectra { 22 | 23 | // For a real value type "Scalar", we want to know its smallest 24 | // positive value, i.e., std::numeric_limits::min(). 25 | // However, we must take non-standard value types into account, 26 | // so we rely on Eigen::NumTraits. 27 | // 28 | // Eigen::NumTraits has defined epsilon() and lowest(), but 29 | // lowest() means negative highest(), which is a very small 30 | // negative value. 31 | // 32 | // Therefore, we manually define this limit, and use eplison()^3 33 | // to mimic it for non-standard types. 34 | 35 | // Generic definition 36 | template 37 | struct TypeTraits 38 | { 39 | static constexpr Scalar epsilon() 40 | { 41 | return Eigen::numext::numeric_limits::epsilon(); 42 | } 43 | static constexpr Scalar (min)() 44 | { 45 | return epsilon() * epsilon() * epsilon(); 46 | } 47 | }; 48 | 49 | // Full specialization 50 | template <> 51 | struct TypeTraits 52 | { 53 | static constexpr float epsilon() 54 | { 55 | return std::numeric_limits::epsilon(); 56 | } 57 | static constexpr float (min)() 58 | { 59 | return (std::numeric_limits::min)(); 60 | } 61 | }; 62 | 63 | template <> 64 | struct TypeTraits 65 | { 66 | static constexpr double epsilon() 67 | { 68 | return std::numeric_limits::epsilon(); 69 | } 70 | static constexpr double (min)() 71 | { 72 | return (std::numeric_limits::min)(); 73 | } 74 | }; 75 | 76 | template <> 77 | struct TypeTraits 78 | { 79 | static constexpr long double epsilon() 80 | { 81 | return std::numeric_limits::epsilon(); 82 | } 83 | static constexpr long double (min)() 84 | { 85 | return (std::numeric_limits::min)(); 86 | } 87 | }; 88 | 89 | // Get the element type of a "scalar" 90 | // ElemType => double 91 | // ElemType> => double 92 | template 93 | using ElemType = typename Eigen::NumTraits::Real; 94 | 95 | } // namespace Spectra 96 | 97 | /// \endcond 98 | 99 | #endif // SPECTRA_TYPE_TRAITS_H 100 | -------------------------------------------------------------------------------- /external/zstd/lib/common/pool.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under both the BSD-style license (found in the 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | * in the COPYING file in the root directory of this source tree). 8 | * You may select, at your option, one of the above-listed licenses. 9 | */ 10 | 11 | #ifndef POOL_H 12 | #define POOL_H 13 | 14 | 15 | #include "zstd_deps.h" 16 | #define ZSTD_STATIC_LINKING_ONLY /* ZSTD_customMem */ 17 | #include "../zstd.h" 18 | 19 | typedef struct POOL_ctx_s POOL_ctx; 20 | 21 | /*! POOL_create() : 22 | * Create a thread pool with at most `numThreads` threads. 23 | * `numThreads` must be at least 1. 24 | * The maximum number of queued jobs before blocking is `queueSize`. 25 | * @return : POOL_ctx pointer on success, else NULL. 26 | */ 27 | POOL_ctx* POOL_create(size_t numThreads, size_t queueSize); 28 | 29 | POOL_ctx* POOL_create_advanced(size_t numThreads, size_t queueSize, 30 | ZSTD_customMem customMem); 31 | 32 | /*! POOL_free() : 33 | * Free a thread pool returned by POOL_create(). 34 | */ 35 | void POOL_free(POOL_ctx* ctx); 36 | 37 | 38 | /*! POOL_joinJobs() : 39 | * Waits for all queued jobs to finish executing. 40 | */ 41 | void POOL_joinJobs(POOL_ctx* ctx); 42 | 43 | /*! POOL_resize() : 44 | * Expands or shrinks pool's number of threads. 45 | * This is more efficient than releasing + creating a new context, 46 | * since it tries to preserve and reuse existing threads. 47 | * `numThreads` must be at least 1. 48 | * @return : 0 when resize was successful, 49 | * !0 (typically 1) if there is an error. 50 | * note : only numThreads can be resized, queueSize remains unchanged. 51 | */ 52 | int POOL_resize(POOL_ctx* ctx, size_t numThreads); 53 | 54 | /*! POOL_sizeof() : 55 | * @return threadpool memory usage 56 | * note : compatible with NULL (returns 0 in this case) 57 | */ 58 | size_t POOL_sizeof(const POOL_ctx* ctx); 59 | 60 | /*! POOL_function : 61 | * The function type that can be added to a thread pool. 62 | */ 63 | typedef void (*POOL_function)(void*); 64 | 65 | /*! POOL_add() : 66 | * Add the job `function(opaque)` to the thread pool. `ctx` must be valid. 67 | * Possibly blocks until there is room in the queue. 68 | * Note : The function may be executed asynchronously, 69 | * therefore, `opaque` must live until function has been completed. 70 | */ 71 | void POOL_add(POOL_ctx* ctx, POOL_function function, void* opaque); 72 | 73 | 74 | /*! POOL_tryAdd() : 75 | * Add the job `function(opaque)` to thread pool _if_ a queue slot is available. 76 | * Returns immediately even if not (does not block). 77 | * @return : 1 if successful, 0 if not. 78 | */ 79 | int POOL_tryAdd(POOL_ctx* ctx, POOL_function function, void* opaque); 80 | 81 | #endif 82 | -------------------------------------------------------------------------------- /scripts/plot-loadings.R: -------------------------------------------------------------------------------- 1 | library(data.table) 2 | library(caTools) 3 | 4 | mycols <- c("#FB8072", "#80B1D3", "#FDB462", "#B3DE69", "#FCCDE5", "#BEBADA", "#FFED6F", "#8DD3C7") 5 | palette(mycols) 6 | 7 | df <- fread("pcaone.loadings", h = F, data.table = F) 8 | npc <- ncol(df) 9 | bim <- fread("plink.bim", h = F, data.table = F) 10 | bim <- bim[, c(1, 2, 4)] 11 | stopifnot(nrow(bim) == nrow(df)) 12 | df <- cbind(bim, df) 13 | colnames(df) <- c("chr", "snp", "bp", paste0("pc", 1:npc)) 14 | chrtable <- table(df$chr) 15 | 16 | window <- 1000 17 | mat <- apply(df[, -(1:3)], 2, function(x) abs(caTools::runmax(x, k = window))) 18 | groups <- list( 19 | "Population structure" = c(1, 2, 4), 20 | "Centromere" = c(3, 5, 8, 9, 10, 11, 13, 14, 19, 20, 22, 29, 32, 34, 35, 37), 21 | "HLA" = c(6, 12, 15, 16, 27, 30, 38), 22 | "Other structure" = c(7, 17, 18, 23:26, 28, 31, 33, 36, 39, 40), 23 | "Inversion" = c(21) 24 | ) 25 | 26 | # anno : a vecotor of pc to be colored 27 | plotLegend <- function(anno = c(1, 2)) { 28 | par(mar = c(0, 0, 0, 0), mgp = c(2, 0.6, 0)) 29 | plot(0, 0, col = "transparent", axes = F, xlab = "", ylab = "") 30 | cats <- names(groups) 31 | letext <- c(cats, paste0("PC", anno)) 32 | legend("bottomleft", 33 | legend = letext, col = 1:length(letext), pch = c(rep(16, length(cats)), rep(NA, 3)), 34 | lty = c(rep(NA, length(cats)), rep(1, 3)), adj = 0, lwd = 4, pt.cex = 3.0, cex = 1.2, text.font = 2, 35 | horiz = T, xjust = 0, yjust = 0, xpd = T, inset = c(0, 0), bty = "n", x.intersp = 0.1 36 | ) 37 | } 38 | 39 | 40 | plotLoadings <- function(mat, chrtable, groups, anno = c(1, 2), title = NULL) { 41 | if (!is.list(groups)) stop("groups must be a list") 42 | cats <- names(groups) 43 | ymax <- c(0, max(mat)) * 1.05 44 | nchr <- length(chrtable) 45 | par(mar = c(3.5, 3.5, 4, 1), mgp = c(2, 0.6, 0)) 46 | 47 | plot(1:nrow(mat), mat[, 1], 48 | type = "l", col = "gray60", lwd = 2, cex.main = 1.5, cex.axis = 1.5, cex.lab = 1.5, 49 | ylim = ymax, axes = F, xlab = "Chromosomes", ylab = "SNP loadings", main = title 50 | ) 51 | axis(2, cex.lab = 1.5, cex.axis = 1.5) 52 | ## text(cumsum(as.vector(chrtable)) - chrtable/2, rep(-0.001,22), 1:22, pch = "|", xpd = T, ...) 53 | text(cumsum(as.vector(chrtable)) - chrtable / 2, rep(-ymax[2] / 30, nchr), 1:nchr, pch = "|", xpd = T, cex = 1.1) 54 | apply(mat, 2, function(x) lines(1:nrow(mat), x, lwd = 2, col = "gray60")) 55 | if (is.vector(anno)) { 56 | sapply(1:length(anno), function(i) lines(1:nrow(mat), mat[, anno[i]], lwd = 2, col = i + length(cats))) 57 | } 58 | abline(v = cumsum(as.vector(chrtable)), col = "white", lwd = 3) 59 | w <- apply(mat, 2, which.max) 60 | for (i in 1:ncol(mat)) { 61 | c <- which(cats == names(which(sapply(groups, function(x) i %in% x)))) 62 | points(w[i], mat[w[i], i], col = c, pch = 16, cex = 3) 63 | text(w[i], mat[w[i], i], i) 64 | } 65 | } 66 | 67 | plotLoadings(mat, chrtable, groups) 68 | -------------------------------------------------------------------------------- /external/Spectra/MatOp/internal/SymGEigsCholeskyOp.h: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2016-2022 Yixuan Qiu 2 | // 3 | // This Source Code Form is subject to the terms of the Mozilla 4 | // Public License v. 2.0. If a copy of the MPL was not distributed 5 | // with this file, You can obtain one at https://mozilla.org/MPL/2.0/. 6 | 7 | #ifndef SPECTRA_SYM_GEIGS_CHOLESKY_OP_H 8 | #define SPECTRA_SYM_GEIGS_CHOLESKY_OP_H 9 | 10 | #include 11 | 12 | #include "../DenseSymMatProd.h" 13 | #include "../DenseCholesky.h" 14 | 15 | namespace Spectra { 16 | 17 | /// 18 | /// \ingroup Operators 19 | /// 20 | /// This class defines the matrix operation for generalized eigen solver in the 21 | /// Cholesky decomposition mode. It calculates \f$y=L^{-1}A(L')^{-1}x\f$ for any 22 | /// vector \f$x\f$, where \f$L\f$ is the Cholesky decomposition of \f$B\f$. 23 | /// This class is intended for internal use. 24 | /// 25 | template , 26 | typename BOpType = DenseCholesky> 27 | class SymGEigsCholeskyOp 28 | { 29 | public: 30 | using Scalar = typename OpType::Scalar; 31 | 32 | private: 33 | using Index = Eigen::Index; 34 | using Vector = Eigen::Matrix; 35 | 36 | const OpType& m_op; 37 | const BOpType& m_Bop; 38 | mutable Vector m_cache; // temporary working space 39 | 40 | public: 41 | /// 42 | /// Constructor to create the matrix operation object. 43 | /// 44 | /// \param op The \f$A\f$ matrix operation object. 45 | /// \param Bop The \f$B\f$ matrix operation object. 46 | /// 47 | SymGEigsCholeskyOp(const OpType& op, const BOpType& Bop) : 48 | m_op(op), m_Bop(Bop), m_cache(op.rows()) 49 | {} 50 | 51 | /// 52 | /// Move constructor. 53 | /// 54 | SymGEigsCholeskyOp(SymGEigsCholeskyOp&& other) : 55 | m_op(other.m_op), m_Bop(other.m_Bop) 56 | { 57 | // We emulate the move constructor for Vector using Vector::swap() 58 | m_cache.swap(other.m_cache); 59 | } 60 | 61 | /// 62 | /// Return the number of rows of the underlying matrix. 63 | /// 64 | Index rows() const { return m_Bop.rows(); } 65 | /// 66 | /// Return the number of columns of the underlying matrix. 67 | /// 68 | Index cols() const { return m_Bop.rows(); } 69 | 70 | /// 71 | /// Perform the matrix operation \f$y=L^{-1}A(L')^{-1}x\f$. 72 | /// 73 | /// \param x_in Pointer to the \f$x\f$ vector. 74 | /// \param y_out Pointer to the \f$y\f$ vector. 75 | /// 76 | // y_out = inv(L) * A * inv(L') * x_in 77 | void perform_op(const Scalar* x_in, Scalar* y_out) const 78 | { 79 | m_Bop.upper_triangular_solve(x_in, y_out); 80 | m_op.perform_op(y_out, m_cache.data()); 81 | m_Bop.lower_triangular_solve(m_cache.data(), y_out); 82 | } 83 | }; 84 | 85 | } // namespace Spectra 86 | 87 | #endif // SPECTRA_SYM_GEIGS_CHOLESKY_OP_H 88 | -------------------------------------------------------------------------------- /src/FileBeagle.cpp: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * @file https://github.com/Zilong-Li/PCAone/src/FileBeagle.cpp 3 | * @author Zilong Li 4 | * Copyright (C) 2022-2024. Use of this code is governed by the LICENSE file. 5 | ******************************************************************************/ 6 | 7 | #include "FileBeagle.hpp" 8 | 9 | using namespace std; 10 | 11 | // read all data and estimate F 12 | void FileBeagle::read_all() { 13 | P = Mat2D::Zero(nsamples * 2, nsnps); 14 | fp = gzopen(params.filein.c_str(), "r"); 15 | parse_beagle_file(P, fp, nsamples, nsnps); 16 | if (!params.pca) return; 17 | cao.print(tick.date(), "begin to estimate allele frequencies"); 18 | F = Mat1D::Constant(nsnps, 0.25); 19 | emMAF_with_GL(F, P, params.maxiter, params.tolmaf); 20 | // filter snps and resize G; 21 | filter_snps_resize_F(); 22 | // resize P, only keep columns matching the indecis in idx; 23 | // P = P(Eigen::all, idx).eval(); // aliasing issue!!! 24 | G = Mat2D::Zero(nsamples, nsnps); // initial E which is G 25 | #pragma omp parallel for 26 | for (uint j = 0; j < nsnps; j++) { 27 | double p0, p1, p2; 28 | uint s = params.keepsnp ? keepSNPs[j] : j; 29 | for (uint i = 0; i < nsamples; i++) { 30 | p0 = P(2 * i + 0, s) * (1.0 - F(j)) * (1.0 - F(j)); 31 | p1 = P(2 * i + 1, s) * 2 * F(j) * (1.0 - F(j)); 32 | p2 = (1 - P(2 * i + 0, s) - P(2 * i + 1, s)) * F(j) * F(j); 33 | G(i, j) = (p1 + 2 * p2) / (p0 + p1 + p2) - 2.0 * F(j); 34 | } 35 | } 36 | } 37 | 38 | void FileBeagle::check_file_offset_first_var() { 39 | if (params.verbose) cao.print("reopen beagle file and read head line"); 40 | fp = gzopen(params.filein.c_str(), "r"); 41 | tgets(fp, &buffer, &bufsize); // parse header line 42 | if (buffer != original) original = buffer; 43 | } 44 | 45 | void FileBeagle::read_block_initial(uint64 start_idx, uint64 stop_idx, bool standardize = false) { 46 | if (params.pca) cao.error("doesn't support out-of-core PCAngsd algorithm"); 47 | uint actual_block_size = stop_idx - start_idx + 1; 48 | if (G.cols() < blocksize || (actual_block_size < blocksize)) { 49 | P = Mat2D::Zero(nsamples * 2, actual_block_size); 50 | } 51 | const char *delims = "\t \n"; 52 | char* tok; 53 | // read all GL data into P 54 | for (uint j = 0; j < actual_block_size; ++j) { 55 | tgets(fp, &buffer, &bufsize); // get a line 56 | if (buffer != original) original = buffer; 57 | tok = strtok_r(buffer, delims, &buffer); 58 | tok = strtok_r(NULL, delims, &buffer); 59 | tok = strtok_r(NULL, delims, &buffer); 60 | for (uint i = 0; i < nsamples; i++) { 61 | tok = strtok_r(NULL, delims, &buffer); 62 | P(2 * i + 0, j) = strtod(tok, NULL); 63 | tok = strtok_r(NULL, delims, &buffer); 64 | P(2 * i + 1, j) = strtod(tok, NULL); 65 | tok = strtok_r(NULL, delims, &buffer); 66 | } 67 | buffer = original; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/Cmd.hpp: -------------------------------------------------------------------------------- 1 | #ifndef CMD_H_ 2 | #define CMD_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | typedef unsigned int uint; 9 | typedef unsigned long long uint64; 10 | 11 | enum class FileType { PLINK, CSV, BEAGLE, BINARY, BGEN }; 12 | 13 | enum class SvdType { IRAM, PCAoneAlg1, PCAoneAlg2, FULL }; 14 | 15 | class Param { 16 | public: 17 | Param(int argc, char** argv); 18 | ~Param(); 19 | 20 | FileType file_t; // PLINK, CSV, BEAGLE, BGEN 21 | SvdType svd_t; 22 | std::string fileU, fileS, fileV; 23 | std::string filein; 24 | std::string fileout = "pcaone"; 25 | double memory = 0; // 0 for disable 26 | uint nsamples = 0; 27 | uint nsnps = 0; 28 | uint k = 10; 29 | uint maxp = 20; // maximum number of power iterations 30 | uint threads = 12; 31 | uint bands = 64; 32 | bool pca = true; 33 | // for normalization 34 | double scaleFactor = 1; 35 | // for emu iteration 36 | uint maxiter = 100; 37 | double alpha = 0.001; 38 | // can be tol_emu or tol_pcangsd 39 | double tolem = 1e-5; 40 | double tolmaf = 1e-6; 41 | double maf = 0.0; 42 | // for arnoldi 43 | uint ncv = 20; // max(20, 2*k + 1) 44 | uint imaxiter = 1000; 45 | double itol = 1e-6; 46 | // for halko 47 | uint oversamples = 10; 48 | double tol = 1e-4; 49 | uint buffer = 2; 50 | uint rand = 1; 51 | bool perm = false; // wheather data is permuted 52 | // for ld stuff 53 | bool print_r2 = false; 54 | // for ld pruning 55 | std::string filebim; // the 7-th column can be MAF 56 | int ld_stats = 0; // 0: adj; 1: std 57 | double ld_r2 = 0; 58 | bool ld = false; // true if tolld > 0 59 | uint ld_bp = 0; // base pairs not number of snps 60 | // for clumping 61 | std::string clump; 62 | std::string assoc_colnames; 63 | double clump_p1 = 0.0001; 64 | double clump_p2 = 0.01; 65 | double clump_r2 = 0.5; 66 | uint clump_bp = 250000; 67 | // for projection 68 | int project = 0; 69 | // for inbreeding 70 | int inbreed = 0; 71 | 72 | // general 73 | uint verbose = 1; // verbose level. 0: no verbose; 1: output to screen; 2: debug info 74 | uint scale = 0; // do scaling. 0: just centering. 1: log scaling. 2: cpmed 75 | bool groff = false; 76 | bool cpmed = false; 77 | bool printv = false; 78 | bool impute = false; // enable EM-PCA for data with uncertainty. impute information! 79 | bool noshuffle = false; 80 | bool emu = false; 81 | bool pcangsd = false; // enable pcangsd procedure 82 | // bool fancyem = false; // true if emu/pcangsd + svd 2 83 | bool mev = true; 84 | bool out_of_core = false; // otherwise load all matrix into RAM. 85 | int ploidy = 2; 86 | int seed = 101; // seeding 87 | bool keepsnp = false; 88 | bool center = true; // false if G is raw data likelihood 89 | bool estaf = true; // false if project,inbreed enabled 90 | // bool estpi = false; // true if output pi is needed 91 | 92 | std::ostringstream ss; 93 | }; 94 | 95 | #endif // CMD_H_ 96 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/arch/SYCL/TypeCasting.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Mehdi Goli Codeplay Software Ltd. 5 | // Ralph Potter Codeplay Software Ltd. 6 | // Luke Iwanski Codeplay Software Ltd. 7 | // Contact: 8 | // 9 | // This Source Code Form is subject to the terms of the Mozilla 10 | // Public License v. 2.0. If a copy of the MPL was not distributed 11 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 12 | 13 | /***************************************************************** 14 | * TypeCasting.h 15 | * 16 | * \brief: 17 | * TypeCasting 18 | * 19 | *****************************************************************/ 20 | 21 | #ifndef EIGEN_TYPE_CASTING_SYCL_H 22 | #define EIGEN_TYPE_CASTING_SYCL_H 23 | 24 | namespace Eigen { 25 | 26 | namespace internal { 27 | #ifdef SYCL_DEVICE_ONLY 28 | template <> 29 | struct type_casting_traits { 30 | enum { VectorizedCast = 1, SrcCoeffRatio = 1, TgtCoeffRatio = 1 }; 31 | }; 32 | 33 | template <> 34 | EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE cl::sycl::cl_int4 35 | pcast(const cl::sycl::cl_float4& a) { 36 | return a 37 | .template convert(); 38 | } 39 | 40 | template <> 41 | struct type_casting_traits { 42 | enum { VectorizedCast = 1, SrcCoeffRatio = 1, TgtCoeffRatio = 1 }; 43 | }; 44 | 45 | template <> 46 | EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE cl::sycl::cl_float4 47 | pcast(const cl::sycl::cl_int4& a) { 48 | return a.template convert(); 50 | } 51 | 52 | template <> 53 | struct type_casting_traits { 54 | enum { VectorizedCast = 1, SrcCoeffRatio = 2, TgtCoeffRatio = 1 }; 55 | }; 56 | 57 | template <> 58 | EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE cl::sycl::cl_float4 59 | pcast( 60 | const cl::sycl::cl_double2& a, const cl::sycl::cl_double2& b) { 61 | auto a1 = a.template convert(); 63 | auto b1 = b.template convert(); 65 | return cl::sycl::float4(a1.x(), a1.y(), b1.x(), b1.y()); 66 | } 67 | 68 | template <> 69 | struct type_casting_traits { 70 | enum { VectorizedCast = 1, SrcCoeffRatio = 1, TgtCoeffRatio = 2 }; 71 | }; 72 | 73 | template <> 74 | EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE cl::sycl::cl_double2 75 | pcast(const cl::sycl::cl_float4& a) { 76 | // Simply discard the second half of the input 77 | return cl::sycl::cl_double2(a.x(), a.y()); 78 | } 79 | 80 | #endif 81 | } // end namespace internal 82 | 83 | } // end namespace Eigen 84 | 85 | #endif // EIGEN_TYPE_CASTING_SYCL_H 86 | -------------------------------------------------------------------------------- /external/zstd/lib/decompress/zstd_decompress_block.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under both the BSD-style license (found in the 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 | * in the COPYING file in the root directory of this source tree). 8 | * You may select, at your option, one of the above-listed licenses. 9 | */ 10 | 11 | 12 | #ifndef ZSTD_DEC_BLOCK_H 13 | #define ZSTD_DEC_BLOCK_H 14 | 15 | /*-******************************************************* 16 | * Dependencies 17 | *********************************************************/ 18 | #include "../common/zstd_deps.h" /* size_t */ 19 | #include "../zstd.h" /* DCtx, and some public functions */ 20 | #include "../common/zstd_internal.h" /* blockProperties_t, and some public functions */ 21 | #include "zstd_decompress_internal.h" /* ZSTD_seqSymbol */ 22 | 23 | 24 | /* === Prototypes === */ 25 | 26 | /* note: prototypes already published within `zstd.h` : 27 | * ZSTD_decompressBlock() 28 | */ 29 | 30 | /* note: prototypes already published within `zstd_internal.h` : 31 | * ZSTD_getcBlockSize() 32 | * ZSTD_decodeSeqHeaders() 33 | */ 34 | 35 | 36 | /* Streaming state is used to inform allocation of the literal buffer */ 37 | typedef enum { 38 | not_streaming = 0, 39 | is_streaming = 1 40 | } streaming_operation; 41 | 42 | /* ZSTD_decompressBlock_internal() : 43 | * decompress block, starting at `src`, 44 | * into destination buffer `dst`. 45 | * @return : decompressed block size, 46 | * or an error code (which can be tested using ZSTD_isError()) 47 | */ 48 | size_t ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx, 49 | void* dst, size_t dstCapacity, 50 | const void* src, size_t srcSize, const streaming_operation streaming); 51 | 52 | /* ZSTD_buildFSETable() : 53 | * generate FSE decoding table for one symbol (ll, ml or off) 54 | * this function must be called with valid parameters only 55 | * (dt is large enough, normalizedCounter distribution total is a power of 2, max is within range, etc.) 56 | * in which case it cannot fail. 57 | * The workspace must be 4-byte aligned and at least ZSTD_BUILD_FSE_TABLE_WKSP_SIZE bytes, which is 58 | * defined in zstd_decompress_internal.h. 59 | * Internal use only. 60 | */ 61 | void ZSTD_buildFSETable(ZSTD_seqSymbol* dt, 62 | const short* normalizedCounter, unsigned maxSymbolValue, 63 | const U32* baseValue, const U8* nbAdditionalBits, 64 | unsigned tableLog, void* wksp, size_t wkspSize, 65 | int bmi2); 66 | 67 | /* Internal definition of ZSTD_decompressBlock() to avoid deprecation warnings. */ 68 | size_t ZSTD_decompressBlock_deprecated(ZSTD_DCtx* dctx, 69 | void* dst, size_t dstCapacity, 70 | const void* src, size_t srcSize); 71 | 72 | 73 | #endif /* ZSTD_DEC_BLOCK_H */ 74 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/Swap.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2006-2008 Benoit Jacob 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | #ifndef EIGEN_SWAP_H 11 | #define EIGEN_SWAP_H 12 | 13 | namespace Eigen { 14 | 15 | namespace internal { 16 | 17 | // Overload default assignPacket behavior for swapping them 18 | template 19 | class generic_dense_assignment_kernel, Specialized> 20 | : public generic_dense_assignment_kernel, BuiltIn> 21 | { 22 | protected: 23 | typedef generic_dense_assignment_kernel, BuiltIn> Base; 24 | using Base::m_dst; 25 | using Base::m_src; 26 | using Base::m_functor; 27 | 28 | public: 29 | typedef typename Base::Scalar Scalar; 30 | typedef typename Base::DstXprType DstXprType; 31 | typedef swap_assign_op Functor; 32 | 33 | EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE 34 | generic_dense_assignment_kernel(DstEvaluatorTypeT &dst, const SrcEvaluatorTypeT &src, const Functor &func, DstXprType& dstExpr) 35 | : Base(dst, src, func, dstExpr) 36 | {} 37 | 38 | template 39 | EIGEN_STRONG_INLINE void assignPacket(Index row, Index col) 40 | { 41 | PacketType tmp = m_src.template packet(row,col); 42 | const_cast(m_src).template writePacket(row,col, m_dst.template packet(row,col)); 43 | m_dst.template writePacket(row,col,tmp); 44 | } 45 | 46 | template 47 | EIGEN_STRONG_INLINE void assignPacket(Index index) 48 | { 49 | PacketType tmp = m_src.template packet(index); 50 | const_cast(m_src).template writePacket(index, m_dst.template packet(index)); 51 | m_dst.template writePacket(index,tmp); 52 | } 53 | 54 | // TODO find a simple way not to have to copy/paste this function from generic_dense_assignment_kernel, by simple I mean no CRTP (Gael) 55 | template 56 | EIGEN_STRONG_INLINE void assignPacketByOuterInner(Index outer, Index inner) 57 | { 58 | Index row = Base::rowIndexByOuterInner(outer, inner); 59 | Index col = Base::colIndexByOuterInner(outer, inner); 60 | assignPacket(row, col); 61 | } 62 | }; 63 | 64 | } // namespace internal 65 | 66 | } // end namespace Eigen 67 | 68 | #endif // EIGEN_SWAP_H 69 | -------------------------------------------------------------------------------- /src/kfunc.h: -------------------------------------------------------------------------------- 1 | /* The MIT License 2 | 3 | Copyright (C) 2010, 2013-2014 Genome Research Ltd. 4 | Copyright (C) 2011 Attractive Chaos 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining 7 | a copy of this software and associated documentation files (the 8 | "Software"), to deal in the Software without restriction, including 9 | without limitation the rights to use, copy, modify, merge, publish, 10 | distribute, sublicense, and/or sell copies of the Software, and to 11 | permit persons to whom the Software is furnished to do so, subject to 12 | the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be 15 | included in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 18 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 20 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 21 | BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 22 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 23 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | SOFTWARE. 25 | */ 26 | 27 | #ifndef HTSLIB_KFUNC_H 28 | #define HTSLIB_KFUNC_H 29 | 30 | 31 | #ifdef __cplusplus 32 | extern "C" { 33 | #endif 34 | 35 | /* Log gamma function 36 | * \log{\Gamma(z)} 37 | * AS245, 2nd algorithm, http://lib.stat.cmu.edu/apstat/245 38 | */ 39 | double kf_lgamma(double z); 40 | 41 | /* complementary error function 42 | * \frac{2}{\sqrt{\pi}} \int_x^{\infty} e^{-t^2} dt 43 | * AS66, 2nd algorithm, http://lib.stat.cmu.edu/apstat/66 44 | */ 45 | double kf_erfc(double x); 46 | 47 | /* The following computes regularized incomplete gamma functions. 48 | * Formulas are taken from Wiki, with additional input from Numerical 49 | * Recipes in C (for modified Lentz's algorithm) and AS245 50 | * (http://lib.stat.cmu.edu/apstat/245). 51 | * 52 | * A good online calculator is available at: 53 | * 54 | * http://www.danielsoper.com/statcalc/calc23.aspx 55 | * 56 | * It calculates upper incomplete gamma function, which equals 57 | * kf_gammaq(s,z)*tgamma(s). 58 | */ 59 | 60 | double kf_gammap(double s, double z); 61 | double kf_gammaq(double s, double z); 62 | 63 | /* Regularized incomplete beta function. The method is taken from 64 | * Numerical Recipe in C, 2nd edition, section 6.4. The following web 65 | * page calculates the incomplete beta function, which equals 66 | * kf_betai(a,b,x) * gamma(a) * gamma(b) / gamma(a+b): 67 | * 68 | * http://www.danielsoper.com/statcalc/calc36.aspx 69 | */ 70 | double kf_betai(double a, double b, double x); 71 | 72 | /* 73 | * n11 n12 | n1_ 74 | * n21 n22 | n2_ 75 | * -----------+---- 76 | * n_1 n_2 | n 77 | */ 78 | double kt_fisher_exact(int n11, int n12, int n21, int n22, double *_left, double *_right, double *two); 79 | 80 | #ifdef __cplusplus 81 | } 82 | #endif 83 | 84 | #endif 85 | -------------------------------------------------------------------------------- /external/Eigen/src/misc/Kernel.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2009 Benoit Jacob 5 | // 6 | // This Source Code Form is subject to the terms of the Mozilla 7 | // Public License v. 2.0. If a copy of the MPL was not distributed 8 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 | 10 | #ifndef EIGEN_MISC_KERNEL_H 11 | #define EIGEN_MISC_KERNEL_H 12 | 13 | namespace Eigen { 14 | 15 | namespace internal { 16 | 17 | /** \class kernel_retval_base 18 | * 19 | */ 20 | template 21 | struct traits > 22 | { 23 | typedef typename DecompositionType::MatrixType MatrixType; 24 | typedef Matrix< 25 | typename MatrixType::Scalar, 26 | MatrixType::ColsAtCompileTime, // the number of rows in the "kernel matrix" 27 | // is the number of cols of the original matrix 28 | // so that the product "matrix * kernel = zero" makes sense 29 | Dynamic, // we don't know at compile-time the dimension of the kernel 30 | MatrixType::Options, 31 | MatrixType::MaxColsAtCompileTime, // see explanation for 2nd template parameter 32 | MatrixType::MaxColsAtCompileTime // the kernel is a subspace of the domain space, 33 | // whose dimension is the number of columns of the original matrix 34 | > ReturnType; 35 | }; 36 | 37 | template struct kernel_retval_base 38 | : public ReturnByValue > 39 | { 40 | typedef _DecompositionType DecompositionType; 41 | typedef ReturnByValue Base; 42 | 43 | explicit kernel_retval_base(const DecompositionType& dec) 44 | : m_dec(dec), 45 | m_rank(dec.rank()), 46 | m_cols(m_rank==dec.cols() ? 1 : dec.cols() - m_rank) 47 | {} 48 | 49 | inline Index rows() const { return m_dec.cols(); } 50 | inline Index cols() const { return m_cols; } 51 | inline Index rank() const { return m_rank; } 52 | inline const DecompositionType& dec() const { return m_dec; } 53 | 54 | template inline void evalTo(Dest& dst) const 55 | { 56 | static_cast*>(this)->evalTo(dst); 57 | } 58 | 59 | protected: 60 | const DecompositionType& m_dec; 61 | Index m_rank, m_cols; 62 | }; 63 | 64 | } // end namespace internal 65 | 66 | #define EIGEN_MAKE_KERNEL_HELPERS(DecompositionType) \ 67 | typedef typename DecompositionType::MatrixType MatrixType; \ 68 | typedef typename MatrixType::Scalar Scalar; \ 69 | typedef typename MatrixType::RealScalar RealScalar; \ 70 | typedef Eigen::internal::kernel_retval_base Base; \ 71 | using Base::dec; \ 72 | using Base::rank; \ 73 | using Base::rows; \ 74 | using Base::cols; \ 75 | kernel_retval(const DecompositionType& dec) : Base(dec) {} 76 | 77 | } // end namespace Eigen 78 | 79 | #endif // EIGEN_MISC_KERNEL_H 80 | -------------------------------------------------------------------------------- /external/Spectra/MatOp/internal/SymGEigsBucklingOp.h: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2020-2022 Yixuan Qiu 2 | // 3 | // This Source Code Form is subject to the terms of the Mozilla 4 | // Public License v. 2.0. If a copy of the MPL was not distributed 5 | // with this file, You can obtain one at https://mozilla.org/MPL/2.0/. 6 | 7 | #ifndef SPECTRA_SYM_GEIGS_BUCKLING_OP_H 8 | #define SPECTRA_SYM_GEIGS_BUCKLING_OP_H 9 | 10 | #include 11 | 12 | #include "../SymShiftInvert.h" 13 | #include "../SparseSymMatProd.h" 14 | 15 | namespace Spectra { 16 | 17 | /// 18 | /// \ingroup Operators 19 | /// 20 | /// This class defines the matrix operation for generalized eigen solver in the 21 | /// buckling mode. It computes \f$y=(K-\sigma K_G)^{-1}Kx\f$ for any 22 | /// vector \f$x\f$, where \f$K\f$ is positive definite, \f$K_G\f$ is symmetric, 23 | /// and \f$\sigma\f$ is a real shift. 24 | /// This class is intended for internal use. 25 | /// 26 | template , 27 | typename BOpType = SparseSymMatProd> 28 | class SymGEigsBucklingOp 29 | { 30 | public: 31 | using Scalar = typename OpType::Scalar; 32 | 33 | private: 34 | using Index = Eigen::Index; 35 | using Vector = Eigen::Matrix; 36 | 37 | OpType& m_op; 38 | const BOpType& m_Bop; 39 | mutable Vector m_cache; // temporary working space 40 | 41 | public: 42 | /// 43 | /// Constructor to create the matrix operation object. 44 | /// 45 | /// \param op The \f$(K-\sigma K_G)^{-1}\f$ matrix operation object. 46 | /// \param Bop The \f$K\f$ matrix operation object. 47 | /// 48 | SymGEigsBucklingOp(OpType& op, const BOpType& Bop) : 49 | m_op(op), m_Bop(Bop), m_cache(op.rows()) 50 | {} 51 | 52 | /// 53 | /// Move constructor. 54 | /// 55 | SymGEigsBucklingOp(SymGEigsBucklingOp&& other) : 56 | m_op(other.m_op), m_Bop(other.m_Bop) 57 | { 58 | // We emulate the move constructor for Vector using Vector::swap() 59 | m_cache.swap(other.m_cache); 60 | } 61 | 62 | /// 63 | /// Return the number of rows of the underlying matrix. 64 | /// 65 | Index rows() const { return m_op.rows(); } 66 | /// 67 | /// Return the number of columns of the underlying matrix. 68 | /// 69 | Index cols() const { return m_op.rows(); } 70 | 71 | /// 72 | /// Set the real shift \f$\sigma\f$. 73 | /// 74 | void set_shift(const Scalar& sigma) 75 | { 76 | m_op.set_shift(sigma); 77 | } 78 | 79 | /// 80 | /// Perform the matrix operation \f$y=(K-\sigma K_G)^{-1}Kx\f$. 81 | /// 82 | /// \param x_in Pointer to the \f$x\f$ vector. 83 | /// \param y_out Pointer to the \f$y\f$ vector. 84 | /// 85 | // y_out = inv(K - sigma * K_G) * K * x_in 86 | void perform_op(const Scalar* x_in, Scalar* y_out) const 87 | { 88 | m_Bop.perform_op(x_in, m_cache.data()); 89 | m_op.perform_op(m_cache.data(), y_out); 90 | } 91 | }; 92 | 93 | } // namespace Spectra 94 | 95 | #endif // SPECTRA_SYM_GEIGS_BUCKLING_OP_H 96 | -------------------------------------------------------------------------------- /external/Eigen/src/Core/Assign.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2007 Michael Olbrich 5 | // Copyright (C) 2006-2010 Benoit Jacob 6 | // Copyright (C) 2008 Gael Guennebaud 7 | // 8 | // This Source Code Form is subject to the terms of the Mozilla 9 | // Public License v. 2.0. If a copy of the MPL was not distributed 10 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | 12 | #ifndef EIGEN_ASSIGN_H 13 | #define EIGEN_ASSIGN_H 14 | 15 | namespace Eigen { 16 | 17 | template 18 | template 19 | EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase 20 | ::lazyAssign(const DenseBase& other) 21 | { 22 | enum{ 23 | SameType = internal::is_same::value 24 | }; 25 | 26 | EIGEN_STATIC_ASSERT_LVALUE(Derived) 27 | EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Derived,OtherDerived) 28 | EIGEN_STATIC_ASSERT(SameType,YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY) 29 | 30 | eigen_assert(rows() == other.rows() && cols() == other.cols()); 31 | internal::call_assignment_no_alias(derived(),other.derived()); 32 | 33 | return derived(); 34 | } 35 | 36 | template 37 | template 38 | EIGEN_DEVICE_FUNC 39 | EIGEN_STRONG_INLINE Derived& DenseBase::operator=(const DenseBase& other) 40 | { 41 | internal::call_assignment(derived(), other.derived()); 42 | return derived(); 43 | } 44 | 45 | template 46 | EIGEN_DEVICE_FUNC 47 | EIGEN_STRONG_INLINE Derived& DenseBase::operator=(const DenseBase& other) 48 | { 49 | internal::call_assignment(derived(), other.derived()); 50 | return derived(); 51 | } 52 | 53 | template 54 | EIGEN_DEVICE_FUNC 55 | EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const MatrixBase& other) 56 | { 57 | internal::call_assignment(derived(), other.derived()); 58 | return derived(); 59 | } 60 | 61 | template 62 | template 63 | EIGEN_DEVICE_FUNC 64 | EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const DenseBase& other) 65 | { 66 | internal::call_assignment(derived(), other.derived()); 67 | return derived(); 68 | } 69 | 70 | template 71 | template 72 | EIGEN_DEVICE_FUNC 73 | EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const EigenBase& other) 74 | { 75 | internal::call_assignment(derived(), other.derived()); 76 | return derived(); 77 | } 78 | 79 | template 80 | template 81 | EIGEN_DEVICE_FUNC 82 | EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const ReturnByValue& other) 83 | { 84 | other.derived().evalTo(derived()); 85 | return derived(); 86 | } 87 | 88 | } // end namespace Eigen 89 | 90 | #endif // EIGEN_ASSIGN_H 91 | -------------------------------------------------------------------------------- /external/Spectra/MatOp/internal/SymGEigsShiftInvertOp.h: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2020-2022 Yixuan Qiu 2 | // 3 | // This Source Code Form is subject to the terms of the Mozilla 4 | // Public License v. 2.0. If a copy of the MPL was not distributed 5 | // with this file, You can obtain one at https://mozilla.org/MPL/2.0/. 6 | 7 | #ifndef SPECTRA_SYM_GEIGS_SHIFT_INVERT_OP_H 8 | #define SPECTRA_SYM_GEIGS_SHIFT_INVERT_OP_H 9 | 10 | #include 11 | 12 | #include "../SymShiftInvert.h" 13 | #include "../SparseSymMatProd.h" 14 | 15 | namespace Spectra { 16 | 17 | /// 18 | /// \ingroup Operators 19 | /// 20 | /// This class defines the matrix operation for generalized eigen solver in the 21 | /// shift-and-invert mode. It computes \f$y=(A-\sigma B)^{-1}Bx\f$ for any 22 | /// vector \f$x\f$, where \f$A\f$ is a symmetric matrix, \f$B\f$ is positive definite, 23 | /// and \f$\sigma\f$ is a real shift. 24 | /// This class is intended for internal use. 25 | /// 26 | template , 27 | typename BOpType = SparseSymMatProd> 28 | class SymGEigsShiftInvertOp 29 | { 30 | public: 31 | using Scalar = typename OpType::Scalar; 32 | 33 | private: 34 | using Index = Eigen::Index; 35 | using Vector = Eigen::Matrix; 36 | 37 | OpType& m_op; 38 | const BOpType& m_Bop; 39 | mutable Vector m_cache; // temporary working space 40 | 41 | public: 42 | /// 43 | /// Constructor to create the matrix operation object. 44 | /// 45 | /// \param op The \f$(A-\sigma B)^{-1}\f$ matrix operation object. 46 | /// \param Bop The \f$B\f$ matrix operation object. 47 | /// 48 | SymGEigsShiftInvertOp(OpType& op, const BOpType& Bop) : 49 | m_op(op), m_Bop(Bop), m_cache(op.rows()) 50 | {} 51 | 52 | /// 53 | /// Move constructor. 54 | /// 55 | SymGEigsShiftInvertOp(SymGEigsShiftInvertOp&& other) : 56 | m_op(other.m_op), m_Bop(other.m_Bop) 57 | { 58 | // We emulate the move constructor for Vector using Vector::swap() 59 | m_cache.swap(other.m_cache); 60 | } 61 | 62 | /// 63 | /// Return the number of rows of the underlying matrix. 64 | /// 65 | Index rows() const { return m_op.rows(); } 66 | /// 67 | /// Return the number of columns of the underlying matrix. 68 | /// 69 | Index cols() const { return m_op.rows(); } 70 | 71 | /// 72 | /// Set the real shift \f$\sigma\f$. 73 | /// 74 | void set_shift(const Scalar& sigma) 75 | { 76 | m_op.set_shift(sigma); 77 | } 78 | 79 | /// 80 | /// Perform the matrix operation \f$y=(A-\sigma B)^{-1}Bx\f$. 81 | /// 82 | /// \param x_in Pointer to the \f$x\f$ vector. 83 | /// \param y_out Pointer to the \f$y\f$ vector. 84 | /// 85 | // y_out = inv(A - sigma * B) * B * x_in 86 | void perform_op(const Scalar* x_in, Scalar* y_out) const 87 | { 88 | m_Bop.perform_op(x_in, m_cache.data()); 89 | m_op.perform_op(m_cache.data(), y_out); 90 | } 91 | }; 92 | 93 | } // namespace Spectra 94 | 95 | #endif // SPECTRA_SYM_GEIGS_SHIFT_INVERT_OP_H 96 | -------------------------------------------------------------------------------- /external/Eigen/src/StlSupport/details.h: -------------------------------------------------------------------------------- 1 | // This file is part of Eigen, a lightweight C++ template library 2 | // for linear algebra. 3 | // 4 | // Copyright (C) 2009 Gael Guennebaud 5 | // Copyright (C) 2009 Hauke Heibel 6 | // 7 | // This Source Code Form is subject to the terms of the Mozilla 8 | // Public License v. 2.0. If a copy of the MPL was not distributed 9 | // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 10 | 11 | #ifndef EIGEN_STL_DETAILS_H 12 | #define EIGEN_STL_DETAILS_H 13 | 14 | #ifndef EIGEN_ALIGNED_ALLOCATOR 15 | #define EIGEN_ALIGNED_ALLOCATOR Eigen::aligned_allocator 16 | #endif 17 | 18 | namespace Eigen { 19 | 20 | // This one is needed to prevent reimplementing the whole std::vector. 21 | template 22 | class aligned_allocator_indirection : public EIGEN_ALIGNED_ALLOCATOR 23 | { 24 | public: 25 | typedef std::size_t size_type; 26 | typedef std::ptrdiff_t difference_type; 27 | typedef T* pointer; 28 | typedef const T* const_pointer; 29 | typedef T& reference; 30 | typedef const T& const_reference; 31 | typedef T value_type; 32 | 33 | template 34 | struct rebind 35 | { 36 | typedef aligned_allocator_indirection other; 37 | }; 38 | 39 | aligned_allocator_indirection() {} 40 | aligned_allocator_indirection(const aligned_allocator_indirection& ) : EIGEN_ALIGNED_ALLOCATOR() {} 41 | aligned_allocator_indirection(const EIGEN_ALIGNED_ALLOCATOR& ) {} 42 | template 43 | aligned_allocator_indirection(const aligned_allocator_indirection& ) {} 44 | template 45 | aligned_allocator_indirection(const EIGEN_ALIGNED_ALLOCATOR& ) {} 46 | ~aligned_allocator_indirection() {} 47 | }; 48 | 49 | #if EIGEN_COMP_MSVC 50 | 51 | // sometimes, MSVC detects, at compile time, that the argument x 52 | // in std::vector::resize(size_t s,T x) won't be aligned and generate an error 53 | // even if this function is never called. Whence this little wrapper. 54 | #define EIGEN_WORKAROUND_MSVC_STL_SUPPORT(T) \ 55 | typename Eigen::internal::conditional< \ 56 | Eigen::internal::is_arithmetic::value, \ 57 | T, \ 58 | Eigen::internal::workaround_msvc_stl_support \ 59 | >::type 60 | 61 | namespace internal { 62 | template struct workaround_msvc_stl_support : public T 63 | { 64 | inline workaround_msvc_stl_support() : T() {} 65 | inline workaround_msvc_stl_support(const T& other) : T(other) {} 66 | inline operator T& () { return *static_cast(this); } 67 | inline operator const T& () const { return *static_cast(this); } 68 | template 69 | inline T& operator=(const OtherT& other) 70 | { T::operator=(other); return *this; } 71 | inline workaround_msvc_stl_support& operator=(const workaround_msvc_stl_support& other) 72 | { T::operator=(other); return *this; } 73 | }; 74 | } 75 | 76 | #else 77 | 78 | #define EIGEN_WORKAROUND_MSVC_STL_SUPPORT(T) T 79 | 80 | #endif 81 | 82 | } 83 | 84 | #endif // EIGEN_STL_DETAILS_H 85 | --------------------------------------------------------------------------------