convert_mcnp_txt_to_root.C
Go to the documentation of this file.
1 // Makes a verbatim translation of the text file into ROOT TTree format to
2 // simplify further processing.
3 
4 #include "TFile.h"
5 #include "TTree.h"
6 #include "Compression.h"
7 
8 #include "stdio.h"
9 #include <iostream>
10 
11 void skip_line(FILE* fin)
12 {
13  size_t n = 0;
14  char* linptr = 0;
15  int nchars = getline(&linptr, &n, fin);
16  std::cout << "Skipped " << nchars << " chars: " << linptr;
17  delete linptr;
18 }
19 
20 void convert_mcnp_txt_to_root(TString fname, bool g4 = false)
21 {
22  // Output fields
23  float x, y, z, px, py, pz, t;
24  int pdg, evt, trk, parent;
25  float wei;
26 
27  FILE* fin = fopen(fname.Data(), "r");
28  std::cout << "Processing " << fname << std::endl;
29 
30  fname.ReplaceAll(".txt", ".root");
31 
32  TFile* fout = new TFile(fname, "RECREATE", "", 100*ROOT::kLZMA+9);
33  TTree* trout = new TTree("tr", "tr");
34 
35  trout->Branch("x", &x);
36  trout->Branch("y", &y);
37  trout->Branch("z", &z);
38  trout->Branch("px", &px);
39  trout->Branch("py", &py);
40  trout->Branch("pz", &pz);
41  trout->Branch("t", &t);
42  trout->Branch("pdg", &pdg);
43  trout->Branch("evt", &evt);
44  trout->Branch("trk", &trk);
45  trout->Branch("parent", &parent);
46  trout->Branch("wei", &wei);
47 
48  std::string fmt = "%f %f %f %f %f %f %f %d %d %d %d %f";
49  int nfields = 12; // number expected
50  if(g4){
51  // g4 files have extra columns for E and B fields, all zero
52  fmt += " %f %f %f %f %f %f";
53  nfields += 6;
54  }
55  else{
56  // While MCNP has integers for cell and material
57  fmt += " %d %d";
58  nfields += 2;
59  }
60 
61  int lineno = 0;
62 
63  while(!feof(fin)){
64  ++lineno;
65  if(lineno%1000000 == 0){
66  std::cout << lineno/1000000 << "m lines processed" << std::endl;
67  }
68 
69  int ret = -1;
70  if(g4){
71  float fjunk;
72  ret = fscanf(fin, fmt.c_str(),
73  &x, &y, &z,
74  &px, &py, &pz,
75  &t,
76  &pdg, &evt, &trk, &parent,
77  &wei,
78  &fjunk, &fjunk, &fjunk,
79  &fjunk, &fjunk, &fjunk);
80  }
81  else{
82  int ijunk;
83  ret = fscanf(fin, fmt.c_str(),
84  &x, &y, &z,
85  &px, &py, &pz,
86  &t,
87  &pdg, &evt, &trk, &parent,
88  &wei,
89  &ijunk, &ijunk);
90  }
91 
92  if(ret == -1){
93  // EOF
94  break;
95  }
96  if(ret == 0){
97  // Comment or empty line, skip over it
98  skip_line(fin);
99  }
100  else if(ret != nfields){
101  // Unexpected error
102  std::cout << "Unexpected number of fields: " << ret << " != " << nfields << std::endl;
103  skip_line(fin);
104  }
105  else{
106  // Was good, use it!
107  trout->Fill();
108  }
109  }
110 
111  std::cout << "Writing output file " << fname << std::endl;
112  trout->Write();
113 }
void skip_line(FILE *fin)
TString fin
Definition: Style.C:24
Track finder for cosmic rays.
void convert_mcnp_txt_to_root(TString fname, bool g4=false)
int evt
z
Definition: test.py:28
OStream cout
Definition: OStream.cxx:6
enum BeamMode string