go-hep.org/x/hep@v0.38.1/hbook/ntup/ntroot/ntroot.go (about)

     1  // Copyright ©2020 The go-hep Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package ntroot provides convenience functions to access ROOT trees as n-tuple
     6  // data.
     7  //
     8  // Example:
     9  //
    10  //	nt, err := ntroot.Open("testdata/simple.root", "mytree")
    11  //	if err != nil {
    12  //	    log.Fatalf("%+v", err)
    13  //	}
    14  //	defer nt.DB().Close()
    15  package ntroot // import "go-hep.org/x/hep/hbook/ntup/ntroot"
    16  
    17  import (
    18  	"fmt"
    19  
    20  	"go-hep.org/x/hep/groot"
    21  	"go-hep.org/x/hep/groot/riofs"
    22  	"go-hep.org/x/hep/groot/rsql/rsqldrv"
    23  	"go-hep.org/x/hep/groot/rtree"
    24  	"go-hep.org/x/hep/hbook/ntup"
    25  )
    26  
    27  // Open opens the named ROOT file in read-only mode and returns an n-tuple
    28  // connected to the named tree.
    29  func Open(name, tree string) (*ntup.Ntuple, error) {
    30  	f, err := groot.Open(name)
    31  	if err != nil {
    32  		return nil, fmt.Errorf("could not open ROOT file: %w", err)
    33  	}
    34  	defer f.Close()
    35  
    36  	obj, err := riofs.Dir(f).Get(tree)
    37  	if err != nil {
    38  		return nil, fmt.Errorf("could not find ROOT tree %q: %w", tree, err)
    39  	}
    40  	if _, ok := obj.(rtree.Tree); !ok {
    41  		return nil, fmt.Errorf("ROOT object %q is not a tree", tree)
    42  	}
    43  
    44  	db, err := rsqldrv.Open(name)
    45  	if err != nil {
    46  		return nil, fmt.Errorf("could not open ROOT db: %w", err)
    47  	}
    48  
    49  	nt, err := ntup.Open(db, tree)
    50  	if err != nil {
    51  		_ = db.Close()
    52  		return nil, fmt.Errorf("could not open n-tuple %q: %w", tree, err)
    53  	}
    54  	return nt, nil
    55  }