Geant 4输出数据整理:ROOT文件转存为MAT文件

前言

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值