前言
Geant 4输出数据往往采用Root文件,其数据输出效率较高,优于文本文件格式,尤其是数据文件较大时。博主在工作中需要用Matlab处理数据,因此整理了Root文件转存为Mat文件的程序。对于1G大小的Root文件,程序处理时间约37秒(读取+保存),完全可以接受。
一、程序编写
参考文献:
1.linux下使用c++读取mat文件的步骤
2.ROOTPrimer.pdf(ROOT官网自查,第22页,关于库文件加载)
#include <iostream>
#include <fstream>
#include "string.h"
#include <mat.h>
#include "matrix.h"
#include "TROOT.h"
#include "TFile.h"
#include "TTree.h"
using namespace std;
void RootToMat(string fileNameRunTime);
int main()
{
// 调用自定义函数
RootToMat(fileNameRunTime);
return 0;
}
void RootToMat(string fileNameRunTime)
{
// 打开 Root 文件
TFile f("info_0_t0.root"); // open a root file
TTree* t = (TTree*)f.Get("infoOp"); // get the tree from the root file
long long int nentries = t->GetEntries();
int mcolumn = 6;
double pID, pSiPM, pe, px, py, pt;
t->SetBranchAddress("eventID",&pID);
t->SetBranchAddress("SiPMNum",&pSiPM);
t->SetBranchAddress("ePho",&pe);
t->SetBranchAddress("xPos",&px);
t->SetBranchAddress("yPos",&py);
t->SetBranchAddress("gloTime",&pt);
// 读取数据
double *outA = new double[mcolumn*nentries];
for (long long int i=0; i<nentries; i++)
{
t->GetEntry(i);
outA[mcolumn*i+0] = pID;
outA[mcolumn*i+1] = pSiPM;
outA[mcolumn*i+2] = pe;
outA[mcolumn*i+3] = px;
outA[mcolumn*i+4] = py;
outA[mcolumn*i+5] = pt;
}
// 保存数据
MATFile *pmatFile = NULL;
mxArray *pMxArray = NULL;
pmatFile = matOpen("myOpPho.mat","w");
pMxArray = mxCreateDoubleMatrix(mcolumn, nentries, mxREAL);
mxSetData(pMxArray, outA);
matPutVariable(pmatFile, "myOpPho", pMxArray);
matClose(pmatFile);
}
二、 程序运行
g++ -I /usr/local/MATLAB/R2018a/extern/include/ -L /usr/local/MATLAB/R2018a/bin/glnxa64/ -cpp Demo_RootToMat.C -o RootToMat -lmat -lmx -Wl,-rpath /usr/local/MATLAB/R2018a/bin/glnxa64 `root-config --cflags --libs`
./RootToMat