CopyTree in combination with AddFriend generates undesired behaviour

Hi,
I am using root 6.26/04. I am reading a TFile with two TTrees, I am trying to make one Tree friend of the other and now I want to remove entries based on a TCut that contains variables on both ttrees. Later I want to open the short file and apply again cuts on it to draw, but fast, since it is small.

However, when I save the E TTree with CopyTree and write and open the small file I find that the new ETree still have access to the friend variables of DTree but in a wrong way. e.g. I cut on “variable_of_DTree<0.5” and if I check the entries as GetEntries(“variable_of_DTree<0.5”) it is not equal to all entries in the file. Is CopyTree not to be used with Friends or am I missing something? Or maybe you are not supposed to use the friends again. I tried to do “RemoveFriend”, but it doesn’t fix the problem.

I have the following code

#include "TFile.h"
#include "TTree.h"
#include "TCut.h"
#include "TROOT.h"

#include <iostream>

int main(int argc, char* argv[]) {
    using namespace std;

    // Open input files
    TFile *f1 = TFile::Open(argv[1]);
    TTree *ETree = (TTree*)f1->Get("E");
    TTree *DTree = (TTree*)f1->Get("D");

    // Add friendships
    ETree->AddFriend(DTree);

    TCut selection = argv[2];

    TFile *newFile = TFile::Open(argv[3], "RECREATE");

    // Copy the filtered entries to new trees
    TTree *newETree = ETree->CopyTree(selection);

    newFile->cd();
    newETree->Write("ETree");
    newFile->Close();
    f1->Close();

    return 0;
}
1 Like

Welcome to the ROOT Forum!
I don’t see anything obviously wrong in your code, but maybe @pcanal can take a second look…

CloneTree only clones the given TTree (and indeed its relationship to a friend) but does not clone the friend tree.

You have two solutions.

One is to use the code you have but to augment the friend with an index (See TTree::BuildIndex) so that the small tree can find the corresponding entries in the friend tree. For this to work you would need to have data/information that is duplicated in the friend and main tree and indentify the entry (Typically this is the “Event Number” and “Run Number”).

The other solution is to also clone the friend tree and to make sure to replace the friendship from the original with the friendship with the shorter friend.

1 Like

Thank you for the quick answer.

I cannot build an index as the friend tree doesn´t have the duplicated info, however, the second option worked. I tried first to copy also the short friend tree and then removing the old friend and add the short new tree as friend using the ¨RemoveFriend¨ function. However, for some reason the friendship stayed (e.g. it was still appearing when doing a print of the GetListOfFriends). I tried instead with a Clear in the list and that worked.

Thank you!

1 Like