CMS 3D CMS Logo

TkAlMap.py
Go to the documentation of this file.
1 import os
2 import ROOT
3 import copy
4 import math
5 import time
6 import ctypes
7 from array import array
8 import FWCore.ParameterSet.Config as cms
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/TkAlMap/'
177  self.data_path = 'Alignment/OfflineValidation/data/TkAlMap/'
178  self.cfg_path = 'Alignment/OfflineValidation/python/TkAlMap_cfg/'
179 
180  # Colorbar stuff
181  self.start_color_idx = 1200
182  self.n_color_color_bar = 1000
183 
184  # Initialization functions
185  self.set_palette(palette)
186  self.set_var(variable)
187  self.load_tree()
188  if check_tracker: self.detect_tracker_version()
189  self.load_geometry()
190  self.set_colorbar_colors()
191 
192  def set_var(self, var, var_range=[None, None]):
193  print('TkAlMap: setting variable to '+var)
194  self.var = var
195  self.var_name = var
196  self.var_units = 'cm'
197  self.var_scale = 1.
198  self.var_min = var_range[0]
199  self.var_max = var_range[1]
200  if var in KNOWN_VARIABLES:
201  self.var_name = KNOWN_VARIABLES[var]['name']
202  self.var_units = KNOWN_VARIABLES[var]['units']
203  self.var_scale = KNOWN_VARIABLES[var]['scale']
204  if self.var_min is None: self.var_min = KNOWN_VARIABLES[var]['range'][0]
205  if self.var_max is None: self.var_max = KNOWN_VARIABLES[var]['range'][1]
206  self.set_canvas()
207 
208  def set_canvas(self):
209  canv_name = 'canvas_'+self.tracker+'_'+self.var
210  if self.two_sigma_cap: canv_name += '_cap'
211  self.canvas = ROOT.TCanvas(canv_name, 'TkAlMap '+self.var+' canvas', self.width, self.height)
212  print('Actual w: '+str(self.canvas.GetWw())+', Actual h: '+str(self.canvas.GetWh()))
213 
214 
215  def setup_colors(self):
216  self.load_var()
217  self.prepare_map_colors()
218  self.fill_colors()
219 
221  print('TkAlMap: preparing map colors')
222 
223  self.colors = []
224  #self.palette = array('i', [])
225  col_idx = self.start_color_idx + self.n_color_color_bar + 10
226  self.col_dic = {}
227  self.rgb_map = {}
228  #pal_idx = 0
229  #self.pal_map = {}
230  for val in self.val_list:
231  cap_val = val
232  if cap_val > self.max_val: cap_val = self.max_val
233  if cap_val < self.min_val: cap_val = self.min_val
234  r, g, b = self.get_color_rgb(cap_val)
235  idx = self.get_color_rgb_idx(cap_val)
236  if idx in self.colors: continue
237  self.colors.append(idx)
238  col_idx +=1
239  self.rgb_map[idx] = col_idx
240  #print( idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
241  #color = ROOT.TColor(col_idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
242 
243  #self.col_dic[idx] = ROOT.TColor(col_idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
244  try:
245  col = ROOT.gROOT.GetColor(col_idx)
246  col.SetRGB((r+0.)/255., (g+0.)/255., (b+0.)/255.)
247  self.col_dic[idx] = col
248  except:
249  self.col_dic[idx] = ROOT.TColor(col_idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
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 
278  if self.palette == 1:
279  r = 255
280  g = 255
281  b = 255
282 
283  if value_frac < 0.25:
284  r = 0
285  g = int(255.*((value_frac/0.25)))
286  b = 255
287  elif value_frac < 0.5:
288  r = 0
289  g = 255
290  b = int(255.*(1. -(value_frac - 0.25)/0.25))
291  elif value_frac < 0.75:
292  r = int(255.*((value_frac - 0.5)/0.25))
293  g = 255
294  b = 0
295  else:
296  r = 255
297  g = int(255.*(1. -(value_frac - 0.75)/0.25))
298  b = 0
299  return r, g, b
300  elif self.palette == 2:
301  red = [59, 76, 192]
302  blue = [180, 4, 38]
303  white = [255, 255, 255]
304  r, g, b = DivergingColor(red, blue, white, value_frac)
305  return r, g, b
306  else: raise ValueError('TkAlMap: unkown palette value '+str(palette)+', allowed values are 1 and 2')
307 
308  def get_color_rgb_idx(self, val):
309  r, g, b = self.get_color_rgb(val)
310  #return r*1000000+g*1000+b+1000000000
311  offset = 100
312  return int(r*255*255 + g*255 + r + g + b + offset)
313 
314  def fill_colors(self):
315  print('TkAlMap: filling the colors')
316  #self.set_palette()
317  for module in self.mod_val_dict:
318  if module in self.TkAlMap_TPL_dict:
319  val = self.mod_val_dict[module]
320  cap_val = val
321  if cap_val > self.max_val: cap_val = self.max_val
322  if cap_val < self.min_val: cap_val = self.min_val
323  rgb = self.get_color_rgb_idx(cap_val)
324  col = self.rgb_map[rgb]
325  #col = self.pal_map[rgb]
326  #col = self.col_dic[rgb]
327  #print(val, rgb, col)
328  self.TkAlMap_TPL_dict[module].SetFillColor(col)
329  #self.TkAlMap_TPL_dict[module].SetFillColor(TEST_COLOR_IDX)
330 
331 
332  def set_colorbar_axis(self):
333  print('TkAlMap: setting color bar axis')
334  b_x1 = self.image_x1
335  b_x2 = self.image_x2
336  b_y1 = 0.06
337  b_y2 = 0.06
338  b_width = 0.01
339  self.color_bar_axis = ROOT.TGaxis(b_x1, b_y1, b_x2, b_y2, self.min_val, self.max_val, 50510, '+S')
340  self.color_bar_axis.SetName('color_bar_axis')
341  self.color_bar_axis.SetLabelSize(0.02)
342  self.color_bar_axis.SetTickSize(0.01)
343  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+']')
344  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+']')
345  else: self.color_bar_axis.SetTitle(self.var_name+' ['+self.var_units+']')
346  self.color_bar_axis.SetTitleSize(0.025)
347 
349  print('TkAlMap: initialize color bar colors')
350  if self.max_val is None or self.min_val is None:
351  col_step = 1./(self.n_color_color_bar + 0.)
352  val = col_step/2.
353  else:
354  b_range = self.max_val - self.min_val
355  col_step = (b_range + 0.)/(self.n_color_color_bar + 0.)
356  val = self.min_val + col_step/2.
357 
358  b_x1 = self.image_x1
359  b_x2 = self.image_x2
360  b_y1 = 0.06
361  b_y2 = 0.06
362  b_width = 0.01
363  b_xrange = b_x2 - b_x1
364  b_yrange = b_y2 - b_y1
365  b_dx = (b_xrange + 0.)/(self.n_color_color_bar + 0.)
366  b_dy = (b_yrange + 0.)/(self.n_color_color_bar + 0.)
367 
368  self.color_bar = {}
369  x1 = b_x1
370  y1 = b_y1
371 
372  col_idx = self.start_color_idx
373  for i_c in range(self.n_color_color_bar):
374  col_idx += 1
375  r, g, b = self.get_color_rgb(val)
376  try:
377  col = ROOT.gROOT.GetColor(col_idx)
378  col.SetRGB((r+0.)/255., (g+0.)/255., (b+0.)/255.)
379  self.color_bar_colors[col_idx] = col
380  except:
381  self.color_bar_colors[col_idx] = ROOT.TColor(col_idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
382  x2 = x1 + b_dx
383  y2 = y1 + b_dy + b_width
384  x = array('d', [x1, x1, x2, x2])
385  y = array('d', [y1, y2, y2, y1])
386  self.color_bar[col_idx] = ROOT.TPolyLine(len(x), x, y)
387  self.color_bar[col_idx].SetFillColor(col_idx)
388  self.color_bar[col_idx].SetLineColor(col_idx)
389 
390  x1 += b_dx
391  y1 += b_dy
392  val += col_step
393 
394 
395  def load_tree(self):
396  print('TkAlMap: loading tree ')
397  tree_name = 'alignTree'
398  r_file = ROOT.TFile(self.root_file)
399  if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
400 
401  tree_tmp = r_file.Get(tree_name)
402  #self.tree = copy.deepcopy(tree_tmp)
403  self.tmp_file_name = str(time.time()).replace('.', '_')+'_TkAlMapTempFile.root'
404  self.tmp_file = ROOT.TFile(self.tmp_file_name, 'recreate')
405  self.tree = tree_tmp.CloneTree()
406  r_file.Close()
407  self.is_cleaned = False
408 
409  if self.tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
410 
411 
412 
413  def load_var(self):
414  print('TkAlMap: loading variable values ')
415  #tree_name = 'alignTree'
416  #r_file = ROOT.TFile(self.root_file)
417  #if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
418 
419  #tree_tmp = r_file.Get(tree_name)
420  #tree = copy.deepcopy(tree_tmp)
421  #r_file.Close()
422 
423  #if tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
424 
425  self.mod_val_dict = {}
426  self.val_list = []
427  for event in self.tree:
428  module = event.id
429  var = self.var
430  if var == 'rdphi':
431  val = getattr(event, 'r')*getattr(event, 'dphi')
432  else:
433  val = getattr(event, var)
434  val *= self.var_scale
435  self.mod_val_dict[module] = val
436  #if val not in self.val_list: self.val_list.append(val)
437  if module in self.TkAlMap_TPL_dict: self.val_list.append(val)
438 
442  if len(self.val_list) == 0:
443  print('Warning: no values filled, 0 moduleId\'s matched')
444  self.val_list = [-10+idx*0.5 for idx in range(41)]
445  self.val_list.sort()
446  self.mean_val = mean(self.val_list)
447  self.std_val = StdDev(self.val_list)
448  self.min_val = min(self.val_list)
449  self.max_val = max(self.val_list)
450 
451  if self.two_sigma_cap and not self.default_range:
452  print('-- Capping max and min: ')
453  print('---- True values : '+str(self.max_val)+', '+str(self.min_val))
454  self.min_val = max(min(self.val_list), self.mean_val - 2*self.std_val)
455  self.max_val = min(max(self.val_list), self.mean_val + 2*self.std_val)
456  print('---- Capped values : '+str(self.max_val)+', '+str(self.min_val))
457 
458  if self.default_range:
459  #if not self.var in KNOWN_VARIABLES: print('Warning: capping to default range not possible for unknown variable "'+self.var+'"')
460  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')
461  else:
462  print('-- Capping max and min to default ranges: ')
463  print('---- True values : '+str(self.max_val)+', '+str(self.min_val))
464  self.min_val = self.var_min
465  self.max_val = self.var_max
466  print('---- Capped values : '+str(self.max_val)+', '+str(self.min_val))
467 
468  if self.min_val == self.max_val:
469  print('Warning: minimum value was equal to maximum value, '+str(self.max_val))
470  self.min_val = self.mean_val - 1.
471  self.max_val = self.mean_val + 1.
472 
473  #print(self.val_list)
474 
476  print('TkAlMap: detecting Tk version')
477  #tree_name = 'alignTree'
478  #r_file = ROOT.TFile(self.root_file)
479  #if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
480 
481 
485 
486  #if tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
487  phase = None
488  for event in self.tree:
489  module = event.id
490  if module > 303040000 and module < 306450000:
491  phase = 1
492  break
493  elif module > 302055000 and module < 302198000:
494  phase = 0
495  break
496  #r_file.Close()
497 
498  if phase is None: raise ValueError('TkAlMap: unknown tracker detected, is this phase2?')
499 
500  pahse_str = 'phase'+str(phase)
501  print('TkAlMap: '+pahse_str+' tracker detected')
502  if not pahse_str in self.GEO_file:
503  print('TkAlMap: changing tracker to '+pahse_str+ ', if this is unwanted set "check_tracker" to False')
504  self.GEO_file = 'TkAlMapDesign_'+pahse_str+'_cfg.py'
505  #self.load_geometry()
506 
507  def load_geometry(self):
508  source_path = os.getenv('CMSSW_BASE') + '/src/'
509  var = {}
510  execfile(source_path + self.cfg_path + self.GEO_file, var)
511 
512  MapStructure = var['TkMap_GEO']
513 
514  all_modules = {}
515  all_text = {}
516  x_max = -9999.
517  y_max = -9999.
518  x_min = 9999.
519  y_min = 9999.
520  for det in MapStructure:
521  if 'pixel' in self.tracker:
522  if not 'pixel' in det: continue
523  elif 'strips' in self.tracker:
524  if not 'strips' in det: continue
525  for sub in MapStructure[det]:
526  for part in MapStructure[det][sub]:
527  if part == 'latex':
528  all_text[det+'_'+sub] = MapStructure[det][sub][part]
529  continue
530  if 'latex' in MapStructure[det][sub][part]:
531  all_text[det+'_'+sub+'_'+part] = MapStructure[det][sub][part]['latex']
532  #TPL_file = source_path + self.data_path +MapStructure[det][sub][part]['file']
533  TPL_file = cms.FileInPath(self.data_path +MapStructure[det][sub][part]['file'])
534  TPL_dict = read_TPLfile(TPL_file)
535  for module in TPL_dict:
536  x_canv = []
537  y_canv = []
538  for idx in range(len(TPL_dict[module]['x'])):
539  x_canv.append(TPL_dict[module]['x'][idx]*MapStructure[det][sub][part]['x_scale'] + MapStructure[det][sub][part]['x_off'])
540  y_canv.append(TPL_dict[module]['y'][idx]*MapStructure[det][sub][part]['y_scale'] + MapStructure[det][sub][part]['y_off'])
541  if max(x_canv) > x_max: x_max = max(x_canv)
542  if max(y_canv) > y_max: y_max = max(y_canv)
543  if min(x_canv) < x_min: x_min = min(x_canv)
544  if min(y_canv) < y_min: y_min = min(y_canv)
545  TPL_dict[module]['x'] = x_canv
546  TPL_dict[module]['y'] = y_canv
547  all_modules.update(TPL_dict)
548 
549  r_margin = 3
550  l_margin = 3
551  #t_margin = 15
552  t_margin = 11
553  b_margin = 8
554 
555  x_max += r_margin
556  x_min -= l_margin
557  y_max += t_margin
558  y_min -= b_margin
559 
560  x_range = x_max - x_min
561  y_range = y_max - y_min
562 
563  self.width = int(self.height*(x_range + 0.)/(y_range + 0.))
564  self.canvas.SetWindowSize(self.width, self.height)
565 
566  if (x_range + 0.)/(self.width + 0.) > (y_range + 0.)/(self.height + 0.):
567  x_scale = x_range
568  y_scale = (self.height + 0.)/(self.width + 0.)*x_range
569  else:
570  y_scale = y_range
571  x_scale = (self.width + 0.)/(self.height + 0.)*y_range
572  self.TkAlMap_TPL_dict = {}
573  for module in all_modules:
574  x = array('d', [])
575  y = array('d', [])
576  for idx in range(len(all_modules[module]['x'])):
577  x.append((all_modules[module]['x'][idx] - x_min + 0.)/(x_scale + 0.))
578  y.append((all_modules[module]['y'][idx] - y_min + 0.)/(y_scale + 0.))
579  # Begin point is end point
580  x.append((all_modules[module]['x'][0] - x_min + 0.)/(x_scale + 0.))
581  y.append((all_modules[module]['y'][0] - y_min + 0.)/(y_scale + 0.))
582  #print(x, y)
583  self.TkAlMap_TPL_dict[module] = ROOT.TPolyLine(len(x), x, y)
584  #self.TkAlMap_TPL_dict[module].SetFillColor(1)
585  self.TkAlMap_TPL_dict[module].SetLineColor(1)
586  #print('lineW', self.TkAlMap_TPL_dict[module].GetLineWidth())
587  #self.TkAlMap_TPL_dict[module].Draw('f')
588  #self.TkAlMap_TPL_dict[module].Draw()
589 
590  self.image_x1 = (l_margin + 0.)/(x_scale + 0.)
591  self.image_x2 = (x_max - r_margin - x_min + 0.)/(x_scale + 0.)
592  self.image_y1 = (b_margin + 0.)/(y_scale + 0.)
593  self.image_y2 = (y_max - t_margin - y_min + 0.)/(y_scale + 0.)
594 
595  self.x_scale = x_scale
596  self.y_scale = y_scale
597 
598  #TL = ROOT.TLatex()
599  #TL.SetTextSize(0.025)
601  for key in all_text:
602  x = (all_text[key]['x'] - x_min + 0.)/(x_scale + 0.)
603  y = (all_text[key]['y'] - y_min + 0.)/(y_scale + 0.)
604  self.TkAlMap_text_dict[key] = {}
605  self.TkAlMap_text_dict[key]['x'] = x
606  self.TkAlMap_text_dict[key]['y'] = y
607  self.TkAlMap_text_dict[key]['alignment'] = all_text[key]['alignment']
608  self.TkAlMap_text_dict[key]['text'] = all_text[key]['text']
609  #TL.SetTextAlign(all_text[key]['alignment'])
610  #TL.DrawLatex(x, y, all_text[key]['text'])
611 
612 
613  def draw_title(self):
614  TL = ROOT.TLatex()
615  TL.SetTextSize(0.035)
616  TL.SetTextFont(42)
617  TL.SetTextAlign(13)
618  x1 = self.image_x1
619  y1 = 1-(5./(self.y_scale+0.))
620  self.canvas.cd()
621  TL.DrawLatex(x1, y1, self.title)
622 
623  def draw_cms_prelim(self):
624  TL = ROOT.TLatex()
625  factor = 1. / 0.82
626  TL.SetTextSize(0.035*factor)
627  TL.SetTextAlign(11)
628  TL.SetTextFont(61)
629 
630  w_cms = ctypes.c_uint(0)
631  h_cms = ctypes.c_uint(0)
632  TL.GetTextExtent(w_cms, h_cms, 'CMS')
633  x1 = self.image_x1
634  y1 = 1. - (h_cms.value+0.)/(self.height+0.) - (1./(self.y_scale+0.))
635  self.canvas.cd()
636  TL.DrawLatex(x1, y1, 'CMS')
637 
638  TL.SetTextSize(0.035)
639  TL.SetTextFont(42)
640  x1_prel = x1 + 1.1*(w_cms.value+0.)/(self.width+0.)
641  TL.DrawLatex(x1_prel, y1, '#it{Preliminary}')
642 
643  self.draw_event_info(y1)
644 
645  def draw_event_info(self, y):
646  TL = ROOT.TLatex()
647  TL.SetTextSize(0.035)
648  TL.SetTextFont(42)
649  TL.SetTextAlign(31)
650 
651  x1 = self.image_x2
652  y1 = y
653  self.canvas.cd()
654  TL.DrawLatex(x1, y1, 'pp collisions 13TeV')
655 
656 
657 
658  def draw_text(self):
659  print('TkAlMap: drawing text')
660  self.canvas.cd()
661  TL = ROOT.TLatex()
662  TL.SetTextSize(0.025)
663  for key in self.TkAlMap_text_dict:
664  TL.SetTextAlign(self.TkAlMap_text_dict[key]['alignment'])
665  TL.DrawLatex(self.TkAlMap_text_dict[key]['x'], self.TkAlMap_text_dict[key]['y'], self.TkAlMap_text_dict[key]['text'])
666  self.draw_cms_prelim()
667  self.draw_title()
668  self.canvas.Update()
669 
670  def draw_TPL(self):
671  print('TkAlMap: drawing PolyLines')
672  self.canvas.cd()
673  for module in self.TkAlMap_TPL_dict:
674  self.TkAlMap_TPL_dict[module].Draw('f')
675  self.TkAlMap_TPL_dict[module].Draw()
676  self.canvas.Update()
677 
678  def draw_color_bar(self):
679  print('TkAlMap: drawing color bar')
680  self.canvas.cd()
681  for box in self.color_bar:
682  self.color_bar[box].Draw('f')
683  #self.color_bar[box].Draw()
684  self.color_bar_axis.Draw()
685  self.canvas.Update()
686 
687  def save(self, out_dir='.', extension='pdf'):
688  name = '_'.join(['TkAlMap', self.tracker, self.var])
689  if self.two_sigma_cap and not self.default_range:
690  name += '_4sig'
691  elif self.default_range:
692  name += '_drange'
693  path = out_dir + '/' + name + '.' + extension
694  print('TkAlMap: saving canvas in "'+path+'"')
695  self.canvas.SaveAs(path)
696 
697 
698 
699  def analyse(self):
700  self.setup_colors()
701  self.set_colorbar_axis()
702  if self.do_tanh: self.set_colorbar_colors()
703  self.draw_TPL()
704  self.draw_text()
705  self.draw_color_bar()
706 
707 
708  def plot_variable_distribution(self, nbins=200, out_dir='.'):
709  print('TkAlMap: drawing variable distribution')
710  canv_name = 'histogram_canvas_'+self.tracker+'_'+self.var
711  if self.two_sigma_cap: canv_name += '_cap'
712  canvas = ROOT.TCanvas(canv_name, 'TkAlMap '+self.var+' histogram canvas', 800, 800)
713 
714  h_min = min(min(self.val_list), self.mean_val - 2*self.std_val) - self.std_val
715  h_max = max(max(self.val_list), self.mean_val + 2*self.std_val) + self.std_val
716  hist = ROOT.TH1F(self.var+'_hist', 'Variable distribution', nbins, h_min, h_max)
717  for val in self.val_list:
718  hist.Fill(val)
719  hist.GetXaxis().SetTitle(self.var_name+' ['+self.var_units+']')
720  hist.GetYaxis().SetTitle('modules')
721  ROOT.gStyle.SetOptStat(0)
722  hist.Draw('e1')
723  canvas.Update()
724  left = ROOT.TLine(self.mean_val - 2*self.std_val, canvas.GetUymin(), self.mean_val - 2*self.std_val, canvas.GetUymax())
725  left.SetLineColor(2)
726  left.SetLineStyle(9)
727  left.Draw()
728  right = ROOT.TLine(self.mean_val + 2*self.std_val, canvas.GetUymin(), self.mean_val + 2*self.std_val, canvas.GetUymax())
729  right.SetLineColor(2)
730  right.SetLineStyle(9)
731  right.Draw()
732  mid = ROOT.TLine(self.mean_val, canvas.GetUymin(), self.mean_val, canvas.GetUymax())
733  mid.SetLineColor(1)
734  mid.SetLineStyle(9)
735  mid.Draw()
736  canvas.Update()
737  name = '_'.join(['VariableDistribution', self.var, self.tracker])
738  path = out_dir + '/' + name + '.png'
739  canvas.SaveAs(path)
740 
741 
742 
743  def clean_up(self):
744  if not self.is_cleaned:
745  print('TkAlMap: deleting temporary file "'+self.tmp_file_name+'"')
746  self.tmp_file.Close()
747  os.remove(self.tmp_file_name)
748  self.is_cleaned = True
749 
750  def __del__(self):
751  self.clean_up()
752 
753 
754 if __name__ == '__main__':
755  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, tracker='strips')
756  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780)
757  TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=1400, GEO_file='TkAlMapDesign_phase0_cfg.py')
758  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py')
759  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py', tracker='pixel')
760  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase1_cfg.py', tracker='pixel')
761  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py', tracker='strips')
762  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, tracker='pixel')
763  #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True)
764 
765  var_list = ['dx', 'dy']
766  #var_list = ['dx']
767  for var in var_list:
768  TkMap_temp = copy.deepcopy(TkMap)
769  TkMap_temp.set_var(var)
770  #TkMap.load_var()
771  #TkMap.draw_text()
772  #TkMap.draw_TPL()
773  TkMap_temp.analyse()
774  TkMap_temp.save(extension='png')
775  TkMap_temp.save()
776  raw_input('exit')
def draw_cms_prelim(self)
Definition: TkAlMap.py:623
def draw_TPL(self)
Definition: TkAlMap.py:670
def draw_text(self)
Draw functions.
Definition: TkAlMap.py:658
def load_geometry(self)
Definition: TkAlMap.py:507
def replace(string, replacements)
def get_color_rgb_idx(self, val)
Definition: TkAlMap.py:308
def detect_tracker_version(self)
Definition: TkAlMap.py:475
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:687
def set_canvas(self)
Definition: TkAlMap.py:208
def load_var(self)
Definition: TkAlMap.py:413
def mean(data_list)
Definition: TkAlMap.py:114
def read_TPLfile(file_name)
Definition: TkAlMap.py:124
def __del__(self)
Definition: TkAlMap.py:750
def load_tree(self)
Load functions.
Definition: TkAlMap.py:395
def draw_color_bar(self)
Definition: TkAlMap.py:678
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def setup_colors(self)
Color setup.
Definition: TkAlMap.py:215
def prepare_map_colors(self)
Definition: TkAlMap.py:220
def set_colorbar_axis(self)
Definition: TkAlMap.py:332
def draw_title(self)
Titles and info.
Definition: TkAlMap.py:613
static std::string join(char **cmd)
Definition: RemoteFile.cc:19
def set_colorbar_colors(self)
Definition: TkAlMap.py:348
def plot_variable_distribution(self, nbins=200, out_dir='.')
Test functions.
Definition: TkAlMap.py:708
def analyse(self)
Do all.
Definition: TkAlMap.py:699
def clean_up(self)
Clean up.
Definition: TkAlMap.py:743
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:192
def fill_colors(self)
Definition: TkAlMap.py:314
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:645
val_list
else: if &#39;full&#39; in self.tracker: print(&#39;Warning: Unknown module &#39;+str(module)) r_file.Close()
Definition: TkAlMap.py:426