CMS 3D CMS Logo

twikiExport.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 import optparse
4 import ConfigParser
5 
6 class Constituent:
7  def __init__(self, line, predefinedMaterials):
8  if len(line.split('"')) < 5 or len(line.split('"')[4].split()) < 3:
9  raise Exception("not a well formed Constituent: "+constString)
10  self.theDescription = line.split('"')[1]
11  self.theName = line.split('"')[3]
12  self.theCount = float(line.split('"')[4].split()[1])
13  self.theVolume = float(line.split('"')[4].split()[0]) * self.theCount
14  self.theType = line.split('"')[4].split()[2]
15  self.theDensity = float(predefinedMaterials[self.theName][2])
16  self.theX0 = float(predefinedMaterials[self.theName][3]) * self.theDensity
17  self.theL0 = float(predefinedMaterials[self.theName][4]) * self.theDensity
18  self.theMass = self.theVolume * self.theDensity
19 # print "%s\tX0: %.3f\trho: %.3f\tX0': %.3f"%(self.theName, float(predefinedMaterials[self.theName][3]), float(predefinedMaterials[self.theName][2]), self.theX0)
20  def __str__(self):
21  return "Name: "+self.theName+" desc: "+self.theDescription+" mass "+self.theMass+" type "+self.theType+" count "+self.theCount
22 
23 class Material:
24  def __init__(self, matString, comment):
25  if matString == "" or not matString[0] == "#":
26  raise Exception("not a valid material Definition: "+matString)
27  line = matString[1:]
28 
29  if len( line.split('"') ) < 5 or len( line.split('"')[4].split() ) < 2:
30  raise Exception("not a well formed Material Definition: "+matString)
31  self.theDescription = line.split('"')[1]
32  self.theName = line.split('"')[3]
33  self.theMcVolume = float(line.split('"')[4].split()[0])
34  self.theComment = comment
35  self.theConstituents = []
36 
37  def getRealValues(self):
38  result = {}
39  result["Volume"] = 0
40  result["X0"] = 0
41  result["L0"] = 0
42 
43  totMass = self.getMass()
44  invX0 = 0
45  invL0 = 0
46  for con in self.theConstituents:
47  pWeight = con.theVolume * con.theDensity / totMass
48  invX0 += pWeight / con.theX0
49  invL0 += pWeight / con.theL0
50  result["Volume"] += con.theVolume
51  result["Density"] = self.getMass() / result["Volume"]
52  result["X0"] = 1 / ( invX0 * result["Density"] )
53  result["L0"] = 1 / ( invL0 * result["Density"] )
54 
55  return result
56 
57  def getSimValues(self):
58  result = self.getRealValues()
59  fraction = self.theMcVolume / result["Volume"]
60  result["Volume"] = self.theMcVolume
61  result["Density"] = self.getMass() / self.theMcVolume
62  result["X0"] *= fraction
63  result["L0"] *= fraction
64 
65  return result
66 
67  def getMass(self):
68  result = 0
69  for con in self.theConstituents:
70  result += con.theMass * con.theCount
71  return result
72 
73  def addConstituent(self, constString, predefinedMaterials):
74  if constString == "" or not constString[0] == "*":
75  raise Exception("not a valid Constituent: "+constString)
76  line = constString[1:]
77  self.theConstituents.append( Constituent(line, predefinedMaterials) )
78 
79  number = int( line.split('"')[0].split()[0] )
80  if not len(self.theConstituents) == number:
81  raise Exception("Constituent Number mismatch for "+str(len(self.theConstituents))+" in: "+line)
82 
83  def __str__(self):
84  result = "[ "+self.theName+" Description: "+self.theDescription+" MC-Volume:"+str(self.theMcVolume)+"\n"
85  result += "Comments:\n"+self.theComment
86  return result
87 
88 #parses the .in File
89 def parseInFile(inFile, predefinedMaterials, config):
90  comment = ""
91  materials = []
92  i = 0
93  for line in inFile.split("\n"):
94  i=i+1
95  if i < int(config["parsing"]["intro"]):
96  continue
97  if not line == "" and line[0] == "#":
98  material = Material( line , comment )
99  if not material.theName == "END":
100  materials.append( material )
101  comment = ""
102 
103  #print "Name: "+name+" Description: "+description+" mcVolume: "+str(mcVolume)
104  elif not line == "" and line[0] == "*":
105 
106  materials[-1].addConstituent(line, predefinedMaterials)
107  else:
108  ignore = False
109  for char in config["parsing"]["ignorelines"]:
110  if len(line.strip()) == line.strip().count(char) and not len(line) == 0:
111  ignore = True
112  if not ignore:
113  comment += line+"\n"
114  return materials
115 
116 def parseComment(comment):
117  result = ""
118  if comment.find("<twiki>") >= 0:
119  result = comment.split("twiki>")[1][:-2]
120  else:
121  result += "<verbatim>\n"
122  result += comment
123  result += "</verbatim>\n"
124  return result
125 
126 def getTwiki(materials,config):
127  result = config["twiki"]["pagename"]+"\n"
128  result += "%TOC%\n\n"
129  for mat in materials:
130  result += config["twiki"]["heading"]+mat.theName+"\n"
131  result += "short Description: *"+mat.theDescription+"* <br>\n"
132  result += "Mass: %.3fg\n" % mat.getMass()
133  result += config["twiki"]["tableformat"]+'\n'
134  result += "| ** | *Volume* | *Density* | *X<sub>0</sub>* | *&lambda;<sub>0</sub>* |\n"
135  result += "| ** | *cms<sup>3</sup>* | *g cm<sup>-3</sup>* | *cm* | *cm* |\n"
136  result += "| Real | %(Volume).3f | %(Density).3f | %(X0).3f | %(L0).3f |\n" % mat.getRealValues()
137  result += "| Simulation | %(Volume).3f | %(Density).3f | %(X0).3f | %(L0).3f |\n" % mat.getSimValues()
138  result += "\n"+config["twiki"]["subheading"]+"Comments\n"
139  result += parseComment(mat.theComment)
140  result += "\n---+++!!Material\n"
141  result += config["twiki"]["tableformat"]+'\n'
142  result += " | *Description* | *Material Name* | *Volume* | *Mass* | *Count* | *Type* | *X<sub>0</sub>* | *&lambda;<sub>0</sub>* |\n"
143  result += ' | ** | ** | *cm<sup>3</sup>* | *g* | ** | ** | *g cm<sup>-2</sup>* | *g cm<sup>-2</sup>* |\n'
144  for const in mat.theConstituents:
145  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 )
146 # result += " | ="+const.theDescription+"= | ="+const.theName+"= | "+str(const.theVolume)+" | "+str(const.theMass)+" | "+str(const.theCount)+" | "+const.theType+" | "+str(const.theX0)+" | "+str(const.theL0)+" |\n"
147  result += "\n"
148 
149  return result
150 
151 #reads mixed_materials.input and pure_materials.input
152 def readMaterialFile(fileName):
153  file = open(fileName,"r")
154  result = {}
155  for line in file:
156  if not line == "\n":
157  name = line.split('"')[1]
158  content = line.split('"')[2].split()
159  result[name] = content
160  return result
161 
162 #reads back one [section] of [config]
163 def readSection(config,section):
164  result = {}
165  for option in config.options(section):
166  result[option] = config.get(section,option)
167  return result
168 
169 # reads the twikiConfig.ini
170 def readConfig(fileName):
171  config = ConfigParser.ConfigParser()
172  config.read(fileName)
173  result = {}
174 # result["general"] = readSection("general")
175  result["parsing"] = readSection(config,"parsing")
176  result["twiki"] = readSection(config,"twiki")
177 
178  return result
179 
180 
181 #main
182 def main():
183  optParser = optparse.OptionParser()
184  optParser.add_option("-i", "--input", dest="inFile",
185  help="the .in material description that is the input", metavar="INPUT")
186  optParser.add_option("-o", "--output", dest="output",
187  help="the file to put the twiki formated output in (default: <.in-Filename>.twiki)", metavar="TWIKIOUT")
188  optParser.add_option("-c", "--config", dest="config",
189  help="configuration to use (default twikiConfig.ini)", metavar="CONFIG")
190 
191  (options, args) = optParser.parse_args()
192 
193  if options.inFile == None:
194  raise Exception("no .in File given!")
195  if options.output == None:
196  options.output = options.inFile.replace(".in",".twiki")
197  if options.config == None:
198  options.config = "twikiConfig.ini"
199 
200  config = readConfig(options.config)
201 
202  predefinedMaterials = {}
203  predefinedMaterials.update( readMaterialFile("pure_materials.input") )
204  predefinedMaterials.update( readMaterialFile("mixed_materials.input") )
205 
206  inFile = open(options.inFile,"r")
207  inFileContent = inFile.read()
208  inFile.close()
209 
210  materials = parseInFile(inFileContent, predefinedMaterials, config)
211  twikiString = getTwiki(materials, config)
212 
213  outFile = open(options.output,"w")
214  outFile.write(twikiString)
215  outFile.close()
216 
217 main()
def addConstituent(self, constString, predefinedMaterials)
Definition: twikiExport.py:73
def __init__(self, line, predefinedMaterials)
Definition: twikiExport.py:7
def getRealValues(self)
Definition: twikiExport.py:37
def readMaterialFile(fileName)
Definition: twikiExport.py:152
def parseInFile(inFile, predefinedMaterials, config)
Definition: twikiExport.py:89
def __init__(self, matString, comment)
Definition: twikiExport.py:24
def getTwiki(materials, config)
Definition: twikiExport.py:126
def getSimValues(self)
Definition: twikiExport.py:57
def readSection(config, section)
Definition: twikiExport.py:163
Definition: main.py:1
def readConfig(fileName)
Definition: twikiExport.py:170
def parseComment(comment)
Definition: twikiExport.py:116
double split
Definition: MVATrainer.cc:139