How to use the uproot.tree function in uproot

To help you get started, we’ve selected a few uproot examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github scikit-hep / uproot / tests / test_tree.py View on Github external
def test_strings_basket(self):
        branch = uproot.open("tests/samples/sample-6.10.05-uncompressed.root")["sample"]["str"]
        interpretation = branch._normalize_interpretation(None, awkward)
        entrystart, entrystop = uproot.tree._normalize_entrystartstop(branch.numentries, None, None)
        local_entrystart, local_entrystop = branch._localentries(0, entrystart, entrystop)

        one = branch.basket(0, interpretation, local_entrystart, local_entrystop)
        two = branch.basket(0, interpretation, local_entrystart, local_entrystop)

        assert one.tolist() == [b"hey-0", b"hey-1", b"hey-2", b"hey-3", b"hey-4", b"hey-5"]
        assert basest(one.content.content) is not basest(two.content.content)

        three = branch.basket(0)
        assert three.tolist() == [b"hey-0", b"hey-1", b"hey-2", b"hey-3", b"hey-4", b"hey-5"]
github diana-hep / oamap / oamap / source / root.py View on Github external
break
                    if not found:
                        raise ValueError("could not find a single-leaf branch corresponding to leaf count {0}".format(leafcount))

                    if hasattr(branch, "_streamer") and hasattr(branch._streamer, "fName"):
                        name = branch._streamer.fName.decode("ascii")
                        name = re.split("[^a-zA-Z_0-9]", name)[-1]
                        if len(name) > 0:
                            rec.name = name

                    if len(rec.fields) > 0:
                        out[branchname.split(".")[-1]] = oamap.schema.List(rec, starts=branchname, stops=branchname)

                if hasattr(parent, "_streamer") and hasattr(parent._streamer, "fName"):
                    name = parent._streamer.fName.decode("ascii")
                elif isinstance(parent, uproot.tree.TTreeMethods):
                    name = parent.name.decode("ascii")
                else:
                    name = None

                if name is not None:
                    name = re.split("[^a-zA-Z_0-9]", name)[-1]
                    if len(name) > 0:
                        out.name = name

                if len(flats) == 0 and len(lists) == 1:
                    out, = out.fields.values()

                return out
github diana-hep / oamap / oamap / backend / root / __init__.py View on Github external
def accumulate(node):
        out = oamap.schema.Record(OrderedDict(), namespace=namespace)
        for branchname, branch in node.iteritems(aliases=False) if isinstance(node, uproot.tree.TTreeMethods) else node.iteritems():
            if not isinstance(branchname, str):
                branchname = branchname.decode("ascii")
            fieldname = branchname.split(".")[-1]

            if len(branch.fBranches) > 0:
                subrecord = accumulate(branch)
                if len(subrecord.fields) > 0:
                    out[fieldname] = subrecord

            elif isinstance(branch.interpretation, (uproot.interp.asdtype, uproot.interp.numerical.asdouble32)):
                subnode = oamap.schema.Primitive(branch.interpretation.todtype, data=branchname, namespace=namespace)
                for i in range(len(branch.interpretation.todims)):
                    subnode = oamap.schema.List(subnode, starts="{0}:/{1}".format(branchname, i), stops="{0}:/{1}".format(branchname, i), namespace=namespace)
                out[fieldname] = subnode

            elif isinstance(branch.interpretation, uproot.interp.asjagged) and isinstance(branch.interpretation.asdtype, uproot.interp.asdtype):
github diana-hep / oamap / oamap / backend / root / cmsnano.py View on Github external
def dataset(path, treepath="Events", namespace=None, **kwargs):
    import uproot

    if namespace is None:
        namespace = "root.cmsnano({0})".format(repr(path))

    if "localsource" not in kwargs:
        kwargs["localsource"] = lambda path: uproot.source.file.FileSource(path, chunkbytes=8*1024, limitbytes=None)
    kwargs["total"] = False
    kwargs["blocking"] = True

    paths2entries = uproot.tree.numentries(path, treepath, **kwargs)
    if len(paths2entries) == 0:
        raise ValueError("path {0} matched no TTrees".format(repr(path)))

    offsets = [0]
    paths = []
    for path, numentries in paths2entries.items():
        offsets.append(offsets[-1] + numentries)
        paths.append(path)

    sch = schema(paths[0], namespace=namespace)
    doc = sch.doc
    sch.doc = None

    return oamap.dataset.Dataset(treepath,
                                 sch,
                                 {namespace: oamap.backend.root.ROOTBackend(paths, treepath, namespace)},
github CoffeaTeam / coffea / coffea / nanoevents / factory.py View on Github external
def __init__(
        self,
        file,
        treename="Events",
        entrystart=None,
        entrystop=None,
        cache=None,
        mixin_map=None,
        metadata=None,
    ):
        if not isinstance(file, uproot.rootio.ROOTDirectory):
            file = uproot.open(file)
        self._tree = file[treename]
        self._entrystart, self._entrystop = uproot.tree._normalize_entrystartstop(
            self._tree.numentries, entrystart, entrystop
        )
        self._keyprefix = "/".join(
            [
                file._context.uuid.hex(),
                treename,
                str(self._entrystart),
                str(self._entrystop),
            ]
        )
        NanoEventsFactory._active[self._keyprefix] = self

        if cache is None:
            cache = awkward1.layout.ArrayCache({})
        else:
            cache = awkward1.layout.ArrayCache(cache)
github scikit-hep / uproot / uproot / interp / auto.py View on Github external
def interpret(branch, awkwardlib=None, swapbytes=True, cntvers=False, tobject=True, speedbump=True):
    import uproot.tree
    awkward = uproot.tree._normalize_awkwardlib(awkwardlib)

    dims, isjagged = (), False
    if len(branch._fLeaves) == 1:
        m = interpret._titlehasdims.match(branch._fLeaves[0]._fTitle)
        if m is not None:
            dims = tuple(int(x) for x in re.findall(interpret._itemdimpattern, branch._fLeaves[0]._fTitle))
            if dims == ():
                dims = (branch._fLeaves[0]._fLen, ) if branch._fLeaves[0]._fLen > 1 else ()
            if any(interpret._itemdimpattern.match(x) is None for x in re.findall(interpret._itemanypattern, branch._fLeaves[0]._fTitle)):
                isjagged = True
    else:
        for leaf in branch._fLeaves:
            if interpret._titlehasdims.match(leaf._fTitle):
                return None

    try:
github scikit-hep / uproot / uproot / _help.py View on Github external
{xrootdsource}

    {httpsource}

    {options}

    Returns
    -------
    ChunkedArray of Table of VirtualArrays
        lazy files of branches of lazy baskets.
""".format(**dict(list(open_fragments.items()) + list(tree_fragments.items())))

################################################################ uproot.tree.daskarray/daskframe

uproot.tree.daskarray.__doc__ = \
u"""Create a Dask array that would read from a set of files as needed.

    Parameters
    ----------

    path : str or list of str
        glob pattern(s) for local file paths (POSIX wildcards like "``*``") or URLs specifying the locations of the files. A list of filenames are processed in the given order, but glob patterns get pre-sorted to ensure a predictable order.

    treepath : str
        path within each ROOT file to find the TTree (may include "``/``" for subdirectories or "``;``" for cycle numbers).

    branchname : str
        path within each TTree to find the TBranch

    {interpretation}
github scikit-hep / uproot / uproot / _help.py View on Github external
{localsource}

    {xrootdsource}

    {httpsource}

    {options}

    Returns
    -------
    dask.array.core.Array
        lazy files of lazy baskets.
""".format(**dict(list(open_fragments.items()) + list(tree_fragments.items())))

uproot.tree.daskframe.__doc__ = \
u"""Create a Dask DataFrame that would read from a set of files as needed.

    Parameters
    ----------

    path : str or list of str
        glob pattern(s) for local file paths (POSIX wildcards like "``*``") or URLs specifying the locations of the files. A list of filenames are processed in the given order, but glob patterns get pre-sorted to ensure a predictable order.

    treepath : str
        path within each ROOT file to find the TTree (may include "``/``" for subdirectories or "``;``" for cycle numbers).

    {branches}

    {namedecode}

    {entrysteps}
github CoffeaTeam / coffea / coffea / nanoaod / nanoawkward1.py View on Github external
def __init__(
        self,
        file,
        treename="Events",
        entrystart=None,
        entrystop=None,
        cache=None,
        mixin_map=None,
        metadata=None,
    ):
        if not isinstance(file, uproot.rootio.ROOTDirectory):
            file = uproot.open(file)
        self._tree = file[treename]
        self._entrystart, self._entrystop = uproot.tree._normalize_entrystartstop(
            self._tree.numentries, entrystart, entrystop
        )
        self._keyprefix = "/".join(
            [
                file._context.uuid.hex(),
                treename,
                str(self._entrystart),
                str(self._entrystop),
            ]
        )
        NanoEventsFactory._active[self._keyprefix] = self

        if cache is None:
            cache = awkward1.layout.ArrayCache({})
        else:
            cache = awkward1.layout.ArrayCache(cache)