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': [-200., 200.],
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 = {}
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  #print( idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
240  #color = ROOT.TColor(col_idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
241 
242  #self.col_dic[idx] = ROOT.TColor(col_idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
243  try:
244  col = ROOT.gROOT.GetColor(col_idx)
245  col.SetRGB((r+0.)/255., (g+0.)/255., (b+0.)/255.)
246  self.col_dic[idx] = col
247  except:
248  self.col_dic[idx] = ROOT.TColor(col_idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
249  #self.palette.append(col_idx)
250  print('TkAlMap: map contains '+str(len(self.colors))+' colors')
251 
252  def set_palette(self, palette):
253  self.palette = palette
254  pal_str = 'TkAlMap: setting the palette to '+str(palette)
255  if palette == 1: pal_str += ' (rainbow)'
256  elif palette == 2: pal_str += ' (B->R diverging)'
257  else: raise ValueError('TkAlMap: unkown palette value '+str(palette)+', allowed values are 1 and 2')
258  print(pal_str)
259  #ROOT.gstyle.SetPalette(len(self.colors), self.colors)
260  #ROOT.gStyle.SetPalette(len(self.palette), self.palette)
261  pass
262 
263  def get_color_rgb(self, val):
264  if self.max_val is None or self.min_val is None:
265  value_frac = val
266  else:
267  if self.do_tanh:
268  val_th = math.tanh((val - self.mean_val)/(self.std_val))
269  max_th = math.tanh((self.max_val - self.mean_val)/(self.std_val))
270  min_th = math.tanh((self.min_val - self.mean_val)/(self.std_val))
271  value_frac = (val_th - min_th + 0.)/(max_th - min_th)
272  else:
273  value_range = self.max_val - self.min_val
274  if value_range == 0.: value_frac = 0.5
275  else: value_frac = (val - self.min_val + 0.)/(value_range + 0.)
276 
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  #print(val, rgb, col)
327  self.TkAlMap_TPL_dict[module].SetFillColor(col)
328  #self.TkAlMap_TPL_dict[module].SetFillColor(TEST_COLOR_IDX)
329 
330 
331  def set_colorbar_axis(self):
332  print('TkAlMap: setting color bar axis')
333  b_x1 = self.image_x1
334  b_x2 = self.image_x2
335  b_y1 = 0.06
336  b_y2 = 0.06
337  b_width = 0.01
338  self.color_bar_axis = ROOT.TGaxis(b_x1, b_y1, b_x2, b_y2, self.min_val, self.max_val, 50510, '+S')
339  self.color_bar_axis.SetName('color_bar_axis')
340  self.color_bar_axis.SetLabelSize(0.02)
341  self.color_bar_axis.SetTickSize(0.01)
342  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+']')
343  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+']')
344  else: self.color_bar_axis.SetTitle(self.var_name+' ['+self.var_units+']')
345  self.color_bar_axis.SetTitleSize(0.025)
346 
348  print('TkAlMap: initialize color bar colors')
349  if self.max_val is None or self.min_val is None:
350  col_step = 1./(self.n_color_color_bar + 0.)
351  val = col_step/2.
352  else:
353  b_range = self.max_val - self.min_val
354  col_step = (b_range + 0.)/(self.n_color_color_bar + 0.)
355  val = self.min_val + col_step/2.
356 
357  b_x1 = self.image_x1
358  b_x2 = self.image_x2
359  b_y1 = 0.06
360  b_y2 = 0.06
361  b_width = 0.01
362  b_xrange = b_x2 - b_x1
363  b_yrange = b_y2 - b_y1
364  b_dx = (b_xrange + 0.)/(self.n_color_color_bar + 0.)
365  b_dy = (b_yrange + 0.)/(self.n_color_color_bar + 0.)
366 
367  self.color_bar = {}
368  x1 = b_x1
369  y1 = b_y1
370 
371  col_idx = self.start_color_idx
372  for i_c in range(self.n_color_color_bar):
373  col_idx += 1
374  r, g, b = self.get_color_rgb(val)
375  try:
376  col = ROOT.gROOT.GetColor(col_idx)
377  col.SetRGB((r+0.)/255., (g+0.)/255., (b+0.)/255.)
378  self.color_bar_colors[col_idx] = col
379  except:
380  self.color_bar_colors[col_idx] = ROOT.TColor(col_idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
381  x2 = x1 + b_dx
382  y2 = y1 + b_dy + b_width
383  x = array('d', [x1, x1, x2, x2])
384  y = array('d', [y1, y2, y2, y1])
385  self.color_bar[col_idx] = ROOT.TPolyLine(len(x), x, y)
386  self.color_bar[col_idx].SetFillColor(col_idx)
387  self.color_bar[col_idx].SetLineColor(col_idx)
388 
389  x1 += b_dx
390  y1 += b_dy
391  val += col_step
392 
393 
394  def load_tree(self):
395  print('TkAlMap: loading tree ')
396  tree_name = 'alignTree'
397  r_file = ROOT.TFile(self.root_file)
398  if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
399 
400  tree_tmp = r_file.Get(tree_name)
401  #self.tree = copy.deepcopy(tree_tmp)
402  self.tmp_file_name = str(time.time()).replace('.', '_')+'_TkAlMapTempFile.root'
403  self.tmp_file = ROOT.TFile(self.tmp_file_name, 'recreate')
404  self.tree = tree_tmp.CloneTree()
405  r_file.Close()
406  self.is_cleaned = False
407 
408  if self.tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
409 
410 
411 
412  def load_var(self):
413  print('TkAlMap: loading variable values ')
414  #tree_name = 'alignTree'
415  #r_file = ROOT.TFile(self.root_file)
416  #if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
417 
418  #tree_tmp = r_file.Get(tree_name)
419  #tree = copy.deepcopy(tree_tmp)
420  #r_file.Close()
421 
422  #if tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
423 
424  self.mod_val_dict = {}
425  self.val_list = []
426  for event in self.tree:
427  module = event.id
428  var = self.var
429  if var == 'rdphi':
430  val = getattr(event, 'r')*getattr(event, 'dphi')
431  else:
432  val = getattr(event, var)
433  val *= self.var_scale
434  self.mod_val_dict[module] = val
435  #if val not in self.val_list: self.val_list.append(val)
436  if module in self.TkAlMap_TPL_dict: self.val_list.append(val)
437 
441  if len(self.val_list) == 0:
442  print('Warning: no values filled, 0 moduleId\'s matched')
443  self.val_list = [-10+idx*0.5 for idx in range(41)]
444  self.val_list.sort()
445  self.mean_val = mean(self.val_list)
446  self.std_val = StdDev(self.val_list)
447  self.min_val = min(self.val_list)
448  self.max_val = max(self.val_list)
449 
450  if self.two_sigma_cap and not self.default_range:
451  print('-- Capping max and min: ')
452  print('---- True values : '+str(self.max_val)+', '+str(self.min_val))
453  self.min_val = max(min(self.val_list), self.mean_val - 2*self.std_val)
454  self.max_val = min(max(self.val_list), self.mean_val + 2*self.std_val)
455  print('---- Capped values : '+str(self.max_val)+', '+str(self.min_val))
456 
457  if self.default_range:
458  #if not self.var in KNOWN_VARIABLES: print('Warning: capping to default range not possible for unknown variable "'+self.var+'"')
459  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')
460  else:
461  print('-- Capping max and min to default ranges: ')
462  print('---- True values : '+str(self.max_val)+', '+str(self.min_val))
463  self.min_val = self.var_min
464  self.max_val = self.var_max
465  print('---- Capped values : '+str(self.max_val)+', '+str(self.min_val))
466 
467  if self.min_val == self.max_val:
468  print('Warning: minimum value was equal to maximum value, '+str(self.max_val))
469  self.min_val = self.mean_val - 1.
470  self.max_val = self.mean_val + 1.
471 
472  #print(self.val_list)
473 
475  print('TkAlMap: detecting Tk version')
476  #tree_name = 'alignTree'
477  #r_file = ROOT.TFile(self.root_file)
478  #if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
479 
480 
484 
485  #if tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
486  phase = None
487  for event in self.tree:
488  module = event.id
489  if module > 303040000 and module < 306450000:
490  phase = 1
491  break
492  elif module > 302055000 and module < 302198000:
493  phase = 0
494  break
495  #r_file.Close()
496 
497  if phase is None: raise ValueError('TkAlMap: unknown tracker detected, is this phase2?')
498 
499  pahse_str = 'phase'+str(phase)
500  print('TkAlMap: '+pahse_str+' tracker detected')
501  if not pahse_str in self.GEO_file:
502  print('TkAlMap: changing tracker to '+pahse_str+ ', if this is unwanted set "check_tracker" to False')
503  self.GEO_file = 'TkAlMapDesign_'+pahse_str+'_cfg.py'
504  #self.load_geometry()
505 
506  def load_geometry(self):
507  source_path = os.getenv('CMSSW_BASE') + '/src/'
508  var = {}
509  if sys.version_info[0] == 2:
510  execfile(source_path + self.cfg_path + self.GEO_file, var)
511  elif sys.version_info[0] == 3:
512  _filename = source_path + self.cfg_path + self.GEO_file
513  exec(compile(open(_filename, "rb").read(), _filename, 'exec'), var)
514 
515  MapStructure = var['TkMap_GEO']
516 
517  all_modules = {}
518  all_text = {}
519  x_max = -9999.
520  y_max = -9999.
521  x_min = 9999.
522  y_min = 9999.
523  for det in MapStructure:
524  if 'pixel' in self.tracker:
525  if not 'pixel' in det: continue
526  elif 'strips' in self.tracker:
527  if not 'strips' in det: continue
528  for sub in MapStructure[det]:
529  for part in MapStructure[det][sub]:
530  if part == 'latex':
531  all_text[det+'_'+sub] = MapStructure[det][sub][part]
532  continue
533  if 'latex' in MapStructure[det][sub][part]:
534  all_text[det+'_'+sub+'_'+part] = MapStructure[det][sub][part]['latex']
535  _filename = self.data_path +MapStructure[det][sub][part]['file']
536  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]
537  TPL_dict = read_TPLfile(TPL_file)
538  for module in TPL_dict:
539  x_canv = []
540  y_canv = []
541  for idx in range(len(TPL_dict[module]['x'])):
542  x_canv.append(TPL_dict[module]['x'][idx]*MapStructure[det][sub][part]['x_scale'] + MapStructure[det][sub][part]['x_off'])
543  y_canv.append(TPL_dict[module]['y'][idx]*MapStructure[det][sub][part]['y_scale'] + MapStructure[det][sub][part]['y_off'])
544  if max(x_canv) > x_max: x_max = max(x_canv)
545  if max(y_canv) > y_max: y_max = max(y_canv)
546  if min(x_canv) < x_min: x_min = min(x_canv)
547  if min(y_canv) < y_min: y_min = min(y_canv)
548  TPL_dict[module]['x'] = x_canv
549  TPL_dict[module]['y'] = y_canv
550  all_modules.update(TPL_dict)
551 
552  r_margin = 3
553  l_margin = 3
554  #t_margin = 15
555  t_margin = 11
556  b_margin = 8
557 
558  x_max += r_margin
559  x_min -= l_margin
560  y_max += t_margin
561  y_min -= b_margin
562 
563  x_range = x_max - x_min
564  y_range = y_max - y_min
565 
566  self.width = int(self.height*(x_range + 0.)/(y_range + 0.))
567  self.canvas.SetWindowSize(self.width, self.height)
568 
569  if (x_range + 0.)/(self.width + 0.) > (y_range + 0.)/(self.height + 0.):
570  x_scale = x_range
571  y_scale = (self.height + 0.)/(self.width + 0.)*x_range
572  else:
573  y_scale = y_range
574  x_scale = (self.width + 0.)/(self.height + 0.)*y_range
575  self.TkAlMap_TPL_dict = {}
576  for module in all_modules:
577  x = array('d', [])
578  y = array('d', [])
579  for idx in range(len(all_modules[module]['x'])):
580  x.append((all_modules[module]['x'][idx] - x_min + 0.)/(x_scale + 0.))
581  y.append((all_modules[module]['y'][idx] - y_min + 0.)/(y_scale + 0.))
582  # Begin point is end point
583  x.append((all_modules[module]['x'][0] - x_min + 0.)/(x_scale + 0.))
584  y.append((all_modules[module]['y'][0] - y_min + 0.)/(y_scale + 0.))
585  #print(x, y)
586  self.TkAlMap_TPL_dict[module] = ROOT.TPolyLine(len(x), x, y)
587  #self.TkAlMap_TPL_dict[module].SetFillColor(1)
588  self.TkAlMap_TPL_dict[module].SetLineColor(1)
589  #print('lineW', self.TkAlMap_TPL_dict[module].GetLineWidth())
590  #self.TkAlMap_TPL_dict[module].Draw('f')
591  #self.TkAlMap_TPL_dict[module].Draw()
592 
593  self.image_x1 = (l_margin + 0.)/(x_scale + 0.)
594  self.image_x2 = (x_max - r_margin - x_min + 0.)/(x_scale + 0.)
595  self.image_y1 = (b_margin + 0.)/(y_scale + 0.)
596  self.image_y2 = (y_max - t_margin - y_min + 0.)/(y_scale + 0.)
597 
598  self.x_scale = x_scale
599  self.y_scale = y_scale
600 
601  #TL = ROOT.TLatex()
602  #TL.SetTextSize(0.025)
604  for key in all_text:
605  x = (all_text[key]['x'] - x_min + 0.)/(x_scale + 0.)
606  y = (all_text[key]['y'] - y_min + 0.)/(y_scale + 0.)
607  self.TkAlMap_text_dict[key] = {}
608  self.TkAlMap_text_dict[key]['x'] = x
609  self.TkAlMap_text_dict[key]['y'] = y
610  self.TkAlMap_text_dict[key]['alignment'] = all_text[key]['alignment']
611  self.TkAlMap_text_dict[key]['text'] = all_text[key]['text']
612  #TL.SetTextAlign(all_text[key]['alignment'])
613  #TL.DrawLatex(x, y, all_text[key]['text'])
614 
615 
616  def draw_title(self):
617  TL = ROOT.TLatex()
618  TL.SetTextSize(0.035)
619  TL.SetTextFont(42)
620  TL.SetTextAlign(13)
621  x1 = self.image_x1
622  y1 = 1-(5./(self.y_scale+0.))
623  self.canvas.cd()
624  TL.DrawLatex(x1, y1, self.title)
625 
626  def draw_cms_prelim(self):
627  TL = ROOT.TLatex()
628  factor = 1. / 0.82
629  TL.SetTextSize(0.035*factor)
630  TL.SetTextAlign(11)
631  TL.SetTextFont(61)
632 
633  w_cms = ctypes.c_uint(0)
634  h_cms = ctypes.c_uint(0)
635  TL.GetTextExtent(w_cms, h_cms, 'CMS')
636  x1 = self.image_x1
637  y1 = 1. - (h_cms.value+0.)/(self.height+0.) - (1./(self.y_scale+0.))
638  self.canvas.cd()
639  TL.DrawLatex(x1, y1, 'CMS')
640 
641  TL.SetTextSize(0.035)
642  TL.SetTextFont(42)
643  x1_prel = x1 + 1.1*(w_cms.value+0.)/(self.width+0.)
644  TL.DrawLatex(x1_prel, y1, '#it{Preliminary}')
645 
646  self.draw_event_info(y1)
647 
648  def draw_event_info(self, y):
649  TL = ROOT.TLatex()
650  TL.SetTextSize(0.035)
651  TL.SetTextFont(42)
652  TL.SetTextAlign(31)
653 
654  x1 = self.image_x2
655  y1 = y
656  self.canvas.cd()
657  TL.DrawLatex(x1, y1, 'pp collisions 13TeV')
658 
659 
660 
661  def draw_text(self):
662  print('TkAlMap: drawing text')
663  self.canvas.cd()
664  TL = ROOT.TLatex()
665  TL.SetTextSize(0.025)
666  for key in self.TkAlMap_text_dict:
667  TL.SetTextAlign(self.TkAlMap_text_dict[key]['alignment'])
668  TL.DrawLatex(self.TkAlMap_text_dict[key]['x'], self.TkAlMap_text_dict[key]['y'], self.TkAlMap_text_dict[key]['text'])
669  self.draw_cms_prelim()
670  self.draw_title()
671  self.canvas.Update()
672 
673  def draw_TPL(self):
674  print('TkAlMap: drawing PolyLines')
675  self.canvas.cd()
676  for module in self.TkAlMap_TPL_dict:
677  self.TkAlMap_TPL_dict[module].Draw('f')
678  self.TkAlMap_TPL_dict[module].Draw()
679  self.canvas.Update()
680 
681  def draw_color_bar(self):
682  print('TkAlMap: drawing color bar')
683  self.canvas.cd()
684  for box in self.color_bar:
685  self.color_bar[box].Draw('f')
686  #self.color_bar[box].Draw()
687  self.color_bar_axis.Draw()
688  self.canvas.Update()
689 
690  def save(self, out_dir='.', extension='pdf'):
691  name = '_'.join(['TkAlMap', self.tracker, self.var])
692  if self.two_sigma_cap and not self.default_range:
693  name += '_4sig'
694  elif self.default_range:
695  name += '_drange'
696  path = out_dir + '/' + name + '.' + extension
697  print('TkAlMap: saving canvas in "'+path+'"')
698  self.canvas.SaveAs(path)
699 
700 
701 
702  def analyse(self):
703  self.setup_colors()
704  self.set_colorbar_axis()
705  if self.do_tanh: self.set_colorbar_colors()
706  self.draw_TPL()
707  self.draw_text()
708  self.draw_color_bar()
709 
710 
711  def plot_variable_distribution(self, nbins=200, out_dir='.'):
712  print('TkAlMap: drawing variable distribution')
713  canv_name = 'histogram_canvas_'+self.tracker+'_'+self.var
714  if self.two_sigma_cap: canv_name += '_cap'
715  canvas = ROOT.TCanvas(canv_name, 'TkAlMap '+self.var+' histogram canvas', 800, 800)
716 
717  h_min = min(min(self.val_list), self.mean_val - 2*self.std_val) - self.std_val
718  h_max = max(max(self.val_list), self.mean_val + 2*self.std_val) + self.std_val
719  hist = ROOT.TH1F(self.var+'_hist', 'Variable distribution', nbins, h_min, h_max)
720  for val in self.val_list:
721  hist.Fill(val)
722  hist.GetXaxis().SetTitle(self.var_name+' ['+self.var_units+']')
723  hist.GetYaxis().SetTitle('modules')
724  ROOT.gStyle.SetOptStat(0)
725  hist.Draw('e1')
726  canvas.Update()
727  left = ROOT.TLine(self.mean_val - 2*self.std_val, canvas.GetUymin(), self.mean_val - 2*self.std_val, canvas.GetUymax())
728  left.SetLineColor(2)
729  left.SetLineStyle(9)
730  left.Draw()
731  right = ROOT.TLine(self.mean_val + 2*self.std_val, canvas.GetUymin(), self.mean_val + 2*self.std_val, canvas.GetUymax())
732  right.SetLineColor(2)
733  right.SetLineStyle(9)
734  right.Draw()
735  mid = ROOT.TLine(self.mean_val, canvas.GetUymin(), self.mean_val, canvas.GetUymax())
736  mid.SetLineColor(1)
737  mid.SetLineStyle(9)
738  mid.Draw()
739  canvas.Update()
740  name = '_'.join(['VariableDistribution', self.var, self.tracker])
741  path = out_dir + '/' + name + '.png'
742  canvas.SaveAs(path)
743 
744 
745 
746  def clean_up(self):
747  if not self.is_cleaned:
748  print('TkAlMap: deleting temporary file "'+self.tmp_file_name+'"')
749  self.tmp_file.Close()
750  os.remove(self.tmp_file_name)
751  self.is_cleaned = True
752 
753  def __del__(self):
754  self.clean_up()
755 
756 
757 if __name__ == '__main__':
758  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, tracker='strips')
759  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780)
760  TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=1400, GEO_file='TkAlMapDesign_phase0_cfg.py')
761  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py')
762  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py', tracker='pixel')
763  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase1_cfg.py', tracker='pixel')
764  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py', tracker='strips')
765  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, tracker='pixel')
766  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True)
767 
768  var_list = ['dx', 'dy']
769  #var_list = ['dx']
770  for var in var_list:
771  TkMap_temp = copy.deepcopy(TkMap)
772  TkMap_temp.set_var(var)
773  #TkMap.load_var()
774  #TkMap.draw_text()
775  #TkMap.draw_TPL()
776  TkMap_temp.analyse()
777  TkMap_temp.save(extension='png')
778  TkMap_temp.save()
779  raw_input('exit')
def draw_cms_prelim(self)
Definition: TkAlMap.py:626
def draw_TPL(self)
Definition: TkAlMap.py:673
def draw_text(self)
Draw functions.
Definition: TkAlMap.py:661
def load_geometry(self)
Definition: TkAlMap.py:506
def replace(string, replacements)
def get_color_rgb_idx(self, val)
Definition: TkAlMap.py:307
def detect_tracker_version(self)
Definition: TkAlMap.py:474
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:690
def set_canvas(self)
Definition: TkAlMap.py:207
def load_var(self)
Definition: TkAlMap.py:412
def mean(data_list)
Definition: TkAlMap.py:114
def read_TPLfile(file_name)
Definition: TkAlMap.py:124
def __del__(self)
Definition: TkAlMap.py:753
def load_tree(self)
Load functions.
Definition: TkAlMap.py:394
def draw_color_bar(self)
Definition: TkAlMap.py:681
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:331
def draw_title(self)
Titles and info.
Definition: TkAlMap.py:616
static std::string join(char **cmd)
Definition: RemoteFile.cc:19
def set_colorbar_colors(self)
Definition: TkAlMap.py:347
def plot_variable_distribution(self, nbins=200, out_dir='.')
Test functions.
Definition: TkAlMap.py:711
def analyse(self)
Do all.
Definition: TkAlMap.py:702
def clean_up(self)
Clean up.
Definition: TkAlMap.py:746
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:263
#define str(s)
def set_palette(self, palette)
Definition: TkAlMap.py:252
def StdDev(data_list)
Definition: TkAlMap.py:117
def draw_event_info(self, y)
Definition: TkAlMap.py:648
val_list
else: if &#39;full&#39; in self.tracker: print(&#39;Warning: Unknown module &#39;+str(module)) r_file.Close()
Definition: TkAlMap.py:425