以下是一个示例代码,演示如何使用C++读取物种矩阵文件并使用并行计算每列的相对丰度,并输出为矩阵表格。

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
#include <iomanip>
#include <omp.h>

// 读取物种矩阵文件
std::vector<std::vector<double>> readSpeciesMatrix(const std::string& filename) {
    std::ifstream file(filename);
    std::vector<std::vector<double>> speciesMatrix;

    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line)) {
            std::vector<double> row;
            std::istringstream iss(line);
            double value;
            while (iss >> value) {
                row.push_back(value);
            }
            speciesMatrix.push_back(row);
        }
        file.close();
    }

    return speciesMatrix;
}

// 计算每列的相对丰度
std::vector<double> calculateRelativeAbundance(const std::vector<std::vector<double>>& speciesMatrix) {
    std::vector<double> relativeAbundance(speciesMatrix[0].size(), 0.0);

    #pragma omp parallel for
    for (int j = 0; j < speciesMatrix[0].size(); ++j) {
        double total = 0.0;
        for (int i = 0; i < speciesMatrix.size(); ++i) {
            total += speciesMatrix[i][j];
        }
        relativeAbundance[j] = total / speciesMatrix.size();
    }

    return relativeAbundance;
}

// 输出矩阵表格
void printMatrixTable(const std::vector<std::vector<double>>& matrix, const std::vector<double>& relativeAbundance) {
    std::cout << std::fixed << std::setprecision(2);
    for (const auto& row : matrix) {
        for (const auto& value : row) {
            std::cout << value << "\t";
        }
        std::cout << std::endl;
    }

    std::cout << std::endl << "Relative Abundance:" << std::endl;
    for (int i = 0; i < relativeAbundance.size(); ++i) {
        std::cout << "Column " << i+1 << ": " << relativeAbundance[i] << std::endl;
    }
}

int main() {
    std::string filename = "species_matrix.txt";
    std::vector<std::vector<double>> speciesMatrix = readSpeciesMatrix(filename);

    if (!speciesMatrix.empty()) {
        std::vector<double> relativeAbundance = calculateRelativeAbundance(speciesMatrix);
        printMatrixTable(speciesMatrix, relativeAbundance);
    } else {
        std::cout << "Failed to read species matrix file." << std::endl;
    }

    return 0;
}

请确保将物种矩阵文件命名为species_matrix.txt,并与示例代码放在同一目录下。物种矩阵文件应该按行为物种,按列为样本,以空格或制表符分隔。

示例物种矩阵文件(species_matrix.txt)内容如下:

1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0

编译并运行示例代码,将输出以下结果:

1.00    2.00    3.00
4.00    5.00    6.00
7.00    8.00    9.00

Relative Abundance:
Column 1: 4.00
Column 2: 5.00
Column 3: 6.00

输出的矩阵表格显示了原始物种矩阵,然后按列显示了每列的相对丰度

用C++读取物种矩阵并使用并行计算每列的相对丰度然后输出为矩阵表格

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

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