Example 2: Read TObjArray with unique known type

Goal: read a TObjArray when you already know every element is of a specific type (TObjInObjArray). We inspect the bytes, write a Detree reader that embeds the rule, register it with Uproot-custom, and read the branch. The Python + C++ route shows the same reader as a Python IReader and ported to C++.

See also

A full example can be found in the example repository.

This example shows how to use user-known rules to read data.

In this example, we define a TObjWithObjArray class, which contains a TObjArray of TObjWithInt objects. We know the type of objects in the TObjArray is always TObjInObjArray, so we can use user-known rules to read the data.

The definition of TObjInObjArray and TObjWithObjArray is as follows:

Definition of TObjInObjArray
class TObjInObjArray : public TObject {
  private:
    // STL
    std::string m_str;
    std::vector<int> m_vec_int;
    std::map<int, float> m_map_if;
    std::map<std::string, double> m_map_sd;
    std::map<int, std::string> m_map_is;
    std::map<int, std::vector<int>> m_map_vec_int;
    std::map<int, std::map<int, float>> m_map_map_if;

    // TArray
    TArrayI m_tarr_i{ 0 };
    TArrayC m_tarr_c{ 0 };
    TArrayS m_tarr_s{ 0 };
    TArrayL m_tarr_l{ 0 };
    TArrayF m_tarr_f{ 0 };
    TArrayD m_tarr_d{ 0 };

    // TString
    TString m_tstr;

    // CStyle array
    int m_carr_int[3]{ 0, 0, 0 };
    std::vector<int> m_carr_vec_int[2];

    // basic types
    bool m_bool{ false };
    int8_t m_int8{ 0 };
    int16_t m_int16{ 0 };
    int32_t m_int32{ 0 };
    int64_t m_int64{ 0 };
    uint8_t m_uint8{ 0 };
    uint16_t m_uint16{ 0 };
    uint32_t m_uint32{ 0 };
    uint64_t m_uint64{ 0 };
    float m_float{ 0.0 };
    double m_double{ 0.0 };

    ClassDef( TObjInObjArray, 1 );

  public:
    // ... (skipped for brevity)
};
Definition of TObjWithObjArray
class TObjWithObjArray : public TObject {
  private:
    TObjArray m_obj_array;

    ClassDef( TObjWithObjArray, 1 );

  public:
    TObjWithObjArray( int val = 0 ) : TObject(), m_obj_array()
    {
        // preallocate space for 5 elements
        for ( int i = 0; i < val % 5; i++ )
        {
            // This will lead to memory leak, but it's just an example.
            m_obj_array.Add( new TObjInObjArray( val + i ) );
        }
    }
};

Step 1: Check binary data

Similar to Example 1, we should check the binary data first. Since ROOT automatically splits TObjWithObjArray into several sub-branches, we can just focus on the branch m_obj_array.

To print the binary data, run:

>>> import uproot
>>> from uproot.interpretation.custom import AsBinary
>>>
>>> br = uproot.open("demo_data.root")["my_tree:obj_with_obj_array/m_obj_array"]
>>> bin_arr = br.array(interpretation=AsBinary())
>>> evt1 = bin_arr[1].to_numpy()
>>> evt1
array([ 64,   0,   1, 155,   0,   3,   0,   1,   0,   0,   0,   0,   0,
         0,   0,   0,   0,   0,   0,   0,   1,   0,   0,   0,   0,  64,
         0,   1, 130, 255, 255, 255, 255,  84,  79,  98, 106,  73, 110,
        79,  98, 106,  65, 114, 114,  97, 121,   0,  64,   0,   1, 107,
         0,   1,   0,   1,   0,   0,   0,   0,   0,   0,   0,   0,  64,
         0,   0,   8,   0,   9,   5, 115, 116, 114,  95,  49,  64,   0,
         0,  10,   0,   9,   0,   0,   0,   1,   0,   0,   0,   1,  64,
         0,   0,  20,  64,   9,   0,   0, 105,   3,  41, 120,   0,   0,
         0,   1,   0,   0,   0,   0,  63, 128,   0,   0,  64,   0,   0,
        32,  64,   9,   0,   0, 250, 148,  40, 178,   0,   0,   0,   1,
        64,   0,   0,   8,   0,   9,   5, 107, 101, 121,  95,  48,  63,
       240,   0,   0,   0,   0,   0,   0,  64,   0,   0,  28,  64,   9,
         0,   0,  11,  95, 183,  82,   0,   0,   0,   1,   0,   0,   0,
         0,  64,   0,   0,   8,   0,   9,   5, 118,  97, 108,  95,  49,
        64,   0,   0,  34,  64,   9,   0,   0,  11,  95, 183,  82,   0,
         0,   0,   1,   0,   0,   0,   0,  64,   0,   0,  14,   0,   9,
         0,   0,   0,   2,   0,   0,   0,   1,   0,   0,   0,  11,  64,
         0,   0,  48,  64,   9,   0,   0,  11,  95, 183,  82,   0,   0,
         0,   1,   0,   0,   0,   0,  64,   0,   0,  28,  64,   9,   0,
         0, 105,   3,  41, 120,   0,   0,   0,   2,   0,   0,   0,   0,
         0,   0,   0,  10,  63, 128,   0,   0,  64,   0,   0,   0,   0,
         0,   0,   1,   0,   0,   0,   1,   0,   0,   0,   1,   1,   0,
         0,   0,   1,   0,   1,   0,   0,   0,   1,   0,   0,   0,   0,
         0,   0,   0,   1,   0,   0,   0,   1,  63, 128,   0,   0,   0,
         0,   0,   1,  63, 240,   0,   0,   0,   0,   0,   0,   6, 116,
       115, 116, 114,  95,  49,   0,   0,   0,   1,   0,   0,   0,   2,
         0,   0,   0,   3,  64,   0,   0,  26,   0,   9,   0,   0,   0,
         2,   0,   0,   0,   1,   0,   0,   0,  11,   0,   0,   0,   2,
         0,   0,   0,   2,   0,   0,   0,  12,   0,   1,   0,   2,   0,
         0,   0,   3,   0,   0,   0,   0,   0,   0,   0,   4,  11,   0,
        12,   0,   0,   0,  13,   0,   0,   0,   0,   0,   0,   0,  14,
        63, 140, 204, 205,  64,   1, 153, 153, 153, 153, 153, 154],
      dtype=uint8)

We can refer to the TObjArray::Streamer method:

TObjArray::Streamer method
 1void TObjArray::Streamer(TBuffer &b)
 2{
 3   UInt_t R__s, R__c;
 4   Int_t nobjects;
 5   if (b.IsReading()) {
 6      Version_t v = b.ReadVersion(&R__s, &R__c);
 7      if (v > 2)
 8         TObject::Streamer(b);
 9      if (v > 1)
10         fName.Streamer(b);
11
12      if (GetEntriesFast() > 0) Clear();
13
14      b >> nobjects;
15      b >> fLowerBound;
16      if (nobjects >= fSize) Expand(nobjects);
17      fLast = -1;
18      TObject *obj;
19      for (Int_t i = 0; i < nobjects; i++) {
20         obj = (TObject*) b.ReadObjectAny(TObject::Class());
21         if (obj) {
22            fCont[i] = obj;
23            fLast = i;
24         }
25      }
26      Changed();
27      b.CheckByteCount(R__s, R__c,TObjArray::IsA());
28   } else {
29      // skipped the writing part for brevity
30   }
31}

According to the Streamer method, the binary data contains:

  1. Line 6: The first 6 bytes are the fNBytes (uint32) +fVersion (int16) header (refer to here).

  2. Line 7-8: Since the fVersion is 3 > 2, the base class TObject is then streamed, which takes 10 bytes.

  3. Line 9-10: Since the fVersion is 3 > 1, the next part is fName (TString).

  4. Line 14: The next 4 bytes is nobjects (int32), which is [0, 0, 0, 1], i.e. 1. This means there is one object in this TObjArray.

  5. Line 15: The next 4 bytes is fLowerBound (int32), which is [0, 0, 0, 0], i.e. 0.

  6. Line 19-25: Loop over nobjects to read each object. Note that the [255, 255, 255, 255] indicates that the objects are stored as pointer, whose binary layout follows this rule. In Uproot-custom, it can be handled by AnyPointerFactory.

Tip

For other ROOT built-in classes, it is suggested to check both the streamer information and the source code. If the Streamer method is not overridden, the streamer information is usually enough.

In summary, the binary data contains:

  • TObjArray header (fNBytes+fVersion+TObject+fName+nobjects+fLowerBound).

  • Loop over nobjects to read each object:

    • Pointer header before each TObjInObjArray object.

    • Data members of TObjInObjArray object.

So we need such factories/readers to read the data:

  • TObjArrayFactory/TObjArrayReader to read TObjArray header and loop over nobjects.

  • AnyPointerFactory/AnyPointerReader to read the object stored as pointer, which are already implemented in Uproot-custom. When the type name ends with *, build_factory automatically resolves to AnyPointerFactory, which in turn delegates to AnyClassFactory to read the pointed object’s data members.

The TObjArrayFactory/TObjArrayReader should be implemented by ourselves. Since we know the type of objects in the TObjArray is always TObjInObjArray, we can pass TObjInObjArray* (with pointer suffix) to build_factory, and it will automatically create the appropriate AnyPointerFactory → AnyClassFactory chain to read all objects. This is also a process of embedding user-known rules.

Step 2: Implement the Detree reader

Our TObjArrayReader declares an offsets buffer and one child reader, and decodes the TObjArray header before handing the elements to the child:

 1import numpy as np
 2
 3from uproot_custom.detree import Buffer, Child, Reader, reader
 4
 5
 6@reader
 7class TObjArrayReader(Reader):
 8    offsets = Buffer("q", init=(0,), kind="offsets")
 9    element = Child()
10
11    def read(self, stream):
12        stream.skip_fNBytes()
13        stream.skip_fVersion()
14        stream.skip_TObject()
15
16        stream.skip_TString()  # fName
17
18        fSize = stream.read_uint32()
19        stream.skip(4)  # fLowerBound
20
21        self.offsets.append(self.offsets[-1] + fSize)
22        self.element.read_many(stream, fSize)
23
24    def data(self):
25        return np.asarray(self.offsets), self.element.data()
  • element = Child() declares the one sub-reader; the factory builds it and passes it in, exactly as the Python version takes an element_reader.

  • read consumes the TObjArray header, records the new offset, then calls self.element.read_many(stream, fSize). A read_many call is compiled, so the loop over the elements stays inside the machine.

  • data returns (offsets, element_data), the same tuple the Python reader returns.

Tip

Read multiple objects in one read_many call rather than in a for loop in the parent: some classes (e.g. std::vector) have a “1 header + many objects” structure, and their reader knows how to consume that header once.

Step 3: Implement the factory

Similar to Example 1, we need to identify the TObjArray branch and implement a corresponding Factory to use our TObjArrayReader.

First, import necessary modules:

import awkward.contents
import awkward.forms
import awkward.index

from uproot_custom import (
    Factory,
    build_factory,
)

Implement build_factory

In this example, we simply regard any TObjArray branch as our target branch. You can implement more specific rules to identify the target branch with item_path.

TObjArrayFactory
 1class TObjArrayFactory(Factory):
 2    @classmethod
 3    def priority(cls):
 4        """
 5        Set a higher priority to ensure this factory is chosen first,
 6        otherwise the pre-defined factory of `Uproot-custom` may be selected.
 7
 8        The default priority is 10 for other factories.
 9        """
10        return 50
11
12    @classmethod
13    def build_factory(
14        cls,
15        top_type_name: str,
16        cur_streamer_info: dict,
17        all_streamer_info: dict,
18        item_path: str,
19        **kwargs,
20    ):
21        # `top_type_name` is the type name of the top-level object.
22        if top_type_name != "TObjArray":
23            return None
24
25        # `item_path` identifies the node by position: the branch's object-path
26        # plus one "." and the member name per level; it holds no type name.
27        obj_typename = "TObjInObjArray*"
28
29        element_factory = build_factory(
30            cur_streamer_info={
31                "fName": obj_typename,
32                "fTypeName": obj_typename,
33            },
34            all_streamer_info=all_streamer_info,
35            item_path=f"{item_path}.{obj_typename}",
36        )
37
38        return cls(name=cur_streamer_info["fName"], element_factory=element_factory)
  • Line 3-10: Override priority method to give a higher priority than the factories with default priority 10, so that our factory can be chosen first.

  • Line 27: The type read from the array is TObjInObjArray*. The trailing * makes build_factory resolve it to AnyPointerFactory, which handles the pointer header and delegates to AnyClassFactory for the members. There is no need to construct those factories by hand.

  • Line 30-37: build_factory is called once for the element, with item_path extended by one component so that two different TObjArray members would remain distinguishable.

Implement constructor

The TObjArrayFactory requires an element_factory to read each object in the TObjArray. So we need to implement the constructor:

def __init__(self, name: str, element_factory: Factory):
    super().__init__(name)
    self.element_factory = element_factory

Implement build_detree_reader

The build_detree_reader method is straightforward:

1def build_detree_reader(self):
2    element_reader = self.element_factory.build_detree_reader()
3    return TObjArrayReader(self.name, element=element_reader)
  • In line 2, we use self.element_factory.build_detree_reader to create the element_reader. Here, AnyPointerFactory.build_detree_reader is called (since TObjInObjArray* matched AnyPointerFactory), which in turn calls AnyClassFactory.build_detree_reader to create the reader chain.

  • In line 3, we create an instance of TObjArrayReader, passing the element_reader as the declared Child field.

Implement make_awkward_content

The make_awkward_content method is also straightforward:

def make_awkward_content(self, raw_data):
    offsets, element_raw_data = raw_data
    element_content = self.element_factory.make_awkward_content(element_raw_data)
    return awkward.contents.ListOffsetArray(
        awkward.index.Index64(offsets),
        element_content,
    )

We use self.element_factory.make_awkward_content to construct the element_content, then combine it with offsets to create a ListOffsetArray.

(Optional) Implement make_awkward_form

You can implement make_awkward_form to provide the awkward form of the final array without reading the binary data:

def make_awkward_form(self):
    element_form = self.element_factory.make_awkward_form()
    return awkward.forms.ListOffsetForm(
        "i64",
        element_form,
    )

This will be used when users try to access the array lazily, e.g. using uproot.dask or b.array(virtual=True).

Step 4: Register target branch and the Factory

Finally, register the branch we want to read with Uproot-custom, and also register the TObjArrayFactory so that it can be used by Uproot-custom.

We can do this by adding the following code in the __init__.py of your package:

from uproot_custom import claim, registered_factories

claim("/my_tree:obj_with_obj_array/m_obj_array")

registered_factories.add(TObjArrayFactory)

The code default backend is cpp, so select Detree next to the registration, when your package is imported:

import uproot_custom as uc
uc.set_backend("detree")  # the default is "cpp"

Step 5: Read data with Uproot

Now we can read the data using Uproot as usual:

>>> b = uproot.open("demo_data.root")["my_tree:obj_with_obj_array/m_obj_array"]
>>> arr = b.array()

The Python + C++ route for the same class

The factory and the data shape stay the same; the reader is written twice, and the factory gains one method per stage.

TObjArrayReader (Python)
from array import array
import numpy as np
from uproot_custom.python import IReader


class TObjArrayReader(IReader):
    def __init__(self, name, element_reader):
        super().__init__(name)
        self.element_reader = element_reader
        self.offsets = array("q", [0])

    def read(self, stream):
        stream.skip_fNBytes()
        stream.skip_fVersion()
        stream.skip_TObject()
        stream.read_TString()  # fName
        fSize = stream.read_uint32()
        stream.skip(4)  # fLowerBound

        self.offsets.append(self.offsets[-1] + fSize)
        self.element_reader.read_many(stream, fSize)

    def data(self):
        return np.asarray(self.offsets), self.element_reader.data()

The Python reader reads the TString name with read_TString(); the Detree reader skips it with skip_TString(), since the value is not used. See stage 1 of the route.

TObjArrayReader (C++)
class TObjArrayReader : public IReader {
  public:
    TObjArrayReader( std::string name, SharedReader element_reader )
        : IReader( name )
        , m_element_reader( element_reader )
        , m_offsets( std::make_shared<std::vector<int64_t>>( 1, 0 ) ) {}

    void read( BinaryStream& stream ) override final {
        stream.skip_fNBytes();
        stream.skip_fVersion();
        stream.skip_TObject();
        stream.read_TString(); // fName
        auto fSize = stream.read<uint32_t>();
        stream.skip( 4 ); // fLowerBound

        m_offsets->push_back( m_offsets->back() + fSize );
        m_element_reader->read_many( stream, fSize );
    }

    py::object data() const override final {
        return py::make_tuple( make_array( m_offsets ),
                               m_element_reader->data() );
    }

  private:
    SharedReader m_element_reader;
    std::shared_ptr<std::vector<int64_t>> m_offsets;
};

PYBIND11_MODULE( my_reader_cpp, m ) {
    declare_reader<TObjArrayReader, std::string, SharedReader>( m, "TObjArrayReader" );
}

See stage 2 of the route for the build and the binding.

Add the matching factory methods to make the backends selectable:

class TObjArrayFactory(Factory):
    # ... build_factory, make_awkward_content, make_awkward_form ...

    def build_detree_reader(self):
        return TObjArrayReader(self.name, element=self.element_factory.build_detree_reader())

    def build_python_reader(self):
        return TObjArrayReader(self.name, self.element_factory.build_python_reader())

    def build_cpp_reader(self):
        return cpp.TObjArrayReader(self.name, self.element_factory.build_cpp_reader())

Only the selected backend’s method is called, so the other two readers are simply unused.