Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-04-06 11:57:12

0001 import os
0002 import sys
0003 import ROOT
0004 import copy
0005 import math
0006 import time
0007 import ctypes
0008 from array import array
0009 from Alignment.OfflineValidation.DivergingColor import DivergingColor
0010 
0011 '''
0012 Class for the TkAlMap plots
0013 to produce the plots use Alignment/OfflineValidation/python/runGCPTkAlMap.py 
0014 '''
0015 
0016 #TEST_COLOR_IDX = 2000
0017 #TEST_COLOR = ROOT.TColor(TEST_COLOR_IDX, (0.)/255., (0.)/255., (255+0.)/255.)
0018 
0019 KNOWN_VARIABLES = {
0020     'dr': {
0021         'name' : '#Deltar',
0022         'units': '#mum',
0023         'scale': 10000.,
0024         'range': [-200., 200.],
0025         },
0026     'dx': {
0027         'name' : '#Deltax',
0028         'units': '#mum',
0029         'scale': 10000.,
0030         'range': [-200., 200.],
0031         },
0032     'dy': {
0033         'name' : '#Deltay',
0034         'units': '#mum',
0035         'scale': 10000.,
0036         'range': [-200., 200.],
0037         },
0038     'dz': {
0039         'name' : '#Deltaz',
0040         'units': '#mum',
0041         'scale': 10000.,
0042         'range': [-200., 200.],
0043         },
0044     'rdphi': {
0045         'name' : 'r #Delta#phi',
0046         'units': '#mum rad',
0047         'scale': 10000.,
0048         'range': [-100., 100.],
0049         },
0050     'dphi': {
0051         'name' : '#Delta#phi',
0052         'units': 'mrad',
0053         'scale': 1000.,
0054         'range': [-100., 100.],
0055         },
0056     'dalpha': {
0057         'name' : '#Delta#alpha',
0058         'units': 'mrad',
0059         'scale': 1000.,
0060         'range': [-100., 100.],
0061         },
0062     'dbeta': {
0063         'name' : '#Delta#beta',
0064         'units': 'mrad',
0065         'scale': 1000.,
0066         'range': [-100., 100.],
0067         },
0068     'dgamma': {
0069         'name' : '#Delta#gamma',
0070         'units': 'mrad',
0071         'scale': 1000.,
0072         'range': [-100., 100.],
0073         },
0074     'du': {
0075         'name' : '#Deltau',
0076         'units': '#mum',
0077         'scale': 10000.,
0078         'range': [-200., 200.],
0079         },
0080     'dv': {
0081         'name' : '#Deltav',
0082         'units': '#mum',
0083         'scale': 10000.,
0084         'range': [-200., 200.],
0085         },
0086     'dw': {
0087         'name' : '#Deltaw',
0088         'units': '#mum',
0089         'scale': 10000.,
0090         'range': [-200., 200.],
0091         },
0092     'da': {
0093         'name' : '#Deltaa',
0094         'units': 'mrad',
0095         'scale': 1000.,
0096         'range': [-100., 100.],
0097         },
0098     'db': {
0099         'name' : '#Deltab',
0100         'units': 'mrad',
0101         'scale': 1000.,
0102         'range': [-100., 100.],
0103         },
0104     'dg': {
0105         'name' : '#Deltag',
0106         'units': 'mrad',
0107         'scale': 1000.,
0108         'range': [-100., 100.],
0109         },  
0110 }
0111 
0112 #ROOT.gStyle.SetLineScalePS(1)
0113 
0114 def mean(data_list):
0115     return sum(data_list)/(len(data_list)+0.)
0116     
0117 def StdDev(data_list):
0118     s2 = 0.
0119     m = mean(data_list)
0120     for point in data_list:
0121         s2 += (point-m)**2
0122     return math.sqrt(s2/(len(data_list)+0.))
0123 
0124 def read_TPLfile(file_name):
0125     o_file = open(file_name, 'r')
0126     lines = o_file.readlines()
0127     o_file.close()
0128 
0129     TPL_dict = {}
0130     for line in lines:
0131         if '#' in line: continue
0132         splt_line = line.replace('\n', '').split(' ')
0133         det_id = int(splt_line[0])
0134         x = []
0135         y = []
0136         for idx,coo in enumerate(splt_line[1:]):
0137             #print(coo)
0138             try:
0139                 val = float(coo)
0140                 if (idx%2) == 0: 
0141                     y.append(val)
0142                 else: 
0143                     x.append(val)
0144             except ValueError:
0145                 continue
0146         TPL_dict[det_id] = {}
0147         TPL_dict[det_id]['x'] = x
0148         TPL_dict[det_id]['y'] = y
0149     return TPL_dict
0150 
0151 class TkAlMap:
0152 
0153     #def __init__(self, variable, title, root_file, two_sigma_cap=False, width=1500, height=800, GEO_file='TkMap_design_cfg.py', tracker='full'):
0154     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):
0155         ROOT.gStyle.SetLineScalePS(1)
0156 
0157         # Configuration parameters
0158         self.GEO_file      = GEO_file
0159         self.tracker       = tracker
0160         self.width         = height 
0161         self.height        = height
0162         self.title         = title
0163         self.default_range = use_default_range
0164         self.two_sigma_cap = two_sigma_cap
0165         self.root_file     = root_file
0166         self.do_tanh       = do_tanh
0167 
0168         # Value Initialization
0169         self.max_val           = None
0170         self.min_val           = None
0171         self.color_bar_colors  = {}
0172         self.tree              = None
0173         self.is_cleaned        = False
0174 
0175         # Internal parameters    
0176         self.data_path = 'Alignment/OfflineValidation/data/TkAlMap/'
0177         self.cfg_path = 'Alignment/OfflineValidation/python/TkAlMap_cfg/'
0178 
0179         # Colorbar stuff
0180         self.start_color_idx   = 1200
0181         self.n_color_color_bar = 1000
0182  
0183         # Initialization functions
0184         self.set_palette(palette)
0185         self.set_var(variable)
0186         self.load_tree()
0187         if check_tracker: self.detect_tracker_version()
0188         self.load_geometry()
0189         self.set_colorbar_colors()
0190 
0191     def set_var(self, var, var_range=[None, None]):
0192         print('TkAlMap: setting variable to '+var)
0193         self.var = var
0194         self.var_name = var
0195         self.var_units = 'cm'
0196         self.var_scale = 1.
0197         self.var_min = var_range[0]
0198         self.var_max = var_range[1]
0199         if var in KNOWN_VARIABLES:
0200             self.var_name  = KNOWN_VARIABLES[var]['name']
0201             self.var_units = KNOWN_VARIABLES[var]['units']
0202             self.var_scale = KNOWN_VARIABLES[var]['scale']
0203             if self.var_min is None: self.var_min = KNOWN_VARIABLES[var]['range'][0]
0204             if self.var_max is None: self.var_max = KNOWN_VARIABLES[var]['range'][1]
0205         self.set_canvas()
0206 
0207     def set_canvas(self):
0208         canv_name = 'canvas_'+self.tracker+'_'+self.var
0209         if self.two_sigma_cap: canv_name += '_cap'
0210         self.canvas = ROOT.TCanvas(canv_name, 'TkAlMap '+self.var+' canvas', self.width, self.height)
0211         print('Actual w: '+str(self.canvas.GetWw())+', Actual h: '+str(self.canvas.GetWh()))
0212 
0213 #### Color setup
0214     def setup_colors(self):
0215         self.load_var()
0216         self.prepare_map_colors()
0217         self.fill_colors()
0218 
0219     def prepare_map_colors(self):
0220         print('TkAlMap: preparing map colors')
0221         
0222         self.colors = []
0223         #self.palette = array('i', [])
0224         col_idx = self.start_color_idx + self.n_color_color_bar + 10
0225         self.col_dic = {} #Never used explicitly but needs to keep TColor values in the global memory
0226         self.rgb_map = {}
0227         #pal_idx = 0
0228         #self.pal_map = {}
0229         for val in self.val_list:
0230             cap_val = val
0231             if cap_val > self.max_val: cap_val = self.max_val
0232             if cap_val < self.min_val: cap_val = self.min_val
0233             r, g, b = self.get_color_rgb(cap_val)
0234             idx = self.get_color_rgb_idx(cap_val)
0235             if idx in self.colors: continue
0236             self.colors.append(idx)
0237             col_idx +=1
0238             self.rgb_map[idx] = col_idx
0239 
0240             try:
0241                 col = ROOT.gROOT.GetColor(col_idx) #Here still OK
0242                 col.SetRGB((r+0.)/255., (g+0.)/255., (b+0.)/255.) #Here segmentation if color index does not exist
0243                 self.col_dic[idx] = col #Here the new color is saved in in the global variable
0244             except:
0245                 #Here the 6 argument TColor init with dummy rgb must be used, 4 argument one does not work (ROOT bug?)
0246                 #New color index is defined and SetRGB must also be called to overwrite dummy rgb
0247                 col = ROOT.TColor(col_idx, 0., 0., 0., "", 1)
0248                 col.SetRGB((r+0.)/255., (g+0.)/255., (b+0.)/255.)
0249                 self.col_dic[idx] = col #Here the new color is saved in in the global variable
0250             #self.palette.append(col_idx)
0251         print('TkAlMap: map contains '+str(len(self.colors))+' colors')
0252      
0253     def set_palette(self, palette):
0254         self.palette = palette
0255         pal_str = 'TkAlMap: setting the palette to '+str(palette)
0256         if palette == 1: pal_str += ' (rainbow)'
0257         elif palette == 2: pal_str += ' (B->R diverging)'
0258         else: raise ValueError('TkAlMap: unkown palette value '+str(palette)+', allowed values are 1 and 2')
0259         print(pal_str)
0260         #ROOT.gstyle.SetPalette(len(self.colors), self.colors)
0261         #ROOT.gStyle.SetPalette(len(self.palette), self.palette)
0262         pass
0263 
0264     def get_color_rgb(self, val):
0265         if self.max_val is None or self.min_val is None:
0266             value_frac = val
0267         else:
0268             if self.do_tanh:
0269                 val_th = math.tanh((val - self.mean_val)/(self.std_val))
0270                 max_th = math.tanh((self.max_val - self.mean_val)/(self.std_val))
0271                 min_th = math.tanh((self.min_val - self.mean_val)/(self.std_val))
0272                 value_frac = (val_th - min_th + 0.)/(max_th - min_th)
0273             else:
0274                 value_range = self.max_val - self.min_val
0275                 if value_range == 0.: value_frac = 0.5
0276                 else: value_frac = (val - self.min_val + 0.)/(value_range + 0.)
0277         if self.palette == 1:
0278             r = 255
0279             g = 255
0280             b = 255
0281 
0282             if value_frac < 0.25:
0283                 r = 0
0284                 g = int(255.*((value_frac/0.25)))
0285                 b = 255         
0286             elif value_frac < 0.5:
0287                 r = 0
0288                 g = 255
0289                 b = int(255.*(1. -(value_frac - 0.25)/0.25)) 
0290             elif value_frac < 0.75:
0291                 r = int(255.*((value_frac - 0.5)/0.25))
0292                 g = 255
0293                 b = 0 
0294             else:
0295                 r = 255 
0296                 g = int(255.*(1. -(value_frac - 0.75)/0.25)) 
0297                 b = 0
0298             return r, g, b 
0299         elif self.palette == 2:
0300             red   = [59,   76, 192]
0301             blue  = [180,   4,  38]
0302             white = [255, 255, 255] 
0303             r, g, b = DivergingColor(red, blue, white, value_frac) 
0304             return r, g, b
0305         else: raise ValueError('TkAlMap: unkown palette value '+str(palette)+', allowed values are 1 and 2')
0306 
0307     def get_color_rgb_idx(self, val):
0308         r, g, b = self.get_color_rgb(val)
0309         #return r*1000000+g*1000+b+1000000000
0310         offset = 100
0311         return int(r*255*255 + g*255 + r + g + b + offset)
0312 
0313     def fill_colors(self):
0314         print('TkAlMap: filling the colors')
0315         #self.set_palette()
0316         for module in self.mod_val_dict:
0317             if module in self.TkAlMap_TPL_dict:
0318                 val = self.mod_val_dict[module]
0319                 cap_val = val
0320                 if cap_val > self.max_val: cap_val = self.max_val
0321                 if cap_val < self.min_val: cap_val = self.min_val
0322                 rgb = self.get_color_rgb_idx(cap_val)
0323                 col = self.rgb_map[rgb]
0324                 #col = self.pal_map[rgb]
0325                 #col = self.col_dic[rgb]
0326                 self.TkAlMap_TPL_dict[module].SetFillColor(col)
0327                 #self.TkAlMap_TPL_dict[module].SetFillColor(TEST_COLOR_IDX)
0328             ####else: print('Warning: Unknown module '+str(module))
0329 
0330     def set_colorbar_axis(self):
0331         print('TkAlMap: setting color bar axis')
0332         b_x1 = self.image_x1
0333         b_x2 = self.image_x2
0334         b_y1 = 0.06
0335         b_y2 = 0.06
0336         b_width = 0.01
0337         self.color_bar_axis = ROOT.TGaxis(b_x1, b_y1, b_x2, b_y2, self.min_val, self.max_val, 50510, '+S')
0338         self.color_bar_axis.SetName('color_bar_axis')
0339         self.color_bar_axis.SetLabelSize(0.02)
0340         self.color_bar_axis.SetTickSize(0.01)
0341         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+']')
0342         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+']')
0343         else: self.color_bar_axis.SetTitle(self.var_name+' ['+self.var_units+']')
0344         self.color_bar_axis.SetTitleSize(0.025)
0345 
0346     def set_colorbar_colors(self):
0347         print('TkAlMap: initialize color bar colors')
0348         if self.max_val is None or self.min_val is None:
0349             col_step = 1./(self.n_color_color_bar + 0.)
0350             val = col_step/2.
0351         else:
0352             b_range = self.max_val - self.min_val
0353             col_step = (b_range + 0.)/(self.n_color_color_bar + 0.)
0354             val = self.min_val + col_step/2.
0355 
0356         b_x1 = self.image_x1
0357         b_x2 = self.image_x2
0358         b_y1 = 0.06
0359         b_y2 = 0.06
0360         b_width = 0.01
0361         b_xrange = b_x2 - b_x1
0362         b_yrange = b_y2 - b_y1
0363         b_dx = (b_xrange + 0.)/(self.n_color_color_bar + 0.)
0364         b_dy = (b_yrange + 0.)/(self.n_color_color_bar + 0.)
0365 
0366         self.color_bar = {}
0367         x1 = b_x1
0368         y1 = b_y1
0369             
0370         col_idx = self.start_color_idx
0371         for i_c in range(self.n_color_color_bar):
0372             col_idx += 1
0373             r, g, b = self.get_color_rgb(val)
0374             try:
0375                 col = ROOT.gROOT.GetColor(col_idx) #Here still OK
0376                 col.SetRGB((r+0.)/255., (g+0.)/255., (b+0.)/255.) #Here segmentation if color index does not exist
0377                 self.color_bar_colors[col_idx] = col #Here the new color is saved in in the global variable
0378             except:
0379                 #Here the 6 argument TColor init with dummy rgb must be used, 4 argument one does not work (ROOT bug?)
0380                 #New color index is defined and SetRGB must also be called to overwrite dummy rgb
0381                 col = ROOT.TColor(col_idx, 0., 0., 0., "", 1)
0382                 col.SetRGB((r+0.)/255., (g+0.)/255., (b+0.)/255.)
0383                 self.color_bar_colors[col_idx] = col #Here the new color is saved in in the global variable 
0384             x2 = x1 + b_dx 
0385             y2 = y1 + b_dy + b_width 
0386             x = array('d', [x1, x1, x2, x2])
0387             y = array('d', [y1, y2, y2, y1])
0388             self.color_bar[col_idx] = ROOT.TPolyLine(len(x), x, y)
0389             self.color_bar[col_idx].SetFillColor(col_idx)
0390             self.color_bar[col_idx].SetLineColor(col_idx)
0391  
0392             x1 += b_dx
0393             y1 += b_dy
0394             val += col_step
0395 
0396 #### Load functions
0397     def load_tree(self):
0398         print('TkAlMap: loading tree ')
0399         tree_name = 'alignTree'
0400         r_file = ROOT.TFile(self.root_file)
0401         if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
0402 
0403         tree_tmp = r_file.Get(tree_name)
0404         #self.tree = copy.deepcopy(tree_tmp)
0405         self.tmp_file_name = str(time.time()).replace('.', '_')+'_TkAlMapTempFile.root'
0406         self.tmp_file = ROOT.TFile(self.tmp_file_name, 'recreate')
0407         self.tree = tree_tmp.CloneTree()
0408         r_file.Close()
0409         self.is_cleaned = False
0410 
0411         if self.tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
0412         
0413 
0414 
0415     def load_var(self):
0416         print('TkAlMap: loading variable values ')
0417         #tree_name = 'alignTree'
0418         #r_file = ROOT.TFile(self.root_file)
0419         #if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
0420 
0421         #tree_tmp = r_file.Get(tree_name)
0422         #tree = copy.deepcopy(tree_tmp)
0423         #r_file.Close()
0424 
0425         #if tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
0426 
0427         self.mod_val_dict = {}
0428         self.val_list = []
0429         for event in self.tree:
0430             module = event.id
0431             var = self.var
0432             if var == 'rdphi':
0433                 val = getattr(event, 'r')*getattr(event, 'dphi')
0434             else: 
0435                 val = getattr(event, var)
0436             val *= self.var_scale
0437             self.mod_val_dict[module] = val
0438             #if val not in self.val_list: self.val_list.append(val)
0439             if module in self.TkAlMap_TPL_dict: self.val_list.append(val)
0440             ####else:
0441             ####    if 'full' in self.tracker:
0442             ####        print('Warning: Unknown module '+str(module))
0443         #r_file.Close()
0444         if len(self.val_list) == 0:
0445             print('Warning: no values filled, 0 moduleId\'s matched')
0446             self.val_list = [-10+idx*0.5 for idx in range(41)]
0447         self.val_list.sort()
0448         self.mean_val = mean(self.val_list)
0449         self.std_val = StdDev(self.val_list)
0450         self.min_val = min(self.val_list) 
0451         self.max_val = max(self.val_list)
0452         
0453         if self.two_sigma_cap and not self.default_range:
0454            print('-- Capping max and min: ')
0455            print('---- True values   : '+str(self.max_val)+', '+str(self.min_val))
0456            self.min_val = max(min(self.val_list), self.mean_val - 2*self.std_val)
0457            self.max_val = min(max(self.val_list), self.mean_val + 2*self.std_val)
0458            print('---- Capped values : '+str(self.max_val)+', '+str(self.min_val))
0459 
0460         if self.default_range:
0461            #if not self.var in KNOWN_VARIABLES: print('Warning: capping to default range not possible for unknown variable "'+self.var+'"')
0462            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')
0463            else:
0464                print('-- Capping max and min to default ranges: ')
0465                print('---- True values   : '+str(self.max_val)+', '+str(self.min_val))
0466                self.min_val = self.var_min
0467                self.max_val = self.var_max
0468                print('---- Capped values : '+str(self.max_val)+', '+str(self.min_val))
0469 
0470         if self.min_val == self.max_val:
0471             print('Warning: minimum value was equal to maximum value, '+str(self.max_val))
0472             self.min_val = self.mean_val - 1.
0473             self.max_val = self.mean_val + 1.
0474 
0475         #print(self.val_list)
0476 
0477     def detect_tracker_version(self):
0478         print('TkAlMap: detecting Tk version')
0479         #tree_name = 'alignTree'
0480         #r_file = ROOT.TFile(self.root_file)
0481         #if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
0482 
0483         ##tree = r_file.Get(tree_name)
0484         #tree_tmp = r_file.Get(tree_name)
0485         #tree = copy.deepcopy(tree_tmp)
0486         #r_file.Close()
0487 
0488         #if tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
0489         phase = None
0490         for event in self.tree:
0491             module = event.id
0492             if module > 303040000 and module < 306450000:
0493                 phase = 1
0494                 break
0495             elif module > 302055000 and module < 302198000:
0496                 phase = 0 
0497                 break
0498         #r_file.Close()
0499 
0500         if phase is None: raise ValueError('TkAlMap: unknown tracker detected, is this phase2?')
0501         
0502         pahse_str = 'phase'+str(phase)
0503         print('TkAlMap: '+pahse_str+' tracker detected')
0504         if not pahse_str in self.GEO_file:
0505             print('TkAlMap: changing tracker to '+pahse_str+ ', if this is unwanted set "check_tracker" to False')
0506             self.GEO_file = 'TkAlMapDesign_'+pahse_str+'_cfg.py'
0507             #self.load_geometry()
0508 
0509     def load_geometry(self):
0510         source_path = os.getenv('CMSSW_BASE') + '/src/' 
0511         var = {}
0512         if sys.version_info[0] == 2:
0513             execfile(source_path + self.cfg_path + self.GEO_file, var)
0514         elif sys.version_info[0] == 3:
0515             _filename = source_path + self.cfg_path + self.GEO_file
0516             exec(compile(open(_filename, "rb").read(), _filename, 'exec'), var)
0517 
0518         MapStructure = var['TkMap_GEO']
0519         
0520         all_modules = {}
0521         all_text = {}
0522         x_max = -9999.
0523         y_max = -9999.
0524         x_min = 9999.
0525         y_min = 9999.
0526         for det in MapStructure:
0527             if 'pixel' in self.tracker:
0528                 if not 'pixel' in det: continue 
0529             elif 'strips' in self.tracker:
0530                 if not 'strips' in det: continue 
0531             for sub in MapStructure[det]:
0532                 for part in MapStructure[det][sub]:
0533                     if part == 'latex':
0534                         all_text[det+'_'+sub] = MapStructure[det][sub][part]
0535                         continue
0536                     if 'latex' in MapStructure[det][sub][part]:
0537                         all_text[det+'_'+sub+'_'+part] = MapStructure[det][sub][part]['latex']
0538                     _filename = self.data_path +MapStructure[det][sub][part]['file']
0539                     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]
0540                     TPL_dict = read_TPLfile(TPL_file)
0541                     for module in TPL_dict:
0542                         x_canv = []
0543                         y_canv = []
0544                         for idx in range(len(TPL_dict[module]['x'])):
0545                             x_canv.append(TPL_dict[module]['x'][idx]*MapStructure[det][sub][part]['x_scale'] + MapStructure[det][sub][part]['x_off'])
0546                             y_canv.append(TPL_dict[module]['y'][idx]*MapStructure[det][sub][part]['y_scale'] + MapStructure[det][sub][part]['y_off'])
0547                         if max(x_canv) > x_max: x_max = max(x_canv)
0548                         if max(y_canv) > y_max: y_max = max(y_canv)
0549                         if min(x_canv) < x_min: x_min = min(x_canv)
0550                         if min(y_canv) < y_min: y_min = min(y_canv)
0551                         TPL_dict[module]['x'] = x_canv
0552                         TPL_dict[module]['y'] = y_canv
0553                     all_modules.update(TPL_dict)
0554 
0555         r_margin = 3
0556         l_margin = 3
0557         #t_margin = 15
0558         t_margin = 11
0559         b_margin = 8
0560 
0561         x_max += r_margin
0562         x_min -= l_margin
0563         y_max += t_margin
0564         y_min -= b_margin
0565 
0566         x_range = x_max - x_min
0567         y_range = y_max - y_min
0568 
0569         self.width = int(self.height*(x_range + 0.)/(y_range + 0.))
0570         self.canvas.SetWindowSize(self.width, self.height)
0571 
0572         if (x_range + 0.)/(self.width + 0.) > (y_range + 0.)/(self.height + 0.):
0573             x_scale = x_range
0574             y_scale = (self.height + 0.)/(self.width + 0.)*x_range
0575         else:
0576             y_scale = y_range
0577             x_scale = (self.width + 0.)/(self.height + 0.)*y_range
0578         self.TkAlMap_TPL_dict = {} 
0579         for module in all_modules:
0580             x = array('d', [])
0581             y = array('d', [])
0582             for idx in range(len(all_modules[module]['x'])):
0583                 x.append((all_modules[module]['x'][idx] - x_min + 0.)/(x_scale + 0.))
0584                 y.append((all_modules[module]['y'][idx] - y_min + 0.)/(y_scale + 0.))
0585             # Begin point is end point
0586             x.append((all_modules[module]['x'][0] - x_min + 0.)/(x_scale + 0.))
0587             y.append((all_modules[module]['y'][0] - y_min + 0.)/(y_scale + 0.))
0588             #print(x, y)
0589             self.TkAlMap_TPL_dict[module] = ROOT.TPolyLine(len(x), x, y) 
0590             #self.TkAlMap_TPL_dict[module].SetFillColor(1)
0591             self.TkAlMap_TPL_dict[module].SetLineColor(1)
0592             #print('lineW', self.TkAlMap_TPL_dict[module].GetLineWidth())
0593             #self.TkAlMap_TPL_dict[module].Draw('f')
0594             #self.TkAlMap_TPL_dict[module].Draw()
0595 
0596         self.image_x1 = (l_margin + 0.)/(x_scale + 0.) 
0597         self.image_x2 = (x_max - r_margin - x_min + 0.)/(x_scale + 0.) 
0598         self.image_y1 = (b_margin + 0.)/(y_scale + 0.) 
0599         self.image_y2 = (y_max - t_margin - y_min + 0.)/(y_scale + 0.) 
0600 
0601         self.x_scale = x_scale
0602         self.y_scale = y_scale
0603 
0604         #TL = ROOT.TLatex()
0605         #TL.SetTextSize(0.025)
0606         self.TkAlMap_text_dict = {}
0607         for key in all_text:
0608             x = (all_text[key]['x'] - x_min + 0.)/(x_scale + 0.)
0609             y = (all_text[key]['y'] - y_min + 0.)/(y_scale + 0.)
0610             self.TkAlMap_text_dict[key] = {}
0611             self.TkAlMap_text_dict[key]['x'] = x
0612             self.TkAlMap_text_dict[key]['y'] = y
0613             self.TkAlMap_text_dict[key]['alignment'] = all_text[key]['alignment']
0614             self.TkAlMap_text_dict[key]['text'] = all_text[key]['text']
0615             #TL.SetTextAlign(all_text[key]['alignment'])
0616             #TL.DrawLatex(x, y, all_text[key]['text'])
0617 
0618 #### Titles and info
0619     def draw_title(self):
0620         TL = ROOT.TLatex()
0621         TL.SetTextSize(0.035)
0622         TL.SetTextFont(42)
0623         TL.SetTextAlign(13)
0624         x1 = self.image_x1
0625         y1 = 1-(5./(self.y_scale+0.))
0626         self.canvas.cd()
0627         TL.DrawLatex(x1, y1, self.title)
0628          
0629     def draw_cms_prelim(self):
0630         TL = ROOT.TLatex()
0631         factor = 1. / 0.82
0632         TL.SetTextSize(0.035*factor)
0633         TL.SetTextAlign(11)
0634         TL.SetTextFont(61)
0635 
0636         w_cms = ctypes.c_uint(0)
0637         h_cms = ctypes.c_uint(0)
0638         TL.GetTextExtent(w_cms, h_cms, 'CMS')
0639         x1 = self.image_x1
0640         y1 = 1. - (h_cms.value+0.)/(self.height+0.) - (1./(self.y_scale+0.))
0641         self.canvas.cd()
0642         TL.DrawLatex(x1, y1, 'CMS')
0643   
0644         TL.SetTextSize(0.035)
0645         TL.SetTextFont(42)
0646         x1_prel = x1 + 1.1*(w_cms.value+0.)/(self.width+0.)
0647         TL.DrawLatex(x1_prel, y1, '#it{Preliminary}')
0648         
0649         self.draw_event_info(y1)
0650 
0651     def draw_event_info(self, y):
0652         TL = ROOT.TLatex()
0653         TL.SetTextSize(0.035)
0654         TL.SetTextFont(42)
0655         TL.SetTextAlign(31)
0656 
0657         x1 = self.image_x2
0658         y1 = y
0659         self.canvas.cd()
0660         TL.DrawLatex(x1, y1, 'pp collisions 13TeV')
0661         
0662 
0663 #### Draw functions
0664     def draw_text(self):
0665         print('TkAlMap: drawing text')
0666         self.canvas.cd()
0667         TL = ROOT.TLatex()
0668         TL.SetTextSize(0.025)
0669         for key in self.TkAlMap_text_dict:
0670             TL.SetTextAlign(self.TkAlMap_text_dict[key]['alignment'])
0671             TL.DrawLatex(self.TkAlMap_text_dict[key]['x'], self.TkAlMap_text_dict[key]['y'], self.TkAlMap_text_dict[key]['text'])
0672         self.draw_cms_prelim()
0673         self.draw_title()
0674         self.canvas.Update()
0675 
0676     def draw_TPL(self):
0677         print('TkAlMap: drawing PolyLines')
0678         self.canvas.cd()
0679         for module in self.TkAlMap_TPL_dict:
0680             self.TkAlMap_TPL_dict[module].Draw('f')
0681             self.TkAlMap_TPL_dict[module].Draw()
0682         self.canvas.Update()
0683 
0684     def draw_color_bar(self):
0685         print('TkAlMap: drawing color bar')
0686         self.canvas.cd()
0687         for box in self.color_bar:
0688             self.color_bar[box].Draw('f')
0689             #self.color_bar[box].Draw()
0690         self.color_bar_axis.Draw()
0691         self.canvas.Update()
0692 
0693     def save(self, out_dir='.', extension='pdf'):
0694         name = '_'.join(['TkAlMap', self.tracker, self.var])
0695         if self.two_sigma_cap and not self.default_range:
0696             name += '_4sig'
0697         elif self.default_range:
0698             name += '_drange'
0699         path = out_dir + '/' + name + '.' + extension
0700         print('TkAlMap: saving canvas in "'+path+'"')
0701         self.canvas.SaveAs(path)
0702 
0703 
0704 #### Do all
0705     def analyse(self):
0706         self.setup_colors()
0707         self.set_colorbar_axis()
0708         if self.do_tanh: self.set_colorbar_colors()
0709         self.draw_TPL()
0710         self.draw_text()
0711         self.draw_color_bar()
0712 
0713 ### Test functions
0714     def plot_variable_distribution(self, nbins=200, out_dir='.'):
0715         print('TkAlMap: drawing variable distribution')
0716         canv_name = 'histogram_canvas_'+self.tracker+'_'+self.var
0717         if self.two_sigma_cap: canv_name += '_cap'
0718         canvas = ROOT.TCanvas(canv_name, 'TkAlMap '+self.var+' histogram canvas', 800, 800)
0719  
0720         h_min = min(min(self.val_list), self.mean_val - 2*self.std_val) - self.std_val
0721         h_max = max(max(self.val_list), self.mean_val + 2*self.std_val) + self.std_val
0722         hist = ROOT.TH1F(self.var+'_hist', 'Variable distribution', nbins, h_min, h_max)
0723         for val in self.val_list:
0724             hist.Fill(val)
0725         hist.GetXaxis().SetTitle(self.var_name+' ['+self.var_units+']')
0726         hist.GetYaxis().SetTitle('modules')
0727         ROOT.gStyle.SetOptStat(0)
0728         hist.Draw('e1')
0729         canvas.Update()
0730         left = ROOT.TLine(self.mean_val - 2*self.std_val, canvas.GetUymin(), self.mean_val - 2*self.std_val, canvas.GetUymax())
0731         left.SetLineColor(2) 
0732         left.SetLineStyle(9) 
0733         left.Draw() 
0734         right = ROOT.TLine(self.mean_val + 2*self.std_val, canvas.GetUymin(), self.mean_val + 2*self.std_val, canvas.GetUymax())
0735         right.SetLineColor(2) 
0736         right.SetLineStyle(9) 
0737         right.Draw() 
0738         mid = ROOT.TLine(self.mean_val, canvas.GetUymin(), self.mean_val, canvas.GetUymax())
0739         mid.SetLineColor(1)
0740         mid.SetLineStyle(9) 
0741         mid.Draw()
0742         canvas.Update()
0743         name = '_'.join(['VariableDistribution', self.var, self.tracker])
0744         path = out_dir + '/' + name + '.png' 
0745         canvas.SaveAs(path)
0746 
0747 
0748 ### Clean up
0749     def clean_up(self):
0750         if not self.is_cleaned:
0751             print('TkAlMap: deleting temporary file "'+self.tmp_file_name+'"')
0752             self.tmp_file.Close()
0753             os.remove(self.tmp_file_name)
0754             self.is_cleaned = True
0755 
0756     def __del__(self):
0757         self.clean_up()
0758 
0759 
0760 if __name__ == '__main__':
0761     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, tracker='strips')
0762     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780)
0763     TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=1400, GEO_file='TkAlMapDesign_phase0_cfg.py')
0764     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py')
0765     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py', tracker='pixel')
0766     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase1_cfg.py', tracker='pixel')
0767     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py', tracker='strips')
0768     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, tracker='pixel')
0769     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True)
0770 
0771     var_list = ['dx', 'dy']
0772     #var_list = ['dx']
0773     for var in var_list:
0774         TkMap_temp = copy.deepcopy(TkMap)
0775         TkMap_temp.set_var(var)
0776         #TkMap.load_var()
0777         #TkMap.draw_text()
0778         #TkMap.draw_TPL()
0779         TkMap_temp.analyse()
0780         TkMap_temp.save(extension='png')
0781         TkMap_temp.save()
0782     raw_input('exit')