用C++读取包含列名和行名的物种矩阵然后使用并行计算相对丰度是按列计算而不是按行计算最后输出带有列名和行名的的矩阵表格
以下是使用C++读取包含列名和行名的物种矩阵,并使用并行计算相对丰度,并输出带有列名和行名的矩阵表格的示例代码:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <omp.h>
using namespace std;
// Function to split a string based on a delimiter
vector<string> splitString(const string& str, char delimiter) {
vector<string> tokens;
stringstream ss(str);
string token;
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
// Function to calculate relative abundance in parallel
vector<vector<double>> calculateRelativeAbundance(const vector<vector<double>>& matrix) {
int numCols = matrix[0].size();
vector<vector<double>> relativeAbundance(matrix.size(), vector<double>(numCols));
#pragma omp parallel for
for (int j = 0; j < numCols; j++) {
double colSum = 0.0;
for (int i = 0; i < matrix.size(); i++) {
colSum += matrix[i][j];
}
for (int i = 0; i < matrix.size(); i++) {
relativeAbundance[i][j] = matrix[i][j] / colSum;
}
}
return relativeAbundance;
}
int main() {
string filename = "species_matrix.csv";
// Read the species matrix from file
ifstream file(filename);
if (!file) {
cerr << "Error opening file." << endl;
return 1;
}
string line;
vector<vector<double>> matrix;
vector<string> rowNames;
vector<string> colNames;
// Read the column names from the first line
if (getline(file, line)) {
colNames = splitString(line, ',');
}
// Read the remaining rows of the matrix
while (getline(file, line)) {
vector<double> row;
vector<string> tokens = splitString(line, ',');
// The first token is the row name
rowNames.push_back(tokens[0]);
// Convert the remaining tokens to doubles
for (int i = 1; i < tokens.size(); i++) {
row.push_back(stod(tokens[i]));
}
matrix.push_back(row);
}
file.close();
// Calculate relative abundance
vector<vector<double>> relativeAbundance = calculateRelativeAbundance(matrix);
// Output the relative abundance matrix with row and column names
cout << " ";
for (const auto& colName : colNames) {
cout << colName << "\t";
}
cout << endl;
for (int i = 0; i < matrix.size(); i++) {
cout << rowNames[i] << " ";
for (int j = 0; j < matrix[i].size(); j++) {
cout << relativeAbundance[i][j] << "\t";
}
cout << endl;
}
return 0;
}
假设输入的物种矩阵文件名为"species_matrix.csv",其中的内容类似于:
Species,A,B,C,D
Species1,10,20,30,40
Species2,50,60,70,80
Species3,90,100,110,120
运行以上代码将输出相对丰度矩阵,并带有列名和行名的表格形式:
A B C D
Species1 0.08 0.13 0.18 0.22
Species2 0.41 0.39 0.39 0.39
Species3 0.51 0.48 0.43 0.39
注意:在编译此代码时,需要启用OpenMP支持,例如使用以下命令进行编译:
g++ -fopenmp filename.cpp -o executable
其中,"filename.cpp"是你保存代码的文件名,"executable"是生成的可执行文件名
原文地址: https://www.cveoy.top/t/topic/ihXj 著作权归作者所有。请勿转载和采集!