CMS 3D CMS Logo

/afs/cern.ch/work/a/aaltunda/public/www/CMSSW_6_2_5/src/Geometry/TrackerCommonData/data/Materials/twikiExport.py

Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 
00003 import optparse
00004 import ConfigParser
00005 
00006 class Constituent:
00007     def __init__(self, line, predefinedMaterials):
00008         if  len(line.split('"')) < 5 or len(line.split('"')[4].split()) < 3:
00009             raise StandardError , "not a well formed Constituent: "+constString
00010         self.theDescription = line.split('"')[1]
00011         self.theName = line.split('"')[3]
00012         self.theCount = float(line.split('"')[4].split()[1])
00013         self.theVolume = float(line.split('"')[4].split()[0]) * self.theCount
00014         self.theType = line.split('"')[4].split()[2]
00015         self.theDensity = float(predefinedMaterials[self.theName][2])
00016         self.theX0 = float(predefinedMaterials[self.theName][3]) * self.theDensity
00017         self.theL0 = float(predefinedMaterials[self.theName][4]) * self.theDensity
00018         self.theMass = self.theVolume * self.theDensity
00019 #        print "%s\tX0: %.3f\trho: %.3f\tX0': %.3f"%(self.theName, float(predefinedMaterials[self.theName][3]), float(predefinedMaterials[self.theName][2]), self.theX0)        
00020     def __str__(self):
00021         return "Name: "+self.theName+" desc: "+self.theDescription+" mass "+self.theMass+" type "+self.theType+" count "+self.theCount
00022         
00023 class Material:
00024     def __init__(self, matString, comment):
00025         if matString == "" or not matString[0] == "#":
00026             raise StandardError , "not a valid material Definition: "+matString
00027         line = matString[1:]
00028 
00029         if    len( line.split('"') ) < 5 or len( line.split('"')[4].split() ) < 2:
00030             raise StandardError , "not a well formed Material Definition: "+matString            
00031         self.theDescription = line.split('"')[1]
00032         self.theName = line.split('"')[3]
00033         self.theMcVolume = float(line.split('"')[4].split()[0])
00034         self.theComment = comment
00035         self.theConstituents = []
00036     
00037     def getRealValues(self):
00038         result = {}
00039         result["Volume"] = 0
00040         result["X0"] = 0
00041         result["L0"] = 0
00042         
00043         totMass =  self.getMass()
00044         invX0 = 0
00045         invL0 = 0
00046         for con in self.theConstituents:
00047             pWeight = con.theVolume * con.theDensity / totMass
00048             invX0 += pWeight / con.theX0
00049             invL0 += pWeight / con.theL0
00050             result["Volume"] += con.theVolume 
00051         result["Density"] = self.getMass() / result["Volume"]            
00052         result["X0"] = 1 / ( invX0 * result["Density"] )
00053         result["L0"] = 1 / ( invL0 * result["Density"] )
00054         
00055         return result
00056     
00057     def getSimValues(self):
00058         result = self.getRealValues()
00059         fraction = self.theMcVolume / result["Volume"]
00060         result["Volume"] = self.theMcVolume
00061         result["Density"] = self.getMass() / self.theMcVolume
00062         result["X0"] *= fraction
00063         result["L0"] *= fraction
00064     
00065         return result
00066    
00067     def getMass(self):
00068         result = 0
00069         for con in self.theConstituents:
00070             result += con.theMass * con.theCount
00071         return result
00072         
00073     def addConstituent(self, constString, predefinedMaterials):
00074         if constString  == "" or not constString[0] == "*":
00075             raise StandardError , "not a valid Constituent: "+constString
00076         line = constString[1:]
00077         self.theConstituents.append( Constituent(line, predefinedMaterials) )
00078 
00079         number = int( line.split('"')[0].split()[0] )
00080         if not len(self.theConstituents) == number:
00081             raise StandardError, "Constituent Number mismatch for "+str(len(self.theConstituents))+" in: "+line
00082     
00083     def __str__(self):
00084         result = "[ "+self.theName+" Description: "+self.theDescription+" MC-Volume:"+str(self.theMcVolume)+"\n"
00085         result += "Comments:\n"+self.theComment
00086         return result
00087 
00088 #parses the .in File
00089 def parseInFile(inFile, predefinedMaterials, config):
00090     comment = ""
00091     materials = []
00092     i = 0
00093     for line in inFile.split("\n"):
00094         i=i+1
00095         if i < int(config["parsing"]["intro"]):
00096             continue
00097         if not line == "" and line[0] == "#":
00098             material = Material( line , comment )
00099             if not material.theName == "END":
00100                 materials.append( material )
00101             comment = ""
00102 
00103             #print "Name: "+name+" Description: "+description+" mcVolume: "+str(mcVolume)
00104         elif not line == "" and line[0] == "*":
00105             
00106                 materials[-1].addConstituent(line, predefinedMaterials)
00107         else:
00108             ignore = False
00109             for char in config["parsing"]["ignorelines"]:
00110                 if len(line.strip()) == line.strip().count(char) and not len(line) == 0:
00111                     ignore = True
00112             if not ignore:
00113                 comment += line+"\n"
00114     return materials
00115 
00116 def parseComment(comment):
00117     result = ""
00118     if comment.find("<twiki>") >= 0:
00119         result = comment.split("twiki>")[1][:-2]
00120     else:
00121         result += "<verbatim>\n"
00122         result += comment
00123         result += "</verbatim>\n"        
00124     return result
00125 
00126 def getTwiki(materials,config):
00127     result = config["twiki"]["pagename"]+"\n"
00128     result += "%TOC%\n\n"
00129     for mat in materials:
00130         result += config["twiki"]["heading"]+mat.theName+"\n"
00131         result += "short Description: *"+mat.theDescription+"* <br>\n"
00132         result += "Mass: %.3fg\n" % mat.getMass()
00133         result += config["twiki"]["tableformat"]+'\n'
00134         result += "| ** | *Volume* | *Density* |  *X<sub>0</sub>* | *&lambda;<sub>0</sub>* |\n"
00135         result += "| ** | *cms<sup>3</sup>* | *g cm<sup>-3</sup>* |  *cm* | *cm* |\n"
00136         result +=  "| Real | %(Volume).3f | %(Density).3f | %(X0).3f | %(L0).3f |\n" % mat.getRealValues()
00137         result +=  "| Simulation | %(Volume).3f | %(Density).3f | %(X0).3f | %(L0).3f |\n" % mat.getSimValues()
00138         result += "\n"+config["twiki"]["subheading"]+"Comments\n"
00139         result += parseComment(mat.theComment)
00140         result += "\n---+++!!Material\n"
00141         result += config["twiki"]["tableformat"]+'\n'
00142         result += "  | *Description* | *Material Name* | *Volume* | *Mass* | *Count* | *Type* | *X<sub>0</sub>* | *&lambda;<sub>0</sub>* |\n"
00143         result += '  | ** | ** | *cm<sup>3</sup>* | *g* | ** | ** | *g cm<sup>-2</sup>* | *g cm<sup>-2</sup>* |\n'
00144         for const in mat.theConstituents:
00145             result += "  | =%s= | =%s= | %.2e | %.2e | %.2f | %s | %.2f | %.2f |\n" % ( const.theDescription , const.theName , const.theVolume , const.theMass , const.theCount , const.theType , const.theX0 , const.theL0 )
00146 #            result += "  | ="+const.theDescription+"= | ="+const.theName+"= | "+str(const.theVolume)+" | "+str(const.theMass)+" | "+str(const.theCount)+" | "+const.theType+" | "+str(const.theX0)+" | "+str(const.theL0)+" |\n"
00147         result += "\n"
00148 
00149     return result
00150 
00151 #reads mixed_materials.input and pure_materials.input
00152 def readMaterialFile(fileName):
00153     file = open(fileName,"r")
00154     result = {}
00155     for line in file:
00156         if not line == "\n":
00157             name = line.split('"')[1]
00158             content = line.split('"')[2].split()
00159             result[name] = content
00160     return result
00161 
00162 #reads back one [section] of [config]
00163 def readSection(config,section):
00164     result = {}
00165     for option in config.options(section):
00166         result[option] = config.get(section,option)
00167     return result
00168 
00169 # reads the twikiConfig.ini
00170 def readConfig(fileName):
00171     config = ConfigParser.ConfigParser()   
00172     config.read(fileName)
00173     result = {}
00174 #    result["general"] = readSection("general")
00175     result["parsing"] = readSection(config,"parsing")
00176     result["twiki"] = readSection(config,"twiki")
00177 
00178     return result
00179 
00180 
00181 #main
00182 def main():
00183     optParser = optparse.OptionParser()
00184     optParser.add_option("-i", "--input", dest="inFile",
00185                   help="the .in material description that is the input", metavar="INPUT")
00186     optParser.add_option("-o", "--output", dest="output",
00187                   help="the file to put the twiki formated output in (default: <.in-Filename>.twiki)", metavar="TWIKIOUT")
00188     optParser.add_option("-c", "--config", dest="config",
00189                   help="configuration to use (default twikiConfig.ini)", metavar="CONFIG")
00190 
00191     (options, args) = optParser.parse_args()
00192 
00193     if options.inFile == None:
00194         raise StandardError, "no .in File given!"
00195     if options.output == None:
00196         options.output = options.inFile.replace(".in",".twiki")
00197     if options.config == None:
00198         options.config = "twikiConfig.ini"
00199     
00200     config = readConfig(options.config)
00201 
00202     predefinedMaterials = {}
00203     predefinedMaterials.update( readMaterialFile("pure_materials.input") )
00204     predefinedMaterials.update( readMaterialFile("mixed_materials.input") )
00205 
00206     inFile = open(options.inFile,"r")
00207     inFileContent = inFile.read()
00208     inFile.close()
00209 
00210     materials = parseInFile(inFileContent, predefinedMaterials, config)
00211     twikiString = getTwiki(materials, config)
00212 
00213     outFile = open(options.output,"w")
00214     outFile.write(twikiString)
00215     outFile.close()
00216 
00217 main()