CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_0/src/DetectorDescription/OnlineDBLoader/scripts/CMS_DTCTR_GEOMETRY_OWNER/loading-scripts/asciidump.py

Go to the documentation of this file.
00001 from  xml.dom.minidom import *
00002 import os
00003 import string
00004 import sys
00005 import glob
00006 import math
00007 
00008 # output directory
00009 CONFIGFILE = "configuration.xml"
00010 #CONFIGFILE = "config_test.xml"
00011 outdir = "./data/"
00012 #outdir = "./Test/"
00013 soldir = ""
00014 #soldir = "solids"
00015 GENSOLID_ONCE = {}
00016 LOGFILE = open("log.txt",'w')
00017 LOGFILE.write("Logfile\n")
00018 #delete previously generated tables
00019 cmd = "rm -rf " + outdir
00020 os.system(cmd)
00021 os.mkdir(outdir)
00022 #os.mkdir(outdir+soldir)
00023 #for i in glob.glob(outdir+"*"):
00024 #    try:
00025 #       os.remove(i)
00026 #    except:
00027 #       print "ex"
00028         
00029 
00030 ##################################################################################
00031 #  Solid actions
00032 ##################################################################################
00033 
00034 # generic for atomic solids ######################################################
00035 # input: table-name, dom-element, current-namespace, other #######################
00036 #      postfix = any other text to be written end of the row, must end with a ',
00037 #      prefix  = any other text to be written beginning of a row, must end with a ','
00038 # output: entry in file 'table-name' of all attributes of 'dom-element' ##########
00039 def generic_solid(table,element,ns,postfix="",prefix="",docpost="[postfix]",docpre="[prefix],"):
00040     if GENSOLID_ONCE.has_key(table) == 0:
00041         GENSOLID_ONCE[table]=1
00042         f = open(outdir+soldir+table+".cdl",'w')
00043         s = "-- "
00044         if len(prefix):
00045             s = s + docpre
00046         for att in element.attributes.values(): 
00047             s = s + att.name + ','
00048         if len(postfix):
00049             s = s + docpost
00050         f.write(s[:-1]+"\n")
00051         f.close()
00052     file = open(outdir+soldir+table,'a')
00053     s=prefix
00054     for att in element.attributes.values():
00055         if att.name == "name":
00056             s = s + qname(att.value,ns) + ','
00057         else:
00058             s = s + unitc(att.value).__str__() + ','
00059     s = s + postfix 
00060     file.write(s[:-1]+"\n")
00061 
00062 # examines the sensfullness of the pcone/phedra z-sections or rz-points (currently z-section only)
00063 def examine_section(r,ns,kind):
00064     # currently only z-sections
00065     if kind != "ZS,":
00066         return
00067     sections = r.getElementsByTagName("ZSection")
00068     z = []
00069     rmin = []
00070     rmax = []
00071     for s in sections:
00072         z.append(unitc(s.getAttribute("z")))
00073         rmin.append(unitc(s.getAttribute("rMin")))
00074         rmax.append(unitc(s.getAttribute("rMax")))
00075     #print z        
00076     # check, whether z-values come in order
00077     xmin = z[0]
00078     for x in z:
00079         if x < xmin:
00080             LOGFILE.write(r.tagName + " " + qname(r.getAttribute("name"),ns) + " z values not z1 <= z2\n")
00081         xmin = x
00082     for i in range(0,len(rmin)):
00083         if rmin[i] == rmax[i]:
00084             LOGFILE.write(r.tagName + " " + qname(r.getAttribute("name"),ns) + " rmin = rmax\n")
00085             if (i != 0) and (i != (len(rmin)-1)):
00086                 LOGFILE.write("   the one above might be a problem!\n")
00087                 print r.tagName + " " + qname(r.getAttribute("name"),ns) + " rmin = rmax\n", i, range(0,len(rmin))
00088                 
00089     for i in range(0,len(rmin)):
00090         if rmin[i] > rmax[i]:
00091             LOGFILE.write(r.tagName + " " + qname(r.getAttribute("name"),ns) + " rmin > rmax\n")
00092     # check pairs of same z-values
00093     zz = {}
00094     for i in range(0,len(rmin)):
00095         zz[z[i]] = 1
00096         #print z[i], zz
00097         if i < len(rmin)-1:
00098             err = 0
00099             if z[i] == z[i+1]:
00100                 if rmax[i+1] < rmin[i]:
00101                     err = 1
00102                 if rmin[i+1] > rmax[i]:
00103                     err = 2
00104             if err>0:
00105                 LOGFILE.write(r.tagName + " " + qname(r.getAttribute("name"),ns) + " discontinuity at " + i.__str__() + "\n")
00106     if len(zz) == 2:
00107          #print zz, qname(r.getAttribute("name"),ns)
00108          #print n
00109          LOGFILE.write(r.tagName + " " + qname(r.getAttribute("name"),ns) + " simpler solid possible\n")
00110         
00111 def poly_section_action(r,ns,kind):
00112     count = 0
00113     name = qname(r.getAttribute("name"),ns) + ","
00114     if r.tagName == "Polycone":
00115         name = name + ","
00116     else:
00117         name = "," + name
00118     #print kind
00119     if kind=="ZS,":
00120         for i in r.getElementsByTagName("ZSection"):
00121             prefix = count.__str__() + ","
00122             generic_solid("ZSECTIONS.dat",i,ns,name,prefix,"polycone_solid_name,polyhedra_solid_name,","sequence_no,")
00123             count = count + 1
00124     else:
00125         for i in r.getElementsByTagName("RZPoint"):
00126             prefix = count.__str__() + ","
00127             generic_solid("RZPOINTS.dat",i,ns,name,prefix,"polycone_solid_name,polyhedra_solid_name,","sequence_no,")
00128             count = count + 1
00129     #if count<5:
00130     #    LOGFILE.write("ZSECTION:" +" " + r.tagName + " " + name + "\n")
00131     examine_section(r,ns,kind)
00132         
00133 def boolean_components(r,ns):
00134     s = ""
00135     for c in r.getElementsByTagName("rSolid"):
00136         s = s + qname(c.getAttribute("name"),ns) + ","
00137     t = r.getElementsByTagName("Translation")
00138     if len(t) != 0:
00139         s = s + unitc(t[0].getAttribute("x")).__str__() + ","
00140         s = s + unitc(t[0].getAttribute("y")).__str__() + ","
00141         s = s + unitc(t[0].getAttribute("z")).__str__() + ","
00142     else:
00143         s = s + "0,0,0,"    
00144     r = r.getElementsByTagName("rRotation")
00145     if len(r) != 0:
00146         s = s + qname(r[0].getAttribute("name"),ns) + ","
00147     else:
00148         s = s + "rotations:UNIT,"
00149     return s
00150 
00151 # Solid-action  ##########################################################################
00152 # called during the SOLIDS-table generation
00153 # each action creates a sub-table containing the data for the solids
00154 # some actions create several sub-tables (e.g. polycones, rz-sectsion ...)
00155 
00156 def box_action(r,s,ns):
00157     s = s + r.tagName +','
00158     generic_solid("BOXES.dat",r,ns)
00159     return s
00160 
00161 def reflectionsolid_action(r,s,ns):
00162     s = s + r.tagName +','
00163     generic_solid("REFLECTIONSOLIDS.dat",r,ns)
00164     return s
00165     
00166 def shapelesssolid_action(r,s,ns):
00167     s = s  + r.tagName +','
00168     generic_solid("SHAPELESSSOLIDS.dat",r,ns)
00169     return s
00170 
00171 def tubs_action(r,s,ns):
00172     s = s  + r.tagName +','
00173     generic_solid("TUBESECTIONS.dat",r,ns)
00174     return s
00175 
00176 def tube_action(r,s,ns):
00177     s = s + r.tagName +','
00178     generic_solid("TUBES.dat",r,ns)
00179     return s
00180 
00181 def trd1_action(r,s,ns):
00182     s = s + r.tagName +','
00183     generic_solid("TRD1S.dat",r,ns)
00184     return s
00185 
00186 def polyhedra_action(r,s,ns):
00187     kind = "RZ"
00188     if len(r.getElementsByTagName("ZSection"))>0:
00189         kind = "ZS,"
00190     poly_section_action(r,ns,kind)    
00191     s = s + r.tagName +','
00192     generic_solid("POLYHEDRAS.dat",r,ns,kind,"","RZ_or_ZS,")
00193     return s
00194 
00195 def polycone_action(r,s,ns):
00196     kind = "RZ"
00197     if len(r.getElementsByTagName("ZSection"))>0:
00198         kind = "ZS,"
00199     poly_section_action(r,ns,kind)
00200     generic_solid("POLYCONES.dat",r,ns,kind,"","RZ_or_ZS,")
00201     s = s + r.tagName +','   
00202     return s
00203 
00204 def cone_action(r,s,ns):
00205     s = s + r.tagName +','
00206     generic_solid("CONES.dat",r,ns)
00207     return s
00208 
00209 def pseudotrap_action(r,s,ns):
00210     s = s + r.tagName +','
00211     generic_solid("PSEUDOTRAPEZOIDS.dat",r,ns)
00212     return s
00213 
00214 def trapezoid_action(r,s,ns):
00215     s = s + r.tagName +','
00216     generic_solid("TRAPEZOIDS.dat",r,ns)
00217     return s
00218 
00219 def intersectionsolid_action(r,s,ns):
00220     s = s + r.tagName +','
00221     comp = boolean_components(r,ns)
00222     generic_solid("BOOLEANSOLIDS.dat",r,ns,"I,"+comp,"","operation,solidA,solidB,x,y,z,rot")
00223     return s
00224 
00225 def unionsolid_action(r,s,ns):
00226     s = s + r.tagName +','
00227     comp = boolean_components(r,ns)
00228     generic_solid("BOOLDEANSOLIDS.dat",r,ns,"U,"+comp,"","operation,solidA,solidB,x,y,z,rot")
00229     return s
00230 
00231 def subtractionsolid_action(r,s,ns):
00232     s = s + r.tagName +','
00233     comp = boolean_components(r,ns)
00234     generic_solid("BOOLEANSOLIDS.dat",r,ns,"S,"+comp,"","operation,solidA,solidB,x,y,z,rot")
00235     return s
00236     
00237 # global things
00238 CATEGORIES = {}
00239 SOLIDTYPES = {
00240                'SubtractionSolid':subtractionsolid_action,
00241                'UnionSolid':unionsolid_action,
00242                'IntersectionSolid':intersectionsolid_action,
00243                'Trapezoid':trapezoid_action,
00244                'PseudoTrap':pseudotrap_action,
00245                'Cone':cone_action,
00246                'Polycone':polycone_action,
00247                'Polyhedra':polyhedra_action,
00248                'Trd1':trd1_action,
00249                'Tube':tube_action,
00250                'Tubs':tubs_action,
00251                'ShapelessSolid':shapelesssolid_action,
00252                'ReflectionSolid':reflectionsolid_action,
00253                'Box':box_action,
00254                }
00255 
00256 rad_to_deg = math.pi/180.
00257 UNITS = { u'deg':rad_to_deg,
00258           u'fm':1e-12,
00259           u'nm':1e-9,
00260           u'mum':1e-3,
00261           u'mm':1.,
00262           u'cm':10.,
00263           u'm':1000.,
00264           u'rad':1,
00265           u'g/cm3':1,
00266           u'mg/cm3':0.001,
00267           u'g/mole':1.,
00268           u'mg/mole':0.001
00269         }
00270 
00271 PPCOUNT = [ 0 ]
00272 
00273 # unitconversion
00274 def unitc(s):
00275     try:
00276         s = string.strip(s)
00277         x = string.split(s,'*')
00278         if len(x) == 1:
00279             return s
00280         if len(x) == 2:
00281             return string.atof(x[0])*UNITS[x[1]]  
00282     except:
00283         print "ERROR IN unitc: >" + s + "<"
00284         print x
00285         print UNITS[x[1]]       
00286 
00287 def get_docs(config):
00288     result = []
00289     print CONFIGFILE
00290     doc = xml.dom.minidom.parse(open(CONFIGFILE,'r'))
00291     file_elements = doc.getElementsByTagName("File")
00292     print `file_elements`   
00293     for file_element in file_elements:
00294         file_name = file_element.getAttribute("name")
00295         url_name = file_element.getAttribute("url")
00296         print url_name + file_name
00297         path = url_name+file_name
00298         ns = string.split(path,'/')[-1][:-4]
00299         result.append([url_name+file_name,ns])
00300     return result
00301 
00302 ##################################################################################
00303 #  other  actions
00304 ##################################################################################
00305 
00306 def rot_action(r,s,ns):
00307     #print r.tagName
00308     if r.tagName=="ReflectionRotation":
00309         s = s + "1,"
00310     else:
00311         s = s + "0,"
00312     return s
00313 
00314 # "ABC:abc" -> "ABC:abc", "abc" -> "ns:abc"
00315 def qname(s,ns):
00316     if string.find(s,':') == -1:
00317         s = ns +':' + s
00318     return s
00319 
00320 def comp_action(e,s,ns):
00321     file = open(outdir+"MATERIALFRACTIONS.dat",'a')
00322     fracs = e.getElementsByTagName("MaterialFraction")
00323     for frac in fracs:
00324         fm = frac.getAttribute("fraction")
00325         mat = qname(frac.getElementsByTagName("rMaterial")[0].getAttribute("name"),ns)
00326         result = "" + qname(e.getAttribute("name"),ns) + ',' + mat + ',' + fm + "\n"
00327         file.write(result)
00328     return s
00329 
00330 def log_action(logp,s,ns):
00331     # isolate the category, name_cat[0]=name, name_cat[1]=category
00332     name_cat = string.split(s,',')
00333     CATEGORIES[name_cat[1]] ='' # put category in global dictionary
00334     #print name_cat[1]
00335     nodelist = logp.childNodes
00336     l = nodelist.length
00337     mat =""
00338     sol =""
00339     for i in range(0,l-1):
00340         if string.find(nodelist[i].nodeName,"Ma") != -1:
00341             mat = qname(nodelist[i].getAttribute("name"),ns)
00342         if string.find(nodelist[i].nodeName,"So") != -1:
00343             sol = qname(nodelist[i].getAttribute("name"),ns)
00344     result =  name_cat[0] + ',' + sol + ',' + mat + ',' + name_cat[1] + ',' 
00345     return result
00346     
00347 def pos_action(posp,s,ns):
00348     PPCOUNT[0] = PPCOUNT[0] + 1
00349     nodelist = posp.childNodes
00350     l = nodelist.length
00351     parent = ""
00352     child = ""
00353     tra = []
00354     rot = ""
00355     for i in range(0,l-1):
00356         nn = nodelist[i].nodeName
00357         if string.find(nn,'Pa') != -1:
00358             parent = qname(nodelist[i].getAttribute("name"),ns)
00359         if string.find(nn,'Child') != -1:
00360             child = qname(nodelist[i].getAttribute("name"),ns)
00361         if string.find(nn,'Tra') != -1:
00362             tra.append(unitc(nodelist[i].getAttribute("x")))
00363             tra.append(unitc(nodelist[i].getAttribute("y")))
00364             tra.append(unitc(nodelist[i].getAttribute("z")))
00365         if string.find(nn,'Rot') != -1:
00366             rot = qname(nodelist[i].getAttribute("name"),ns)
00367     result = PPCOUNT[0].__str__() + ',' + s 
00368     if len(tra) != 0:
00369         result = result + tra[0].__str__() + ',' + tra[1].__str__() + ',' + tra[2].__str__() + ','
00370     else:
00371         result = result + ",,,"
00372     result = result + rot + ',' + parent + ',' + child + ','
00373     return result
00374     
00375 docs_ns = get_docs("configuration.xml")
00376 print `docs_ns`
00377 for doc in docs_ns:
00378     document_path = doc[0]
00379     namespace = doc[1]
00380     print "Processing document: " + doc[0] + " ns=" + doc[1] 
00381     doc = xml.dom.minidom.parse(open(doc[0],'r'));
00382 
00383     # syntax: list( tablename, list(elements), list(attributes) )
00384     # prefixing an attribute name with ":"  =  convert to a q-name
00385     # prefixing an attribute name with ";"  =  do NOT perform unit-conversion
00386     table = [
00387               [ 'MATERIALS.dat', ['ElementaryMaterial', 'CompositeMaterial'] ,
00388                 [':name','density'] ,0 ],
00389 
00390               [ 'ELEMENTARYMATERIALS.dat', ['ElementaryMaterial'],
00391                 [':name', ';atomicNumber', 'atomicWeight',  ';symbol' ], 0 ],
00392 
00393               [ 'COMPOSITEMATERIALS.dat', ['CompositeMaterial'],
00394                 [':name',';method' ], comp_action ],
00395 
00396               [ 'ROTATIONS.dat', ['Rotation', 'ReflectionRotation'],
00397                 [':name', 'thetaX', 'phiX', 'thetaY', 'phiY', 'thetaZ', 'phiZ'], rot_action ],
00398 
00399               [ 'LOGICALPARTS.dat', ['LogicalPart'],
00400                 [':name', ';category', 'itemid' ], log_action ],
00401 
00402               [ 'POSPARTS.dat', ['PosPart'],
00403                 ['copyNumber'], pos_action ],
00404 
00405               [ 'SOLIDS.dat', SOLIDTYPES.keys(),
00406                 [':name'], SOLIDTYPES.values() ]
00407             
00408             ]
00409 
00410     for i in table:
00411         tablename = i[0]
00412         filename=outdir+tablename
00413         file = open(outdir+tablename,'a')    
00414         elements = i[1]
00415         attributes = i[2]
00416         action = i[3]
00417         elCount = -1
00418         for el in elements:
00419             elCount = elCount + 1
00420             els = doc.getElementsByTagName(el)
00421             for e in els:
00422                 s = ""
00423                 for at in attributes:
00424                     flagQ = 0 # q-name
00425                     flagU = 0 # unit converson
00426                     if at[0]==':': # process a q-name
00427                         flagQ = 1
00428                         at = at[1:]
00429                     if at[0]==';': # don't do a unit-conversion
00430                         flagU = 1
00431                         at = at[1:]
00432                     attr = e.getAttribute(at)    
00433                     if flagQ == 1: # process a q-name
00434                         attr = qname(attr,namespace)
00435                     else:
00436                         if flagU == 0:    
00437                              attr = unitc(attr)
00438                         else:     
00439                              if attr == " ": # fix symbol=" " in ElementaryMaterial (could be done in an action)
00440                                  attr = "0"
00441                     s = s + attr.__str__() + ","
00442                 if action != 0: # trigger special action if defined in the processing-table
00443                     le=0
00444                     try:
00445                         le=len(action)
00446                     except TypeError:
00447                         s = action(e,s,namespace)
00448                     else:
00449                         s = action[elCount](e,s,namespace)
00450                 #print s[:len(s)-1]
00451                 file.write(s[:len(s)-1]+"\n")
00452         file.close()
00453 
00454 file = open(outdir+"CATEGORIES.dat",'w')
00455 for i in CATEGORIES.keys():
00456     file.write(i+"\n")
00457 file.close()
00458 
00459 LOGFILE.close()