Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-02-14 23:31:27

0001 #!/usr/bin/env python
0002 
0003 from __future__ import print_function
0004 import argparse
0005 import os, sys
0006 import pprint
0007 from shutil import copy2
0008 import xml.etree.ElementTree as ET
0009 
0010 TAG_PREFIX='{http://www.cern.ch/cms/DDL}'
0011 CMSSW_NOT_SET=1
0012 TRACKER_MATERIAL_FILE_MISSING=2
0013 
0014 HEADER = """
0015 #ifndef SIMTRACKER_TRACKERMATERIALANALYSIS_LISTGROUPS_MATERIALDIFFERENCE_H
0016 #define SIMTRACKER_TRACKERMATERIALANALYSIS_LISTGROUPS_MATERIALDIFFERENCE_H
0017 
0018 void ListGroups::fillMaterialDifferences() {
0019 """
0020 
0021 TRAILER = """
0022 }
0023 
0024 #endif //  SIMTRACKER_TRACKERMATERIALANALYSIS_LISTGROUPS_MATERIALDIFFERENCE_H
0025 """
0026 
0027 def checkEnvironment():
0028     if not 'CMSSW_RELEASE_BASE' in os.environ.keys():
0029         print('CMSSW Environments not setup, quitting\n')
0030         sys.exit(CMSSW_NOT_SET)
0031 
0032 def getTrackerRecoMaterialCopy(filename):
0033     tracker_reco_material = os.path.join(os.environ['CMSSW_BASE'],
0034                                          'src/Geometry/TrackerRecoData/data/PhaseI/v1/trackerRecoMaterial.xml')
0035     if not os.path.exists(tracker_reco_material):
0036       tracker_reco_material = os.path.join(os.environ['CMSSW_RELEASE_BASE'],
0037                                            'src/Geometry/TrackerRecoData/data/PhaseI/v1/trackerRecoMaterial.xml')
0038       if not os.path.exists(tracker_reco_material):
0039           print('Something is wrong with the CMSSW installation. The file %s is missing. Quitting.\n' % tracker_reco_material)
0040           sys.exit(TRACKER_MATERIAL_FILE_MISSING)
0041     copy2(tracker_reco_material, filename)
0042                                                 
0043 def produceXMLFromParameterFile():
0044     """
0045     Starting from the file parameters.xml produced by the
0046     TrackingMaterialAnalyser via cmsRun, it writes out a new XML,
0047     taking into account the proper names and grouping of detectors
0048     together.
0049 
0050     The skeleton of the XML is taken directly from the release the
0051     user is currently using, i.e. from
0052     $CMSSW_RELEASE_BASE/src/Geometry/TrackerRecoData/data/{,PhaseI/pixfwd}trackerRecoMaterial.xml.
0053 
0054     A new file, named trackerRecoMaterial.xml, is saved in the
0055     current directory.
0056     """
0057 
0058     tracker_reco_material = './trackerRecoMaterialFromRelease.xml'
0059     tracker_reco_material_updated = './parameters.xml'
0060     ET.register_namespace('', "http://www.cern.ch/cms/DDL")
0061     tree = ET.parse(tracker_reco_material)
0062     root = tree.getroot()
0063     tree_updated = ET.parse(tracker_reco_material_updated)
0064     root_updated = tree_updated.getroot()
0065     sections = root.getchildren()
0066     for child in sections[0]:
0067         print(child.attrib['name'])
0068 
0069     for spec_par in root.iter('%sSpecPar' % TAG_PREFIX):
0070         current_detector = spec_par.attrib['name']
0071         for parameter in spec_par.iter('%sParameter' % TAG_PREFIX):
0072             print(current_detector, parameter.attrib['name'], parameter.attrib['value'])
0073             updated_current_detector_node = root_updated.find(".//Group[@name='%s']" % current_detector)
0074             if updated_current_detector_node:
0075               for child in updated_current_detector_node:
0076                   if child.attrib['name'] == parameter.attrib['name']:
0077                       parameter.set('name', child.attrib['name'])
0078                       parameter.set('value', child.attrib['value'])
0079                       print(current_detector, parameter.attrib['name'], parameter.attrib['value'])
0080             else:
0081               print("Missing group: %s" % current_detector)
0082     tree.write('trackerRecoMaterial.xml', encoding='UTF-8', xml_declaration=True)
0083 
0084 def compareNewXMLWithOld(format_for_twiki):
0085     """
0086     Computes the difference between the old values, stored in the
0087     central repository for the current release, i.e. from
0088     $CMSSW_RELEASE_BASE/src/Geometry/TrackerRecoData/data/{,PhaseI/pixfwd}trackerRecoMaterial.xml,
0089     and the new values that we assume are present in the same file
0090     under the locally installed release, i.e. under
0091     $CMSSW_BASE/src/Geometry/TrackerRecoData/data/{,PhaseI/pixfwd}trackerRecoMaterial.xml. No
0092     check is performed to guarantee that the files are already
0093     there. If the file is not there, it is searched in the current
0094     folder. A missing file will result in an exception.
0095 
0096     The output of this function is a formatted structured as:
0097     ComponentsName KindOfParameter OldValue NewValue Difference
0098     where the Difference is computed as (NewValue-OldValue)/OldValue.
0099 
0100     Results are flushed at the terminal, nothing is saved.
0101     """
0102     
0103     tracker_reco_material = './trackerRecoMaterialFromRelease.xml'
0104     tracker_reco_material_updated = os.path.join(os.environ['CMSSW_BASE'],
0105                                                  'src/SimTracker/TrackerMaterialAnalysis/test/trackerRecoMaterial.xml')
0106     if not os.path.exists(tracker_reco_material_updated):
0107         tracker_reco_material_updated = './trackerRecoMaterial.xml'
0108         if not os.path.exists(tracker_reco_material_updated):
0109             raise os.error('Missing trackerRecoMaterial.xml file.')
0110     ET.register_namespace('', "http://www.cern.ch/cms/DDL")
0111     tree = ET.parse(tracker_reco_material)
0112     root = tree.getroot()
0113     tree_updated = ET.parse(tracker_reco_material_updated)
0114     root_updated = tree_updated.getroot()
0115     sections = root.getchildren()
0116 
0117     header = open(os.path.join(os.environ['CMSSW_BASE'],
0118                                'src/SimTracker/TrackerMaterialAnalysis/plugins/ListGroupsMaterialDifference.h'), 'w')
0119     header.write(HEADER)
0120     differences = {}
0121     values = {}
0122     ordered_keys = []
0123     for spec_par in root.iter('%sSpecPar' % TAG_PREFIX):
0124         current_detector = spec_par.attrib['name']
0125         ordered_keys.append(current_detector)
0126         for parameter in spec_par.iter('%sParameter' % TAG_PREFIX):
0127             updated_current_detector_node = root_updated.find(".//%sSpecPar[@name='%s']" % (TAG_PREFIX,current_detector))
0128             if updated_current_detector_node:
0129                 for child in updated_current_detector_node:
0130                     name = child.get('name', None)
0131                     if name and name == parameter.attrib['name']:
0132                         differences.setdefault(current_detector, {}).setdefault(name, [float(parameter.attrib['value']),
0133                                                                                        float(child.attrib['value']),
0134                                                                                        ((float(child.attrib['value'])-float(parameter.attrib['value']))
0135                                                                                        /float(parameter.attrib['value'])*100.)]
0136                                                                                 )
0137             else:
0138                 print('Element not found: %s' % current_detector)
0139     for group in differences.keys():
0140         header.write('  m_diff["%s"] = std::make_pair<float, float>(%f, %f);\n' % (group,
0141                                                                                    differences[group]['TrackerRadLength'][2],
0142                                                                                    differences[group]['TrackerXi'][2]))
0143     for group in differences.keys():
0144         header.write('  m_values["%s"] = std::make_pair<float, float>(%f, %f);\n' % (group,
0145                                                                                      differences[group]['TrackerRadLength'][1],
0146                                                                                      differences[group]['TrackerXi'][1]))
0147 #    pprint.pprint(differences)
0148     for i in xrange(len(ordered_keys)):
0149         key = ordered_keys[i]
0150         if format_for_twiki:
0151             print("| %s | %f | %f | %f%% | %f | %f | %f%% |" % (key,
0152                                                                 differences[key]['TrackerRadLength'][0],
0153                                                                 differences[key]['TrackerRadLength'][1],
0154                                                                 differences[key]['TrackerRadLength'][2],
0155                                                                 differences[key]['TrackerXi'][0],
0156                                                                 differences[key]['TrackerXi'][1],
0157                                                                 differences[key]['TrackerXi'][2]
0158                                                                 ))
0159         else:
0160             print("%s %f %f %f%% %f %f %f%%" % (key,
0161                                                 differences[key]['TrackerRadLength'][0],
0162                                                 differences[key]['TrackerRadLength'][1],
0163                                                 differences[key]['TrackerRadLength'][2],
0164                                                 differences[key]['TrackerXi'][0],
0165                                                 differences[key]['TrackerXi'][1],
0166                                                 differences[key]['TrackerXi'][2]
0167                                                 ))
0168     header.write(TRAILER)
0169     header.close
0170     
0171     
0172 if __name__ == '__main__':
0173     parser = argparse.ArgumentParser(description='Easily manipulate and inspect XML files related to Tracking Material.')
0174     parser.add_argument('-p', '--produce', action='store_true',
0175                         default=False,
0176                         help='Produce a trackerRecoMaterial.xml starting from the paramters.xml file produced by the trackingMaterialProducer.')
0177     parser.add_argument('-c', '--compare', action='store_true',
0178                         default=False,
0179                         help='Compares a local trackerRecoMaterial.xml against the one bundled with the release.')
0180     parser.add_argument('-w', '--twiki', action='store_true',
0181                         default=False,
0182                         help="""Compares a local trackerRecoMaterial.xml against the one bundled
0183                                 with the release and produces and output that is Twiki compatible
0184                                 to be put into a table.""")
0185     args = parser.parse_args()
0186     checkEnvironment()
0187     getTrackerRecoMaterialCopy('trackerRecoMaterialFromRelease.xml')
0188     if args.produce:
0189         produceXMLFromParameterFile()
0190     if args.compare or args.twiki:
0191         compareNewXMLWithOld(args.twiki)