go-hep.org/x/hep@v0.38.1/cmd/hepmc2root/main.go (about) 1 // Copyright ©2022 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 // Command hepmc2root converts a HepMC2 ASCII file into a ROOT file and (flat) tree. 6 // 7 // Usage: hepmc2root [OPTIONS] hepmc.ascii 8 // 9 // Example: 10 // 11 // $> hepmc2root ./hepmc.ascii 12 // $> hepmc2root -o out.root -t mytree ./hepmc.ascii 13 // 14 // Options: 15 // 16 // -o string 17 // path to output ROOT file name (default "out.root") 18 // -t string 19 // name of the output tree (default "tree") 20 package main // import "go-hep.org/x/hep/cmd/hepmc2root" 21 22 import ( 23 "flag" 24 "fmt" 25 "log" 26 "os" 27 28 "go-hep.org/x/hep/groot" 29 "go-hep.org/x/hep/groot/rtree" 30 "go-hep.org/x/hep/hepmc" 31 "go-hep.org/x/hep/hepmc/rootcnv" 32 ) 33 34 func main() { 35 log.SetPrefix("hepmc2root: ") 36 log.SetFlags(0) 37 38 oname := flag.String("o", "out.root", "path to output ROOT file name") 39 tname := flag.String("t", "tree", "name of the output tree") 40 41 flag.Usage = func() { 42 fmt.Fprintf(os.Stderr, `hepmc2root converts a HepMC2 ASCII file into a ROOT file and (flat) tree. 43 44 Usage: hepmc2root [OPTIONS] hepmc.ascii 45 46 Example: 47 48 $> hepmc2root ./hepmc.ascii 49 $> hepmc2root -o out.root -t mytree ./hepmc.ascii 50 51 Options: 52 `) 53 flag.PrintDefaults() 54 } 55 56 flag.Parse() 57 58 if flag.NArg() != 1 { 59 flag.Usage() 60 log.Fatalf("missing input HepMC filename argument") 61 } 62 fname := flag.Arg(0) 63 64 err := process(*oname, *tname, fname) 65 if err != nil { 66 log.Fatalf("%+v", err) 67 } 68 } 69 70 func process(oname, tname, fname string) error { 71 f, err := os.Open(fname) 72 if err != nil { 73 return fmt.Errorf("could not open HepMC file %q: %w", fname, err) 74 } 75 defer f.Close() 76 77 o, err := groot.Create(oname) 78 if err != nil { 79 return fmt.Errorf("could not create output ROOT file %q: %w", oname, err) 80 } 81 defer o.Close() 82 83 tree, err := rootcnv.NewFlatTreeWriter(o, tname, rtree.WithTitle(tname)) 84 if err != nil { 85 return fmt.Errorf("could not create output ROOT tree %q: %w", tname, err) 86 } 87 88 _, err = hepmc.Copy(tree, hepmc.NewASCIIReader(f)) 89 if err != nil { 90 return fmt.Errorf("could not write HepMC events to ROOT: %w", err) 91 } 92 93 err = tree.Close() 94 if err != nil { 95 return fmt.Errorf("could not close ROOT tree writer: %w", err) 96 } 97 98 err = o.Close() 99 if err != nil { 100 return fmt.Errorf("could not close output ROOT file %q: %w", oname, err) 101 } 102 103 return nil 104 }