CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
RootCanvasView.py
Go to the documentation of this file.
1 import logging
2 
3 from PyQt4.QtCore import SIGNAL,Qt,QCoreApplication
4 from PyQt4.QtGui import QWidget
5 
6 from Vispa.Views.AbstractView import AbstractView
7 from Vispa.Main.Exceptions import exception_traceback
8 from Vispa.Share.BasicDataAccessor import BasicDataAccessor
9 
10 try:
11  import ROOT
12  import pxl.core,pxl.astro,pxl.hep
13  import_root_error=None
14 except Exception,e:
15  import_root_error=(str(e),exception_traceback())
16 
17 from array import array
18 
19 class RootCanvasView(AbstractView, QWidget):
20 
21  LABEL = "&ROOT Canvas View"
22 
23  def __init__(self, parent=None):
24  AbstractView.__init__(self)
25  QWidget.__init__(self, parent)
26  ROOT.gROOT.SetStyle('Plain')
27  #ROOT.gStyle.SetPalette(1)
28  self.canvas = ROOT.TCanvas()
29  #self.canvas.SetEditable(False)
30  #self.canvas = None
31  self._operationId = 0
32  self._updatingFlag = 0
33 
34  def setDataAccessor(self, accessor):
35  """ Sets the DataAccessor from which the data is read
36  You need to call updateContent() in order to make the changes visible.
37  """
38  if not isinstance(accessor, BasicDataAccessor):
39  raise TypeError(__name__ + " requires data accessor of type BasicDataAccessor.")
40  #if not isinstance(accessor, RelativeDataAccessor):
41  # raise TypeError(__name__ + " requires data accessor of type RelativeDataAccessor.")
42  AbstractView.setDataAccessor(self, accessor)
43 
44  def updateContent(self):
45  """ Clear the view and refill it.
46  """
47  logging.debug(__name__ + ": updateContent")
48  if import_root_error!=None:
49  logging.error(__name__ + ": Could not import pxl and ROOT: "+import_root_error[1])
50  QCoreApplication.instance().errorMessage("Could not import pxl and ROOT (see logfile for details):\n"+import_root_error[0])
51  return
52  self._updatingFlag +=1
53  operationId = self._operationId
54  #if self._dataAccessor:
55  #objects = self._filter(self._dataObjects)
56  objects = self.applyFilter(self.dataObjects())
57  i = 0
58  for object in objects:
59  if operationId != self._operationId:
60  break
61  self._plotscript(self.canvas, object)
62 
63  self._updatingFlag -=1
64  return operationId == self._operationId
65 
66  def _plotscript(self, canvas, object):
67  ''' The actual plotting script - has to be replaced later with
68  script from external file by user'''
69 
70 
71  logging.debug(__name__ + ": _plotscript")
72  canvas.cd()
73  if isinstance(object, pxl.core.BasicContainer):
74  self.basiccontainer = object
75  abos = object.getObjectsOfType(pxl.astro.AstroBasicObject)
76  logging.debug(__name__ + ": _plotscript: Plotting " + str(len(abos)) + " AstroObjects")
77  lat = []
78  lon = []
79  for ao in abos:
80  lat.append(ao.getLatitude())
81  lon.append(ao.getLongitude())
82 
83  self.f = ROOT.TGraph(len(lat), array('f', lon), array('f', lat))
84  #self.f.SetEditable(False)
85  self.f.SetTitle('')
86  self.f.GetXaxis().SetTitle('Longitude')
87  self.f.GetYaxis().SetTitle('Latitude')
88  self.f.SetName('')
89  self.f.Draw('ap')
90  self.f.SetEditable(False)
91  self.p = None
92  elif isinstance(object, pxl.astro.RegionOfInterest) or isinstance(object, pxl.astro.UHECRSource):
93  self.p = []
94  self.p.append(ROOT.TMarker(object.getLongitude(), object.getLatitude(), 3))
95  logging.debug(__name__ + 'DrawROI with ' + str(len(object.getSoftRelations().getContainer().items())) + ' UHECR')
96  for key, item in object.getSoftRelations().getContainer().items():
97 
98  uhecr = pxl.astro.toUHECR(self.basiccontainer.getById(item))
99  if isinstance(uhecr,pxl.astro.UHECR):
100  self.p.append(ROOT.TMarker(uhecr.getLongitude(), uhecr.getLatitude(), 7))
101  self.p[ - 1].SetMarkerSize(10)
102  self.p[ - 1].SetMarkerColor(ROOT.kGreen + 1)
103  else:
104  uhecr = pxl.astro.toAstroObject(self.basiccontainer.getById(item))
105  if isinstance(uhecr,pxl.astro.AstroObject):
106  self.p.append(ROOT.TMarker(uhecr.getLongitude(), uhecr.getLatitude(), 7))
107  self.p[ - 1].SetMarkerSize(8)
108  self.p[ - 1].SetMarkerColor(ROOT.kOrange + 1)
109 
110  for x in self.p:
111  x.Draw()
112 
113  elif isinstance(object, pxl.astro.AstroBasicObject):
114  self.p = ROOT.TMarker(object.getLongitude(), object.getLatitude(), 7)
115  self.p.SetMarkerSize(10)
116  self.p.SetMarkerColor(ROOT.kRed)
117  self.p.Draw()
118  elif isinstance(object, pxl.hep.EventView):
119  self.createLegoPlot(object)
120  elif isinstance(object, pxl.core.Event):
121  for eventview in object.getObjectsOfType(pxl.hep.EventView):
122  self.createLegoPlot(object)
123  elif isinstance(object, pxl.hep.Particle):
124  self.p = ROOT.TMarker(object.getPhi(), object.getEta(), 20)
125  if (object.getName() == "Muon"):
126  h2 = ROOT.TH2F('muon-plot', '', 50, - 4, 4, 50, - 3.141593, 3.141593)
127  h2.SetFillColor(2)
128  h2.Fill(object.getEta(), object.getPhi(), object.getPt())
129  h2.DrawCopy('SAME LEGO A')
130  elif (object.getName() == "Jet"):
131  h2 = ROOT.TH2F('jet-plot', '', 50, - 4, 4, 50, - 3.141593, 3.141593)
132  h2.SetFillColor(4)
133  h2.Fill(object.getEta(), object.getPhi(), object.getPt())
134  h2.DrawCopy('SAME LEGO A')
135  elif (object.getName() == "Electron"):
136  h2 = ROOT.TH2F('electron-plot', '', 50, - 4, 4, 50, - 3.141593, 3.141593)
137  h2.SetFillColor(3)
138  h2.Fill(object.getEta(), object.getPhi(), object.getPt())
139  h2.DrawCopy('SAME LEGO A')
140  elif (object.getName() == "MET"):
141  h2 = ROOT.TH2F('met-plot', '', 50, - 4, 4, 50, - 3.141593, 3.141593)
142  h2.SetFillColor(6)
143  h2.Fill(object.getEta(), object.getPhi(), object.getPt())
144  h2.DrawCopy('SAME LEGO A')
145  else:
146  h2 = ROOT.TH2F('all-plot', '', 50, - 4, 4, 50, - 3.141593, 3.141593)
147  h2.SetFillColor(1)
148  h2.Fill(object.getEta(), object.getPhi(), object.getPt())
149  h2.DrawCopy('SAME LEGO A')
150  self.p.Draw()
151 
152  canvas.Modified()
153  canvas.Update()
154 
155  def createGraph(self, eventview):
156  particles = eventview.getObjectsOfType(pxl.hep.Particle)
157  logging.info("Display " + str(len(particles)) + " Particles.")
158  if (len(particles) > 0):
159  etas = []
160  phis = []
161  for particle in particles:
162  if (particle.getEta() < 1000.):
163  etas.append(particle.getEta())
164  phis.append(particle.getPhi())
165  self.f = ROOT.TGraph(len(etas), array('f', phis), array('f', etas))
166  self.f.SetTitle('')
167  self.f.GetXaxis().SetTitle('#Phi')
168  self.f.GetXaxis().SetRangeUser(- 3.14156, 3.14156)
169  self.f.GetYaxis().SetTitle('#eta')
170  self.f.GetXaxis().SetRangeUser(- 5., 5.)
171  self.f.SetMarkerSize(1)
172  self.f.SetMarkerStyle(20)
173  self.f.SetName('')
174  self.f.Draw('ap')
175  self.f.SetEditable(False)
176  self.p = None
177 
178  def createLegoPlot(self, eventview):
179  particles = eventview.getObjectsOfType(pxl.hep.Particle)
180  logging.info("Display " + str(len(particles)) + " Particles")
181  if (len(particles) > 0):
182  self.f = ROOT.TH2F('eta-phi-plot', '', 50, - 4, 4, 50, - 3.141593, 3.141593)
183  for particle in particles:
184  self.f.Fill(particle.getEta(), particle.getPhi(), particle.getPt())
185 
186  self.f.SetTitle('')
187  self.f.GetXaxis().SetTitle('#eta')
188  self.f.GetYaxis().SetTitle('#Phi')
189  self.f.GetZaxis().SetTitle('p_{T} (GeV)')
190  self.f.SetName('')
191  self.f.DrawCopy('LEGO2')
192  self.p = None
193 
194  def cancel(self):
195  """ Stop all running operations.
196  """
197  self._operationId += 1
198 
199  def mousePressEvent(self,event):
200  QWidget.mousePressEvent(self,event)
201  if event.button()==Qt.RightButton:
202  self.emit(SIGNAL("mouseRightPressed"), event.globalPos())
203 
204  def isBusy(self):
205  return self._updatingFlag>0