Classes | Functions | Variables
RemoveMathFromGDML Namespace Reference

Classes

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

Functions

def RemoveMathFromGDMLfile (InputFileName, OutputFileName=None, options=None)
 
def ApplyToNodes (node, level, func, args, kargs)
 
def ApplyToDocument (document, func, args, kargs)
 
def RemoveMathFromXMLfile (InputFileName, OutputFileName=None, options=None)
 
def LoggingSetup (LoggingLevel=logging.INFO)
 
def RunParserOn (parser, InputFileName, options=None)
 
def RemoveMathFromGDML ()
 

Variables

string __doc__
 
string __version__ = "1.6"
 
bool hasXML = True
 

Function Documentation

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

Definition at line 298 of file RemoveMathFromGDML.py.

298 def ApplyToDocument(document, func, *args, **kargs):
299  ApplyToNodes(document, 0, func, *args, **kargs)
300 
301 
def ApplyToNodes(node, level, func, args, kargs)
def ApplyToDocument(document, func, args, kargs)
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.

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

Definition at line 333 of file RemoveMathFromGDML.py.

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

Definition at line 387 of file RemoveMathFromGDML.py.

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

Definition at line 223 of file RemoveMathFromGDML.py.

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

Definition at line 302 of file RemoveMathFromGDML.py.

302 def RemoveMathFromXMLfile(InputFileName, OutputFileName = None, options = None):
303 
304  # if InputFileName is empty, use standard input
305  InputFile = open(InputFileName, 'r') if InputFileName else sys.stdin
306 
307  # parse GDML document using minidom parser
308  DOMTree = xml.dom.minidom.parse(InputFile)
309  GDML = DOMTree.documentElement
310 
311  RemoveGDMLexpression = XMLpurifier()
312 
313  ApplyToDocument(GDML, RemoveGDMLexpression.purifyNode)
314 
315 
316  if options.Fake:
317  logging.info("Output will not be written in dry-run mode.")
318  else:
319  # if OutputFileName is empty, use standard output; otherwise, overwrite
320  OutputFile = open(OutputFileName, 'w') if OutputFileName else sys.stdout
321 
322  OutputFile.write(GDML.toxml())
323  OutputFile.write("\n")
324 
325  if OutputFileName:
326  logging.debug("GDML written to file '%s'", OutputFileName)
327  # if output
328 
329 # RemoveMathFromXMLfile()
330 
331 
int open(const char *, int)
Opens a file descriptor.
def ApplyToDocument(document, func, args, kargs)
def RemoveMathFromXMLfile(InputFileName, OutputFileName=None, options=None)
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.

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

Variable Documentation

string RemoveMathFromGDML.__doc__
private
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"
private

Definition at line 53 of file RemoveMathFromGDML.py.

RemoveMathFromGDML.hasXML = True

Definition at line 61 of file RemoveMathFromGDML.py.