latte2latcXML.py

Go to the documentation of this file.
00001 #!/usr/local/bin/python
00002 #
00003 #                               Copyright 2004
00004 #                                     by
00005 #                        The Board of Trustees of the
00006 #                     Leland Stanford Junior University.
00007 #                            All rights reserved.
00008 #
00009 
00010 __facility__ = "Online"
00011 __abstract__ = "LATTE to LATC XML converter"
00012 __author__  = "Jim Panetta <panetta@slac.stanford.edu> SLAC - GLAST LAT I&T/Online"
00013 __date__     = ("$Date: 2006/04/21 14:13:40 $").split(' ')[1]
00014 __version__ = "$Revision: 1.17 $"
00015 __release__  = "$Name: HEAD $"
00016 __credits__ = "SLAC"
00017 
00018 import LICOS.copyright_SLAC
00019 
00020 import         os, time, sys, types, re
00021 from           ConfigParser import *
00022 
00023 from xml.dom         import Node
00024 from Ft.Xml.Domlette import NonvalidatingReader, PrettyPrint, implementation
00025 from Ft.Lib          import Uri
00026 from Ft.Xml          import EMPTY_NAMESPACE
00027 
00028 
00029 import         Numeric
00030 # import         scipy.stats.stats as stats
00031 import         logging
00032 import         LICOS.util.gOptions as gOptions
00033 from           LICOS.lib.LATconstants import *
00034 
00035 
00036 tccSide = ['+x','+x','+y','+y','-x','-x','-y','-y','all']
00037 tccDirection = ['lo','hi','hi','lo','hi','lo','lo','hi','hilo']
00038 #Hierarchial list of BCAST components for BCAST document generation purposes
00039 
00040 LATC_BCAST_DICT = {'TEM': {'CCC': {'CRC': {'CFE': None}},
00041                            'TCC': {'TRC': None },
00042                            'SPT': {'TFE': {'TDC': None}},
00043                            'TIC': None},
00044                    'AEM': {'ARC': {'AFE': None}},
00045                    'GEM': {'TAM': None,
00046                            'SCH': None,
00047                            'ROI': None,
00048                            'TIE': None,
00049                            'WIN': None,
00050                            'AOC': None}
00051                   }
00052 
00053 # Default configuration files
00054 LATTE2LATC_CONFIG   = os.path.join(ONLINE_ROOT, "LICOS/tools/LATc/L52LATc.cfg")
00055 LATCREGATTR_CONFIG  = os.path.join(ONLINE_ROOT, "LICOS/tools/LATc/regAttrDef.cfg")
00056 
00057 # Default namespace for all XML files used by LATTE.
00058 # This currently has to be None or '' since we do not
00059 # currently qualify tags and attributes with a namespace.
00060 LAT_NAMESPACE = EMPTY_NAMESPACE
00061 
00062 ##########################################################################################
00063 ##
00064 ## \class latte2latcXML
00065 ##
00066 ## \brief Converts LATTE schema into LATC input .xml format.
00067 ##
00068 ## This application accepts LATTE schema in .xml or
00069 ## in the <i> \%CAL_ROOT\% </i> root directory.
00070 ##
00071 ## The following actions are performed: \n
00072 ##    -# Copy the file <i> \%CAL_ROOT%\\setup\\Configurations\\runId.cfg.template </i> to
00073 ##       <i> \%ONLINE_ROOT\%\\LATTE\\start\\runId.cfg </i>
00074 ##    -# Copy the file <i> \%CAL_ROOT%\\setup\\Configurations\\runControl.cfg.template to </i>
00075 ##       <i> \%ONLINE_ROOT\%\\LATTE\\start\\runControl.cfg </i>
00076 ##    -# Queries the user for the name of the test unit name (e.g. FM101).
00077 ##    -# Creates a subdirectory <i> \%CAL_ROOT\%\<Test_Unit> </i>
00078 ##    -# Creates the <i> \%CAL_ROOT\%\\Configurations </i> subdirectory
00079 ##    -# Queries the user for the test setup parameters such as test site, test phase, etc.
00080 ##    -# Creates the test configuration files in <i> \%CAL_ROOT\%\\Configurations </i> and
00081 ##       <i> \%CAL_ROOT\%\<Test_Unit>\\Configurations </i> from the template files in
00082 ##       <i> \%CAL_ROOT\%\\setup\\Configurations </i>
00083 ##    -# Runs the calDoc utility to generate the calorimeter API documentation files
00084 ##
00085 ##########################################################################################
00086 
00087 
00088 class latte2latcXML(object):
00089   def __init__(self, configMap, regAttrDef, logLevel = logging.WARN, trace = False):
00090     """
00091     \brief latte2latcXML constructor.
00092 
00093     \param configMap The name of the configuration file mapping LATTE register names to LATC names.
00094     \param regAttrDef The name of the configuration file defining broadcast components and their registers.
00095     \param logLevel Logger level.
00096     \param trace Module execution trace enable flag
00097     """
00098 
00099     self.__map = ConfigParser()
00100     self.__map.read(configMap)
00101     self.__attrDef = ConfigParser()
00102     self.__attrDef.read(regAttrDef)
00103 
00104     self.__currentTCCid = -1
00105     self.__currentTRCid = -1
00106     self.__latteInputType = 'GLAT object'
00107     self.__latteInputFile ='NA'
00108     self.__latteCfgName = ''
00109     self.__latteCfgVersion = ''
00110 
00111     self.__bcastFlag = False
00112     self.__log = logging.getLogger()
00113     self.setLogLevel(logLevel)
00114     self.setTrace(trace)
00115     self.__latcInputType = 'GLATC object'
00116     self.__latcInputFile ='NA'
00117     self.__latcDOM = {}
00118 
00119     self.__convertDate = time.strftime("%a %b %d, %Y %H:%M:%S GMT", time.gmtime())
00120     try:
00121       self.__convertPC = os.environ['COMPUTERNAME']
00122     except:
00123       self.__convertPC = "UNKNOWN"
00124     try:
00125       self.__convertUser = os.environ['USERNAME']
00126     except:
00127       self.__convertUser = "UNKNOWN"
00128 
00129     # masks: allow to mask the snapshot value for LATc
00130     self.__maskDict = {}
00131     for register in self.__attrDef.options('MASKS'):
00132       self.__maskDict[register]=int(self.__attrDef.get('MASKS',register),0)
00133 
00134   def __trace(self,prefix, n = 0):
00135     """
00136     \brief latte2latcXML module execution trace routine.
00137 
00138     \param prefix Execution message prefix string.
00139     \param n Stack level, 0 = top level.
00140     """
00141     if self.__traceFlag:
00142       from traceback import extract_stack
00143       stack = extract_stack()
00144 #      return stack[-n-2][2]
00145       print prefix + stack[-n-2][2]
00146 
00147   def setLogLevel(self, logLevel):
00148     """
00149     \brief logger level setting method.
00150 
00151     \param logLevel Log Level(DEBUG/WARN/INFO...).
00152     """
00153     self.__log.setLevel(logLevel)
00154 
00155   def setTrace(self, state):
00156     """
00157     \brief Module execution trace enable/disable setting.
00158 
00159     \param state Trace state (True/False).
00160     """
00161     self.__traceFlag = state
00162 
00163   def readLatteXML(self, file):
00164     """
00165     \brief LATTE schema/config xml parser (returns LATTE gLat object).
00166 
00167     \param file LATTE schema/config xml file name.
00168     """
00169     file_uri = Uri.OsPathToUri(file, attemptAbsolute=1)
00170     latteDOC = NonvalidatingReader.parseUri(file_uri)
00171 
00172     gLat = self.getGLAT(latteDOC.documentElement)
00173     self.__latteInputType = 'Schema File'
00174     self.__latteInputFile = file
00175     return gLat
00176 
00177   def readLatcXML(self, file):
00178     """
00179     \brief LATC config xml parser (returns gLatc object).
00180 
00181     \param file LATC config xml file name.
00182     """
00183     file_uri = Uri.OsPathToUri(file, attemptAbsolute=1)
00184     latcDOC = NonvalidatingReader.parseUri(file_uri)
00185 
00186     self.__latcInputType = 'broadcast config File'
00187     self.__latcInputFile = file
00188     return latcDOC
00189 
00190   def __seedLists(self):
00191     """! Seed the list of lists, keyed on the broadcast section.
00192          Some lists aren't used for a particular mode of operation
00193     """
00194     aDef = self.__attrDef
00195     cMap = self.__map
00196     self.__lb = {}
00197     self.__lb['BCAST'] = []
00198     self.__bcastSections = cMap.get('SETUP','bcast').split(',')
00199     self.__bcastSections = [ self.__bcastSections[i].strip() for i in range(len(self.__bcastSections)) ]
00200 
00201     self.__nbcastSections = cMap.get('SETUP','nobcast').split(',')
00202     self.__nbcastSections = [ self.__nbcastSections[i].strip() for i in range(len(self.__nbcastSections)) ]
00203 
00204     for section in self.__bcastSections:
00205       lbName = cMap.get('nodes', section)
00206 
00207       # in place strip of register lists
00208       regList = aDef.get(section, 'regList').split(',')
00209       regList = [ regList[i].strip() for i in range(len(regList)) ]
00210       latcRegList = aDef.get(section, 'latcregList').split(',')
00211       #latcRegList = [ latcRegList[i].strip().lower() for i in range(len(latcRegList)) ]
00212       latcRegList = [ latcRegList[i].strip() for i in range(len(latcRegList)) ]
00213 
00214       self.__lb[lbName] = {}
00215       regs = []
00216       for option in cMap.options(section):
00217         #regs.append(cMap.get(section,option).lower())
00218         regs.append(cMap.get(section,option))
00219       self.__lb[lbName]['regs'] = regs
00220       self.__lb[lbName]['stats'] = {}
00221       self.__lb['BCAST'].append(lbName)
00222 
00223     for section in self.__nbcastSections:
00224       lbName = cMap.get('nodes', section)
00225       self.__lb[lbName] = {}
00226       regs = []
00227       for option in cMap.options(section):
00228         #regs.append(cMap.get(section,option).lower())
00229         regs.append(cMap.get(section,option))
00230       self.__lb[lbName]['regs'] = regs
00231       self.__lb[lbName]['stats'] = {}
00232 
00233     self.__lb['SPT'] = {}
00234     self.__lb['SPT']['regs'] = ['low', 'high']
00235     self.__lb['SPT']['stats'] = {}
00236     self.__lb['TDC'] = {}
00237     self.__lb['TDC']['regs'] = ['tfe_dac']
00238     self.__lb['TDC']['stats'] = {}
00239     self.__lb['TFE']['regs'].remove('tfe_dac')
00240     self.__lb['BCAST'].append('SPT')
00241     self.__lb['BCAST'].append('TDC')
00242 
00243     
00244   def computeNodeModes(self, gLatc):
00245     """! \brief Computes broadcast nodes from a starting glatc block
00246     """
00247     self.__trace('entering ')
00248 
00249     self.__seedLists()
00250     for child in self.__getChildNodes(gLatc):
00251       self.__buildNodeStats(child)
00252 
00253     for key in self.__lb.keys():
00254       if key == 'BCAST': continue
00255       maxRate = 0
00256       maxSettings = None
00257       total = 0
00258       for settings,rate in self.__lb[key]['stats'].items():
00259         total += rate
00260         if rate > maxRate:
00261           maxRate = rate
00262           maxSettings = settings
00263       if key == 'SPT':  # special logic for broadcasting Splits
00264         maxLow = 0
00265         maxHigh = 0
00266         lowSet = None
00267         hiSet  = None
00268         lowSpot = self.__lb[key]['regs'].index('low')
00269         hiSpot  = self.__lb[key]['regs'].index('high')
00270         for settings, rate in self.__lb[key]['stats'].items():
00271           if rate > maxLow and settings[lowSpot] is not None:
00272             maxLow = rate
00273             lowSet = settings[lowSpot]
00274           if rate > maxHigh and settings[hiSpot] is not None:
00275             maxHigh = rate
00276             hiSet   = settings[hiSpot]
00277         maxSettings = (lowSet, hiSet)
00278 
00279       self.__lb[key]['max'] = maxSettings
00280 
00281 
00282   def __buildNodeStats(self, node, indent=""):
00283     nodeInBcast = node.nodeName.upper() in self.__lb.keys()
00284     if nodeInBcast:
00285       nodeSettings = []
00286       regs   = self.__lb[node.nodeName.upper()]['regs']
00287       stats  = self.__lb[node.nodeName.upper()]['stats']
00288       for reg in regs:
00289         nodeSettings.append(None)
00290 
00291     for child in self.__getChildNodes(node):
00292       self.__buildNodeStats(child, indent+"  ")
00293       if nodeInBcast:
00294         try:
00295           cDataNode = self.__getChildNodes(child)[0]
00296           if cDataNode.nodeType == Node.TEXT_NODE:
00297             nodeSettings[regs.index(child.nodeName)] = self.__getChildNodes(child)[0].data
00298         except:
00299           print child.nodeName, self.__getChildNodes(child)
00300           print regs
00301           raise
00302 
00303     if nodeInBcast:
00304       tns = tuple(nodeSettings)  # needs to be hashable
00305       if tns in stats.keys():
00306         stats[tns] += 1
00307       else:
00308         stats[tns]  = 1
00309 
00310   def buildLatcBcast(self):
00311     latcDOM = self.getLatcDOM('bcast')
00312 
00313     self.addBcastNode(latcDOM, latcDOM.documentElement, LATC_BCAST_DICT)
00314     # fiddle with the node to get AOC right
00315     latcDOM = self.convertAOCNode(latcDOM)
00316     return latcDOM
00317 
00318   def convertAOCNode(self,bcastNode):
00319     # move GEM.AOC.periodic_rate to GEM.periodic_rate
00320     # move GEM.AOC.configuration to GEM.configuration
00321     # move GEM.WIN.window_open_mask to GEM.AOC.window_open_mask
00322     womNode = None
00323     for c1 in self.__getChildNodes(bcastNode):
00324       for c2 in self.__getChildNodes(c1):
00325         if c2.nodeName=='GEM':
00326           for c3 in self.__getChildNodes(c2):
00327             if c3.nodeName=='WIN':
00328               for c4 in self.__getChildNodes(c3):
00329                 print "WIN node:",c4.nodeName
00330                 if c4.nodeName=='window_open_mask':
00331                   womNode = c4
00332                   c3.removeChild(c4)
00333           for c3 in self.__getChildNodes(c2):
00334             if c3.nodeName=='AOC':
00335               for c4 in self.__getChildNodes(c3):
00336                 if c4.nodeName=='periodic_rate' or c4.nodeName=='configuration':
00337                   c3.removeChild(c4)
00338                   c2.appendChild(c4)
00339               if womNode is not None:
00340                 c3.appendChild(womNode)
00341     return bcastNode
00342     
00343   def addBcastNode( self, doc, parent, nodeDict):
00344     nodeList = nodeDict.items()
00345 
00346     for n in nodeList:
00347       nodeName = n[0]
00348       node = createElement(doc,nodeName)
00349       nodeInBcast = node.nodeName.upper() in self.__lb['BCAST']
00350 
00351       if nodeInBcast and nodeName <> 'TDC':
00352         setAttribute(node, 'ID', 'BCAST')
00353       newNode = parent.appendChild(node)
00354       lbNode = self.__lb[nodeName]
00355       for i in range(len(lbNode['regs'])):
00356         childNodeName = lbNode['regs'][i]
00357         childNodeValue = lbNode['max'][i]
00358         childNode = createElement(doc, childNodeName)
00359         try:
00360           childNode.appendChild(doc.createTextNode(childNodeValue))
00361         except:
00362           print childNodeValue, type(childNodeValue), childNode
00363           raise
00364         newNode.appendChild(childNode)
00365       newNodeDict = n[1]
00366       # print newNodeDict
00367       if newNodeDict is not None:
00368         self.addBcastNode(doc, newNode, newNodeDict)
00369         pass
00370 
00371   def purgeBcast(self, gLatcRaw, gLatcBcast):
00372 
00373     raw = gLatcRaw.documentElement
00374     bcast = gLatcBcast.documentElement
00375 
00376     self.purgeBcastNodes( raw, bcast)
00377 
00378     return gLatcRaw
00379 
00380   def purgeBcastNodes(self, raw, bcast):
00381 
00382     for childRaw in self.__getChildNodes(raw):
00383       childBcast = self.__findBcastChild(childRaw.nodeName, bcast)
00384       if childRaw.nodeName.upper() in self.__lb.keys():
00385         self.purgeBcastNodes( childRaw, childBcast)
00386         #print childBcast, childRaw, self.__isNodeContentsBcast(childRaw, childBcast)
00387         if self.__isNodeContentsBcast(childRaw, childBcast):
00388           # print 'Removing', childRaw
00389           self.__killDataChildren(childRaw)
00390 
00391   def __findBcastChild(self, name, bcastNode):
00392     for child in self.__getChildNodes(bcastNode):
00393       if child.nodeName.lower() == name.lower():
00394         return child
00395     return None
00396 
00397   def __isNodeContentsBcast(self, node, bcast):
00398     allChildren = True
00399     for child in self.__getChildNodes(node):
00400       bcastChild = self.__findBcastChild(child.nodeName,bcast)
00401       if bcastChild is not None and len(self.__getChildNodes(child)) > 0:
00402         try:
00403           cDataNode = self.__getChildNodes(child)[0]
00404           cbcDataNode = self.__getChildNodes(bcastChild)[0]
00405         except:
00406           print child
00407           raise
00408         if cDataNode.nodeType == Node.TEXT_NODE:
00409           if not cDataNode.data == cbcDataNode.data:
00410             allChildren = False
00411       else:
00412         print "\nfound no bcast:", node, bcast, child, len(self.__getChildNodes(child))
00413         allChildren = False
00414     return allChildren
00415 
00416   def __killDataChildren(self, node):
00417     for child in self.__getChildNodes(node):
00418       cDataNode = self.__getChildNodes(child)[0]
00419       if cDataNode.nodeType == Node.TEXT_NODE:
00420         node.removeChild(child)
00421     if not(node.hasChildNodes()):
00422       par = node.parentNode
00423       par.removeChild(node)
00424 
00425 
00426   def writeLatcXML(self, id, file = 'latc.xml',path=None):
00427     """
00428     \brief Write a LATC .xml file given a LATC document in miniDOM format.
00429 
00430     \param latcDOM LATC document in miniDOM format
00431     \param file LATC .xml output file name or open file object.
00432     """
00433     # special modifications to LATc from snapshot values
00434     doc = self.__latcDOM[id].documentElement
00435     # LHM convert the TDC.tfe_dac to fields
00436     self.convertTfeDacToFields(doc,self.__latcDOM[id])
00437     
00438     if type(file) == str:
00439       fileName = file
00440       if path is not None:
00441         fileName = os.path.join(path,file)
00442       f = open(fileName, 'w')
00443     else:              # already opened file
00444       f = file
00445     f.write('<?xml version="1.0" ?>\n')
00446     PrettyPrint(doc,f)
00447 
00448     if id=='bcast':
00449       # need to revert to the original form...
00450       self.convertTfeFieldsToDac(doc,self.__latcDOM[id])
00451       
00452   def convertTfeDacToFields(self,node,doc):
00453     if str(node.nodeName)=='tfe_dac':
00454       # if child is text element (no fields) remove it and add fields
00455       children = self.__getChildNodes(node)
00456       if len(children)==1 and children[0].nodeType == Node.TEXT_NODE:
00457         child=children[0]
00458         value = self.intValue(str(child.nodeValue))
00459         # take the value and fieldify it. Fields are 'threshold' and 'injection'
00460         # calibration is bits 13-7, threshold is 6-0
00461         threshold=0x0
00462         calibration=0x0
00463         for bit in range(7):
00464           calShift = 13-bit
00465           thrShift = 6-bit
00466           if value&(0x1<<calShift):
00467             calibration |= 0x1<<bit
00468           if value&(0x1<<thrShift):
00469             threshold   |= 0x1<<bit          
00470             #print "threshold, calibration:",hex(value),threshold,calibration
00471         node.removeChild(child)
00472         thrNode = createElement(doc, 'threshold')
00473         thrNode.appendChild(doc.createTextNode("0x%x"%(threshold)))
00474         calNode = createElement(doc, 'injection')
00475         calNode.appendChild(doc.createTextNode("0x%x"%(calibration)))
00476         node.appendChild(thrNode)
00477         node.appendChild(calNode)
00478     else:
00479       for child in self.__getChildNodes(node):
00480         self.convertTfeDacToFields(child,doc)
00481         
00482   def convertTfeFieldsToDac(self,node,doc):
00483     if str(node.nodeName)=='tfe_dac':
00484       # if child is text element (no fields) remove it and add fields
00485       children = self.__getChildNodes(node)
00486       if len(children)==2: # we have threshold and injection
00487         payload = 0x0
00488         for child in children:
00489           value = self.intValue(str(self.__getChildNodes(child)[0].data))
00490           if str(child.nodeName)=='threshold':
00491             offset=0
00492             value1=value
00493           elif str(child.nodeName)=='injection':
00494             offset=7
00495             value2=value
00496           else:
00497             raise
00498           node.removeChild(child)
00499           for bit in range(7):
00500             if value&(0x1<<bit):
00501               payloadbit=(6-bit)+offset
00502               payload|=0x1<<payloadbit
00503         node.appendChild(doc.createTextNode("0x%x"%(payload)))
00504         #print "reconverting, ",value1,value2,payload
00505     else:
00506       for child in self.__getChildNodes(node):
00507         self.convertTfeFieldsToDac(child,doc)
00508         
00509   # returns an integer value from a string
00510   def intValue(self,strValue):
00511     # quick helper function to deal with hex literals
00512     # first see if it seems to be a reasonable format.
00513     if type(strValue)==type(0): # it's already an integer
00514       return strValue
00515     strValue = strValue.strip().lower()
00516     intPattern = re.compile('^(0x)?[0-9,a-f]+$')
00517     intMatch = intPattern.search(strValue)
00518     if intMatch:
00519       if strValue[0:2]=='0x':
00520         intValue = int(strValue,16)
00521       else:
00522         intValue = int(strValue)
00523       return intValue
00524 
00525   def getLatcDOM(self, id='base'):
00526     """!\brief Return the DOM corresponding to \a id creating it if necessary.
00527 
00528     \param id The id that identifies the LATc DOM
00529 
00530     \return LATc DOM
00531     """
00532     if id in self.__latcDOM:
00533       return self.__latcDOM[id]
00534     else:
00535       latcDOM = implementation.createDocument(None,None,None)
00536       docElem = createElement(latcDOM,"LATC_XML")
00537       setAttribute(docElem, 'convertDate',self.__convertDate)
00538       setAttribute(docElem, 'convertUser',self.__convertUser)
00539       setAttribute(docElem, 'convertPC',self.__convertPC)
00540       setAttribute(docElem, 'latteInputType',self.__latteInputType)
00541       setAttribute(docElem, 'latteInputFile',self.__latteInputFile)
00542       setAttribute(docElem, 'latteCfgName',self.__latteCfgName)
00543       setAttribute(docElem, 'latteCfgVersion',self.__latteCfgVersion)
00544       latcDOM.appendChild(docElem)
00545       self.__latcDOM[id] = latcDOM
00546       return latcDOM
00547 
00548 
00549   def makeLatcDOC(self, gLat, gLatDict = None, bcastFlag = False):
00550     """
00551     \brief Generate a LATC .xml formatted document inMemory.
00552 
00553     \param gLat gLat document object.
00554     \param gLatDict Dictionary of LATTE to LATC register mappings.
00555     \param bcastFlag Flag indicating whether to check for BCast settings for appropriate components and registers
00556     """
00557     # Pull sections out of the map:
00558     if gLatDict is None:
00559       gLatItems = self.__map.items('nodes')
00560       gLatDict = {}
00561       for ( lat, latc ) in gLatItems:
00562         gLatDict[lat.upper()] = latc
00563     latcDOM = self.getLatcDOM()
00564 
00565     for n in self.__getChildNodes(gLat):
00566       if n.tagName.upper() in gLatDict:
00567         self.__addChildren(latcDOM, n, latcDOM.documentElement, gLatDict, bcastFlag)
00568 
00569     return latcDOM
00570 
00571   def __addChildren( self, doc, gLatNode, latcNode, gLatDict, bcastFlag):
00572     """
00573     \brief Generate a LATC .xml formatted document inMemory.
00574 
00575     \param doc doc LATC document object.
00576     \param gLatNode Current gLat node object.
00577     \param latcNode Current LATC node object.
00578     \param gLatDict Dictionary of LATTE to LATC register mappings.
00579     \param bcastFlag Flag indicating whether to check for BCast settings for appropriate components and registers
00580     """
00581     newNode = latcNode
00582     #Check for gLat node to LATC conversion candidate
00583     if gLatNode.tagName.upper() in gLatDict:
00584       #generate new LATC node from gLat node
00585       newNode = createElement(doc, gLatDict[gLatNode.tagName.upper()])
00586       if gLatNode.attributes is not None:
00587         #Copy node attributes
00588         for i in range(len(gLatNode.attributes)):
00589           cNode = cloneAttrNode(doc,gLatNode.attributes.values()[i])
00590           #cNode = gLatNode.attributes.values()[i].cloneNode(True)
00591           #if GTCC node, save ID for SPT node generation
00592           if gLatNode.tagName.upper() == 'GTCC' and cNode.nodeName == 'ID':
00593             try:
00594               self.__currentTCCid = int(cNode.nodeValue)
00595             except:
00596               #set BCAST identifier
00597               self.__currentTCCid = 8
00598           #if GTRC node, save ID for SPT node generation
00599           if gLatNode.tagName.upper() == 'GTRC' and cNode.nodeName == 'ID':
00600             try:
00601               self.__currentTRCid = int(cNode.nodeValue)
00602             except:
00603               #set BCAST identifier
00604               self.__currentTRCid = 24
00605           setAttributeNode(newNode, cNode)
00606       newNode = latcNode.appendChild(newNode)
00607     #acquire appropriate gLat to LATC register mapping dictionary for current component
00608     localDict = gLatDict
00609     if gLatNode.tagName.upper() in self.__map.sections():
00610       localDict = {}
00611       localItems = self.__map.items(gLatNode.tagName)
00612       for ( lat, latc ) in localItems:
00613         localDict[lat.upper()] = latc
00614 
00615     #select BCAST data for this component if appropriate
00616     if bcastFlag and gLatNode.tagName in self.__bcastSections:
00617       bcastSection = gLatNode.tagName
00618     else:
00619       bcastSection = None
00620     #If GTRC node, perform special processing (SPT node generation, etc).
00621     if gLatNode.tagName.upper() == 'GTRC':
00622       self.__handleGTRCnode(doc, gLatNode, latcNode.parentNode, newNode, gLatDict, localDict, bcastFlag, bcastSection)
00623     else:
00624       #process child nodes
00625       for n in self.__getChildNodes(gLatNode):
00626         cNodes = self.__getChildNodes(n)
00627         #Determine if child node is a register setting or another element to decompose
00628         if len(cNodes) == 1 and cNodes[0].nodeType == Node.TEXT_NODE:
00629           #register setting
00630           #For GTFE DAC registers, create psuedo GTDC childnode and put DAC register under it
00631           if gLatNode.tagName.upper() == 'GTFE' and n.tagName.upper() == 'DAC':
00632             tdcNode = createElement(doc, 'TDC')
00633             tdcNode = newNode.appendChild(tdcNode)
00634             self.__addNode(doc, n,tdcNode,localDict,bcastSection)
00635           else:
00636             self.__addNode(doc, n,newNode,localDict,bcastSection)
00637           pass
00638         else:
00639           #decompose element
00640           self.__addChildren(doc, n, newNode, gLatDict,bcastFlag)
00641     
00642   def __handleGTRCnode(self, doc, gLatNode, platcNode, latcNode, gLatDict, localDict, bcastFlag, bcastSection):
00643     """
00644     \brief Generate a LATC .xml formatted document inMemory.
00645 
00646     \param doc doc LATC document object.
00647     \param gLatNode Current gLat node object.
00648     \param latcNode Current LATC node object.
00649     \param gLatDict Dictionary of LATTE to LATC register mappings.
00650     \param bcastFlag Flag indicating whether to check for BCast settings for appropriate components and registers
00651     """
00652     #get GTFE count for this GTRC (controller) by looking at CSR register field
00653     for n in self.__getChildNodes(gLatNode):
00654       if n.tagName.upper() == 'CSR':
00655         csr = long(self.__getChildNodes(n)[0].nodeValue,16)
00656         feCount = (csr >> 7) & 0x1f
00657     #create pseudo component SPT
00658     # if one already exists, use it
00659     # need the node's ID
00660     if self.__currentTCCid < 8:
00661       sptId = '%s%d' %(tccSide[self.__currentTCCid],self.__currentTRCid)
00662     else:
00663       sptId = 'BCAST'
00664     newNode = self.findSptChild(platcNode,sptId)
00665     if newNode is None:
00666       newNode = createElement(doc, 'SPT')
00667       cNode = cloneAttrNode(doc,gLatNode.attributes.values()[0])
00668       #cNode = gLatNode.attributes.values()[0].cloneNode(True)
00669       #set SPT node's ID
00670       cNode.value = sptId
00671       setAttributeNode(newNode, cNode)
00672       #newNode = platcNode.appendChild(newNode)
00673       platcNode.appendChild(newNode)
00674     #Check whether Hi FE controller (note BCAST GTRC can specify both)
00675     if 'hi' in tccDirection[self.__currentTCCid]:
00676       #add 'hi" pseudo register to SPT pseudo component
00677       deafNode = createElement(doc, 'high')
00678       deafValue = '%d' %(24-feCount)
00679       sptRange = range(24-feCount,24)
00680       deafNode.appendChild(doc.createTextNode(deafValue))
00681       newNode.appendChild(deafNode)
00682     #Check whether Lo FE controller (note BCAST GTRC can specify both)
00683     if 'lo' in tccDirection[self.__currentTCCid]:
00684       #add 'lo" pseudo register to SPT pseudo component
00685       deafNode = createElement(doc, 'low')
00686       # workaround for LATC_parser not understanding minus signs.
00687       if feCount>0:
00688         deafValue = '%d' %(feCount-1)
00689       else:
00690         deafValue = '0xffff'
00691       sptRange = range(feCount)
00692       deafNode.appendChild(doc.createTextNode(deafValue))
00693       newNode.appendChild(deafNode)
00694 
00695     #process GTFE and its child nodes under SPT Node
00696     for n in self.__getChildNodes(gLatNode):
00697       cNodes = self.__getChildNodes(n)
00698       if len(cNodes) == 1 and cNodes[0].nodeType == Node.TEXT_NODE:
00699         self.__addNode(doc, n,latcNode,localDict, bcastSection)
00700       else:
00701         if n.attributes is not None:
00702           for i in range(len(n.attributes)):
00703             if n.attributes.values()[i].nodeName == 'ID':
00704               try:
00705                 if n.attributes.values()[i].nodeValue == 'BCAST' or int(n.attributes.values()[i].nodeValue) in sptRange:
00706                   self.__addChildren(doc, n, newNode, gLatDict, bcastFlag)
00707                 else:
00708                   pass
00709               except:
00710                 pass
00711 
00712   def findSptChild(self,pNode,sptId):
00713     for child in self.__getChildNodes(pNode):
00714       if child.tagName.upper() == 'SPT':
00715         if hasAttribute(child, 'ID') and getAttribute(child, 'ID') == sptId:
00716           return child
00717   
00718   def __addNode(self, doc, gLatNode, latcNode, localDict, bcastSection = None):
00719     """
00720     \brief Generate a LATC .xml formatted document inMemory.
00721 
00722     \param doc doc LATC document object.
00723     \param gLatNode Current gLat node object.
00724     \param latcNode Current LATC node object.
00725     \param localDict Dictionary of LATTE to LATC register mappings for current component.
00726     \param bcastSection BCAST data for this component (None if not a BCAST component)
00727     """
00728     tag = gLatNode.tagName.upper()
00729     cNode = self.__getChildNodes(gLatNode)[0]
00730     if tag in localDict:
00731       #If BCAST register and setting equals BCAST value then skip delta setting node
00732       newNode = createElement(doc, localDict[tag])
00733       newValue = cNode.nodeValue
00734       if localDict[tag] in self.__maskDict:
00735         oldValue = newValue
00736         newValue = int(newValue,0)&self.__maskDict[localDict[tag]]
00737         newValue = "0x%x"%(newValue)
00738       # LHM special change CRC.config to 0xa500
00739       # LHM removed this for now
00740       #if tag=='CONFIG':
00741       if False:
00742         newValue = self.intValue(newValue) | 0xa500
00743         newValue = "0x%x"%(newValue)
00744       newText = doc.createTextNode(newValue)
00745       newNode.appendChild(newText)
00746       latcNode.appendChild(newNode)
00747 
00748   def getGLAT(self, node):
00749     """
00750     \brief get start of gLat node pointer from inMemory .xml document.
00751 
00752     \param node gLat node pointer.
00753     """
00754     gLat = None
00755     for n in self.__getChildNodes(node):
00756       if n.tagName.upper() == 'GLAT':
00757         gLat = n
00758       #
00759       if n.tagName.upper() == 'CONFIGURATION':
00760         if n.attributes is not None:
00761           for i in range(len(n.attributes)):
00762             cNode = n.attributes.values()[i]
00763             if  cNode.nodeName.upper() == 'NAME':
00764               self.__latteCfgName = cNode.nodeValue
00765             if  cNode.nodeName.upper() == 'VERSION':
00766               self.__latteCfgVersion = cNode.nodeValue
00767     self.__latteInputType = 'Schema Object'
00768     return gLat
00769 
00770   def getLATC(self, node):
00771     """!\brief get start of LATC hierarchy from in memory .xml
00772     """
00773     return node.documentElement
00774 
00775 
00776   def __getChildNodes(self, node):
00777     """
00778     \brief get list of child node pointers.
00779 
00780     \param node parent node.
00781     """
00782     childNodes = []
00783     try:
00784       for n in node.childNodes:
00785         if (n.nodeType == Node.TEXT_NODE and \
00786            (n.data[0] == '\n' or n.data[0].strip() == '')) \
00787           or n.nodeType == Node.COMMENT_NODE:
00788           pass
00789         else:
00790           childNodes.append(n)
00791     except:
00792       pass
00793     return childNodes
00794 
00795   def splitLatcXML(self, latcDOM):
00796     """!\brief Given a LATc DOM split it into multiple DOMs.
00797 
00798     The split is based on the nodes which have declared registers.
00799     When the split is made the hierarchy of each split node is preserved.
00800 
00801     \param latcDOM LATc DOM that will be split
00802     """
00803     for child in self.__getChildNodes(latcDOM):
00804       if child.nodeType == Node.ELEMENT_NODE:
00805         if child.tagName in self.__lb:
00806           if not self.isEmptyNode(child):
00807             branch = self.calculateBranch(child)
00808             self.addSplitNode(child, branch)
00809         self.splitLatcXML(child)
00810 
00811   def isEmptyNode(self, node):
00812     """!\brief Check if there are any registers declared under \a node
00813 
00814     \param node Node that is being checked
00815 
00816     \return True if the node does not declare any registers, False otherwise
00817     """
00818     childTagNames = [str(child.tagName) for child in self.__getChildNodes(node)]
00819     for childTagName in childTagNames:
00820       if childTagName in self.__lb[str(node.tagName)]['regs']:
00821         return False
00822     return True
00823 
00824   def addSplitNode(self, splitNode, branch):
00825     """!\brief Adds a copy of \a splitNode and its registers,
00826                creating the parents listed in \a branch if necessary.
00827 
00828     \param splitNode
00829     \param branch    List of parent nodes that need to exist before adding
00830                      a copy of \a splitNode
00831     """
00832     splitDom = self.getLatcDOM(str(splitNode.tagName))
00833     xNode = splitDom.documentElement
00834     for pNode in branch:
00835       spNode = self.findNode(pNode, xNode)
00836       if spNode is not None:
00837         xNode = spNode
00838       else:
00839         node = createElement(splitDom, pNode.tagName)
00840         setAttribute(node, 'ID', str(getAttribute(pNode, 'ID')))
00841         newNode = xNode.appendChild(node)
00842         xNode = newNode
00843     node = createElement(splitDom, splitNode.tagName)
00844     if node.tagName <> 'TDC':
00845       setAttribute(node, 'ID', str(getAttribute(splitNode, 'ID')))
00846     xNode.appendChild(node)
00847     for child in self.__getChildNodes(splitNode):
00848       tagName = str(child.tagName)
00849       if tagName in self.__lb[str(splitNode.tagName)]['regs']:
00850         cNode = createElement(splitDom, tagName)
00851         node.appendChild(cNode)
00852         cNode.appendChild(splitDom.createTextNode(child.firstChild.data))
00853     #PrettyPrint(splitDom, sys.stdout)
00854 
00855   def findNode(self, node, xNode):
00856     """!\brief Find a LATc node based on its tagName and ID attribute value.
00857 
00858     Go through the children of \a xNode and find if any of them matches
00859     the tagname and the ID attribute of \a node
00860 
00861     \param node Node to be matched
00862     \param xNode Parent node of the children searched
00863 
00864     \return Matching child node or None if not found
00865     """
00866     for child in self.__getChildNodes(xNode):
00867       if child.tagName == node.tagName:
00868         if hasAttribute(child, 'ID') and getAttribute(child, 'ID') == getAttribute(node, 'ID'):
00869           return child
00870     return None
00871 
00872   def calculateBranch(self, node):
00873     """!\brief Calculate a list of parents leading to \a node in the DOM tree.
00874 
00875     Go through the parents of \a node and construct the branch in the form
00876     of a list (not including \a node itself).
00877 
00878     \param node Node whose parent list is being requested
00879 
00880     \return A list of parents along the branch leading to \a node
00881     """
00882     branch = []
00883     while node.parentNode.tagName != 'LATC_XML':
00884       branch = [node.parentNode] + branch
00885       node = node.parentNode
00886     return branch
00887 
00888   def getDomList(self):
00889     """!\brief Return a list of DOMs created during processing.
00890 
00891     \return List of DOM ids
00892     """
00893     return self.__latcDOM.keys()
00894 
00895 
00896 def getAttribute(node, attr):
00897   return node.getAttributeNS(LAT_NAMESPACE, attr)
00898 
00899 def hasAttribute(node, attr):
00900   return node.hasAttributeNS(LAT_NAMESPACE, attr)
00901 
00902 def setAttribute(node, attr, value):
00903   return node.setAttributeNS(LAT_NAMESPACE, attr, value)
00904 
00905 def setAttributeNode(node, attr):
00906   return node.setAttributeNodeNS(attr)
00907 
00908 def cloneAttrNode(node,attrNode):
00909   cNode = node.createAttributeNS(LAT_NAMESPACE,attrNode.nodeName)
00910   #print dir(cNode)
00911   #cNode.setValue(attrNode.nodeValue)
00912   #cNode.appendChild(node.createTextNode(attrNode.nodeValue))
00913   cNode.nodeValue = attrNode.nodeValue
00914   return cNode
00915 
00916 def createElement(node, elem):
00917   return node.createElementNS(LAT_NAMESPACE, elem)
00918 
00919 def appendChild(node, elem):
00920   return node.appendChildNS(LAT_NAMESPACE, elem)
00921 
00922 def usage(msg):
00923   print """
00924 Error %s
00925 Usage:  python latte2latcXML.py --i <input snapshot> --o <output stub> [--b <bcast override>] [--s]
00926 """ % msg
00927 
00928 
00929 if __name__ == '__main__':
00930 
00931   forceBcast = False
00932   logging.basicConfig()
00933   options = gOptions.Options(['i','o'],['b'],['s'])
00934   try:
00935     options.parse()
00936   except Exception, msg:
00937     usage(msg)
00938     sys.exit()
00939 
00940   latteXML     = options.i
00941   #latcXML      = options.o
00942   # try splitting a root directory off the output
00943   (latcXMLdir,latcXML) = os.path.split(options.o)
00944   if latcXMLdir == '':
00945     latcXMLdir = None
00946   if options.b is not None:
00947     forceBcast = True
00948     bcastLatcXML = options.b
00949   else:
00950     bcastLatcXML = "bcast_"+latcXML
00951 
00952   configMap = LATTE2LATC_CONFIG
00953   regAttrDef = LATCREGATTR_CONFIG
00954 
00955   # print "reading LATTE xml"
00956   converter = latte2latcXML(configMap,regAttrDef)
00957   gLat = converter.readLatteXML(latteXML)
00958 
00959   gLatcRaw = converter.makeLatcDOC(gLat,bcastFlag=False)
00960 
00961   converter.computeNodeModes(converter.getLATC(gLatcRaw))
00962 
00963   if forceBcast:
00964     bcast = converter.readLatcXML(bcastLatcXML)
00965   else:
00966     bcast = converter.buildLatcBcast()
00967     if latcXMLdir is not None:
00968       bcastLatcXML = os.path.join(latcXMLdir,bcastLatcXML)
00969     bcastLatcXML = open(bcastLatcXML, 'w')
00970     converter.writeLatcXML(id='bcast', file=bcastLatcXML, path = latcXMLdir)
00971     bcastLatcXML.close()
00972     
00973   purged = converter.purgeBcast(gLatcRaw, bcast)
00974 
00975 #  gLatcRaw = converter.readXML('x.xml')
00976 #  converter._latte2latcXML__latcDOM['base'] = gLatcRaw
00977 
00978 #  converter._latte2latcXML__seedLists()
00979 
00980   if options.s is not None:
00981     converter.splitLatcXML(gLatcRaw.documentElement)
00982     for domId in converter.getDomList():
00983       if domId not in ('bcast','base','AOC','WIN'):
00984         (fname, ext) = os.path.splitext(latcXML)
00985         converter.writeLatcXML(domId, "%s_%s%s" % (fname, domId, ext), path=latcXMLdir)
00986   else:
00987     converter.writeLatcXML(id='base', file=latcXML, path=latcXMLdir)
00988 

Generated on Thu Apr 27 20:52:42 2006 for LICOS L02-01-00 by doxygen 1.4.6-NO