CMS 3D CMS Logo

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