Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-02-14 12:46:00

0001 import os
0002 import ROOT
0003 import copy
0004 import math
0005 import time
0006 import ctypes
0007 from array import array
0008 import FWCore.ParameterSet.Config as cms
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': [-200., 200.],
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/TkAlMap/'
0177         self.data_path = 'Alignment/OfflineValidation/data/TkAlMap/'
0178         self.cfg_path = 'Alignment/OfflineValidation/python/TkAlMap_cfg/'
0179 
0180         # Colorbar stuff
0181         self.start_color_idx   = 1200
0182         self.n_color_color_bar = 1000
0183  
0184         # Initialization functions
0185         self.set_palette(palette)
0186         self.set_var(variable)
0187         self.load_tree()
0188         if check_tracker: self.detect_tracker_version()
0189         self.load_geometry()
0190         self.set_colorbar_colors()
0191 
0192     def set_var(self, var, var_range=[None, None]):
0193         print('TkAlMap: setting variable to '+var)
0194         self.var = var
0195         self.var_name = var
0196         self.var_units = 'cm'
0197         self.var_scale = 1.
0198         self.var_min = var_range[0]
0199         self.var_max = var_range[1]
0200         if var in KNOWN_VARIABLES:
0201             self.var_name  = KNOWN_VARIABLES[var]['name']
0202             self.var_units = KNOWN_VARIABLES[var]['units']
0203             self.var_scale = KNOWN_VARIABLES[var]['scale']
0204             if self.var_min is None: self.var_min = KNOWN_VARIABLES[var]['range'][0]
0205             if self.var_max is None: self.var_max = KNOWN_VARIABLES[var]['range'][1]
0206         self.set_canvas()
0207 
0208     def set_canvas(self):
0209         canv_name = 'canvas_'+self.tracker+'_'+self.var
0210         if self.two_sigma_cap: canv_name += '_cap'
0211         self.canvas = ROOT.TCanvas(canv_name, 'TkAlMap '+self.var+' canvas', self.width, self.height)
0212         print('Actual w: '+str(self.canvas.GetWw())+', Actual h: '+str(self.canvas.GetWh()))
0213 
0214 #### Color setup
0215     def setup_colors(self):
0216         self.load_var()
0217         self.prepare_map_colors()
0218         self.fill_colors()
0219 
0220     def prepare_map_colors(self):
0221         print('TkAlMap: preparing map colors')
0222         
0223         self.colors = []
0224         #self.palette = array('i', [])
0225         col_idx = self.start_color_idx + self.n_color_color_bar + 10
0226         self.col_dic = {}
0227         self.rgb_map = {}
0228         #pal_idx = 0
0229         #self.pal_map = {}
0230         for val in self.val_list:
0231             cap_val = val
0232             if cap_val > self.max_val: cap_val = self.max_val
0233             if cap_val < self.min_val: cap_val = self.min_val
0234             r, g, b = self.get_color_rgb(cap_val)
0235             idx = self.get_color_rgb_idx(cap_val)
0236             if idx in self.colors: continue
0237             self.colors.append(idx)
0238             col_idx +=1
0239             self.rgb_map[idx] = col_idx
0240             #print( idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
0241             #color = ROOT.TColor(col_idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
0242 
0243             #self.col_dic[idx] = ROOT.TColor(col_idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
0244             try:
0245                 col = ROOT.gROOT.GetColor(col_idx)
0246                 col.SetRGB((r+0.)/255., (g+0.)/255., (b+0.)/255.)
0247                 self.col_dic[idx] = col
0248             except:
0249                 self.col_dic[idx] = ROOT.TColor(col_idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
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 
0278         if self.palette == 1:
0279             r = 255
0280             g = 255
0281             b = 255
0282 
0283             if value_frac < 0.25:
0284                 r = 0
0285                 g = int(255.*((value_frac/0.25)))
0286                 b = 255         
0287             elif value_frac < 0.5:
0288                 r = 0
0289                 g = 255
0290                 b = int(255.*(1. -(value_frac - 0.25)/0.25)) 
0291             elif value_frac < 0.75:
0292                 r = int(255.*((value_frac - 0.5)/0.25))
0293                 g = 255
0294                 b = 0 
0295             else:
0296                 r = 255 
0297                 g = int(255.*(1. -(value_frac - 0.75)/0.25)) 
0298                 b = 0
0299             return r, g, b 
0300         elif self.palette == 2:
0301             red   = [59,   76, 192]
0302             blue  = [180,   4,  38]
0303             white = [255, 255, 255] 
0304             r, g, b = DivergingColor(red, blue, white, value_frac) 
0305             return r, g, b
0306         else: raise ValueError('TkAlMap: unkown palette value '+str(palette)+', allowed values are 1 and 2')
0307 
0308     def get_color_rgb_idx(self, val):
0309         r, g, b = self.get_color_rgb(val)
0310         #return r*1000000+g*1000+b+1000000000
0311         offset = 100
0312         return int(r*255*255 + g*255 + r + g + b + offset)
0313 
0314     def fill_colors(self):
0315         print('TkAlMap: filling the colors')
0316         #self.set_palette()
0317         for module in self.mod_val_dict:
0318             if module in self.TkAlMap_TPL_dict:
0319                 val = self.mod_val_dict[module]
0320                 cap_val = val
0321                 if cap_val > self.max_val: cap_val = self.max_val
0322                 if cap_val < self.min_val: cap_val = self.min_val
0323                 rgb = self.get_color_rgb_idx(cap_val)
0324                 col = self.rgb_map[rgb]
0325                 #col = self.pal_map[rgb]
0326                 #col = self.col_dic[rgb]
0327                 #print(val, rgb, col)
0328                 self.TkAlMap_TPL_dict[module].SetFillColor(col)
0329                 #self.TkAlMap_TPL_dict[module].SetFillColor(TEST_COLOR_IDX)
0330             ####else: print('Warning: Unknown module '+str(module))
0331 
0332     def set_colorbar_axis(self):
0333         print('TkAlMap: setting color bar axis')
0334         b_x1 = self.image_x1
0335         b_x2 = self.image_x2
0336         b_y1 = 0.06
0337         b_y2 = 0.06
0338         b_width = 0.01
0339         self.color_bar_axis = ROOT.TGaxis(b_x1, b_y1, b_x2, b_y2, self.min_val, self.max_val, 50510, '+S')
0340         self.color_bar_axis.SetName('color_bar_axis')
0341         self.color_bar_axis.SetLabelSize(0.02)
0342         self.color_bar_axis.SetTickSize(0.01)
0343         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+']')
0344         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+']')
0345         else: self.color_bar_axis.SetTitle(self.var_name+' ['+self.var_units+']')
0346         self.color_bar_axis.SetTitleSize(0.025)
0347 
0348     def set_colorbar_colors(self):
0349         print('TkAlMap: initialize color bar colors')
0350         if self.max_val is None or self.min_val is None:
0351             col_step = 1./(self.n_color_color_bar + 0.)
0352             val = col_step/2.
0353         else:
0354             b_range = self.max_val - self.min_val
0355             col_step = (b_range + 0.)/(self.n_color_color_bar + 0.)
0356             val = self.min_val + col_step/2.
0357 
0358         b_x1 = self.image_x1
0359         b_x2 = self.image_x2
0360         b_y1 = 0.06
0361         b_y2 = 0.06
0362         b_width = 0.01
0363         b_xrange = b_x2 - b_x1
0364         b_yrange = b_y2 - b_y1
0365         b_dx = (b_xrange + 0.)/(self.n_color_color_bar + 0.)
0366         b_dy = (b_yrange + 0.)/(self.n_color_color_bar + 0.)
0367 
0368         self.color_bar = {}
0369         x1 = b_x1
0370         y1 = b_y1
0371             
0372         col_idx = self.start_color_idx
0373         for i_c in range(self.n_color_color_bar):
0374             col_idx += 1
0375             r, g, b = self.get_color_rgb(val)
0376             try:
0377                 col = ROOT.gROOT.GetColor(col_idx)
0378                 col.SetRGB((r+0.)/255., (g+0.)/255., (b+0.)/255.)
0379                 self.color_bar_colors[col_idx] = col
0380             except:
0381                 self.color_bar_colors[col_idx] = ROOT.TColor(col_idx, (r+0.)/255., (g+0.)/255., (b+0.)/255.)
0382             x2 = x1 + b_dx 
0383             y2 = y1 + b_dy + b_width 
0384             x = array('d', [x1, x1, x2, x2])
0385             y = array('d', [y1, y2, y2, y1])
0386             self.color_bar[col_idx] = ROOT.TPolyLine(len(x), x, y)
0387             self.color_bar[col_idx].SetFillColor(col_idx)
0388             self.color_bar[col_idx].SetLineColor(col_idx)
0389  
0390             x1 += b_dx
0391             y1 += b_dy
0392             val += col_step
0393 
0394 #### Load functions
0395     def load_tree(self):
0396         print('TkAlMap: loading tree ')
0397         tree_name = 'alignTree'
0398         r_file = ROOT.TFile(self.root_file)
0399         if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
0400 
0401         tree_tmp = r_file.Get(tree_name)
0402         #self.tree = copy.deepcopy(tree_tmp)
0403         self.tmp_file_name = str(time.time()).replace('.', '_')+'_TkAlMapTempFile.root'
0404         self.tmp_file = ROOT.TFile(self.tmp_file_name, 'recreate')
0405         self.tree = tree_tmp.CloneTree()
0406         r_file.Close()
0407         self.is_cleaned = False
0408 
0409         if self.tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
0410         
0411 
0412 
0413     def load_var(self):
0414         print('TkAlMap: loading variable values ')
0415         #tree_name = 'alignTree'
0416         #r_file = ROOT.TFile(self.root_file)
0417         #if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
0418 
0419         #tree_tmp = r_file.Get(tree_name)
0420         #tree = copy.deepcopy(tree_tmp)
0421         #r_file.Close()
0422 
0423         #if tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
0424 
0425         self.mod_val_dict = {}
0426         self.val_list = []
0427         for event in self.tree:
0428             module = event.id
0429             var = self.var
0430             if var == 'rdphi':
0431                 val = getattr(event, 'r')*getattr(event, 'dphi')
0432             else: 
0433                 val = getattr(event, var)
0434             val *= self.var_scale
0435             self.mod_val_dict[module] = val
0436             #if val not in self.val_list: self.val_list.append(val)
0437             if module in self.TkAlMap_TPL_dict: self.val_list.append(val)
0438             ####else:
0439             ####    if 'full' in self.tracker:
0440             ####        print('Warning: Unknown module '+str(module))
0441         #r_file.Close()
0442         if len(self.val_list) == 0:
0443             print('Warning: no values filled, 0 moduleId\'s matched')
0444             self.val_list = [-10+idx*0.5 for idx in range(41)]
0445         self.val_list.sort()
0446         self.mean_val = mean(self.val_list)
0447         self.std_val = StdDev(self.val_list)
0448         self.min_val = min(self.val_list) 
0449         self.max_val = max(self.val_list)
0450         
0451         if self.two_sigma_cap and not self.default_range:
0452            print('-- Capping max and min: ')
0453            print('---- True values   : '+str(self.max_val)+', '+str(self.min_val))
0454            self.min_val = max(min(self.val_list), self.mean_val - 2*self.std_val)
0455            self.max_val = min(max(self.val_list), self.mean_val + 2*self.std_val)
0456            print('---- Capped values : '+str(self.max_val)+', '+str(self.min_val))
0457 
0458         if self.default_range:
0459            #if not self.var in KNOWN_VARIABLES: print('Warning: capping to default range not possible for unknown variable "'+self.var+'"')
0460            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')
0461            else:
0462                print('-- Capping max and min to default ranges: ')
0463                print('---- True values   : '+str(self.max_val)+', '+str(self.min_val))
0464                self.min_val = self.var_min
0465                self.max_val = self.var_max
0466                print('---- Capped values : '+str(self.max_val)+', '+str(self.min_val))
0467 
0468         if self.min_val == self.max_val:
0469             print('Warning: minimum value was equal to maximum value, '+str(self.max_val))
0470             self.min_val = self.mean_val - 1.
0471             self.max_val = self.mean_val + 1.
0472 
0473         #print(self.val_list)
0474 
0475     def detect_tracker_version(self):
0476         print('TkAlMap: detecting Tk version')
0477         #tree_name = 'alignTree'
0478         #r_file = ROOT.TFile(self.root_file)
0479         #if r_file is None: raise ValueError('The file "'+self.root_file+'" could not be opened')
0480 
0481         ##tree = r_file.Get(tree_name)
0482         #tree_tmp = r_file.Get(tree_name)
0483         #tree = copy.deepcopy(tree_tmp)
0484         #r_file.Close()
0485 
0486         #if tree is None: raise ValueError('The tree "'+tree_name+'" was not found in file "'+self.root_file+'"')
0487         phase = None
0488         for event in self.tree:
0489             module = event.id
0490             if module > 303040000 and module < 306450000:
0491                 phase = 1
0492                 break
0493             elif module > 302055000 and module < 302198000:
0494                 phase = 0 
0495                 break
0496         #r_file.Close()
0497 
0498         if phase is None: raise ValueError('TkAlMap: unknown tracker detected, is this phase2?')
0499         
0500         pahse_str = 'phase'+str(phase)
0501         print('TkAlMap: '+pahse_str+' tracker detected')
0502         if not pahse_str in self.GEO_file:
0503             print('TkAlMap: changing tracker to '+pahse_str+ ', if this is unwanted set "check_tracker" to False')
0504             self.GEO_file = 'TkAlMapDesign_'+pahse_str+'_cfg.py'
0505             #self.load_geometry()
0506 
0507     def load_geometry(self):
0508         source_path = os.getenv('CMSSW_BASE') + '/src/' 
0509         var = {}
0510         execfile(source_path + self.cfg_path + self.GEO_file, var)
0511 
0512         MapStructure = var['TkMap_GEO']
0513         
0514         all_modules = {}
0515         all_text = {}
0516         x_max = -9999.
0517         y_max = -9999.
0518         x_min = 9999.
0519         y_min = 9999.
0520         for det in MapStructure:
0521             if 'pixel' in self.tracker:
0522                 if not 'pixel' in det: continue 
0523             elif 'strips' in self.tracker:
0524                 if not 'strips' in det: continue 
0525             for sub in MapStructure[det]:
0526                 for part in MapStructure[det][sub]:
0527                     if part == 'latex':
0528                         all_text[det+'_'+sub] = MapStructure[det][sub][part]
0529                         continue
0530                     if 'latex' in MapStructure[det][sub][part]:
0531                         all_text[det+'_'+sub+'_'+part] = MapStructure[det][sub][part]['latex']
0532                     #TPL_file = source_path + self.data_path +MapStructure[det][sub][part]['file']
0533                     TPL_file = cms.FileInPath(self.data_path +MapStructure[det][sub][part]['file'])
0534                     TPL_dict = read_TPLfile(TPL_file)
0535                     for module in TPL_dict:
0536                         x_canv = []
0537                         y_canv = []
0538                         for idx in range(len(TPL_dict[module]['x'])):
0539                             x_canv.append(TPL_dict[module]['x'][idx]*MapStructure[det][sub][part]['x_scale'] + MapStructure[det][sub][part]['x_off'])
0540                             y_canv.append(TPL_dict[module]['y'][idx]*MapStructure[det][sub][part]['y_scale'] + MapStructure[det][sub][part]['y_off'])
0541                         if max(x_canv) > x_max: x_max = max(x_canv)
0542                         if max(y_canv) > y_max: y_max = max(y_canv)
0543                         if min(x_canv) < x_min: x_min = min(x_canv)
0544                         if min(y_canv) < y_min: y_min = min(y_canv)
0545                         TPL_dict[module]['x'] = x_canv
0546                         TPL_dict[module]['y'] = y_canv
0547                     all_modules.update(TPL_dict)
0548 
0549         r_margin = 3
0550         l_margin = 3
0551         #t_margin = 15
0552         t_margin = 11
0553         b_margin = 8
0554 
0555         x_max += r_margin
0556         x_min -= l_margin
0557         y_max += t_margin
0558         y_min -= b_margin
0559 
0560         x_range = x_max - x_min
0561         y_range = y_max - y_min
0562 
0563         self.width = int(self.height*(x_range + 0.)/(y_range + 0.))
0564         self.canvas.SetWindowSize(self.width, self.height)
0565 
0566         if (x_range + 0.)/(self.width + 0.) > (y_range + 0.)/(self.height + 0.):
0567             x_scale = x_range
0568             y_scale = (self.height + 0.)/(self.width + 0.)*x_range
0569         else:
0570             y_scale = y_range
0571             x_scale = (self.width + 0.)/(self.height + 0.)*y_range
0572         self.TkAlMap_TPL_dict = {} 
0573         for module in all_modules:
0574             x = array('d', [])
0575             y = array('d', [])
0576             for idx in range(len(all_modules[module]['x'])):
0577                 x.append((all_modules[module]['x'][idx] - x_min + 0.)/(x_scale + 0.))
0578                 y.append((all_modules[module]['y'][idx] - y_min + 0.)/(y_scale + 0.))
0579             # Begin point is end point
0580             x.append((all_modules[module]['x'][0] - x_min + 0.)/(x_scale + 0.))
0581             y.append((all_modules[module]['y'][0] - y_min + 0.)/(y_scale + 0.))
0582             #print(x, y)
0583             self.TkAlMap_TPL_dict[module] = ROOT.TPolyLine(len(x), x, y) 
0584             #self.TkAlMap_TPL_dict[module].SetFillColor(1)
0585             self.TkAlMap_TPL_dict[module].SetLineColor(1)
0586             #print('lineW', self.TkAlMap_TPL_dict[module].GetLineWidth())
0587             #self.TkAlMap_TPL_dict[module].Draw('f')
0588             #self.TkAlMap_TPL_dict[module].Draw()
0589 
0590         self.image_x1 = (l_margin + 0.)/(x_scale + 0.) 
0591         self.image_x2 = (x_max - r_margin - x_min + 0.)/(x_scale + 0.) 
0592         self.image_y1 = (b_margin + 0.)/(y_scale + 0.) 
0593         self.image_y2 = (y_max - t_margin - y_min + 0.)/(y_scale + 0.) 
0594 
0595         self.x_scale = x_scale
0596         self.y_scale = y_scale
0597 
0598         #TL = ROOT.TLatex()
0599         #TL.SetTextSize(0.025)
0600         self.TkAlMap_text_dict = {}
0601         for key in all_text:
0602             x = (all_text[key]['x'] - x_min + 0.)/(x_scale + 0.)
0603             y = (all_text[key]['y'] - y_min + 0.)/(y_scale + 0.)
0604             self.TkAlMap_text_dict[key] = {}
0605             self.TkAlMap_text_dict[key]['x'] = x
0606             self.TkAlMap_text_dict[key]['y'] = y
0607             self.TkAlMap_text_dict[key]['alignment'] = all_text[key]['alignment']
0608             self.TkAlMap_text_dict[key]['text'] = all_text[key]['text']
0609             #TL.SetTextAlign(all_text[key]['alignment'])
0610             #TL.DrawLatex(x, y, all_text[key]['text'])
0611 
0612 #### Titles and info
0613     def draw_title(self):
0614         TL = ROOT.TLatex()
0615         TL.SetTextSize(0.035)
0616         TL.SetTextFont(42)
0617         TL.SetTextAlign(13)
0618         x1 = self.image_x1
0619         y1 = 1-(5./(self.y_scale+0.))
0620         self.canvas.cd()
0621         TL.DrawLatex(x1, y1, self.title)
0622          
0623     def draw_cms_prelim(self):
0624         TL = ROOT.TLatex()
0625         factor = 1. / 0.82
0626         TL.SetTextSize(0.035*factor)
0627         TL.SetTextAlign(11)
0628         TL.SetTextFont(61)
0629 
0630         w_cms = ctypes.c_uint(0)
0631         h_cms = ctypes.c_uint(0)
0632         TL.GetTextExtent(w_cms, h_cms, 'CMS')
0633         x1 = self.image_x1
0634         y1 = 1. - (h_cms.value+0.)/(self.height+0.) - (1./(self.y_scale+0.))
0635         self.canvas.cd()
0636         TL.DrawLatex(x1, y1, 'CMS')
0637   
0638         TL.SetTextSize(0.035)
0639         TL.SetTextFont(42)
0640         x1_prel = x1 + 1.1*(w_cms.value+0.)/(self.width+0.)
0641         TL.DrawLatex(x1_prel, y1, '#it{Preliminary}')
0642         
0643         self.draw_event_info(y1)
0644 
0645     def draw_event_info(self, y):
0646         TL = ROOT.TLatex()
0647         TL.SetTextSize(0.035)
0648         TL.SetTextFont(42)
0649         TL.SetTextAlign(31)
0650 
0651         x1 = self.image_x2
0652         y1 = y
0653         self.canvas.cd()
0654         TL.DrawLatex(x1, y1, 'pp collisions 13TeV')
0655         
0656 
0657 #### Draw functions
0658     def draw_text(self):
0659         print('TkAlMap: drawing text')
0660         self.canvas.cd()
0661         TL = ROOT.TLatex()
0662         TL.SetTextSize(0.025)
0663         for key in self.TkAlMap_text_dict:
0664             TL.SetTextAlign(self.TkAlMap_text_dict[key]['alignment'])
0665             TL.DrawLatex(self.TkAlMap_text_dict[key]['x'], self.TkAlMap_text_dict[key]['y'], self.TkAlMap_text_dict[key]['text'])
0666         self.draw_cms_prelim()
0667         self.draw_title()
0668         self.canvas.Update()
0669 
0670     def draw_TPL(self):
0671         print('TkAlMap: drawing PolyLines')
0672         self.canvas.cd()
0673         for module in self.TkAlMap_TPL_dict:
0674             self.TkAlMap_TPL_dict[module].Draw('f')
0675             self.TkAlMap_TPL_dict[module].Draw()
0676         self.canvas.Update()
0677 
0678     def draw_color_bar(self):
0679         print('TkAlMap: drawing color bar')
0680         self.canvas.cd()
0681         for box in self.color_bar:
0682             self.color_bar[box].Draw('f')
0683             #self.color_bar[box].Draw()
0684         self.color_bar_axis.Draw()
0685         self.canvas.Update()
0686 
0687     def save(self, out_dir='.', extension='pdf'):
0688         name = '_'.join(['TkAlMap', self.tracker, self.var])
0689         if self.two_sigma_cap and not self.default_range:
0690             name += '_4sig'
0691         elif self.default_range:
0692             name += '_drange'
0693         path = out_dir + '/' + name + '.' + extension
0694         print('TkAlMap: saving canvas in "'+path+'"')
0695         self.canvas.SaveAs(path)
0696 
0697 
0698 #### Do all
0699     def analyse(self):
0700         self.setup_colors()
0701         self.set_colorbar_axis()
0702         if self.do_tanh: self.set_colorbar_colors()
0703         self.draw_TPL()
0704         self.draw_text()
0705         self.draw_color_bar()
0706 
0707 ### Test functions
0708     def plot_variable_distribution(self, nbins=200, out_dir='.'):
0709         print('TkAlMap: drawing variable distribution')
0710         canv_name = 'histogram_canvas_'+self.tracker+'_'+self.var
0711         if self.two_sigma_cap: canv_name += '_cap'
0712         canvas = ROOT.TCanvas(canv_name, 'TkAlMap '+self.var+' histogram canvas', 800, 800)
0713  
0714         h_min = min(min(self.val_list), self.mean_val - 2*self.std_val) - self.std_val
0715         h_max = max(max(self.val_list), self.mean_val + 2*self.std_val) + self.std_val
0716         hist = ROOT.TH1F(self.var+'_hist', 'Variable distribution', nbins, h_min, h_max)
0717         for val in self.val_list:
0718             hist.Fill(val)
0719         hist.GetXaxis().SetTitle(self.var_name+' ['+self.var_units+']')
0720         hist.GetYaxis().SetTitle('modules')
0721         ROOT.gStyle.SetOptStat(0)
0722         hist.Draw('e1')
0723         canvas.Update()
0724         left = ROOT.TLine(self.mean_val - 2*self.std_val, canvas.GetUymin(), self.mean_val - 2*self.std_val, canvas.GetUymax())
0725         left.SetLineColor(2) 
0726         left.SetLineStyle(9) 
0727         left.Draw() 
0728         right = ROOT.TLine(self.mean_val + 2*self.std_val, canvas.GetUymin(), self.mean_val + 2*self.std_val, canvas.GetUymax())
0729         right.SetLineColor(2) 
0730         right.SetLineStyle(9) 
0731         right.Draw() 
0732         mid = ROOT.TLine(self.mean_val, canvas.GetUymin(), self.mean_val, canvas.GetUymax())
0733         mid.SetLineColor(1)
0734         mid.SetLineStyle(9) 
0735         mid.Draw()
0736         canvas.Update()
0737         name = '_'.join(['VariableDistribution', self.var, self.tracker])
0738         path = out_dir + '/' + name + '.png' 
0739         canvas.SaveAs(path)
0740 
0741 
0742 ### Clean up
0743     def clean_up(self):
0744         if not self.is_cleaned:
0745             print('TkAlMap: deleting temporary file "'+self.tmp_file_name+'"')
0746             self.tmp_file.Close()
0747             os.remove(self.tmp_file_name)
0748             self.is_cleaned = True
0749 
0750     def __del__(self):
0751         self.clean_up()
0752 
0753 
0754 if __name__ == '__main__':
0755     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, tracker='strips')
0756     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780)
0757     TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=1400, GEO_file='TkAlMapDesign_phase0_cfg.py')
0758     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py')
0759     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py', tracker='pixel')
0760     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase1_cfg.py', tracker='pixel')
0761     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, height=780, GEO_file='TkAlMapDesign_phase0_cfg.py', tracker='strips')
0762     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True, tracker='pixel')
0763     #TkMap = TkAlMap('test', 'Here goes the title', 'run/tree.root', True)
0764 
0765     var_list = ['dx', 'dy']
0766     #var_list = ['dx']
0767     for var in var_list:
0768         TkMap_temp = copy.deepcopy(TkMap)
0769         TkMap_temp.set_var(var)
0770         #TkMap.load_var()
0771         #TkMap.draw_text()
0772         #TkMap.draw_TPL()
0773         TkMap_temp.analyse()
0774         TkMap_temp.save(extension='png')
0775         TkMap_temp.save()
0776     raw_input('exit')