fudge.core.utilities package

Submodules

fudge.core.utilities.abundance module

Directory: masses/ File: abundance.readme (December 10, 2007) *******************************************

abundance.dat

Natural abundances of stable isotopes

Content

The abundance file is a reformatted version of the file from the Nuclear Wallet cards (2005), as retrieved from Brookhaven National Laboratory. The abundances are given for all stable isotopes.

Format

Each record of the file contains:

Z : charge number A : mass number El : element symbol abundance: abundance in % uncert : uncertainties in abundance in %

The corresponding FORTRAN format is (2i4,1x,a2,1x,2f10.6)

References

[1] J.K. Tuli, Nuclear Wallet Cards (NNDC, Brookhaven National Laboratory), 2005.

Dates: Original 10 December, 2007

fudge.core.utilities.abundance.getAbundance(Z, A)[source]
fudge.core.utilities.abundance.getElementsNaturalIsotopes(Z)[source]

fudge.core.utilities.argparse module

fudge.core.utilities.brb module

This module contains a set of functions that are hopefully useful when using python.

fudge.core.utilities.brb.CheckListForSameTypeOfObjects(l, e)[source]

For internal use only.

fudge.core.utilities.brb.Pause(Prompt='Enter <RET> to continue : ', ExtraStr='')[source]

Prompts and waits for user to enter a line. The line is returned. ExtraStr is added to the prompt string.

fudge.core.utilities.brb.banner(s, justification='c')[source]

A flower-box ascii banner generator. The input string can have line feeds. Each line will get centered in the box.

fudge.core.utilities.brb.doc(a)[source]

This function simply executes “print a.__doc__” where “a” is the argument.

fudge.core.utilities.brb.docmethods(o, Full=1)[source]

This function attempts to print all methods and their documentation contained in the first argument.

fudge.core.utilities.brb.getType(o)[source]
fudge.core.utilities.brb.get_dict_attr(obj, attr)[source]
fudge.core.utilities.brb.isFunctionLike(obj)[source]
fudge.core.utilities.brb.limitObjectToString(object)[source]
fudge.core.utilities.brb.objectoutline(o, MaxLevel=1, Full=1)[source]

This routine attempts to print the objects - methods, members and possible other things - that are a part of the first argument. It will recursively traverse each object found down to level MaxLevel.

fudge.core.utilities.brb.objectoutline2(o, MaxLevel, level, name, Full)[source]

For internal use only.

fudge.core.utilities.brb.objectoutline2ClassesOnly(o, level, name)[source]

For internal use only!

fudge.core.utilities.brb.objectvalues(o)[source]

Prints a list of all objects return by dir( o ) and their data (or object type) where “o” is the first argument.

fudge.core.utilities.brb.objectvalues2(o, name)[source]

For internal use only.

fudge.core.utilities.brb.py(depth=1, start=0)[source]

This routine prints all python scripts in sys.path[start:start+depth] in a nice format.

fudge.core.utilities.brb.tdir(a=None, w=5, pattern=None, wpattern=None)[source]

This function is an attempt at improving the output of python’s dir function. It uses tlist to print the output in a more readable format. The argument w is passed to tlist. The argument pattern, if not None, is used to restrict the items displayed to those that match it. Pattern can be any pattern understood by the re module (e.g., to display all items containing the two consecutive letters “2d” set pattern to “.*2d.*”). If pattern is None and wpattern is NOT None then pattern is set to “.*” + wpattern + “.*”.

fudge.core.utilities.brb.tlist(l, w=5, sep=None, rightJustify=0)[source]

Calls tylist with arguments passed.

fudge.core.utilities.brb.tlistMaxLen(l, rightJustify)[source]

For internal use only.

fudge.core.utilities.brb.txlist(l, w=5, sep=None, rightJustify=0)[source]

Prints the list given by the first argument in a tabled format. The purpose of this function is to print a python list in a more readable format. The number of items from list printed per line is set by w. The argument sep, if not None, is printed as a separator between each item on a line. The items are left justified unless the argument rightJustify is true. This function prints each w consecutive items horizontally. Also see tylist.

fudge.core.utilities.brb.tylist(l, w=5, sep=None, rightJustify=0)[source]

Prints the list given by the first argument in a tabled format. The purpose of this function is to print a python list in a more readable format. The number of items from list printed per line is set by w. The argument sep, if not None, is printed as a separator between each item on a line. The items are left justified unless the argument rightJustify is true. This function prints each consecutive item vertically while maintaining w columns. Also see txlist.

fudge.core.utilities.brb.uniquify(seq)[source]

Fast implimentation of a function to strip out non-unique entries in a Python list, but preserving list order. Usage:

>>> print uniquify( [1,4,2,4,7,2,1,1,1,'s','a',0.1] ) 
    [1, 4, 2, 7, 's', 'a', 0.10000000000000001]
fudge.core.utilities.brb.winged_banner(x, wingsize=10)[source]

fudge.core.utilities.fudgeExceptions module

This module contains the fudge exception classes.

exception fudge.core.utilities.fudgeExceptions.ENDL_CheckerException(value)[source]

Bases: fudge.core.utilities.fudgeExceptions.FUDGE_Exception

This class is raised whenever a check method detects bad ENDL data.

exception fudge.core.utilities.fudgeExceptions.ENDL_DesignerIsotopeReadException[source]

Bases: exceptions.Exception

This class is raised whenever read is called on a designer isotope.

exception fudge.core.utilities.fudgeExceptions.ENDL_addFileException_FileExist(value)[source]

Bases: fudge.core.utilities.fudgeExceptions.FUDGE_Exception

This class is raised whenever endlZA.addFile is called and the file already exists.

exception fudge.core.utilities.fudgeExceptions.ENDL_fixHeadersException_NoC10Data(value)[source]

Bases: fudge.core.utilities.fudgeExceptions.FUDGE_Exception

This class is raised whenever endlZA.fixHeaders needs missing header data and cannot find the C = 10, I = 0 which it assumes as valid header data.

exception fudge.core.utilities.fudgeExceptions.ENDL_numpyException[source]

Bases: exceptions.Exception

This class is raised whenever an error is detected with the numpy module.

exception fudge.core.utilities.fudgeExceptions.FUDGE_Exception(value)[source]

Bases: exceptions.Exception

This class is raised whenever fudge detects an error that is not handled by another FUDGE/ENDL exception.

fudge.core.utilities.fudgeFileMisc module

This module contains the class fudgeTempFile which simplies the functions in the tempfile module.

class fudge.core.utilities.fudgeFileMisc.fudgeTempFile(prefix=None, suffix='', dir=None, deleteOnClose=False)[source]

Bases: object

This class creates a temporary file using tempfile.mkstemp and supports common functionallity for the file (e.g., write). Currently, reading from the temporary file is not supported.

close(raiseIfClosed=True)[source]

Closes the file if still opened. If raiseIfClosed is ‘True’ and file is already closed, a raise is executed.

delete()[source]

Deletes file if it still exist. If required, this method calls close first. If file has already been deleted, a raise is executed.

getFileDescriptor()[source]

Returns self’s file descriptor.

getName()[source]

Returns self’s name which is the full path name of the temporary file.

isDeleted()[source]

Returns ‘True’ if the file has been deleted.

isOpened()[source]

Returns ‘True’ if the file is still opened.

write(str)[source]

Write str to file. If file is closed or not all characters were written then a raise is executed.

fudge.core.utilities.fudgeZA module

Convert between Z, symbol and element name. adapted from endl_Z cmattoon, March 2011

fudge.core.utilities.fudgeZA.LabelToZ(label)[source]

Returns the Z for the specified label or ‘None’ if no match for label.

fudge.core.utilities.fudgeZA.SymbolToZ(symbol)[source]

Returns the Z for the specified symbol or ‘None’ if no match for symbol.

fudge.core.utilities.fudgeZA.ZAToGNDSName(ZA)[source]

Converts an ENDL ZA or ‘zaZZZAAA_suffix’ into a GNDS name. For example ENDL 94239 or ‘za094239’, is converted to ‘Pu239’.

fudge.core.utilities.fudgeZA.ZToLabel(Z)[source]

Returns the label (i.e., name) for the specified Z or ‘None’ if Z is out-of-bounds.

fudge.core.utilities.fudgeZA.ZToSymbol(Z)[source]

Returns the symbol for the specified Z or ‘None’ if Z is out-of-bounds.

fudge.core.utilities.fudgeZA.gndsNameToZ_A_Suffix(name)[source]

Returns the tuple (Z, A, suffix, ZA) for an gnds isotope name (e.g., gnds name = ‘Am242_m1’ returns ( 95, 242, ‘m1’, 95242 ).

fudge.core.utilities.pyparsing module

pyparsing module - Classes and methods to define and execute parsing grammars

The pyparsing module is an alternative approach to creating and executing simple grammars, vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you don’t need to learn a new syntax for defining grammars or matching expressions - the parsing module provides a library of classes that you use to construct the grammar directly in Python.

Here is a program to parse “Hello, World!” (or any greeting of the form C{“<salutation>, <addressee>!”}):

from pyparsing import Word, alphas

# define grammar of a greeting
greet = Word( alphas ) + "," + Word( alphas ) + "!"

hello = "Hello, World!"
print hello, "->", greet.parseString( hello )

The program outputs the following:

Hello, World! -> ['Hello', ',', 'World', '!']

The Python representation of the grammar is quite readable, owing to the self-explanatory class names, and the use of ‘+’, ‘|’ and ‘^’ operators.

The parsed results returned from C{parseString()} can be accessed as a nested list, a dictionary, or an object with named attributes.

The pyparsing module handles some of the problems that are typically vexing when writing text parsers:
  • extra or missing whitespace (the above program will also handle “Hello,World!”, “Hello , World !”, etc.)
  • quoted strings
  • embedded comments
class fudge.core.utilities.pyparsing.And(exprs, savelist=True)[source]

Bases: fudge.core.utilities.pyparsing.ParseExpression

Requires all given C{ParseExpressions} to be found in the given order. Expressions may be separated by whitespace. May be constructed using the ‘+’ operator.

checkRecursion(parseElementList)[source]
parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.CaselessKeyword(matchString, identChars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$')[source]

Bases: fudge.core.utilities.pyparsing.Keyword

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.CaselessLiteral(matchString)[source]

Bases: fudge.core.utilities.pyparsing.Literal

Token to match a specified string, ignoring case of letters. Note: the matched results will always be in the case of the given match string, NOT the case of the input text.

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.CharsNotIn(notChars, min=1, max=0, exact=0)[source]

Bases: fudge.core.utilities.pyparsing.Token

Token for matching words composed of characters not in a given set. Defined with string containing all disallowed characters, and an optional minimum, maximum, and/or exact length. The default value for C{min} is 1 (a minimum value < 1 is not valid); the default values for C{max} and C{exact} are 0, meaning no maximum or exact length restriction.

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.Combine(expr, joinString='', adjacent=True)[source]

Bases: fudge.core.utilities.pyparsing.TokenConverter

Converter to concatenate all matching tokens to a single string. By default, the matching patterns must also be contiguous in the input string; this can be disabled by specifying C{‘adjacent=False’} in the constructor.

ignore(other)[source]
postParse(instring, loc, tokenlist)[source]
class fudge.core.utilities.pyparsing.Dict(exprs)[source]

Bases: fudge.core.utilities.pyparsing.TokenConverter

Converter to return a repetitive expression as a list, but also as a dictionary. Each element can also be referenced using the first token in the expression as its key. Useful for tabular report scraping when the first column can be used as a item key.

postParse(instring, loc, tokenlist)[source]
class fudge.core.utilities.pyparsing.Each(exprs, savelist=True)[source]

Bases: fudge.core.utilities.pyparsing.ParseExpression

Requires all given C{ParseExpressions} to be found, but in any order. Expressions may be separated by whitespace. May be constructed using the ‘&’ operator.

checkRecursion(parseElementList)[source]
parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.Empty[source]

Bases: fudge.core.utilities.pyparsing.Token

An empty token, will always match.

class fudge.core.utilities.pyparsing.FollowedBy(expr)[source]

Bases: fudge.core.utilities.pyparsing.ParseElementEnhance

Lookahead matching of the given parse expression. C{FollowedBy} does not advance the parsing position within the input string, it only verifies that the specified parse expression matches at the current position. C{FollowedBy} always returns a null token list.

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.Forward(other=None)[source]

Bases: fudge.core.utilities.pyparsing.ParseElementEnhance

Forward declaration of an expression to be defined later - used for recursive grammars, such as algebraic infix notation. When the expression is known, it is assigned to the C{Forward} variable using the ‘<<’ operator.

Note: take care when assigning to C{Forward} not to overlook precedence of operators. Specifically, ‘|’ has a lower precedence than ‘<<’, so that:

fwdExpr << a | b | c
will actually be evaluated as::
(fwdExpr << a) | b | c

thereby leaving b and c out as parseable alternatives. It is recommended that you explicitly group the values inserted into the C{Forward}:

fwdExpr << (a | b | c)
copy()[source]
leaveWhitespace()[source]
streamline()[source]
validate(validateTrace=[])[source]
class fudge.core.utilities.pyparsing.GoToColumn(colno)[source]

Bases: fudge.core.utilities.pyparsing._PositionToken

Token to advance to a specific column of input text; useful for tabular report scraping.

parseImpl(instring, loc, doActions=True)[source]
preParse(instring, loc)[source]
class fudge.core.utilities.pyparsing.Group(expr)[source]

Bases: fudge.core.utilities.pyparsing.TokenConverter

Converter to return the matched tokens as a list - useful for returning tokens of ZeroOrMore and OneOrMore expressions.

postParse(instring, loc, tokenlist)[source]
class fudge.core.utilities.pyparsing.Keyword(matchString, identChars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$', caseless=False)[source]

Bases: fudge.core.utilities.pyparsing.Token

Token to exactly match a specified string as a keyword, that is, it must be immediately followed by a non-keyword character. Compare with C{Literal}:

Literal("if") will match the leading 'if' in 'ifAndOnlyIf'.
Keyword("if") will not; it will only match the leading 'if in 'if x=1', or 'if(y==2)'

Accepts two optional constructor arguments in addition to the keyword string: C{identChars} is a string of characters that would be valid identifier characters, defaulting to all alphanumerics + “_” and “$”; C{caseless} allows case-insensitive matching, default is False.

DEFAULT_KEYWORD_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$'
copy()[source]
parseImpl(instring, loc, doActions=True)[source]
static setDefaultKeywordChars(chars)[source]

Overrides the default Keyword chars

class fudge.core.utilities.pyparsing.LineEnd[source]

Bases: fudge.core.utilities.pyparsing._PositionToken

Matches if current position is at the end of a line within the parse string

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.LineStart[source]

Bases: fudge.core.utilities.pyparsing._PositionToken

Matches if current position is at the beginning of a line within the parse string

parseImpl(instring, loc, doActions=True)[source]
preParse(instring, loc)[source]
class fudge.core.utilities.pyparsing.Literal(matchString)[source]

Bases: fudge.core.utilities.pyparsing.Token

Token to exactly match a specified string.

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.MatchFirst(exprs, savelist=False)[source]

Bases: fudge.core.utilities.pyparsing.ParseExpression

Requires that at least one C{ParseExpression} is found. If two expressions match, the first one listed is the one that will match. May be constructed using the ‘|’ operator.

checkRecursion(parseElementList)[source]
parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.NoMatch[source]

Bases: fudge.core.utilities.pyparsing.Token

A token that will never match.

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.NotAny(expr)[source]

Bases: fudge.core.utilities.pyparsing.ParseElementEnhance

Lookahead to disallow matching with the given parse expression. C{NotAny} does not advance the parsing position within the input string, it only verifies that the specified parse expression does not match at the current position. Also, C{NotAny} does not skip over leading whitespace. C{NotAny} always returns a null token list. May be constructed using the ‘~’ operator.

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.OneOrMore(expr, savelist=False)[source]

Bases: fudge.core.utilities.pyparsing.ParseElementEnhance

Repetition of one or more of the given expression.

parseImpl(instring, loc, doActions=True)[source]
setResultsName(name, listAllMatches=False)[source]
class fudge.core.utilities.pyparsing.OnlyOnce(methodCall)[source]

Bases: object

Wrapper for parse actions, to ensure they are only called once.

reset()[source]
class fudge.core.utilities.pyparsing.Optional(exprs, default=<fudge.core.utilities.pyparsing._NullToken object>)[source]

Bases: fudge.core.utilities.pyparsing.ParseElementEnhance

Optional matching of the given expression. A default return string can also be specified, if the optional expression is not found.

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.Or(exprs, savelist=False)[source]

Bases: fudge.core.utilities.pyparsing.ParseExpression

Requires that at least one C{ParseExpression} is found. If two expressions match, the expression that matches the longest string will be used. May be constructed using the ‘^’ operator.

checkRecursion(parseElementList)[source]
parseImpl(instring, loc, doActions=True)[source]
exception fudge.core.utilities.pyparsing.ParseBaseException(pstr, loc=0, msg=None, elem=None)[source]

Bases: exceptions.Exception

Base exception class for all parsing runtime exceptions

markInputline(markerString='>!<')[source]

Extracts the exception line from the input string, and marks the location of the exception with a special symbol.

class fudge.core.utilities.pyparsing.ParseElementEnhance(expr, savelist=False)[source]

Bases: fudge.core.utilities.pyparsing.ParserElement

Abstract subclass of C{ParserElement}, for combining and post-processing parsed tokens.

checkRecursion(parseElementList)[source]
ignore(other)[source]
leaveWhitespace()[source]
parseImpl(instring, loc, doActions=True)[source]
streamline()[source]
validate(validateTrace=[])[source]
exception fudge.core.utilities.pyparsing.ParseException(pstr, loc=0, msg=None, elem=None)[source]

Bases: fudge.core.utilities.pyparsing.ParseBaseException

Exception thrown when parse expressions don’t match class; supported attributes by name are:

  • lineno - returns the line number of the exception text
  • col - returns the column number of the exception text
  • line - returns the line containing the exception text
class fudge.core.utilities.pyparsing.ParseExpression(exprs, savelist=False)[source]

Bases: fudge.core.utilities.pyparsing.ParserElement

Abstract subclass of ParserElement, for combining and post-processing parsed tokens.

append(other)[source]
ignore(other)[source]
leaveWhitespace()[source]

Extends leaveWhitespace defined in base class, and also invokes leaveWhitespace on all contained expressions.

setResultsName(name, listAllMatches=False)[source]
streamline()[source]
validate(validateTrace=[])[source]
exception fudge.core.utilities.pyparsing.ParseFatalException(pstr, loc=0, msg=None, elem=None)[source]

Bases: fudge.core.utilities.pyparsing.ParseBaseException

User-throwable exception thrown when inconsistent parse content is found; stops all parsing immediately

class fudge.core.utilities.pyparsing.ParseResults(toklist, name=None, asList=True, modal=True, isinstance=<built-in function isinstance>)[source]

Bases: object

Structured parse results, to provide multiple means of access to the parsed data: - as a list (C{len(results)}) - by list index (C{results[0], results[1]}, etc.) - by attribute (C{results.<resultsName>})

asDict()[source]

Returns the named parse results as dictionary.

asList()[source]

Returns the parse results as a nested list of matching tokens, all converted to strings.

asXML(doctag=None, namedItemsOnly=False, indent='', formatted=True)[source]

Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.

copy()[source]

Returns a new copy of a C{ParseResults} object.

dump(indent='', depth=0)[source]

Diagnostic method for listing out the contents of a C{ParseResults}. Accepts an optional C{indent} argument so that this string can be embedded in a nested display of other data.

get(key, defaultValue=None)[source]

Returns named result matching the given key, or if there is no such name, then returns the given C{defaultValue} or C{None} if no C{defaultValue} is specified.

getName()[source]

Returns the results name for this token expression.

insert(index, insStr)[source]

Inserts new element at location index in the list of parsed tokens.

items()[source]

Returns all named result keys and values as a list of tuples.

keys()[source]

Returns all named result keys.

pop(index=-1)[source]

Removes and returns item at specified index (default=last). Will work with either numeric indices or dict-key indicies.

values()[source]

Returns all named result values.

exception fudge.core.utilities.pyparsing.ParseSyntaxException(pe)[source]

Bases: fudge.core.utilities.pyparsing.ParseFatalException

Just like C{ParseFatalException}, but thrown internally when an C{ErrorStop} (‘-‘ operator) indicates that parsing is to stop immediately because an unbacktrackable syntax error has been found

class fudge.core.utilities.pyparsing.ParserElement(savelist=False)[source]

Bases: object

Abstract base level parser element class.

DEFAULT_WHITE_CHARS = ' \n\t\r'
addParseAction(*fns, **kwargs)[source]

Add parse action to expression’s list of parse actions. See L{I{setParseAction}<setParseAction>}.

checkRecursion(parseElementList)[source]
copy()[source]

Make a copy of this C{ParserElement}. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element.

static enablePackrat()[source]

Enables “packrat” parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing parsing/validating code. Memoizing is done of both valid results and parsing exceptions.

This speedup may break existing programs that use parse actions that have side-effects. For this reason, packrat parsing is disabled when you first import pyparsing. To activate the packrat feature, your program must call the class method C{ParserElement.enablePackrat()}. If your program uses C{psyco} to “compile as you go”, you must call C{enablePackrat} before calling C{psyco.full()}. If you do not do this, Python will crash. For best results, call C{enablePackrat()} immediately after importing pyparsing.

getException()[source]
ignore(other)[source]

Define expression to be ignored (e.g., comments) while doing pattern matching; may be called repeatedly, to define multiple comment or other ignorable patterns.

leaveWhitespace()[source]

Disables the skipping of whitespace before matching the characters in the C{ParserElement}’s defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars.

parseFile(file_or_filename, parseAll=False)[source]

Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing.

parseImpl(instring, loc, doActions=True)[source]
parseString(instring, parseAll=False)[source]

Execute the parse expression with the given string. This is the main interface to the client code, once the complete expression has been built.

If you want the grammar to require that the entire input string be successfully parsed, then set C{parseAll} to True (equivalent to ending the grammar with C{StringEnd()}).

Note: C{parseString} implicitly calls C{expandtabs()} on the input string, in order to report proper column numbers in parse actions. If the input string contains tabs and the grammar uses parse actions that use the C{loc} argument to index into the string being parsed, you can ensure you have a consistent view of the input string by:

  • calling C{parseWithTabs} on your grammar before calling C{parseString} (see L{I{parseWithTabs}<parseWithTabs>})
  • define your parse action using the full C{(s,loc,toks)} signature, and reference the input string using the parse action’s C{s} argument
  • explictly expand the tabs in your input string before calling C{parseString}
parseWithTabs()[source]

Overrides default behavior to expand <TAB>s to spaces before parsing the input string. Must be called before C{parseString} when the input grammar contains elements that match <TAB> characters.

postParse(instring, loc, tokenlist)[source]
preParse(instring, loc)[source]
static resetCache()[source]
scanString(instring, maxMatches=9223372036854775807)[source]

Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional C{maxMatches} argument, to clip scanning after ‘n’ matches are found.

Note that the start and end locations are reported relative to the string being parsed. See L{I{parseString}<parseString>} for more information on parsing strings with embedded tabs.

searchString(instring, maxMatches=9223372036854775807)[source]

Another extension to C{scanString}, simplifying the access to the tokens found to match the given parse expression. May be called with optional C{maxMatches} argument, to clip searching after ‘n’ matches are found.

setBreak(breakFlag=True)[source]

Method to invoke the Python pdb debugger when this element is about to be parsed. Set C{breakFlag} to True to enable, False to disable.

setDebug(flag=True)[source]

Enable display of debugging messages while doing pattern matching. Set C{flag} to True to enable, False to disable.

setDebugActions(startAction, successAction, exceptionAction)[source]

Enable display of debugging messages while doing pattern matching.

static setDefaultWhitespaceChars(chars)[source]

Overrides the default whitespace chars

setFailAction(fn)[source]

Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments C{fn(s,loc,expr,err)} where:

  • s = string being parsed
  • loc = location where expression match was attempted and failed
  • expr = the parse expression that failed
  • err = the exception thrown

The function returns no value. It may throw C{ParseFatalException} if it is desired to stop parsing immediately.

setName(name)[source]

Define name for this expression, for use in debugging.

setParseAction(*fns, **kwargs)[source]

Define action to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:

  • s = the original string being parsed (see note below)
  • loc = the location of the matching substring
  • toks = a list of the matched tokens, packaged as a ParseResults object

If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value.

Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{parseString}<parseString>} for more information on parsing strings containing <TAB>s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string.

setResultsName(name, listAllMatches=False)[source]

Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a copy of the original C{ParserElement} object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names.

You can also set results names using the abbreviated syntax, C{expr(“name”)} in place of C{expr.setResultsName(“name”)} - see L{I{__call__}<__call__>}.

setWhitespaceChars(chars)[source]

Overrides the default whitespace chars

streamline()[source]
suppress()[source]

Suppresses the output of this C{ParserElement}; useful to keep punctuation from cluttering up returned output.

transformString(instring)[source]

Extension to C{scanString}, to modify matching text with modified tokens that may be returned from a parse action. To use C{transformString}, define a grammar and attach a parse action to it that modifies the returned token list. Invoking C{transformString()} on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. C{transformString()} returns the resulting transformed string.

tryParse(instring, loc)[source]
validate(validateTrace=[])[source]

Check defined expressions for valid structure, check for infinite recursive definitions.

verbose_stacktrace = False
class fudge.core.utilities.pyparsing.QuotedString(quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None)[source]

Bases: fudge.core.utilities.pyparsing.Token

Token for matching strings that are delimited by quoting characters.

parseImpl(instring, loc, doActions=True)[source]
exception fudge.core.utilities.pyparsing.RecursiveGrammarException(parseElementList)[source]

Bases: exceptions.Exception

Exception thrown by C{validate()} if the grammar could be improperly recursive

class fudge.core.utilities.pyparsing.Regex(pattern, flags=0)[source]

Bases: fudge.core.utilities.pyparsing.Token

Token for matching strings that match a given regular expression. Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module.

compiledREtype

alias of SRE_Pattern

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.SkipTo(other, include=False, ignore=None, failOn=None)[source]

Bases: fudge.core.utilities.pyparsing.ParseElementEnhance

Token for skipping over all undefined text until the matched expression is found. If C{include} is set to true, the matched expression is also parsed (the skipped text and matched expression are returned as a 2-element list). The C{ignore} argument is used to define grammars (typically quoted strings and comments) that might contain false matches.

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.StringEnd[source]

Bases: fudge.core.utilities.pyparsing._PositionToken

Matches if current position is at the end of the parse string

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.StringStart[source]

Bases: fudge.core.utilities.pyparsing._PositionToken

Matches if current position is at the beginning of the parse string

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.Suppress(expr, savelist=False)[source]

Bases: fudge.core.utilities.pyparsing.TokenConverter

Converter for ignoring the results of a parsed expression.

postParse(instring, loc, tokenlist)[source]
suppress()[source]
class fudge.core.utilities.pyparsing.Token[source]

Bases: fudge.core.utilities.pyparsing.ParserElement

Abstract C{ParserElement} subclass, for defining atomic matching patterns.

setName(name)[source]
class fudge.core.utilities.pyparsing.TokenConverter(expr, savelist=False)[source]

Bases: fudge.core.utilities.pyparsing.ParseElementEnhance

Abstract subclass of ParseExpression, for converting parsed results.

class fudge.core.utilities.pyparsing.Upcase(*args)[source]

Bases: fudge.core.utilities.pyparsing.TokenConverter

Converter to upper case all matching tokens.

postParse(instring, loc, tokenlist)[source]
class fudge.core.utilities.pyparsing.White(ws=' trn', min=1, max=0, exact=0)[source]

Bases: fudge.core.utilities.pyparsing.Token

Special matching class for matching whitespace. Normally, whitespace is ignored by pyparsing grammars. This class is included when some whitespace structures are significant. Define with a string containing the whitespace characters to be matched; default is C{” trn”}. Also takes optional C{min}, C{max}, and C{exact} arguments, as defined for the C{Word} class.

parseImpl(instring, loc, doActions=True)[source]
whiteStrs = {'\t': '<TAB>', ' ': '<SPC>', '\n': '<LF>', '\r': '<CR>', '\x0c': '<FF>'}
class fudge.core.utilities.pyparsing.Word(initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False)[source]

Bases: fudge.core.utilities.pyparsing.Token

Token for matching words composed of allowed character sets. Defined with string containing all allowed initial characters, an optional string containing allowed body characters (if omitted, defaults to the initial character set), and an optional minimum, maximum, and/or exact length. The default value for C{min} is 1 (a minimum value < 1 is not valid); the default values for C{max} and C{exact} are 0, meaning no maximum or exact length restriction.

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.WordEnd(wordChars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+, -./:;<=>?@[\]^_`{|}~')[source]

Bases: fudge.core.utilities.pyparsing._PositionToken

Matches if the current position is at the end of a Word, and is not followed by any character in a given set of wordChars (default=C{printables}). To emulate the C{} behavior of regular expressions, use C{WordEnd(alphanums)}. C{WordEnd} will also match at the end of the string being parsed, or at the end of a line.

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.WordStart(wordChars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+, -./:;<=>?@[\]^_`{|}~')[source]

Bases: fudge.core.utilities.pyparsing._PositionToken

Matches if the current position is at the beginning of a Word, and is not preceded by any character in a given set of wordChars (default=C{printables}). To emulate the C{} behavior of regular expressions, use C{WordStart(alphanums)}. C{WordStart} will also match at the beginning of the string being parsed, or at the beginning of a line.

parseImpl(instring, loc, doActions=True)[source]
class fudge.core.utilities.pyparsing.ZeroOrMore(expr)[source]

Bases: fudge.core.utilities.pyparsing.ParseElementEnhance

Optional repetition of zero or more of the given expression.

parseImpl(instring, loc, doActions=True)[source]
setResultsName(name, listAllMatches=False)[source]
fudge.core.utilities.pyparsing.col(loc, strg)[source]

Returns current column within a string, counting newlines as line separators. The first column is number 1.

Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information on parsing strings containing <TAB>s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string.

fudge.core.utilities.pyparsing.countedArray(expr)[source]

Helper to define a counted list of expressions. This helper defines a pattern of the form:

integer expr expr expr...

where the leading integer tells how many expr expressions follow. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.

fudge.core.utilities.pyparsing.delimitedList(expr, delim=', ', combine=False)[source]

Helper to define a delimited list of expressions - the delimiter defaults to ‘,’. By default, the list elements and delimiters can have intervening whitespace, and comments, but this can be overridden by passing C{combine=True} in the constructor. If C{combine} is set to True, the matching tokens are returned as a single token string, with the delimiters included; otherwise, the matching tokens are returned as a list of tokens, with the delimiters suppressed.

fudge.core.utilities.pyparsing.dictOf(key, value)[source]

Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the C{Dict}, C{ZeroOrMore}, and C{Group} tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the C{Dict} results can include named token fields.

fudge.core.utilities.pyparsing.downcaseTokens(s, l, t)[source]

Helper parse action to convert tokens to lower case.

fudge.core.utilities.pyparsing.getTokensEndLoc()[source]

Method to be called from within a parse action to determine the end location of the parsed tokens.

fudge.core.utilities.pyparsing.keepOriginalText(s, startLoc, t)[source]

DEPRECATED - use new helper method C{originalTextFor}. Helper parse action to preserve original parsed text, overriding any nested parse actions.

fudge.core.utilities.pyparsing.line(loc, strg)[source]

Returns the line of text containing loc within a string, counting newlines as line separators.

fudge.core.utilities.pyparsing.lineno(loc, strg)[source]

Returns current line number within a string, counting newlines as line separators. The first line is number 1.

Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information on parsing strings containing <TAB>s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string.

fudge.core.utilities.pyparsing.makeHTMLTags(tagStr)[source]

Helper to construct opening and closing tag expressions for HTML, given a tag name

fudge.core.utilities.pyparsing.makeXMLTags(tagStr)[source]

Helper to construct opening and closing tag expressions for XML, given a tag name

fudge.core.utilities.pyparsing.matchOnlyAtCol(n)[source]

Helper method for defining parse actions that require matching at a specific column in the input text.

fudge.core.utilities.pyparsing.matchPreviousExpr(expr)[source]

Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a ‘repeat’ of a previous expression. For example:

first = Word(nums)
second = matchPreviousExpr(first)
matchExpr = first + ":" + second

will match C{“1:1”}, but not C{“1:2”}. Because this matches by expressions, will not match the leading C{“1:1”} in C{“1:10”}; the expressions are evaluated first, and then compared, so C{“1”} is compared with C{“10”}. Do not use with packrat parsing enabled.

fudge.core.utilities.pyparsing.matchPreviousLiteral(expr)[source]

Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a ‘repeat’ of a previous expression. For example:

first = Word(nums)
second = matchPreviousLiteral(first)
matchExpr = first + ":" + second

will match C{“1:1”}, but not C{“1:2”}. Because this matches a previous literal, will also match the leading C{“1:1”} in C{“1:10”}. If this is not desired, use C{matchPreviousExpr}. Do not use with packrat parsing enabled.

fudge.core.utilities.pyparsing.nestedExpr(opener='(', closer=')', content=None, ignoreExpr=quotedString using single or double quotes)[source]

Helper method for defining nested lists enclosed in opening and closing delimiters (“(” and “)” are the default).

Parameters:
  • opener - opening character for a nested list (default=”(“); can also be a pyparsing expression
  • closer - closing character for a nested list (default=”)”); can also be a pyparsing expression
  • content - expression for items within the nested lists (default=None)
  • ignoreExpr - expression for ignoring opening and closing delimiters (default=quotedString)

If an expression is not provided for the content argument, the nested expression will capture all whitespace-delimited content between delimiters as a list of separate values.

Use the ignoreExpr argument to define expressions that may contain opening or closing characters that should not be treated as opening or closing characters for nesting, such as quotedString or a comment expression. Specify multiple expressions using an Or or MatchFirst. The default is quotedString, but if no expressions are to be ignored, then pass None for this argument.

fudge.core.utilities.pyparsing.nullDebugAction(*args)[source]

‘Do-nothing’ debug action, to suppress debugging output during parsing.

fudge.core.utilities.pyparsing.oneOf(strs, caseless=False, useRegex=True)[source]

Helper to quickly define a set of alternative Literals, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a C{MatchFirst} for best performance.

Parameters:
  • strs - a string of space-delimited literals, or a list of string literals
  • caseless - (default=False) - treat all literals as caseless
  • useRegex - (default=True) - as an optimization, will generate a Regex object; otherwise, will generate a C{MatchFirst} object (if C{caseless=True}, or if creating a C{Regex} raises an exception)
fudge.core.utilities.pyparsing.operatorPrecedence(baseExpr, opList)[source]

Helper method for constructing grammars of expressions made up of operators working in a precedence hierarchy. Operators may be unary or binary, left- or right-associative. Parse actions can also be attached to operator expressions.

Parameters:
  • baseExpr - expression representing the most basic element for the nested

  • opList - list of tuples, one for each operator precedence level in the expression grammar; each tuple is of the form (opExpr, numTerms, rightLeftAssoc, parseAction), where:

    • opExpr is the pyparsing expression for the operator;
      may also be a string, which will be converted to a Literal; if numTerms is 3, opExpr is a tuple of two expressions, for the two operators separating the 3 terms
    • numTerms is the number of terms for this operator (must
      be 1, 2, or 3)
    • rightLeftAssoc is the indicator whether the operator is
      right or left associative, using the pyparsing-defined constants opAssoc.RIGHT and opAssoc.LEFT.
    • parseAction is the parse action to be associated with
      expressions matching this operator expression (the parse action tuple member may be omitted)
fudge.core.utilities.pyparsing.removeQuotes(s, l, t)[source]

Helper parse action for removing quotation marks from parsed quoted strings. To use, add this parse action to quoted string using:

quotedString.setParseAction( removeQuotes )
fudge.core.utilities.pyparsing.replaceHTMLEntity(t)
fudge.core.utilities.pyparsing.replaceWith(replStr)[source]

Helper method for common parse actions that simply return a literal value. Especially useful when used with C{transformString()}.

fudge.core.utilities.pyparsing.srange(s)[source]

Helper to easily define string ranges for use in Word construction. Borrows syntax from regexp ‘[]’ string range definitions:

srange("[0-9]")   -> "0123456789"
srange("[a-z]")   -> "abcdefghijklmnopqrstuvwxyz"
srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"

The input string must be enclosed in []’s, and the returned string is the expanded character set joined into a single string. The values enclosed in the []’s may be:

a single character
an escaped character with a leading backslash (such as \- or \])
an escaped hex character with a leading '\0x' (\0x21, which is a '!' character)
an escaped octal character with a leading '\0' (\041, which is a '!' character)
a range of any of the above, separated by a dash ('a-z', etc.)
any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.)
fudge.core.utilities.pyparsing.traceParseAction(f)[source]

Decorator for debugging parse actions.

fudge.core.utilities.pyparsing.upcaseTokens(s, l, t)[source]

Helper parse action to convert tokens to upper case.

fudge.core.utilities.pyparsing.withAttribute(*args, **attrDict)[source]

Helper to create a validating parse action to be used with start tags created with makeXMLTags or makeHTMLTags. Use withAttribute to qualify a starting tag with a required attribute value, to avoid false matches on common tags such as <TD> or <DIV>.

Call withAttribute with a series of attribute names and values. Specify the list of filter attributes names and values as:

  • keyword arguments, as in (class=”Customer”,align=”right”), or
  • a list of name-value tuples, as in ( (“ns1:class”, “Customer”), (“ns2:align”,”right”) )

For attribute names with a namespace prefix, you must use the second form. Attribute names are matched insensitive to upper/lower case.

To verify that the attribute exists, but without specifying a value, pass withAttribute.ANY_VALUE as the value.

fudge.core.utilities.pyparsing.indentedBlock(blockStatementExpr, indentStack, indent=True)[source]

Helper method for defining space-delimited indentation blocks, such as those used to define block statements in Python source code.

Parameters:
  • blockStatementExpr - expression defining syntax of statement that
    is repeated within the indented block
  • indentStack - list created by caller to manage indentation stack
    (multiple statementWithIndentedBlock expressions within a single grammar should share a common indentStack)
  • indent - boolean indicating whether block must be indented beyond the
    the current level; set to False for block of left-most statements (default=True)

A valid block must contain at least one blockStatement.

fudge.core.utilities.pyparsing.originalTextFor(expr, asString=True)[source]

Helper to return the original, untokenized text for a given expression. Useful to restore the parsed fields of an HTML start tag into the raw tag text itself, or to revert separate tokens with intervening whitespace back to the original matching input text. Simpler to use than the parse action C{keepOriginalText}, and does not require the inspect module to chase up the call stack. By default, returns a string containing the original parsed text.

If the optional C{asString} argument is passed as False, then the return value is a C{ParseResults} containing any results names that were originally matched, and a single token containing the original matched text from the input string. So if the expression passed to C{originalTextFor} contains expressions with defined results names, you must set C{asString} to False if you want to preserve those results name values.

fudge.core.utilities.reactionStrings module

Containers for a particle and a reaction, plus utility to parse in string representations to containers: >>> parseReaction(“n + Fe56 -> n[multiplicity:‘2’] + (Fe55_s -> gamma)”)

fudge.core.utilities.reactionStrings.parseReaction(str)[source]
fudge.core.utilities.reactionStrings.particleParser()[source]

Parse string of form “Pu239_e2[option1:’value’, option2:’value’ … ]” into particle class.

class fudge.core.utilities.reactionStrings.particleString(symbol, A, excitation=0, opts=None, decaysTo=None)[source]

Bases: object

optionList = ('multiplicity', 'emissionMode', 'decayRate')
specialNames = ('gamma', 'e')
fudge.core.utilities.reactionStrings.reactionParser()[source]

Parse reaction of form “n + Fe56 -> n[options…] + (Fe55_u -> gamma)” into reaction class.

class fudge.core.utilities.reactionStrings.reactionString(projectile, target, products, info=None)[source]

Bases: object

fudge.core.utilities.subprocessing module

fudge.core.utilities.subprocessing.deleteFilesUsingGlob(patterns)[source]
fudge.core.utilities.subprocessing.executeCommand(args, raiseOnError=True, useExecutable=False, stdout=-1, stderr=-1)[source]
fudge.core.utilities.subprocessing.spawn(args)[source]

fudge.core.utilities.times module

class fudge.core.utilities.times.times[source]
delta(reset=False)[source]
delta_cpu(reset=False, includeChildren=True, includeSystem=True)[source]
delta_wall(reset=False)[source]
reset()[source]
toString(prefix='', reset=False, includeChildren=True, includeSystem=True, current=True)[source]

fudge.core.utilities.xmlNode module

Wrapper for xml parsers (Etree, DOM, etc), in case we need to support multiple parsers. For now only supporting python’s xml.etree. This is only for reading (not writing) xml; creating new elements should happen within fudge

class fudge.core.utilities.xmlNode.xmlNode(parsedXMLNode, parser)[source]

Bases: object

allowedParsers = ('etree', 'dom')
dom = 'dom'
etree = 'etree'
find(path)[source]

Searches for child elements matching the path, and returns the first match.

findall(path)[source]

Searches for child elements matching the path, and returns all matches.

get(attribute, defaultValue=None)[source]

Returns the value of the specified attribute. If the attribute is not present, returns defaultValue.

getchildren()[source]

Returns a list of all child elements.

items()[source]

Returns the name and value of all attributes in this element, as a list of tuples.

keys()[source]

Returns the name of all attributes in this element, as a list.

xpath(xpath)[source]

Searches for child elements matching the xpath, and returns all matches.

Module contents