2014年5月21日水曜日

PyROOTを使いこなすためには…?

PyROOTを使ってROOTファイルの解析を行う。

設定方法はGoogleで検索すれば見つかるでしょう…
問題は使い方!そんなに普及していない(?)のか日本語記事がなかなか見つからない!!
ROOT自体を使いこなしている訳ではないので,Python内で何のオブジェクトを使えばいいのかに結構悩んだ。。。

ってことでROOTを使い始めて,というかPyROOTを使い始めて数ヶ月経ったので,新しくROOTファイルを作る方法について重点をおいてまとめてみる。


・PythonにROOTをimport
>>> import PyROOT as pR

・ROOTファイルを開く
>>> # 既存のfileを開く
>>> f_in = pR.TFile("test.root")
>>> # 新しいroot fileを作る
>>> f_new = pR.TFile("output.root","recreate")

・1次元ヒストグラム
TH1を使う。
>>> # 0から1024の間を1024ビンに区切ったヒストグラム
>>> h1 = pR.TH1D("h1","h1",1024,0,1024)
>>> h1.SetBinContent(10,10)  # 10ビン目に10つめる 
>>> h1.Fill(350) # 350ビン目に1つだけつめる。
>>> h1.Draw()    # 描画
以上の操作で以下の図ができる。

・ディレクトリ構造を作る
>>> # カレントディレクトリの表示
>>> f_new.pwd()
output.root:/
>>>
>>>
>>> # ディレクトリ操作
>>> cur_dir = pR.gDirectory
>>> cur_dir.ls()
TFile**  output.root  
 TFile*  output.root   
>>> cur_dir.pwd()
output.root:/
>>>
>>>
>>> # ディレクトリ作成
>>> subdir = f_new.mkdir("subdir")
>>> f_new.ls()
TFile**  output.root  
 TFile*  output.root   
  TDirectoryFile*  subdir subdir  
  KEY: TDirectoryFile subdir;1 subdir
>>>
>>>
>>> # ディレクトリ移動
>>> f_new.cd("subdir")
True
>>> cur_dir.pwd()
output.root:/subdir
>>> f_new.pwd()
output.root:/
>>>
>>>
>>> # subdir 内に平均が512で分散が10となる
>>> # ガウス分布のヒストグラムを作る
>>> h1 = pR.TH1D("h1","h1",1024,0,1024)
>>> for i in range(1000) :
...    h1.Fill(pR.gRandom.Gaus(512,10)
>>> cur_dir.ls()
TDirectoryFile*       subdir subdir
 OBJ: TH1D      h1    h1 : 0 at: 0x7faa9aeec930 
>>>
>>>
>>> # 上位ディレクトリへ移動
>>> f_new.cd("../")
>>> cur_dir.pwd()
output.root:/
>>> f_new.ls()
TFile**         output.root
 TFile*         output.root
  TDirectoryFile*             subdir subdir
   OBJ: TH1D    h1    h1 : 0 at: 0x7faa9aeec930
>>>
>>>
>>> # 平均が512で分散が10となる
>>> # ガウス分布のヒストグラムを作る
>>> h2 = pR.TH1D("h2","h2",1024,0,1024)
>>> for i in range(1000) :
...    h2.Fill(pR.gRandom.Gaus(512,10)
>>> f_new.ls()
TFile**         output.root
 TFile*         output.root
  TDirectoryFile*             subdir subdir
   OBJ: TH1D    h1    h1 : 0 at: 0x7faa9aeec930
  OBJ: TH1D     h2    h2 : 0 at: 0x7faa9e10e730
>>>
>>>
>>> # ヒストグラムを作る
>>> h3 = pR.TH1D("h3","h3",1024,0,1024)
>>> f_new.ls()
TFile**         output.root
 TFile*         output.root
  TDirectoryFile*             subdir subdir
   OBJ: TH1D    h1    h1 : 0 at: 0x7faa9aeec930
  OBJ: TH1D     h2    h2 : 0 at: 0x7faa9e10e730 
  OBJ: TH1D     h3    h3 : 0 at: 0x7faa9dba1ec0
>>>
>>>
>>> # ヒストグラムの削除
>>> h3.Delete()
>>> f_new.ls()
TFile**         output.root
 TFile*         output.root
  TDirectoryFile*             subdir subdir
   OBJ: TH1D    h1    h1 : 0 at: 0x7faa9aeec930
  OBJ: TH1D     h2    h2 : 0 at: 0x7faa9e10e730
>>>
>>>
>>> # ヒストグラムをファイルへ書き込み,閉じる
>>> f_new.Write()
>>> f_new.Close()

てな感じかな。やり方にはいろいろあるだろうけど自分が試してみてできたやり方が上の方法。(なんかみにくいね…)