All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Classes | Functions | Variables
RemoveMathFromGDML Namespace Reference

Classes

class  ConfigurationError
 
class  GDMLexpressionRemover
 
class  GDMLpurifier
 
class  XMLpurifier
 XML parsing approach. More...
 

Functions

def RemoveMathFromGDMLfile
 
def ApplyToNodes
 
def ApplyToDocument
 
def RemoveMathFromXMLfile
 
def LoggingSetup
 
def RunParserOn
 
def RemoveMathFromGDML
 

Variables

string __doc__
 
string __version__ = "1.6"
 
 hasXML = True
 

Function Documentation

def RemoveMathFromGDML.ApplyToDocument (   document,
  func,
  args,
  kargs 
)

Definition at line 298 of file RemoveMathFromGDML.py.

299 def ApplyToDocument(document, func, *args, **kargs):
300  ApplyToNodes(document, 0, func, *args, **kargs)
301 
def RemoveMathFromGDML.ApplyToNodes (   node,
  level,
  func,
  args,
  kargs 
)
Applies a function to the specified node and all its descendants.

Definition at line 288 of file RemoveMathFromGDML.py.

289 def ApplyToNodes(node, level, func, *args, **kargs):
290  """Applies a function to the specified node and all its descendants."""
291  if node.childNodes:
292  for child in node.childNodes:
293  ApplyToNodes(child, level + 1, func, *args, **kargs)
294  func(node, level, *args, **kargs)
295 
296 # ApplyToNodes()
297 
def RemoveMathFromGDML.LoggingSetup (   LoggingLevel = logging.INFO)

Definition at line 333 of file RemoveMathFromGDML.py.

334 def LoggingSetup(LoggingLevel = logging.INFO):
335 
336  logging.basicConfig(
337  level=LoggingLevel,
338  format="%(levelname)s: %(message)s",
339  stream=sys.stderr # do not pollute standard output
340  )
341 
342 # def LoggingSetup()
343 
def RemoveMathFromGDML.RemoveMathFromGDML ( )

Definition at line 387 of file RemoveMathFromGDML.py.

388 def RemoveMathFromGDML():
389  import argparse
390 
391  LoggingSetup(logging.WARN)
392 
393  ###
394  ### argument parsing
395  ###
396  # the first parser is the default one
397  SupportedParsers = [ 'direct', 'xml', 'list' ]
398  if not hasXML:
399  logging.warn("XML parser is not supported (cam't find python XML module)")
400  SupportedParsers.remove('xml')
401  # if
402 
403  parser = argparse.ArgumentParser(description=__doc__)
404  parser.set_defaults(NoROOTformula=False, Parser=SupportedParsers[0])
405 
406  parser.add_argument('--stdin', dest="FromSTDIN", action='store_true',
407  help="read input from stdin")
408 
409  parser.add_argument("InputFiles", nargs="*", default=None,
410  help="input GDML files [default: stdin]")
411 
412  parser.add_argument("--parser", choices=SupportedParsers, dest="Parser",
413  help="choose which parser to use ('list' for a list) [%(default)s]")
414 
415  parser.add_argument("--direct", action="store_const", const="direct",
416  dest="Parser", help="use simple internal parser [%(default)s]")
417 
418  parser.add_argument("--xml", action="store_const", const="xml",
419  dest="Parser", help="use complete XML parser [%(default)s]")
420 
421  # mode disabled because it may give wrong answers;
422  # the implementation is still available; to enable it, you have to change
423  # the hard-coded value of arguments.NoROOTformula.
424 # parser.add_argument("--noroot", action="store_true",
425 # dest="NoROOTformula",
426 # help="use python instead of ROOT TFormula to evaluate expressions [%(default)s]"
427 # )
428 
429  parser.add_argument("--output", "-o", dest="OutputFile", default=None,
430  help="for a single input, use this as output file")
431 
432  parser.add_argument('--warnzero', '-z', dest="WarnZero", action='store_true',
433  help="emit a warning each time an expression evaluates to 0 [%(default)s]")
434  parser.add_argument('--dryrun', '--fake', '-n', dest="Fake", action='store_true',
435  help="do not write output [%(default)s]")
436  parser.add_argument('--verbose', '-v', dest="DoVerbose", action='store_true',
437  help="shows all the changes on screen [%(default)s]")
438  parser.add_argument('--debug', dest="DoDebug", action='store_true',
439  help="enables debug messages on screen")
440 
441  parser.add_argument('--version', action='version',
442  version='%(prog)s ' + __version__)
443 
444  arguments = parser.parse_args()
445 
446  ###
447  ### set up and parameter check
448  ###
449  # set up the logging system
450  logging.getLogger().setLevel \
451  (logging.DEBUG if arguments.DoDebug else logging.INFO)
452 
453  arguments.LogMsg = logging.info if arguments.DoVerbose else logging.debug
454 
455  if arguments.Parser == 'list':
456  SupportedParsers.remove('list')
457  logging.info("Supported parsers: '%s'.", "', '".join(SupportedParsers))
458  return 0
459  # if list parsers
460 
461  if arguments.Parser == 'direct':
462  Parser = RemoveMathFromGDMLfile
463  elif arguments.Parser == 'xml':
464  Parser = RemoveMathFromXMLfile
465  else:
466  raise ConfigurationError("Unexpected parser '%s' requested" % arguments.Parser)
467 
468  if bool(arguments.FromSTDIN) == bool(arguments.InputFiles):
469  raise ConfigurationError \
470  ("Please either specify option --stdin OR some input files.")
471  #
472 
473  ###
474  ### run
475  ###
476  if arguments.FromSTDIN:
477  Parser(None, options=arguments)
478  elif arguments.OutputFile is not None:
479  if len(arguments.InputFiles) > 1:
480  raise ConfigurationError \
481  ("Named output is supported only when a single input file is specified.")
482  # if
483  Parser(arguments.InputFiles[0], arguments.OutputFile, options=arguments)
484  else:
485  for InputFileName in arguments.InputFiles:
486  RunParserOn(Parser, InputFileName, options=arguments)
487  # if ... else
488 
489  ###
490  ### done
491  ###
492  return 0
493 # RemoveMathFromGDML()
494 
static constexpr bool
S join(S const &sep, Coll const &s)
Returns a concatenation of strings in s separated by sep.
def RemoveMathFromGDML.RemoveMathFromGDMLfile (   InputFileName,
  OutputFileName = None,
  options = None 
)

Definition at line 223 of file RemoveMathFromGDML.py.

224 def RemoveMathFromGDMLfile(InputFileName, OutputFileName = None, options = None):
225 
226  if not options.Fake and OutputFileName and (InputFileName == OutputFileName):
227  raise ConfigurationError \
228  ("With the direct parser the input and output file must be different.")
229 
230  # if InputFileName is empty, use standard input
231  InputFile = open(InputFileName, 'r') if InputFileName else sys.stdin
232 
233  if options.Fake:
234  logging.info("Output will not be written in dry-run mode.")
235  OutputFile = None
236  else:
237  # if OutputFileName is empty, use standard output; otherwise, overwrite
238  OutputFile = open(OutputFileName, 'w') if OutputFileName else sys.stdout
239 
240  RemoveGDMLexpression = GDMLpurifier(options=options)
241 
242  for iLine, line in enumerate(InputFile):
243 
244  # save indentation
245  beef = line.lstrip()
246  indent = line[:-len(beef)]
247  beef = beef.rstrip() # remove stuff at the end of line too (will be lost)
248 
249  # we keep the words after removal in a new list
250  purified = RemoveGDMLexpression.apply(beef, iLine)
251 
252  if OutputFile:
253  # output accumulates the output line
254  output = indent + purified
255  print >>OutputFile, output
256  # if output
257  # for
258 
259  if OutputFileName and OutputFile:
260  logging.debug("GDML written to file '%s'", OutputFileName)
261 
262 # RemoveMathFromGDMLfile()
263 
auto enumerate(Iterables &&...iterables)
Range-for loop helper tracking the number of iteration.
Definition: enumerate.h:69
open(RACETRACK) or die("Could not open file $RACETRACK for writing")
def RemoveMathFromGDML.RemoveMathFromXMLfile (   InputFileName,
  OutputFileName = None,
  options = None 
)

Definition at line 302 of file RemoveMathFromGDML.py.

303 def RemoveMathFromXMLfile(InputFileName, OutputFileName = None, options = None):
304 
305  # if InputFileName is empty, use standard input
306  InputFile = open(InputFileName, 'r') if InputFileName else sys.stdin
307 
308  # parse GDML document using minidom parser
309  DOMTree = xml.dom.minidom.parse(InputFile)
310  GDML = DOMTree.documentElement
311 
312  RemoveGDMLexpression = XMLpurifier()
313 
314  ApplyToDocument(GDML, RemoveGDMLexpression.purifyNode)
315 
316 
317  if options.Fake:
318  logging.info("Output will not be written in dry-run mode.")
319  else:
320  # if OutputFileName is empty, use standard output; otherwise, overwrite
321  OutputFile = open(OutputFileName, 'w') if OutputFileName else sys.stdout
322 
323  OutputFile.write(GDML.toxml())
324  OutputFile.write("\n")
325 
326  if OutputFileName:
327  logging.debug("GDML written to file '%s'", OutputFileName)
328  # if output
329 
330 # RemoveMathFromXMLfile()
331 
open(RACETRACK) or die("Could not open file $RACETRACK for writing")
def RemoveMathFromGDML.RunParserOn (   parser,
  InputFileName,
  options = None 
)
Renames the input file into '.bak', then runs the parser

Definition at line 344 of file RemoveMathFromGDML.py.

345 def RunParserOn(parser, InputFileName, options = None):
346  """Renames the input file into '.bak', then runs the parser"""
347 
348  OldInputFileName = InputFileName
349  OutputFileName = OldInputFileName
350 
351  if not options.Fake:
352  InputFileName += ".bak"
353 
354  # rename the input file
355  if os.path.exists(InputFileName):
356  raise ConfigurationError(
357  "Backup file '%s' is on the way. Please remove it first."
358  % InputFileName
359  )
360  # if exists
361  logging.debug("Renaming the input file into '%s'", InputFileName)
362  os.rename(OldInputFileName, InputFileName)
363  # if not dry run
364 
365  # run the parser
366  try:
367  parser(InputFileName, OutputFileName, options=options)
368  except Exception, e:
369  if not options.Fake:
370  # if no output file was produced, rename back the input
371  if not os.path.exists(OutputFileName):
372  logging.debug("Restoring the input file name after a fatal error.")
373  os.rename(InputFileName, OldInputFileName)
374  # if
375  raise e
376  # try ... except
377 
378  if not options.Fake:
379  logging.info("File '%s' rewritten (old file in '%s')",
380  OutputFileName, InputFileName
381  )
382  # if
383 
384 # RunParserOn()
385 

Variable Documentation

string RemoveMathFromGDML.__doc__
Initial value:
1 = """Evaluates and replaces mathematical expressions from a GDML file.
2 
3 By default, each of the input file is renamed into a .bak file, and the output
4 replaces the old file. If no input file is specified, the file is read from standard
5 input and output to standard output, or to the value of the '--output' option.
6 The output option can also be specified to set the output file name, in which case
7 the input file is not renamed. If empty, output will be to standard output.
8 
9 This scripts supports two modes:
10 - direct parser: a simple parser that looks for patterns '="xxx"' in a line
11  and replaces xxx with its value; it preserves the form of the input,
12  but it might silently fail to parse good GDML
13 - XML parser: a python XML parser evaluates the GDML file completely, then it
14  writes it anew; it will parse any XML, but it loses comments and can change
15  the order of the attributes
16 The XML parser is easy to extend to include "define" GDML lines, that are not
17 currently supported.
18 
19 Expressions are evaluated by ROOT TFormula.
20 """

Definition at line 33 of file RemoveMathFromGDML.py.

string RemoveMathFromGDML.__version__ = "1.6"

Definition at line 53 of file RemoveMathFromGDML.py.

RemoveMathFromGDML.hasXML = True

Definition at line 61 of file RemoveMathFromGDML.py.