CopyTree method creat random Tree

Dear rooters

I have an input file with one tree called (Tree0)
I want to copy part of entries with condition into a new tree,(separate one tree into multi trees)

so I wrote this script

TFile *input = new TFile(input_rootfile,"READ");
TTree *input_tree = (TTree*)input->Get("Tree0");  


TFile *output = new TFile(output_rootfile,"RECREATE");

   for (int k=0; k<number_of_channels; k++)
    {
       
        std::cout << k << endl;
        sprintf(tree_name,"Channel_%02d",k);  // name of tree
        sprintf(condition,"ch==%d",k);
        new_trees[k]= input_tree->CopyTree(condition);
        new_trees[k]->SetName(tree_name);
        new_trees[k]->Write();
    }
output->Close();

I have two input files, first with two conditions (k=2), this work fine and seperate the input tree into two trees.
but I have another input file with 4 conditions(k=4), this file create an extra tree with name Tree0, and if I comment the line (new_trees[k]->Write()) I should not obtain any trees, but in this case I will still get the (Tree0) Tree with random numbers of entries.

does CopyTree Method not appropriate in this case,???

I will appreciate your ideas

The relevant CopyTree tutorial uses an alternate approach, doing the filling manually. (Which happens to be slightly more efficient as well, although a bit more cumbersome).

https://root.cern.ch/doc/master/copytree3_8C.html

As to why your initial approach seems not to work I cannot offer insight.

Cheers,
Kim

This is likely a ‘cycle’. See https://root.cern.ch/input-and-output.

Note that a slight improvement on your code would be:

TFile *input = new TFile(input_rootfile,"READ");
TTree *input_tree = (TTree*)input->Get("Tree0");  


TFile *output = new TFile(output_rootfile,"RECREATE");

   for (int k=0; k<number_of_channels; k++)
    {
       
        std::cout << k << endl;
        sprintf(tree_name,"Channel_%02d",k);  // name of tree
        sprintf(condition,"ch==%d",k);
        new_trees[k]= input_tree->CopyTree(condition);
        new_trees[k]->SetName(tree_name);
    }
output->Write();
output->Close();

But Kim’s solution is likely to be the best solution.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.