CMS 3D CMS Logo

TkAlMap.py
Go to the documentation of this file.
1 import os
2 import sys
3 import ROOT
4 import copy
5 import math
6 import time
7 import ctypes
8 from array import array
9 from Alignment.OfflineValidation.DivergingColor import DivergingColor
10 
11 '''
12 Class for the TkAlMap plots
13 to produce the plots use Alignment/OfflineValidation/python/runGCPTkAlMap.py
14 '''
15 
16 #TEST_COLOR_IDX = 2000
17 #TEST_COLOR = ROOT.TColor(TEST_COLOR_IDX, (0.)/255., (0.)/255., (255+0.)/255.)
18 
19 KNOWN_VARIABLES = {
20  'dr': {
21  'name' : '#Deltar',
22  'units': '#mum',
23  'scale': 10000.,
24  'range': [-200., 200.],
25  },
26  'dx': {
27  'name' : '#Deltax',
28  'units': '#mum',
29  'scale': 10000.,
30  'range': [-200., 200.],
31  },
32  'dy': {
33  'name' : '#Deltay',
34  'units': '#mum',
35  'scale': 10000.,
36  'range': [-200., 200.],
37  },
38  'dz': {
39  'name' : '#Deltaz',
40  'units': '#mum',
41  'scale': 10000.,
42  'range': [-200., 200.],
43  },
44  'rdphi': {
45  'name' : 'r #Delta#phi',
46  'units': '#mum rad',
47  'scale': 10000.,
48  'range': [-100., 100.],
49  },
50  'dphi': {
51  'name' : '#Delta#phi',
52  'units': 'mrad',
53  'scale': 1000.,
54  'range': [-100., 100.],
55  },
56  'dalpha': {
57  'name' : '#Delta#alpha',
58  'units': 'mrad',
59  'scale': 1000.,
60  'range': [-100., 100.],
61  },
62  'dbeta': {
63  'name' : '#Delta#beta',
64  'units': 'mrad',
65  'scale': 1000.,
66  'range': [-100., 100.],
67  },
68  'dgamma': {
69  'name' : '#Delta#gamma',
70  'units': 'mrad',
71  'scale': 1000.,
72  'range': [-100., 100.],
73  },
74  'du': {
75  'name' : '#Deltau',
76  'units': '#mum',
77  'scale': 10000.,
78  'range': [-200., 200.],
79  },
80  'dv': {
81  'name' : '#Deltav',
82  'units': '#mum',
83  'scale': 10000.,
84  'range': [-200., 200.],
85  },
86  'dw': {
87  'name' : '#Deltaw',
88  'units': '#mum',
89  'scale': 10000.,
90  'range': [-200., 200.],
91  },
92  'da': {
93  'name' : '#Deltaa',
94  'units': 'mrad',
95  'scale': 1000.,
96  'range': [-100., 100.],
97  },
98  'db': {
99  'name' : '#Deltab',
100  'units': 'mrad',
101  'scale': 1000.,
102  'range': [-100., 100.],
103  },
104  'dg': {
105  'name' : '#Deltag',
106  'units': 'mrad',
107  'scale': 1000.,
108  'range': [-100., 100.],
109  },
110 }
111 
112 #ROOT.gStyle.SetLineScalePS(1)
113 
114 def mean(data_list):
115  return sum(data_list)/(len(data_list)+0.)
116 
117 def StdDev(data_list):
118  s2 = 0.
119  m = mean(data_list)
120  for point in data_list:
121  s2 += (point-m)**2
122  return math.sqrt(s2/(len(data_list)+0.))
123 
124 def read_TPLfile(file_name):
125  o_file = open(file_name, 'r')
126  lines = o_file.readlines()
127  o_file.close()
128 
129  TPL_dict = {}
130  for line in lines:
131  if '#' in line: continue
132  splt_line = line.replace('\n', '').split(' ')
133  det_id = int(splt_line[0])
134  x = []
135  y = []
136  for idx,coo in enumerate(splt_line[1:]):
137  #print(coo)
138  try:
139  val = float(coo)
140  if (idx%2) == 0:
141  y.append(val)
142  else:
143  x.append(val)
144  except ValueError:
145  continue
146  TPL_dict[det_id] = {}
147  TPL_dict[det_id]['x'] = x
148  TPL_dict[det_id]['y'] = y
149  return TPL_dict
150 
151 class TkAlMap:
152 
153  #def __init__(self, variable, title, root_file, two_sigma_cap=False, width=1500, height=800, GEO_file='TkMap_design_cfg.py', tracker='full'):
154  def __init__(self, variable, title, root_file, use_default_range=False, two_sigma_cap=False, height=1400, GEO_file='TkAlMapDesign_phase1_cfg.py', tracker='full', palette=2, do_tanh=False, check_tracker=True):
155  ROOT.gStyle.SetLineScalePS(1)
156 
157  # Configuration parameters
158  self.GEO_file = GEO_file
159  self.tracker = tracker
160  self.width = height
161  self.height = height
162  self.title = title
163  self.default_range = use_default_range
164  self.two_sigma_cap = two_sigma_cap
165  self.root_file = root_file
166  self.do_tanh = do_tanh
167 
168  # Value Initialization
169  self.max_val = None
170  self.min_val = None
172  self.tree = None
173  self.is_cleaned = False
174 
175  # Internal parameters
176  self.data_path = 'Alignment/OfflineValidation/data/TkAlMap/'
177  self.cfg_path = 'Alignment/OfflineValidation/python/TkAlMap_cfg/'
178 
179  # Colorbar stuff
180  self.start_color_idx = 1200
181  self.n_color_color_bar = 1000
182 
183  # Initialization functions
184  self.set_palette(palette)
185  self.set_var(variable)
186  self.load_tree()
187  if check_tracker: self.detect_tracker_version()
188  self.load_geometry()
189  self.set_colorbar_colors()
190 
191  def set_var(self, var, var_range=[None, None]):
192  print('TkAlMap: setting variable to '+var)
193  self.var = var
194  self.var_name = var
195  self.var_units = 'cm'
196  self.var_scale = 1.
197  self.var_min = var_range[0]
198  self.var_max = var_range[1]
199  if var in KNOWN_VARIABLES:
200  self.var_name = KNOWN_VARIABLES[var]['name']
201  self.var_units = KNOWN_VARIABLES[var]['units']
202  self.var_scale = KNOWN_VARIABLES[var]['scale']
203  if self.var_min is None: self.var_min = KNOWN_VARIABLES[var]['range'][0]
204  if self.var_max is None: self.var_max = KNOWN_VARIABLES[var]['range'][1]
205  self.set_canvas()
206 
207  def set_canvas(self):
208  canv_name = 'canvas_'+self.tracker+'_'+self.var
209  if self.two_sigma_cap: canv_name += '_cap'
210  self.canvas = ROOT.TCanvas(canv_name, 'TkAlMap '+self.var+' canvas', self.width, self.height)
211  print('Actual w: '+str(self.canvas.GetWw())+', Actual h: '+str(self.canvas.GetWh()))
212 
213 
214  def setup_colors(self):
215  self.load_var()
216  self.prepare_map_colors()
217  self.fill_colors()
218 
220  print('TkAlMap: preparing map colors')
221 
222  self.colors = []
223  #self.palette = array('i', [])
224  col_idx = self.start_color_idx + self.n_color_color_bar + 10
225  self.col_dic = {} #Never used explicitly but needs to keep TColor values in the global memory
226  self.rgb_map = {}
227  #pal_idx = 0
228  #self.pal_map = {}
229  for val in self.val_list:
230  cap_val = val
231  if cap_val > self.max_val: cap_val = self.max_val
232  if cap_val < self.min_val: cap_val = self.min_val
233  r, g, b = self.get_color_rgb(cap_val)
234  idx = self.get_color_rgb_idx(cap_val)
235  if idx in self.colors: continue
236  self.colors.append(idx)
237  col_idx +=1
238  self.rgb_map[idx] = col_idx
239 
240  try:
241  col = ROOT.gROOT.GetColor(col_idx) #Here still OK
242  col.SetRGB((r+0.)/255., (g+0.)/255., (b+0.)/255.) #Here segmentation if color index does not exist
243  self.col_dic[idx] = col #Here the new color is saved in in the global variable
244  except:
245  #Here the 6 argument TColor init with dummy rgb must be used, 4 argument one does not work (ROOT bug?)
246  #New color index is defined and SetRGB must also be called to overwrite dummy rgb
247  col = ROOT.TColor(col_idx, 0., 0., 0., "", 1)
248  col.SetRGB((r+0.)/255., (g+0.)/255., (b+0.)/255.)
249  self.col_dic[idx] = col #Here the new color is saved in in the global variable
250  #self.palette.append(col_idx)
251  print('TkAlMap: map contains '+str(len(self.colors))+' colors')
252 
253  def set_palette(self, palette):
254  self.palette = palette
255  pal_str = 'TkAlMap: setting the palette to '+str(palette)
256  if palette == 1: pal_str += ' (rainbow)'
257  elif palette == 2: pal_str += ' (B->R diverging)'
258  else: raise ValueError('TkAlMap: unkown palette value '+str(palette)+', allowed values are 1 and 2')
259  print(pal_str)
260  #ROOT.gstyle.SetPalette(len(self.colors), self.colors)
261  #ROOT.gStyle.SetPalette(len(self.palette), self.palette)
262  pass
263 
264  def get_color_rgb(self, val):
265  if self.max_val is None or self.min_val is None:
266  value_frac = val
267  else:
268  if self.do_tanh:
269  val_th = math.tanh((val - self.mean_val)/(self.std_val))
270  max_th = math.tanh((self.max_val - self.mean_val)/(self.std_val))
271  min_th = math.tanh((self.min_val - self.mean_val)/(self.std_val))
272  value_frac = (val_th - min_th + 0.)/(max_th - min_th)
273  else:
274  value_range = self.max_val - self.min_val
275  if value_range == 0.: value_frac = 0.5
276  else: value_frac = (val - self.min_val + 0.)/(value_range + 0.)
277  if self.palette == 1:
278  r = 255
279  g = 255
280  b = 255
281 
282  if value_frac < 0.25:
283  r = 0
284  g = int(255.*((value_frac/0.25)))
285  b = 255
286  elif value_frac < 0.5:
287  r = 0
288  g = 255
289  b = int(255.*(1. -(value_frac - 0.25)/0.25))
290  elif value_frac < 0.75:
291  r = int(255.*((value_frac - 0.5)/0.25))
292  g = 255
293  b = 0
294  else:
295  r = 255
296  g = int(255.*(1. -(value_frac - 0.75)/0.25))
297  b = 0
298  return r, g, b
299  elif self.palette == 2:
300  red = [59, 76, 192]
301  blue = [180, 4, 38]
302  white = [255, 255, 255]
303  r, g, b = DivergingColor(red, blue, white, value_frac)
304  return r, g, b
305  else: raise ValueError('TkAlMap: unkown palette value '+str(palette)+', allowed values are 1 and 2')
306 
307  def get_color_rgb_idx(self, val):
308  r, g, b = self.get_color_rgb(val)
309  #return r*1000000+g*1000+b+1000000000
310  offset = 100
311  return int(r*255*255 + g*255 + r + g + b + offset)
312 
313  def fill_colors(self):
314  print('TkAlMap: filling the colors')
315  #self.set_palette()
316  for module in self.mod_val_dict:
317  if module in self.TkAlMap_TPL_dict:
318  val = self.mod_val_dict[module]
319  cap_val = val
320  if cap_val > self.max_val: cap_val = self.max_val
321  if cap_val < self.min_val: cap_val = self.min_val
322  rgb = self.get_color_rgb_idx(cap_val)
323  col = self.rgb_map[rgb]
324  #col = self.pal_map[rgb]
325  #col = self.col_dic[rgb]
326  self.TkAlMap_TPL_dict[module].SetFillColor(col)
327  #self.TkAlMap_TPL_dict[module].SetFillColor(TEST_COLOR_IDX)
328 
329 
330  def set_colorbar_axis(self):
331  print('TkAlMap: setting color bar axis')
332  b_x1 = self.image_x1
333  b_x2 = self.image_x2
334  b_y1 = 0.06
335  b_y2 = 0.06
336  b_width = 0.01
337  self.color_bar_axis = ROOT.TGaxis(b_x1, b_y1, b_x2, b_y2, self.min_val, self.max_val, 50510, '+S')
338  self.color_bar_axis.SetName('color_bar_axis')
339  self.color_bar_axis.SetLabelSize(0.02)
340  self.color_bar_axis.SetTickSize(0.01)
341  if self.two_sigma_cap and not self.default_range: self.color_bar_axis.SetTitle('{#mu - 2#sigma #leq '+self.var_name+' #leq #mu + 2#sigma} ['+self.var_units+']')
342  elif self.default_range: self.color_bar_axis.SetTitle('{'+str(self.min_val)+' #leq '+self.var_name+' #leq '+str(self.max_val)+'} ['+self.var_units+']')
343  else: self.color_bar_axis.SetTitle(self.var_name+' ['+self.var_units+']')
344  self.color_bar_axis.SetTitleSize(0.025)
345 
347  print('TkAlMap: initialize color bar colors')
348  if self.max_val is None or self.min_val is None:
349  col_step = 1./(self.n_color_color_bar + 0.)
350  val = col_step/2.
351  else:
352  b_range = self.max_val - self.min_val
353  col_step = (b_range + 0.)/(self.n_color_color_bar + 0.)
354  val = self.min_val + col_step/2.
355 
356  b_x1 = self.image_x1
357  b_x2 = self.image_x2
358  b_y1 = 0.06
359  b_y2 = 0.06
360  b_width = 0.01
361  b_xrange = b_x2 - b_x1
362  b_yrange = b_y2 - b_y1
363  b_dx = (b_xrange + 0.)/(self.n_color_color_bar + 0.)
364  b_dy = (b_yrange + 0.)/(self.n_color_color_bar + 0.)
365 
366  self.color_bar = {}
367  x1 = b_x1
368  y1 = b_y1
369 
370  col_idx = self.start_color_idx
371  for i_c in range(self.n_color_color_bar):
372  col_idx += 1
373  r, g, b = self.get_color_rgb(val)
374  try:
375  col = ROOT.gROOT.GetColor(col_idx) #Here still OK
376  col.SetRGB((r+0.)/255., (g+0.)/255., (b+0.)/255.) #Here segmentation if color index does not exist
377  self.color_bar_colors[col_idx] = col #Here the new color is saved in in the global variable
378  except:
379  #Here the 6 argument TColor init with dummy rgb must be used, 4 argument one does not work (ROOT bug?)
380  #New color index is defined and SetRGB must also be called to overwrite dummy rgb
381  col = ROOT.TColor(col_idx, 0., 0., 0., "", 1)
382  col.SetRGB((r+0.)/255., (g+0.)/255., (b+0.)/255.)
383  self.color_bar_colors[col_idx] = col #Here the new color is saved in in the global variable
384  x2 = x1 + b_dx
385  y2 = y1 + b_dy + b_width
386  x = array('d', [x1, x1, x2, x2])
387  y = array('d', [y1, y2, y2, y1])
388  self.color_bar[col_idx] = ROOT.TPolyLine(len(x), x, y)
389  self.color_bar[col_idx].SetFillColor(col_idx)
390  self.color_bar[col_idx].SetLineColor(col_idx)
391 
392  x1 += b_dx
393  y1 += b_dy
394  val += col_step
395 
396 
397  def load_tree(self):
398  print('TkAlMap: loading tree ')
399  tree_name = 'alignTree'
400  r_file = ROOT.TFile(self.root_file)
401  if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
402 
403  tree_tmp = r_file.Get(tree_name)
404  #self.tree = copy.deepcopy(tree_tmp)
405  self.tmp_file_name = str(time.time()).replace('.', '_')+'_TkAlMapTempFile.root'
406  self.tmp_file = ROOT.TFile(self.tmp_file_name, 'recreate')
407  self.tree = tree_tmp.CloneTree()
408  r_file.Close()
409  self.is_cleaned = False
410 
411  if self.tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
412 
413 
414 
415  def load_var(self):
416  print('TkAlMap: loading variable values ')
417  #tree_name = 'alignTree'
418  #r_file = ROOT.TFile(self.root_file)
419  #if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
420 
421  #tree_tmp = r_file.Get(tree_name)
422  #tree = copy.deepcopy(tree_tmp)
423  #r_file.Close()
424 
425  #if tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
426 
427  self.mod_val_dict = {}
428  self.val_list = []
429  for event in self.tree:
430  module = event.id
431  var = self.var
432  if var == 'rdphi':
433  val = getattr(event, 'r')*getattr(event, 'dphi')
434  else:
435  val = getattr(event, var)
436  val *= self.var_scale
437  self.mod_val_dict[module] = val
438  #if val not in self.val_list: self.val_list.append(val)
439  if module in self.TkAlMap_TPL_dict: self.val_list.append(val)
440 
444  if len(self.val_list) == 0:
445  print('Warning: no values filled, 0 moduleId\'s matched')
446  self.val_list = [-10+idx*0.5 for idx in range(41)]
447  self.val_list.sort()
448  self.mean_val = mean(self.val_list)
449  self.std_val = StdDev(self.val_list)
450  self.min_val = min(self.val_list)
451  self.max_val = max(self.val_list)
452 
453  if self.two_sigma_cap and not self.default_range:
454  print('-- Capping max and min: ')
455  print('---- True values : '+str(self.max_val)+', '+str(self.min_val))
456  self.min_val = max(min(self.val_list), self.mean_val - 2*self.std_val)
457  self.max_val = min(max(self.val_list), self.mean_val + 2*self.std_val)
458  print('---- Capped values : '+str(self.max_val)+', '+str(self.min_val))
459 
460  if self.default_range:
461  #if not self.var in KNOWN_VARIABLES: print('Warning: capping to default range not possible for unknown variable "'+self.var+'"')
462  if self.var_min is None or self.var_max is None: print('Warning: capping to default range for unknown variable "'+self.var+'" while range was not set is not possible')
463  else:
464  print('-- Capping max and min to default ranges: ')
465  print('---- True values : '+str(self.max_val)+', '+str(self.min_val))
466  self.min_val = self.var_min
467  self.max_val = self.var_max
468  print('---- Capped values : '+str(self.max_val)+', '+str(self.min_val))
469 
470  if self.min_val == self.max_val:
471  print('Warning: minimum value was equal to maximum value, '+str(self.max_val))
472  self.min_val = self.mean_val - 1.
473  self.max_val = self.mean_val + 1.
474 
475  #print(self.val_list)
476 
478  print('TkAlMap: detecting Tk version')
479  #tree_name = 'alignTree'
480  #r_file = ROOT.TFile(self.root_file)
481  #if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
482 
483 
487 
488  #if tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
489  phase = None
490  for event in self.tree:
491  module = event.id
492  if module > 303040000 and module < 306450000:
493  phase = 1
494  break
495  elif module > 302055000 and module < 302198000:
496  phase = 0
497  break
498  #r_file.Close()
499 
500  if phase is None: raise ValueError('TkAlMap: unknown tracker detected, is this phase2?')
501 
502  pahse_str = 'phase'+str(phase)
503  print('TkAlMap: '+pahse_str+' tracker detected')
504  if not pahse_str in self.GEO_file:
505  print('TkAlMap: changing tracker to '+pahse_str+ ', if this is unwanted set "check_tracker" to False')
506  self.GEO_file = 'TkAlMapDesign_'+pahse_str+'_cfg.py'
507  #self.load_geometry()
508 
509  def load_geometry(self):
510  source_path = os.getenv('CMSSW_BASE') + '/src/'
511  var = {}
512  if sys.version_info[0] == 2:
513  execfile(source_path + self.cfg_path + self.GEO_file, var)
514  elif sys.version_info[0] == 3:
515  _filename = source_path + self.cfg_path + self.GEO_file
516  exec(compile(open(_filename, "rb").read(), _filename, 'exec'), var)
517 
518  MapStructure = var['TkMap_GEO']
519 
520  all_modules = {}
521  all_text = {}
522  x_max = -9999.
523  y_max = -9999.
524  x_min = 9999.
525  y_min = 9999.
526  for det in MapStructure:
527  if 'pixel' in self.tracker:
528  if not 'pixel' in det: continue
529  elif 'strips' in self.tracker:
530  if not 'strips' in det: continue
531  for sub in MapStructure[det]:
532  for part in MapStructure[det][sub]:
533  if part == 'latex':
534  all_text[det+'_'+sub] = MapStructure[det][sub][part]
535  continue
536  if 'latex' in MapStructure[det][sub][part]:
537  all_text[det+'_'+sub+'_'+part] = MapStructure[det][sub][part]['latex']
538  _filename = self.data_path +MapStructure[det][sub][part]['file']
539  TPL_file = [os.path.join(dir,_filename) for dir in os.getenv('CMSSW_SEARCH_PATH','').split(":") if os.path.exists(os.path.join(dir,_filename))][0]
540  TPL_dict = read_TPLfile(TPL_file)
541  for module in TPL_dict:
542  x_canv = []
543  y_canv = []
544  for idx in range(len(TPL_dict[module]['x'])):
545  x_canv.append(TPL_dict[module]['x'][idx]*MapStructure[det][sub][part]['x_scale'] + MapStructure[det][sub][part]['x_off'])
546  y_canv.append(TPL_dict[module]['y'][idx]*MapStructure[det][sub][part]['y_scale'] + MapStructure[det][sub][part]['y_off'])
547  if max(x_canv) > x_max: x_max = max(x_canv)
548  if max(y_canv) > y_max: y_max = max(y_canv)
549  if min(x_canv) < x_min: x_min = min(x_canv)
550  if min(y_canv) < y_min: y_min = min(y_canv)
551  TPL_dict[module]['x'] = x_canv
552  TPL_dict[module]['y'] = y_canv
553  all_modules.update(TPL_dict)
554 
555  r_margin = 3
556  l_margin = 3
557  #t_margin = 15
558  t_margin = 11
559  b_margin = 8
560 
561  x_max += r_margin
562  x_min -= l_margin
563  y_max += t_margin
564  y_min -= b_margin
565 
566  x_range = x_max - x_min
567  y_range = y_max - y_min
568 
569  self.width = int(self.height*(x_range + 0.)/(y_range + 0.))
570  self.canvas.SetWindowSize(self.width, self.height)
571 
572  if (x_range + 0.)/(self.width + 0.) > (y_range + 0.)/(self.height + 0.):
573  x_scale = x_range
574  y_scale = (self.height + 0.)/(self.width + 0.)*x_range
575  else:
576  y_scale = y_range
577  x_scale = (self.width + 0.)/(self.height + 0.)*y_range
578  self.TkAlMap_TPL_dict = {}
579  for module in all_modules:
580  x = array('d', [])
581  y = array('d', [])
582  for idx in range(len(all_modules[module]['x'])):
583  x.append((all_modules[module]['x'][idx] - x_min + 0.)/(x_scale + 0.))
584  y.append((all_modules[module]['y'][idx] - y_min + 0.)/(y_scale + 0.))
585  # Begin point is end point
586  x.append((all_modules[module]['x'][0] - x_min + 0.)/(x_scale + 0.))
587  y.append((all_modules[module]['y'][0] - y_min + 0.)/(y_scale + 0.))
588  #print(x, y)
589  self.TkAlMap_TPL_dict[module] = ROOT.TPolyLine(len(x), x, y)
590  #self.TkAlMap_TPL_dict[module].SetFillColor(1)
591  self.TkAlMap_TPL_dict[module].SetLineColor(1)
592  #print('lineW', self.TkAlMap_TPL_dict[module].GetLineWidth())
593  #self.TkAlMap_TPL_dict[module].Draw('f')
594  #self.TkAlMap_TPL_dict[module].Draw()
595 
596  self.image_x1 = (l_margin + 0.)/(x_scale + 0.)
597  self.image_x2 = (x_max - r_margin - x_min + 0.)/(x_scale + 0.)
598  self.image_y1 = (b_margin + 0.)/(y_scale + 0.)
599  self.image_y2 = (y_max - t_margin - y_min + 0.)/(y_scale + 0.)
600 
601  self.x_scale = x_scale
602  self.y_scale = y_scale
603 
604  #TL = ROOT.TLatex()
605  #TL.SetTextSize(0.025)
607  for key in all_text:
608  x = (all_text[key]['x'] - x_min + 0.)/(x_scale + 0.)
609  y = (all_text[key]['y'] - y_min + 0.)/(y_scale + 0.)
610  self.TkAlMap_text_dict[key] = {}
611  self.TkAlMap_text_dict[key]['x'] = x
612  self.TkAlMap_text_dict[key]['y'] = y
613  self.TkAlMap_text_dict[key]['alignment'] = all_text[key]['alignment']
614  self.TkAlMap_text_dict[key]['text'] = all_text[key]['text']
615  #TL.SetTextAlign(all_text[key]['alignment'])
616  #TL.DrawLatex(x, y, all_text[key]['text'])
617 
618 
619  def draw_title(self):
620  TL = ROOT.TLatex()
621  TL.SetTextSize(0.035)
622  TL.SetTextFont(42)
623  TL.SetTextAlign(13)
624  x1 = self.image_x1
625  y1 = 1-(5./(self.y_scale+0.))
626  self.canvas.cd()
627  TL.DrawLatex(x1, y1, self.title)
628 
629  def draw_cms_prelim(self):
630  TL = ROOT.TLatex()
631  factor = 1. / 0.82
632  TL.SetTextSize(0.035*factor)
633  TL.SetTextAlign(11)
634  TL.SetTextFont(61)
635 
636  w_cms = ctypes.c_uint(0)
637  h_cms = ctypes.c_uint(0)
638  TL.GetTextExtent(w_cms, h_cms, 'CMS')
639  x1 = self.image_x1
640  y1 = 1. - (h_cms.value+0.)/(self.height+0.) - (1./(self.y_scale+0.))
641  self.canvas.cd()
642  TL.DrawLatex(x1, y1, 'CMS')
643 
644  TL.SetTextSize(0.035)
645  TL.SetTextFont(42)
646  x1_prel = x1 + 1.1*(w_cms.value+0.)/(self.width+0.)
647  TL.DrawLatex(x1_prel, y1, '#it{Preliminary}')
648 
649  self.draw_event_info(y1)
650 
651  def draw_event_info(self, y):
652  TL = ROOT.TLatex()
653  TL.SetTextSize(0.035)
654  TL.SetTextFont(42)
655  TL.SetTextAlign(31)
656 
657  x1 = self.image_x2
658  y1 = y
659  self.canvas.cd()
660  TL.DrawLatex(x1, y1, 'pp collisions 13TeV')
661 
662 
663 
664  def draw_text(self):
665  print('TkAlMap: drawing text')
666  self.canvas.cd()
667  TL = ROOT.TLatex()
668  TL.SetTextSize(0.025)
669  for key in self.TkAlMap_text_dict:
670  TL.SetTextAlign(self.TkAlMap_text_dict[key]['alignment'])
671  TL.DrawLatex(self.TkAlMap_text_dict[key]['x'], self.TkAlMap_text_dict[key]['y'], self.TkAlMap_text_dict[key]['text'])
672  self.draw_cms_prelim()
673  self.draw_title()
674  self.canvas.Update()
675 
676  def draw_TPL(self):
677  print('TkAlMap: drawing PolyLines')
678  self.canvas.cd()
679  for module in self.TkAlMap_TPL_dict:
680  self.TkAlMap_TPL_dict[module].Draw('f')
681  self.TkAlMap_TPL_dict[module].Draw()
682  self.canvas.Update()
683 
684  def draw_color_bar(self):
685  print('TkAlMap: drawing color bar')
686  self.canvas.cd()
687  for box in self.color_bar:
688  self.color_bar[box].Draw('f')
689  #self.color_bar[box].Draw()
690  self.color_bar_axis.Draw()
691  self.canvas.Update()
692 
693  def save(self, out_dir='.', extension='pdf'):
694  name = '_'.join(['TkAlMap', self.tracker, self.var])
695  if self.two_sigma_cap and not self.default_range:
696  name += '_4sig'
697  elif self.default_range:
698  name += '_drange'
699  path = out_dir + '/' + name + '.' + extension
700  print('TkAlMap: saving canvas in "'+path+'"')
701  self.canvas.SaveAs(path)
702 
703 
704 
705  def analyse(self):
706  self.setup_colors()
707  self.set_colorbar_axis()
708  if self.do_tanh: self.set_colorbar_colors()
709  self.draw_TPL()
710  self.draw_text()
711  self.draw_color_bar()
712 
713 
714  def plot_variable_distribution(self, nbins=200, out_dir='.'):
715  print('TkAlMap: drawing variable distribution')
716  canv_name = 'histogram_canvas_'+self.tracker+'_'+self.var
717  if self.two_sigma_cap: canv_name += '_cap'
718  canvas = ROOT.TCanvas(canv_name, 'TkAlMap '+self.var+' histogram canvas', 800, 800)
719 
720  h_min = min(min(self.val_list), self.mean_val - 2*self.std_val) - self.std_val
721  h_max = max(max(self.val_list), self.mean_val + 2*self.std_val) + self.std_val
722  hist = ROOT.TH1F(self.var+'_hist', 'Variable distribution', nbins, h_min, h_max)
723  for val in self.val_list:
724  hist.Fill(val)
725  hist.GetXaxis().SetTitle(self.var_name+' ['+self.var_units+']')
726  hist.GetYaxis().SetTitle('modules')
727  ROOT.gStyle.SetOptStat(0)
728  hist.Draw('e1')
729  canvas.Update()
730  left = ROOT.TLine(self.mean_val - 2*self.std_val, canvas.GetUymin(), self.mean_val - 2*self.std_val, canvas.GetUymax())
731  left.SetLineColor(2)
732  left.SetLineStyle(9)
733  left.Draw()
734  right = ROOT.TLine(self.mean_val + 2*self.std_val, canvas.GetUymin(), self.mean_val + 2*self.std_val, canvas.GetUymax())
735  right.SetLineColor(2)
736  right.SetLineStyle(9)
737  right.Draw()
738  mid = ROOT.TLine(self.mean_val, canvas.GetUymin(), self.mean_val, canvas.GetUymax())
739  mid.SetLineColor(1)
740  mid.SetLineStyle(9)
741  mid.Draw()
742  canvas.Update()
743  name = '_'.join(['VariableDistribution', self.var, self.tracker])
744  path = out_dir + '/' + name + '.png'
745  canvas.SaveAs(path)
746 
747 
748 
749  def clean_up(self):
750  if not self.is_cleaned:
751  print('TkAlMap: deleting temporary file "'+self.tmp_file_name+'"')
752  self.tmp_file.Close()
753  os.remove(self.tmp_file_name)
754  self.is_cleaned = True
755 
756  def __del__(self):
757  self.clean_up()
758 
759 
760 if __name__ == '__main__':
761  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, tracker='strips')
762  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780)
763  TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=1400, GEO_file='TkAlMapDesign_phase0_cfg.py')
764  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py')
765  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py', tracker='pixel')
766  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase1_cfg.py', tracker='pixel')
767  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py', tracker='strips')
768  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, tracker='pixel')
769  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True)
770 
771  var_list = ['dx', 'dy']
772  #var_list = ['dx']
773  for var in var_list:
774  TkMap_temp = copy.deepcopy(TkMap)
775  TkMap_temp.set_var(var)
776  #TkMap.load_var()
777  #TkMap.draw_text()
778  #TkMap.draw_TPL()
779  TkMap_temp.analyse()
780  TkMap_temp.save(extension='png')
781  TkMap_temp.save()
782  raw_input('exit')
def draw_cms_prelim(self)
Definition: TkAlMap.py:629
def draw_TPL(self)
Definition: TkAlMap.py:676
def draw_text(self)
Draw functions.
Definition: TkAlMap.py:664
def load_geometry(self)
Definition: TkAlMap.py:509
def replace(string, replacements)
def get_color_rgb_idx(self, val)
Definition: TkAlMap.py:307
def detect_tracker_version(self)
Definition: TkAlMap.py:477
def __init__(self, variable, title, root_file, use_default_range=False, two_sigma_cap=False, height=1400, GEO_file='TkAlMapDesign_phase1_cfg.py', tracker='full', palette=2, do_tanh=False, check_tracker=True)
Definition: TkAlMap.py:154
def save(self, out_dir='.', extension='pdf')
Definition: TkAlMap.py:693
def set_canvas(self)
Definition: TkAlMap.py:207
def load_var(self)
Definition: TkAlMap.py:415
def mean(data_list)
Definition: TkAlMap.py:114
def read_TPLfile(file_name)
Definition: TkAlMap.py:124
def __del__(self)
Definition: TkAlMap.py:756
def load_tree(self)
Load functions.
Definition: TkAlMap.py:397
def draw_color_bar(self)
Definition: TkAlMap.py:684
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def setup_colors(self)
Color setup.
Definition: TkAlMap.py:214
def prepare_map_colors(self)
Definition: TkAlMap.py:219
def set_colorbar_axis(self)
Definition: TkAlMap.py:330
def draw_title(self)
Titles and info.
Definition: TkAlMap.py:619
static std::string join(char **cmd)
Definition: RemoteFile.cc:19
def set_colorbar_colors(self)
Definition: TkAlMap.py:346
def plot_variable_distribution(self, nbins=200, out_dir='.')
Test functions.
Definition: TkAlMap.py:714
def analyse(self)
Do all.
Definition: TkAlMap.py:705
def clean_up(self)
Clean up.
Definition: TkAlMap.py:749
GEO_file
tree = r_file.Get(tree_name) tree_tmp = r_file.Get(tree_name) tree = copy.deepcopy(tree_tmp) r_file...
Definition: TkAlMap.py:158
def set_var(self, var, var_range=[None, None)
Definition: TkAlMap.py:191
def fill_colors(self)
Definition: TkAlMap.py:313
def get_color_rgb(self, val)
Definition: TkAlMap.py:264
#define str(s)
def set_palette(self, palette)
Definition: TkAlMap.py:253
def StdDev(data_list)
Definition: TkAlMap.py:117
def draw_event_info(self, y)
Definition: TkAlMap.py:651
val_list
else: if &#39;full&#39; in self.tracker: print(&#39;Warning: Unknown module &#39;+str(module)) r_file.Close()
Definition: TkAlMap.py:428