CMS 3D CMS Logo

insertMaterial.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 import sys
3 import xml.dom.minidom
4 import math
5 import optparse
6 
7 maxDist = 0.0001
8 
9 #parse .tiles-File
10 def readFractions(fileName, materialMap):
11  result = {}
12  file = open(fileName,"r")
13  name = None
14  dens = None
15  fractions = {}
16  for line in file:
17  line = line.strip("\n")
18  if len(line.split("\""))==3:
19  contentName = line.split("\"")[1]
20  content = line.split("\"")[2].split()
21  if len(content) == 2:
22  if not name == None:
23  result[name] = dens,fractions
24  name = contentName
25  dens = content[1]
26  fractions = {}
27  elif len(content) == 1:
28  # print " "+contentName+" "+str(float(content[0][1:])*0.01)
29  fractions[getMaterial(contentName,materialMap)] = float(content[0][1:])*0.01
30 
31  if not name == None:
32  result[name] = dens,fractions
33 
34  for material in result:
35  sum = 0
36  for fraction in result[material][1]:
37  sum+= result[material][1][fraction]
38  if math.fabs(sum - 1.0) > maxDist:
39  raise Exception("Material Fractions do not add up to 100%: "+ material+" "+str(sum))
40  return result
41 
42 #get a source:material from the [material] only
43 def getMaterial(material, fileName):
44  materialMap ={}
45  file = open(fileName,"r")
46  for line in file:
47  line = line.strip("\n")
48  content = line.split()
49  if len(content) == 2:
50  materialMap[content[0]] = content[1]
51  if material in materialMap:
52  result = materialMap[material]+":"+material
53  else:
54  result = "materials:"+material
55  return result
56 
57 #parse XML-File
58 def readXML(fileName):
59  file = open(fileName,'r')
60  dom = xml.dom.minidom.parse(file)
61  file.close()
62  return dom
63 
64 #get the last subnode named [name] of [rootNode]
65 def getSection(rootNode, name):
66  result = None
67  for node in rootNode.childNodes:
68  if node.nodeName == name:
69  result = node
70  if result == None:
71  raise Exception("Could not find: \""+name+"\" in childnodes of the rootNode!")
72  return result
73 
74 #returns a map of [name] nodes by their names. stating from rootNode
75 def getNodes(rootNode, name):
76  result = {}
77  for node in rootNode.childNodes:
78  if node.nodeName == name and node.nodeType == node.ELEMENT_NODE:
79  for i in range(0,node.attributes.length):
80  if node.attributes.item(i).name == "name":
81  result[node.attributes.item(i).nodeValue] = node
82  return result
83 #returns a pretty printed string of [dom] withot whitespace-only-lines
84 def prettierprint(dom):
85  result = ""
86  output = dom.toprettyxml()
87  for line in output.splitlines():
88  if not line.strip(" \t") == "":
89  result+= line+"\n"
90  return result
91 
92 #gets a map of attributes and their values of [node]
93 #(not used but interessting for debug)
94 def getAttributes(node):
95  result = {};
96  for i in range(0,node.attributes.length):
97 # print " "+node.attributes.item(i).name+" = "+node.attributes.item(i).nodeValue
98  result[node.attributes.item(i).name] = node.attributes.item(i).nodeValue
99  return result
100 
101 #print information on all subnodes of [domina]
102 #(not used but interessting for debug)
103 def dokument(domina):
104  for node in domina.childNodes:
105  print "NodeName:", node.nodeName,
106  if node.nodeType == node.ELEMENT_NODE:
107  print "Typ ELEMENT_NODE"
108  print getAttributes(node)
109  elif node.nodeType == node.TEXT_NODE:
110  print "Typ TEXT_NODE, Content: ", node.nodeValue.strip()
111  elif node.nodeType == node.COMMENT_NODE:
112  print "Typ COMMENT_NODE, "
113  #dokument(node)
114 
115 #prints all CompositeMaterials beneeth [rootNode]
116 #(not used but interessting for debug)
117 def printMaterials(rootNode):
118  matNodes = getNodes(rootNode,"CompositeMaterial")
119  for name in matNodes:
120  print " "+name+" (dens = "+getAttributes(matNodes[name])["density"]+")"
121  for fractionNode in matNodes[name].childNodes:
122  if fractionNode.nodeName == "MaterialFraction":
123  fractionString = getAttributes(fractionNode)["fraction"]
124  for materialNode in fractionNode.childNodes:
125  if materialNode.nodeName == "rMaterial":
126  fractionString += "\tof "+getAttributes(materialNode)["name"].split(":")[1]
127  fractionString += "\tfrom "+getAttributes(materialNode)["name"].split(":")[0]
128  print " |-- "+fractionString
129 
130 #returns the Material Section doe of a DDD Material xmlfile
131 def getMaterialSection(rootNode):
132  dddef = getSection(rootNode,'DDDefinition')
133  matSec = getSection(dddef,'MaterialSection')
134  return matSec
135 
136 #creates a CompositeMaterial with [name] [method] [density] and [symbol] beneeth [rootNode].
137 #fractions is a map of material Names containing the fractions
138 #NOTE: if an material of that name allready exists it will be overridden.
139 def createCompositeMaterial(doc,rootNode,name, density,fractions,method="mixture by weight", symbol=" "):
140  newMaterial = doc.createElement("CompositeMaterial")
141  newMaterial.setAttribute("name",name)
142  newMaterial.setAttribute("density",density)
143  newMaterial.setAttribute("method",method)
144  newMaterial.setAttribute("symbol",symbol)
145 
146  for fracMaterialName in fractions:
147  fraction = doc.createElement("MaterialFraction")
148  fraction.setAttribute("fraction",str(fractions[fracMaterialName]))
149  newMaterial.appendChild(fraction)
150  fracMaterial = doc.createElement("rMaterial")
151  fracMaterial.setAttribute("name",fracMaterialName)
152  fraction.appendChild(fracMaterial)
153 
154  exMaterials = getNodes(rootNode,"CompositeMaterial")
155  if name in exMaterials:
156  rootNode.replaceChild(newMaterial,exMaterials[name])
157  else:
158  rootNode.appendChild(newMaterial)
159 
160 #main
161 def main():
162  optParser = optparse.OptionParser()
163  optParser.add_option("-t", "--titles", dest="titlesFile",
164  help="the .titles file to parse (as generated by mixture)", metavar="TITLES")
165  optParser.add_option("-x", "--xml", dest="xmlFile",
166  help="the .xml file to parse (must be DDD complient)", metavar="XML")
167  optParser.add_option("-o", "--output", dest="output",
168  help="the file to write the new materials into default: materialOutput.xml", metavar="XMLOUT")
169  optParser.add_option("-m", "--materialMap", dest="materialMap",
170  help="file containing map of materials not defined in materials.xml. default: material.map", metavar="MMAP")
171 
172  (options, args) = optParser.parse_args()
173 
174  if options.titlesFile == None:
175  raise Exception("no .titles File given!")
176  if options.xmlFile == None:
177  raise Exception("no .xml File given!")
178  if options.output == None:
179  options.output = "materialOutput.xml"
180  if options.materialMap == None:
181  options.materialMap = "material.map"
182  theOptions = options
183 
184  materials = readFractions(options.titlesFile, options.materialMap)
185 
186  dom = readXML(options.xmlFile)
187  matSec = getMaterialSection(dom)
188 
189  # print "before:"
190  # printMaterials(matSec)
191 
192  for material in materials:
193  createCompositeMaterial(dom,matSec,material,str(materials[material][0])+"*g/cm3",materials[material][1])
194 
195 # print "after:"
196 # printMaterials(matSec)
197  outFile = open(options.output,"w")
198  outFile.write(prettierprint(dom))
199  outFile.close()
200 
201 main()
202 
def readXML(fileName)
def getNodes(rootNode, name)
def dokument(domina)
def printMaterials(rootNode)
def getAttributes(node)
def getSection(rootNode, name)
def createCompositeMaterial(doc, rootNode, name, density, fractions, method="mixture by weight", symbol=" ")
Definition: main.py:1
def prettierprint(dom)
def getMaterialSection(rootNode)
def readFractions(fileName, materialMap)
#define str(s)
def getMaterial(material, fileName)
double split
Definition: MVATrainer.cc:139