Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-11-27 03:18:09

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