GRSISort
Created by P.C. Bender
Developement Team: P.C. Bender, R. Dunlop, V. Bildstein
An extension of the ROOT analysis Framework
tcut_tab.py
Go to the documentation of this file.
1 #!/usr/bin/env python2
2 
3 import Tkinter as tk
4 import ttk
5 import re
6 
7 import ROOT
8 ROOT.PyConfig.IgnoreCommandLineOptions = True
9 
10 from .util import increment_name
11 
12 class TCutTab(object):
13 
14  def __init__(self, main, frame):
15  self.main = main
16  self._setup_GUI(frame)
17 
18  self.cuts = {}
19  self.detector_classes = {}
20 
21  #frame.after_idle(self._repeatedly_check)
22 
23  def _setup_GUI(self, frame):
24  self.frame = frame
25  self._MakeNaming(frame)
26  self._MakeTreeView(frame)
27 
28  def _repeatedly_check(self):
29  self._check_for_tcut()
30  self.frame.after(1000,self._repeatedly_check)
31 
32  def _dump_to_tfile(self):
33  for cut in self.cuts.values():
34  cut.Write()
35 
36  def _tcut_patterns(self):
37  output = []
38  for name, cut in self.cuts.items():
39  points = []
40  for i in xrange(cut.GetN()):
41  points.append((cut.GetX()[i], cut.GetY()[i]))
42 
43  pattern = {'name':name,
44  'points':points,
45  'varx':cut.GetVarX(),
46  'vary':cut.GetVarY(),
47  }
48  output.append(pattern)
49  return output
50 
51  def _load_tcut_patterns(self, patterns):
52  for pattern in patterns:
53  cut = ROOT.TCutG(pattern['name'],len(pattern['points']))
54  cut.SetVarX(pattern['varx'])
55  cut.SetVarY(pattern['vary'])
56  for i,(x,y) in enumerate(pattern['points']):
57  cut.SetPoint(i, x, y)
58  self.AddCut(cut)
59 
60  def _check_for_tcut(self):
61  # Does CUTG exist?
62  cutg = ROOT.gROOT.GetListOfSpecials().FindObject('CUTG')
63  if not cutg:
64  return None
65 
66  # Does it have 3 or more points?
67  npoints = cutg.GetN()
68  if npoints < 3:
69  return None
70 
71  # Is the first point equal to the last point?
72  xi = cutg.GetX()[0]
73  yi = cutg.GetY()[0]
74  xf = cutg.GetX()[npoints-1]
75  yf = cutg.GetY()[npoints-1]
76  if xi!=xf or yi!=yf:
77  return None
78 
79  return cutg
80 
81  def AddDirectory(self, tdir):
82  gchain = ROOT.gFragment
83  # If the chain doesn't exist, or if it is empty.
84  if not gchain or gchain.GetEntries()==0:
85  return
86 
87  for branch in gchain.GetListOfBranches():
88  cls_name = branch.GetName()
89  cls = getattr(ROOT, cls_name)
90  if cls_name not in self.detector_classes:
91  top = self.tree.insert('','end',
92  cls_name, text=cls_name)
93  self.tree.insert(top,'end',
94  '{}/Draw PID'.format(cls_name),
95  text='Draw PID')
96  self.detector_classes[cls_name] = cls
97 
98  def AddFile(self, tfile):
99  for key in tfile.GetListOfKeys():
100  if key.GetClassName()=='TCutG':
101  self.AddCut(key.ReadObj())
102 
103  def AddCut(self, cut, det_type = None):
104  name = cut.GetName()
105  full_name = '{}/{}'.format(det_type,name) if det_type is not None else name
106  cut.SetLineColor(ROOT.kRed)
107  cut.SetLineWidth(3)
108  self.cuts[full_name] = cut
109 
110  if det_type is None:
111  parent = ''
112  else:
113  parent = det_type
114  self.detector_classes[det_type].AddGate(cut)
115 
116  self.tree.insert(parent, 'end', full_name, text=name, values='2D Cut',
117  image = self.main.icons['tcutg'])
118 
119  if ROOT.gPad:
120  ROOT.gPad.Modified()
121  ROOT.gPad.Update()
122 
123  def StartCut(self):
124  ROOT.gROOT.SetEditorMode('CutG')
125 
126  def SaveCut(self):
127  cutg = self._check_for_tcut()
128  if cutg is None:
129  return
130 
131  ROOT.gROOT.GetListOfSpecials().Remove(cutg)
132 
133  cutg.SetName(self._increment_name())
134  for prim in ROOT.gPad.GetListOfPrimitives():
135  if isinstance(prim, ROOT.TH2):
136  title = prim.GetName()
137  det_type = title[:title.index('_')]
138  break
139  else:
140  det_type = None
141 
142  self.AddCut(cutg, det_type)
143 
144  def DeleteCut(self):
145  cutg = self._check_for_tcut()
146  if(cutg is None):
147  return
148 
149  cutg.Delete()
150 
151  def CopyCut(self):
152  cuts = self.tree.selection()
153  if not cuts:
154  return
155  cutname = cuts[0]
156  tcutg = self.cuts[cutname]
157  newcut = tcutg.Clone(self._increment_name())
158 
159  xmin = min(newcut.GetX()[i] for i in range(newcut.GetN()))
160  xmax = max(newcut.GetX()[i] for i in range(newcut.GetN()))
161  xshift = 0.5*(xmax-xmin)
162  for i in range(newcut.GetN()):
163  newcut.GetX()[i] += xshift
164 
165 
166  newcut.Draw('same')
167  self.AddCut(newcut)
168 
169 
170  def _increment_name(self):
171  name = self.next_name.get()
172  self.next_name.set(increment_name(name))
173  return name
174 
175  def _MakeNaming(self, parent):
176  self.next_name = tk.StringVar(value='tcutg_0')
177  frame = tk.Frame(parent)
178  tk.Label(frame, text='Name:').pack(side=tk.LEFT)
179  tk.Entry(frame, textvariable=self.next_name).pack(side=tk.LEFT)
180  frame.pack(fill=tk.X,expand=False)
181 
182  frame = tk.Frame(parent)
183  tk.Button(frame, text='Make Gate', fg="black",bg="light goldenrod", command=self.StartCut).pack(side=tk.LEFT)
184  tk.Button(frame, text='Save Gate', fg="black",bg="light goldenrod", command=self.SaveCut).pack(side=tk.LEFT)
185  tk.Button(frame, text='Copy Gate',fg="black",bg="light goldenrod", command=self.CopyCut).pack(side=tk.LEFT)
186  tk.Button(frame, text='Delete Gate',fg="black",bg="firebrick", command=self.DeleteCut).pack(side=tk.LEFT)
187  frame.pack(fill=tk.X,expand=False)
188 
189  def _MakeTreeView(self, parent):
190  self.tree = ttk.Treeview(parent, columns=('type',))
191  self.tree.column('type', width=50, anchor='e')
192  self.tree.heading('type', text='Type')
193  self.tree.pack(fill=tk.BOTH,expand=True)
194  self.tree.bind("<Double-1>",self.TreeView_OnDoubleClick)
195 
196  def _draw_cut(self,cut):
197  tcut.Draw('same')
198  if ROOT.gPad:
199  ROOT.gPad.Modified()
200  ROOT.gPad.Update()
201 
202  def TreeView_OnDoubleClick(self, event):
203  selection = event.widget.selection()[0]
204  if selection in self.cuts:
205  self._draw_cut(self.cuts[selection])
206  else:
207  if selection.endswith('Draw PID'):
208  cls_name = selection[:selection.index('/')]
209  try:
210  self.detector_classes[cls_name].DrawPID('','',1000)
211  except AttributeError:
212  print 'You did not implement {}::DrawPID.\nPlease do so.'.format(cls_name)
def _dump_to_tfile(self)
Definition: tcut_tab.py:32
def TreeView_OnDoubleClick(self, event)
Definition: tcut_tab.py:202
def __init__(self, main, frame)
Definition: tcut_tab.py:14
def increment_name(name)
Definition: util.py:27
def _check_for_tcut(self)
Definition: tcut_tab.py:60
def _tcut_patterns(self)
Definition: tcut_tab.py:36
def _setup_GUI(self, frame)
Definition: tcut_tab.py:23
def _increment_name(self)
Definition: tcut_tab.py:170
def _MakeTreeView(self, parent)
Definition: tcut_tab.py:189
def _load_tcut_patterns(self, patterns)
Definition: tcut_tab.py:51
def AddDirectory(self, tdir)
Definition: tcut_tab.py:81
def _draw_cut(self, cut)
Definition: tcut_tab.py:196
def _repeatedly_check(self)
Definition: tcut_tab.py:28
def _MakeNaming(self, parent)
Definition: tcut_tab.py:175
def AddFile(self, tfile)
Definition: tcut_tab.py:98
if(hist) hist -> Fill(fragment->GetCharge())
def AddCut(self, cut, det_type=None)
Definition: tcut_tab.py:103