ラベル python の投稿を表示しています。 すべての投稿を表示
ラベル python の投稿を表示しています。 すべての投稿を表示

2009年7月22日水曜日

How to user pyROOT 応用編 その6

・軸を log スケールにする


cv = ROOT.TCanvas("cv", "Graph Test", 800, 800)

cv.SetLogx()
cv.SetLogy()



・grid を描く


cv = ROOT.TCanvas("cv", "Graph Test", 800, 800)

cv.SetGridx()
cv.SetGridy()



・大題を付ける


cv = ROOT.TCanvas("cv", "Graph Test", 800, 800)

pl = ROOT.TPaveLabel(0.3, 0.91, 0.7, 0.99, "Global Title")
pl.Draw()

pad = ROOT.TPad("pad", "title", 0, 0, 1, 0.9)
pad.Draw()
pad.cd()

graph.Draw("APL")

cv.Update();






・X軸, Y軸のタイトルを修飾


axisX = graph.GetXaxis()
axisX.SetTitle("x")
axisX.SetLabelFont(112)
axisX.SetTitleOffset(0.5)
axisX.SetTitleSize(0.07)

axisY = graph.GetYaxis()
axisY.SetTitle("x**2")






・ヒストグラムの修飾


hpx.SetFillColor(2)
hpx.SetLineWidth(5)






hp1.SetFillColor(2)
hp1.SetFillStyle(3002)
hp1.Draw()

hp2.SetFillColor(4)
hp2.SetFillStyle(3002)
hp2.Draw("SAME")






・マーカーの修飾


graph = ROOT.TGraph()
graph.SetMarkerColor(6)
graph.SetMarkerSize(1)
graph.SetMarkerStyle(12)

2009年7月17日金曜日

How to use pyROOT 基礎編 その8

・直線を描く

line = ROOT.TLine(start_x, start_y, end_x, end_y)
line.Draw()


・長方形を描く

box = ROOT.TBox(start_x, start_y, end_x, end_y)
box.Draw("SAME")



・円を描く

arc = ROOT.TArc(center_x, center_y, radius)
arc.Draw("SAME")


・楕円を描く

ell = ROOT.TEllipse( center_x, center_y, radius_x, radius_y)
ell.Draw("SAME")


・マーカーを描く

mark = ROOT.TMarker( x, y, 20)
mark.Draw("SAME")


・文字を入れる

text = ROOT.TText( start_x, start_y, "This is a pen." )
text.Draw("SAME")





#/bin/usr/env python

import sys, os
import ROOT


if __name__=='__main__':


graph = ROOT.TGraph()

for x in range(10) :
np = graph.GetN()
graph.SetPoint(np, x, x)

cv = ROOT.TCanvas("cv", "Graphics Example", 200, 10, 700, 500)


graph.SetLineWidth(3)
graph.SetLineColor(1)
graph.SetLineStyle(1)
graph.Draw("APC")

line = ROOT.TLine( 1, 3, 1, 8)
line.SetLineWidth(3)
line.SetLineColor(2)
line.SetLineStyle(2)
line.Draw("SAME")

box = ROOT.TBox( 3, 1, 5, 2)
box.SetFillColor(3)
box.Draw("SAME")

arc = ROOT.TArc( 5, 6, 2)
arc.SetLineWidth(3)
arc.SetLineColor(4)
arc.SetLineStyle(1)
arc.Draw("SAME")

ell = ROOT.TEllipse( 8, 3, 1.3, 2)
ell.SetLineWidth(3)
ell.SetLineColor(6)
ell.SetLineStyle(1)
ell.Draw("SAME")

mark = ROOT.TMarker( 2, 3, 20 )
mark.Draw("SAME")

text = ROOT.TText( 3, 9, "This is a pen." )
text.Draw("SAME")

cv.Update()


# export
cv.Print("graphics.png")

How to use pyROOT 基礎編 その7

Ntuple

ntuple は、 double, triple, quadruple, ・・・ の n番目のこと
Ntuple クラスを使うと、いろいろなヒストグラムを作ることができる


Ntuple の使い方は

1. 空の Ntuple を作成する
ntuple = ROOT.TNtuple("name", "title", "変数リスト" [, バッファサイズ])

変数リストは次のように ':' で区切る
"x:y:z:energy"
"px:py"


2. ファイルからデータを読み込む
ntuple.Fill(px, py)

3. Ntuple の中身を確認する
ntuple.Print()

4. ヒストグラムを作成する
ntuple.Draw("変数リスト" [, "条件"] [, "表示オプション"] )

変数リストは、ヒストグラムを作成するときに使用する式
"x"
"sqrt(x)"
"x+y/z"
"x:y"
"x:y:z"
"x*2:sqrt(y)"


条件は特定のデータからヒストグラムを作成することに使う
"x<0"
"sart(x+y)>4"
"x>0&&z<0"



* 条件用の変数を作成するには TCut を使う
cut1 = ROOT.TCut("x>0 && y>0 && z > 0")

複数の条件を組み合わせる
ntuple.Draw("sqrt(x):y*2", cut1 && cut2)



#/bin/usr/env python

import sys, os
import ROOT


if __name__=='__main__':


if len(sys.argv) < 2 :
sys.exit(1)

if not os.path.exists(sys.argv[1]) :
sys.exit(1)

# read data from file
fin = open(sys.argv[1], "r")
fins = fin.readlines()
fin.close()


# create Ntuple
ntuple = ROOT.TNtuple("n", "Tuple Example", "x:y:z:energy")


# set data point
for data in fins :
item = data.split(None)
ntuple.Fill(float(item[0]), float(item[1]),
float(item[2]), float(item[3]))

# print
ntuple.Print()

cv = ROOT.TCanvas("cv", "Graph Example", 200, 10, 700, 500)

ntuple.Draw("sqrt(x):y*2 >> hist", "z<0", "APL")
cv.Update()


# export
cv.Print("ntuple1.png")




ntuple に データを読み込ませたあと中身を表示するとこんな感じ

$ python ntuple1.py data2.dat
******************************************************************************
*Tree :n : Tuple Example *
*Entries : 5 : Total = 2773 bytes File Size = 0 *
* : : Tree compression factor = 1.00 *
******************************************************************************
*Br 0 :x : *
*Entries : 5 : Total Size= 622 bytes One basket in memory *
*Baskets : 0 : Basket Size= 32000 bytes Compression= 1.00 *
*............................................................................*
*Br 1 :y : *
*Entries : 5 : Total Size= 622 bytes One basket in memory *
*Baskets : 0 : Basket Size= 32000 bytes Compression= 1.00 *
*............................................................................*
*Br 2 :z : *
*Entries : 5 : Total Size= 622 bytes One basket in memory *
*Baskets : 0 : Basket Size= 32000 bytes Compression= 1.00 *
*............................................................................*
*Br 3 :energy : *
*Entries : 5 : Total Size= 652 bytes One basket in memory *
*Baskets : 0 : Basket Size= 32000 bytes Compression= 1.00 *
*............................................................................*

How to use pyROOT 基礎編 その6

関数 - Function -


1次元関数

TF1 クラスを使用する


f1 = ROOT.TF1('f1', 'x * sin(x) * exp(-0.1 * x)', -10, 10)
f1.Draw()





2次元関数

TF2 クラスを使用する


f2 = ROOT.TF2('f2', 'abs(sin(x) / x) * y * cos(y)', -5, 5, -5, 5)
f2.Draw("surf")
#f2.Draw("cont1")
#f2.Draw("lego")


f2.Draw("surf")



f2.Draw("cont1")



f2.Draw("lego")





パラメータ付きの関数

パラメータを [0], [1], [2],,, で置き換える


f3 = ROOT.TF1('f3', '[0] + [1] * exp(x)', -5, 5)

// set value of parameters
f3.setParameters(1, 2)

f3.Draw()


fitting にこの関数をつかう場合、設定したパラメータ値が初期値になる

How to use pyROOT 基礎編 その5

2次元データのプロット

TGraph というクラスを使用する


次のコードでは、引数にプロットするデータファイルを指定する。

データファイルの形式は
data_x data_y



#/bin/usr/env python

import sys, os
import ROOT


if __name__=='__main__':


if len(sys.argv) < 2 :
sys.exit(1)

if not os.path.exists(sys.argv[1]) :
sys.exit(1)

# read data from file
fin = open(sys.argv[1], "r")
fins = fin.readlines()
fin.close()


graph = ROOT.TGraph()

# set data point
for data in fins :
item = data.split(None)
np = graph.GetN()
graph.SetPoint(np, float(item[0]), float(item[1]))


cv = ROOT.TCanvas("cv", "Graph Example", 200, 10, 700, 500)

pad = cv.cd()
pad.SetGridx(1)
pad.SetGridy(1)

graph.Draw("APL")
cv.Update()


# export
cv.Print("graph1.png")






エラーバー付きのプロット

エラーバーを付けてプロットするには、 TGraphErrors クラスを使用する

ここでの引数にしていするデータファイルの形式は
data_x data_y data_x_err data_y_err



#/bin/usr/env python

import sys, os, array
import ROOT


if __name__=='__main__':


if len(sys.argv) < 2 :
sys.exit(1)

if not os.path.exists(sys.argv[1]) :
sys.exit(1)

# read data from file
fin = open(sys.argv[1], "r")
fins = fin.readlines()
fin.close()


dat = {'X' : array.array('f'),
'X_ERR' : array.array('f'),
'Y' : array.array('f'),
'Y_ERR' : array.array('f')}


# set data point
for data in fins :
item = data.split(None)
dat['X'].append(float(item[0]))
dat['X_ERR'].append(float(item[2]))
dat['Y'].append(float(item[1]))
dat['Y_ERR'].append(float(item[3]))


graph = ROOT.TGraphErrors(len(dat), dat['X'], dat['Y'],
dat['X_ERR'], dat['Y_ERR'])


cv = ROOT.TCanvas("cv", "Graph Example", 200, 10, 700, 500)

pad = cv.cd()
pad.SetGridx(1)
pad.SetGridy(1)

graph.Draw("APL")
cv.Update()


# export
cv.Print("graph2.png")






Tips プロット時のオプション

Draw("**") のときの ** を変えることで、いろいろなグラフが描ける

A : 軸をグラフの周りに描く
P : データを指定したマーカー (default は ・) でプロットする
L : 折れ線グラフ
C : データの間を滑らかな曲線で結ぶ


1次関数で fitting


#/bin/usr/env python

import sys, os, array
import ROOT


if __name__=='__main__':


if len(sys.argv) < 2 :
sys.exit(1)

if not os.path.exists(sys.argv[1]) :
sys.exit(1)

# read data from file
fin = open(sys.argv[1], "r")
fins = fin.readlines()
fin.close()


dat = {'X' : array.array('f'),
'X_ERR' : array.array('f'),
'Y' : array.array('f'),
'Y_ERR' : array.array('f')}


# set data point
for data in fins :
item = data.split(None)
dat['X'].append(float(item[0]))
dat['X_ERR'].append(float(item[2]))
dat['Y'].append(float(item[1]))
dat['Y_ERR'].append(float(item[3]))


graph = ROOT.TGraphErrors(len(dat), dat['X'], dat['Y'],
dat['X_ERR'], dat['Y_ERR'])


# fitting
graph.Fit("pol1")

# output fitting parameters
ROOT.gStyle.SetOptFit()

cv = ROOT.TCanvas("cv", "Graph Example", 200, 10, 700, 500)

pad = cv.cd()
pad.SetGridx(1)
pad.SetGridy(1)

graph.Draw("AP")
cv.Update()

# export
cv.Print("graph3.png")


How to use pyROOT 応用編 その5

ヒストグラムの一部を表示する

GetXaxis() と SetRange()
で X軸 の表示範囲を設定する



#/bin/usr/env python

import sys, math
import ROOT


if __name__=='__main__':

cv = ROOT.TCanvas("cv", "Histogram Example", 200, 10, 700, 500)

# create histogram ( identify, Title, number of class, xmin, xmax )
h1 = ROOT.TH1S('h', 'px', 100, -5., 5.)

for i in xrange(25000):
px = ROOT.gRandom.Gaus()
h1.Fill(px)

# fitting
h1.Fit("gaus")

# output fitting parameters
ROOT.gStyle.SetOptFit()

# set xrange
axisX = h1.GetXaxis()
axisX.SetRange(axisX.FindBin(-1), axisX.FindBin(1))

h1.Draw()
cv.Update()

# export
cv.Print("histogram6.png")


How to use pyROOT 基礎編 その3

ビルトイン関数で fitting

2. ヒストグラムの fitting

h1 = ROOT.TH1S(...)

・Gaussian fitting
h1.Fit("gaus")

・exponential fitting
h1.Fit("expo")

n次のべき関数 fitting
h1.Fit("poln")



fitting parameters を表示するには
ROOT.gStyle.SetOptFit()




#/bin/usr/env python

import sys, math
import ROOT


if __name__=='__main__':

cv = ROOT.TCanvas("cv", "Histogram Example", 200, 10, 700, 500)

# create histogram ( identify, Title, number of class, xmin, xmax )
h1 = ROOT.TH1S('h', 'px', 100, -5., 5.)

for i in xrange(25000):
px = ROOT.gRandom.Gaus()
h1.Fill(px)

# fitting
h1.Fit("gaus")

# output fitting parameters
ROOT.gStyle.SetOptFit()

h1.Draw()
cv.Update()


# export
cv.Print("histogram5.png")



How to use pyROOT 基礎編 その2

ヒストグラム - Histogram -


1. 1次元のヒストグラム

TH1S クラスを使う

引数は、 (名前, グラフの題名, ヒストグラムの階級数, xmin, xmax)



#/bin/usr/env python

import sys, math
import ROOT


if __name__=='__main__':

cv = ROOT.TCanvas("cv", "Histogram Example", 200, 10, 700, 500)

# create histogram ( identify, Title, number of class, xmin, xmax )
h1 = ROOT.TH1S('h', 'px', 100, -1., 1.)

for i in xrange(50000):
px = ROOT.gRandom.Gaus()
h1.Fill(px)

h1.Draw()
cv.Update()


# export
cv.Print("histogram1.png")






Draw() の引数を変えて、いろいろなヒストグラムを描くことができる


・エラーバー Draw("E")



・折れ線 Draw("L")



・点 Draw("P")

2009年7月10日金曜日

How to use pyROOT 応用編 その4

関数の表示


identity 関数の引数 x は 長さ 4 の配列で、 (x, y, z, t) を表す。
ここでの TF1 の引数は ( グラフのタイトル、関数、関数の範囲 )
で、ROOT の TF1 コンストラクタには引数は与えられない。


#/bin/usr/env python

import sys, math
from ROOT import *

def identity( x ):
return x[0]

if __name__=='__main__' :

# create an identity function
f = TF1( 'pyf1', identity, -1., 1. )

# plot the function
cv = TCanvas()
f.Draw()

# export
cv.Print("graphtest6.png")







ここでの TF1 の引数は ( グラフのタイトル、関数、関数の範囲、媒介変数の数)
で、ROOT の TF1 コンストラクタには、2つの媒介変数が指定される。


import sys, math
from ROOT import *

class Linear:
def __call__(self, x, par):
return par[0] + x[0] * par[1]

if __name__=='__main__' :

# create a linear function with offset 5, and pitch 2
f = TF1( 'pyf2', Linear(), -1., 1., 2 )
f.SetParameters( 5., 2. )


# plot the function
cv = TCanvas()
f.Draw()


# export
cv.Print("graphtest7.png")


How to use pyROOT 応用編 その3

任意関数での ヒストグラムの fitting


#/bin/usr/env python

import sys, math
import ROOT


class Linear:
def __call__(self, x, par):
return par[0] + x[0] * par[1]

if __name__=='__main__':

cv = ROOT.TCanvas("cv", "Fitting Example", 200, 10, 700, 500)

# create a linear function for fitting
f = ROOT.TF1('f', Linear(), -1., 1., 2)

# create histogram ( identify, Title, ?, xmin, xmax )
h = ROOT.TH1F('h', 'px', 100, -1., 1.)
f2= ROOT.TF1('f2', '6. + x * 4.5', -1, 1.)

h.FillRandom('f2', 10000)


# fits the hitstogram with the 'Linear' function
h.Fit(f)

# export
cv.Print("graphtest4.png")

# print results
par = f.GetParameters()
print 'fitting result: const = ', par[0], ', pitch = ', par[1]


実行結果


$ python graphtest4.py
FCN=101.388 FROM MIGRAD STATUS=CONVERGED 29 CALLS 30 TOTAL
EDM=2.65063e-16 STRATEGY= 1 ERROR MATRIX ACCURATE
EXT PARAMETER STEP FIRST
NO. NAME VALUE ERROR SIZE DERIVATIVE
1 p0 9.89861e+01 9.94918e-01 4.29016e-03 -2.65160e-08
2 p1 7.57130e+01 1.55891e+00 6.72214e-03 8.21832e-09
Info in : file graphtest4.png has been created
fitting result: const = 98.9861239576 , pitch = 75.7130326833



2009年7月8日水曜日

How to use pyROOT 応用編 その2

Gauss 分布のヒストグラムを書いてみよう


#/bin/usr/env python

import sys, math
import ROOT

if __name__=='__main__':

cv = ROOT.TCanvas("cv", "Gauss Example", 200, 10, 700, 500)

# create histogram( identify, Title, ?, xmin, xmax )
hpx = ROOT.TH1F('hpx', 'px', 100, -4, 4)

for i in xrange(25000):
px = ROOT.gRandom.Gaus()
hpx.Fill(px)

hpx.Draw()
cv.Update()

# export
cv.Print("graphtest3.png")


2009年7月2日木曜日

How to use pyROOT 応用編 その1

上下に2つのグラフを表示したいなー。

そんなときはこれを使うべし。

cv.Divide( 1, 2 )



#/bin/usr/env python

import sys, math
import ROOT

if __name__=='__main__':

# set graph1 style
graph1 = ROOT.TGraph()
graph1.SetLineWidth(2)
graph1.SetLineColor(4)
graph1.SetLineStyle(1)

# set graph2 style
graph2 = ROOT.TGraph()
graph2.SetLineWidth(2)
graph2.SetLineColor(3)
graph2.SetLineStyle(1)

# set title
graph1.SetTitle("Graph Test 2 top")
graph2.SetTitle("Graph Test 2 bottom")

# set data point
for x in range(10) :
np = graph1.GetN()
graph1.SetPoint(np, x, x**2)
graph2.SetPoint(np, x, x)

# open canvas
cv = ROOT.TCanvas("cv", "Graph Test", 800, 800)

# divide canvas to two
cv.Divide(1,2)

# top plot
pad = cv.cd(1)
pad.SetGridx(1)
pad.SetGridy(1)

# plot to top pannel
graph1.Draw("APC")

# set X axise of graph1
axisY = graph1.GetYaxis()
axisY.SetTitle("x**2")


# bottom plot
pad = cv.cd(2)
pad.SetGridx(1)
pad.SetGridy(1)

# plot to bottom pannel
graph2.Draw("APC")

# set Y axise of graph1
axisY = graph2.GetYaxis()
axisY.SetTitle("x")


# set X axis
axisX = graph2.GetXaxis()
axisX.SetTitle("x")


# export
cv.Print("graphtest2.png")


How to use pyROOT 基礎編

・pyROOT の使い方

グラフツールの ROOT を python で import できるようにしたのが pyROOT

いよいよ ROOT でグラフを描きたくなったので、練習練習

必要なもの
・python
・pyROOT

今回はすでに設定されている PC で使い方を練習するので、
設定方法は他のところで調べて下さい
http://root.cern.ch/root/HowtoPyROOT.html
あたりで
もしかしたら後で書くかも
マニュアルはこちら
http://wlav.web.cern.ch/wlav/pyroot/


#/bin/usr/env python

import sys, math
import ROOT

if __name__=='__main__':

graph = ROOT.TGraph()

# set line width
graph.SetLineWidth(2)

# set line color
# 1: black (default)
# 2: red
# 3: green
# 4: blue
# 5: yellow
# 6: magenda
# 7: cyan
# 8: yellowgreen
# 9: purple
# 10: white
graph.SetLineColor(4)

# set line style
# 1: line (default)
# 2: dashed line
# 3: dot line
# 4: dot-dashed line
graph.SetLineStyle(1)

# set title
graph.SetTitle("Graph Test 1")


# set data point
for x in range(10) :
np = graph.GetN()
graph.SetPoint(np, x, x**2)

# open canvas
cv = ROOT.TCanvas("cv", "Graph Test", 800, 800)

pad = cv.cd()

# set grid
pad.SetGridx(1)
pad.SetGridy(1)

# set axises
axisX = graph.GetXaxis()
axisX.SetTitle("x")

axisY = graph.GetYaxis()
axisY.SetTitle("x**2")

# plot
graph.Draw("APC")


# plot line
line = ROOT.TLine(0, 40, 10, 40)
line.SetLineWidth(4)
line.SetLineColor(2)
line.SetLineStyle(2)
line.Draw("SAME")

# export
cv.Print("graphtest1.png")