{/'title/':/'C++ 并行计算物种矩阵相对丰度:带行名和列名的矩阵表格输出/',/'description/':/'使用C++读取包含行名和列名的物种矩阵,并利用OpenMP进行并行计算相对丰度。最后以表格形式输出结果,包含行名和列名。/',/'keywords/':/'C++,并行计算,OpenMP,物种矩阵,相对丰度,矩阵表格/',/'content/':/'#include ///'iostream///'//n#include ///'fstream///'//n#include ///'vector///'//n#include ///'string///'//n#include ///'sstream///'//n#include ///'algorithm///'//n#include ///'numeric///'//n#include ///'cmath///'//n#include ///'iomanip///'//n#include ///'omp.h///'//n//n// 定义物种矩阵类型//ntypedef std::vector<std::vector> Matrix;//n//n// 读取物种矩阵//nMatrix readMatrix(const std::string& filename) {//n std::ifstream file(filename);//n Matrix matrix;//n//n if (file.is_open()) {//n std::string line, cell;//n while (std::getline(file, line)) {//n std::vector row;//n std::stringstream lineStream(line);//n//n while (std::getline(lineStream, cell, '//t')) {//n row.push_back(std::stod(cell));//n }//n//n matrix.push_back(row);//n }//n//n file.close();//n }//n//n return matrix;//n}//n//n// 计算每行的和//nstd::vector calculateRowSums(const Matrix& matrix) {//n std::vector rowSums(matrix.size());//n//n #pragma omp parallel for//n for (size_t i = 0; i < matrix.size(); ++i) {//n rowSums[i] = std::accumulate(matrix[i].begin(), matrix[i].end(), 0.0);//n }//n//n return rowSums;//n}//n//n// 计算相对丰度//nMatrix calculateRelativeAbundance(const Matrix& matrix) {//n Matrix relativeAbundance(matrix.size(), std::vector(matrix[0].size()));//n std::vector rowSums = calculateRowSums(matrix);//n//n #pragma omp parallel for collapse(2)//n for (size_t i = 0; i < matrix.size(); ++i) {//n for (size_t j = 0; j < matrix[i].size(); ++j) {//n relativeAbundance[i][j] = matrix[i][j] / rowSums[i];//n }//n }//n//n return relativeAbundance;//n}//n//n// 输出带有行名和列名的矩阵表格//nvoid printMatrix(const Matrix& matrix, const std::vectorstd::string& rowNames, const std::vectorstd::string& colNames) {//n std::cout << std::setw(10) << ///' ///';//n for (const auto& colName : colNames) {//n std::cout << std::setw(10) << colName;//n }//n std::cout << std::endl;//n//n for (size_t i = 0; i < matrix.size(); ++i) {//n std::cout << std::setw(10) << rowNames[i];//n for (size_t j = 0; j < matrix[i].size(); ++j) {//n std::cout << std::setw(10) << matrix[i][j];//n }//n std::cout << std::endl;//n }//n}//n//nint main() {//n std::string filename = ///'species_matrix.txt///';//n//n // 读取物种矩阵//n Matrix matrix = readMatrix(filename);//n//n // 物种矩阵的行名和列名//n std::vectorstd::string rowNames = {///'Species1///', ///'Species2///', ///'Species3///'} ;//n std::vectorstd::string colNames = {///'Sample1///', ///'Sample2///', ///'Sample3///', ///'Sample4///'} ;//n//n // 计算相对丰度//n Matrix relativeAbundance = calculateRelativeAbundance(matrix);//n//n // 输出带有行名和列名的矩阵表格//n printMatrix(relativeAbundance, rowNames, colNames);//n//n return 0;//n}//n/

C++ 并行计算物种矩阵相对丰度:带行名和列名的矩阵表格输出

原文地址: https://www.cveoy.top/t/topic/pZ9I 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录