Problem reading data from root file

hi guys…
I did some simulation and saved the data (PropagatedCharge and DepositedCharge) using RootObjectWriter module. Only one particle is simulated.
I opened the root file and get the Tree in root environment by the following code:
TFile* f0=new TFile(“data_1.root”)
TTree* t0=(TTree*) f0->Get("DepositedCharge”)
There is only one entry in the tree t0, corrosponding to the one particle. But there are 22 entries of the “DepositedCharge” object. My purpose is to extract the information of each entry. Can anyone tell me how to do it?
Thanks~

data_1.root (979.2 KB)

1 Like

Hi,

the individual trees contain separate branches for each detectors, so if you have a single detector, you expect one branch in the tree. You can read the entries like this:

$ root -l data_1.root
root [1] .L ~/path/to/your/allpix-squared/lib/libAllpixObjects.so
root [2] .L analyzeData.C+
root [3] readTree(_file0, "detector1")

with the following ROOT macro, stored as analyzeData.C - you have to adapt the location of the header int he file:

#include <TFile.h>
#include <TTree.h>

// FIXME: dapt path to the include file of your APSQ installation
#include "/path/to/your/allpix-squared/src/objects/DepositedCharge.hpp"

/**
 * Read ROOT TTree from the data objects
 */
void readTree(TFile* file, std::string detector) {

    // Read tree of deposited charges:
    TTree* deposited_tree = static_cast<TTree*>(file->Get("DepositedCharge"));
    if(!deposited_tree) {
        std::cout << "Could not read tree DepositedCharge, cannot continue." << std::endl;
        return;
    }

    TBranch* deposited_branch = deposited_tree->FindBranch(detector.c_str());
    if(!deposited_branch) {
        std::cout << "Could not find the detector branch on tree DepositedCharge, cannot continue." << std::endl;
        return;
    }

    std::vector<allpix::DepositedCharge*> deposited_charges;
    deposited_branch->SetObject(&deposited_charges);

    // Go through the tree event-by-event:
    for(int i = 0; i < deposited_tree->GetEntries(); ++i) {
        deposited_tree->GetEntry(i);

	// Loop over all deposited charges
        for(auto& deposited_charge : deposited_charges) {
	    std::cout << "Event " << i << ": charge = " << deposited_charge->getCharge()
	              << ", position = " << deposited_charge->getGlobalPosition() << std::endl;
        }
    }

    return;
}

There is a longer example in the repository at tools/root_analysis_macro, youc an find a description of it in the user manual.

Let me know if that works for you!

/Simon

1 Like

It works! Thank you, Simon.:grinning:

where is tools/root_analysis_macro?

Hi @pan_kuang

It’s here in the code repository:

Best regards,
Simon