使用 C++ 并行计算物种矩阵的相对丰度
#include
using namespace std;
// 读取包含行名和列名的物种矩阵
vector<vector
vector<vector<double>> matrix;
// 读取列名
string line;
getline(file, line);
stringstream colNames(line);
string colName;
while (colNames >> colName) {
matrix.push_back(vector<double>());
}
// 读取行名和矩阵数据
string rowName;
double value;
while (file >> rowName) {
for (int i = 0; i < matrix.size(); i++) {
file >> value;
matrix[i].push_back(value);
}
}
file.close();
return matrix;
}
// 计算相对丰度
vector<vector
double rowSum;
#pragma omp parallel for private(rowSum)
for (int i = 0; i < matrix.size(); i++) {
rowSum = 0.0;
for (int j = 0; j < matrix[i].size(); j++) {
rowSum += matrix[i][j];
}
for (int j = 0; j < matrix[i].size(); j++) {
relAbundance[i][j] = matrix[i][j] / rowSum;
}
}
return relAbundance;
}
// 输出带有行名和列名的矩阵表格
void printMatrix(const vector<vector
// 输出行名和矩阵数据
for (int i = 0; i < matrix.size(); i++) {
cout << rowNames[i] << "\t";
for (int j = 0; j < matrix[i].size(); j++) {
cout << matrix[i][j] << "\t";
}
cout << endl;
}
}
int main() {
// 读取物种矩阵
vector<vector
// 读取行名和列名
ifstream file("matrix.txt");
string rowNamesLine;
getline(file, rowNamesLine);
stringstream rowNamesStream(rowNamesLine);
string rowName;
vector<string> rowNames;
while (rowNamesStream >> rowName) {
rowNames.push_back(rowName);
}
file.close();
// 计算相对丰度
vector<vector<double>> relAbundance = calculateRelativeAbundance(matrix);
// 输出带有行名和列名的矩阵表格
printMatrix(relAbundance, rowNames, rowNames);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/pZ9x 著作权归作者所有。请勿转载和采集!