本文整理汇总了Python中pyparsing.Suppress.parseString方法的典型用法代码示例。如果您正苦于以下问题:Python Suppress.parseString方法的具体用法?Python Suppress.parseString怎么用?Python Suppress.parseString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing.Suppress
的用法示例。
在下文中一共展示了Suppress.parseString方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parseReactions
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import parseString [as 别名]
def parseReactions(reaction):
name = Word(alphanums + '_-') + ':'
species = (Word(alphanums + "_:#-")
+ Suppress('()')) + ZeroOrMore(Suppress('+') + Word(alphanums + "_:#-")
+ Suppress("()"))
rate = Word(alphanums + "()")
grammar = Suppress(Optional(name)) + ((Group(species) | '0') + Suppress(Optional("<") + "->") +
(Group(species) | '0') + Suppress(rate)) \
^ (species + Suppress(Optional("<") + "->") + Suppress(rate))
result = grammar.parseString(reaction).asList()
if len(result) < 2:
result = [result, []]
if '<->' in reaction and len(result[0]) == 1 and len(result[1]) == 2:
result2 = [result[1], result[0]]
result = result2
return result
示例2: Lindenmayer
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import parseString [as 别名]
#.........这里部分代码省略.........
if(suma > 0):
m = 1/suma
#if(delta*m < 1): return np.random.randint(0,2)
if(cant>10): return 0
return np.random.randint(0,delta*m+2)/baking
else: # free
return np.random.randint(0,delta/2+delta/2)/baking
def rotate(self):
#self.x += self.r
#self.y += self.r
#d = 2*np.pi*random.random()
ang = self.angle+random.random()/6
self.x = self.xparent + np.int32(fdist(self.r)*np.cos(ang))+randint(-int(self.r),int(self.r))
self.y = self.yparent + np.int32(fdist(self.r)*np.sin(ang))+randint(-int(self.r),int(self.r))
#self.x = self.xparent + np.int32(fdist(self.r)*np.cos(ang))+randint(-int(self.r),int(self.r))
#self.y = self.yparent + np.int32(fdist(self.r)*np.sin(ang))+randint(-int(self.r),int(self.r))
#pass
def moveX(self):
self.x += self.r
def mmoveX(self):
self.x -= self.r
def moveY(self):
self.y += self.r
def mmoveY(self):
self.y -= self.r
def initialize(self):
ParserElement.setDefaultWhitespaceChars(' \t\r')
integer = Regex(r"[+-]?\d+") \
.setParseAction(lambda s,l,t: [ int(t[0]) ])
number = Regex(r"[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?") \
.setParseAction(lambda s,l,t: [ float(t[0]) ])
color = Regex(r"#([0-9a-fA-F]{6})")
angle = "'" + Regex(r"(360|3[0-5][0-9]|[12][0-9]{2}|[0-9]{1,2})") \
.setParseAction(lambda s,l,t: [ int(t[0]) ])
alpha = "'" + Regex(r"(360|3[0-5][0-9]|[12][0-9]{2}|[0-9]{1,2})") \
.setParseAction(lambda s,l,t: [ int(t[0]) ])
variable = Word(alphas, exact=1).setParseAction(self.addVar)
colon = Literal(":").suppress()
comma = Literal(",")
lBrace = Literal("(")
rBrace = Literal(")")
lBracket = Literal("[")
rBracket = Literal("]")
lAngle = Literal("<")
rAngle = Literal(">")
plus = Literal("+")
minus = Literal("-")
FTerm = Literal("F")
fTerm = Literal("f")
ZTerm = Literal("Z")
zTerm = Literal("z")
xTerm = Literal("x")
cTerm = Literal("c")
eol = OneOrMore(LineEnd()).suppress()
param = ( angle | color | "!" + number | "|" + number )
self.pList = lBrace + param + ZeroOrMore(comma + param) + rBrace
literal = ((lBracket + ( variable + Optional(self.pList)
| plus + Optional(self.pList) | minus + Optional(self.pList) ) + rBracket)
| (variable + Optional(self.pList) | plus + Optional(self.pList)
| minus + Optional(self.pList)))
terminal = (ZTerm | zTerm | FTerm | fTerm | xTerm | cTerm
| plus | minus | lBracket | rBracket)
lprod = (
(OneOrMore(terminal) + lAngle + variable + rAngle + OneOrMore(terminal))
| (OneOrMore(terminal) + lAngle + variable)
| (variable + rAngle + OneOrMore(terminal))
| variable )
rProd = OneOrMore(literal | terminal)
comment = Suppress((LineStart() + "#" + SkipTo(eol, include=True)))
rules = (
(lprod + Literal("=") + rProd + eol).setParseAction(self.addRule) \
| comment )
defaults = ( ( ("Dimensions" + colon + integer + comma + integer)
| ("Position" + colon + integer + comma + integer)
| ("Iterations" + colon + integer)
| ("Angle" + colon + angle)
| ("Linelength" + colon + number)
| ("Linewidth" + colon + number)
| ("Linecolor" + colon + color)
| ("Background" + colon + color)
| ("Axiom" + colon + rProd) ) + eol ).setParseAction(self.setAttribute)
header = ( defaults | comment )
self.grammar = Suppress(ZeroOrMore(LineEnd())) \
+ ZeroOrMore(header) \
+ OneOrMore(rules)
try:
L = self.grammar.parseString( self.stream )
except ParseException, err:
print err.line
print " "*(err.column-1) + "^"
print err
print 'Rules:', self.rules
示例3: len
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import parseString [as 别名]
labels = [ 'Northwest', 'North Central', 'Northeast', 'Southwest', 'South Central', 'Southeast' ]
# list of each crop in the report
crop_labels = [ '#2 Yellow Corn', '#1 Yellow Soybeans' ]
ending_index = 0 # initializes to 0 so that it can be later used to divide site_contents into sections
# Loops through each location in labels and finds the data for that location.
# Pyparsing is used to store each data element in a list so that it can be
# used to create a table.
z = 0
while z < len(labels):
starting_index = site_contents.find(labels[z], ending_index)
line = Suppress(Literal(labels[z])) + (Word(nums+'.'+'*') + (Suppress(Literal('\x96')) | Suppress(Literal('-'))) + Word(nums+'.'+'*') + Word(nums+'.'+'*'))*2
ending_index = site_contents.find('\r\n', starting_index)
ending_index1 = site_contents.find('\t', starting_index)
if ending_index1 != -1:
ending_index = min([ending_index, ending_index1])
line = line.parseString(site_contents[starting_index:ending_index])
# Loops through each crop in crop_labels and creates a table using the location
# in labels and the crop in crop_labels.
y = 0
while y < len(crop_labels):
headings = [ 'Date', 'Minimum Bid', 'Maximum Bid', 'Average Bid' ]
data = { 'Date': [string_date], 'Minimum Bid': [line[0].replace('*','')], 'Maximum Bid': [line[1].replace('*','')], 'Average Bid': [line[2].replace('*','')] }
del line[0:3]
data_df = pd.DataFrame(data, columns = headings)
data_df.index = data_df['Date']
data_df = data_df.drop('Date', 1)
replace = re.compile('[ /]') # list of characters to be replaced in the pork cut description
remove = re.compile('[,%#-&()!$+<>?/\'"{}.*@ ]') # list of characters to be removed from the pork cut description
name1 = replace.sub('_', crop_labels[y].upper()) # replace certain characters with '_'
name2 = remove.sub('', name1).upper() # remove certain characters and convert to upper case
name2 = name2.translate(None, '-') # ensure '-' character is removed
示例4: RaxmlParser
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import parseString [as 别名]
class RaxmlParser(object):
def __init__(self):
self.ALPHA_LABEL = Regex(r'alpha\[\d+\]:')
self.LNL_LABEL = Literal('Final GAMMA-based Score of best tree')
self.FRQ_LABEL = Regex(r'Base frequencies: (?=\d+)') ^ Regex(r'ML estimate base freqs\[\d+\]:')
self.NAMES_LABEL = Regex(r'Partition: \d+ with name:\s+')
self.RATES_LABEL = Regex(r'rates\[\d+\].+?:')
self.MODEL_LABEL = Literal('Substitution Matrix:')
self.alpha = OneOrMore(Suppress(SkipTo(self.ALPHA_LABEL)) + Suppress(self.ALPHA_LABEL) + FLOAT)
self.lnl = Suppress(SkipTo(self.LNL_LABEL)) + Suppress(self.LNL_LABEL) + FLOAT
self.frq = OneOrMore(Group(Suppress(SkipTo(self.FRQ_LABEL)) + Suppress(self.FRQ_LABEL) + OneOrMore(FLOAT)))
self.names = OneOrMore(Suppress(SkipTo(self.NAMES_LABEL)) + Suppress(self.NAMES_LABEL) + CharsNotIn('\n') + Suppress(LineEnd()))
self.rates = OneOrMore(Group(Suppress(SkipTo(self.RATES_LABEL)) + Suppress(self.RATES_LABEL) + OneOrMore(FLOAT)))
self.model = Suppress(SkipTo(self.MODEL_LABEL)) + Suppress(self.MODEL_LABEL) + WORD
MODEL_LABEL = Literal('Substitution Matrix:')
SCORE_LABEL = Literal('Final GAMMA likelihood:')
DESC_LABEL = Literal('Model Parameters of Partition')
NAME_LEADIN = Literal(', Name:')
DATATYPE_LEADIN = Literal(', Type of Data:')
ALPHA_LEADIN = Literal('alpha:')
TREELENGTH_LEADIN = Literal('Tree-Length:')
RATES_LABEL = Regex(r'rate \w <-> \w:')
FREQS_LABEL = Regex(r'freq pi\(\w\):')
BEST_LEADIN = Literal('Starting final GAMMA-based thorough Optimization on tree ')
PARTITION_LEADIN = Literal('Partition:')
INFERENCE_LEADIN = Literal('Inference[')
model = Suppress(SkipTo(MODEL_LABEL)) + Suppress(MODEL_LABEL) + WORD
likelihood = Suppress(SkipTo(SCORE_LABEL)) + Suppress(SCORE_LABEL) + FLOAT
description = (Suppress(SkipTo(DESC_LABEL)) +
Suppress(DESC_LABEL) + INT +
Suppress(NAME_LEADIN) +
SPACEDWORD +
Suppress(DATATYPE_LEADIN) +
WORD)
alpha = Suppress(ALPHA_LEADIN) + FLOAT
rates = Suppress(RATES_LABEL) + FLOAT
freqs = Suppress(FREQS_LABEL) + FLOAT
self.partition = OneOrMore(Suppress(SkipTo(PARTITION_LEADIN)) + Suppress(PARTITION_LEADIN) + INT)
self.inference = OneOrMore(Suppress(SkipTo(INFERENCE_LEADIN)) + Suppress(INFERENCE_LEADIN) + INT)
self.best = Suppress(SkipTo(BEST_LEADIN)) + Suppress(BEST_LEADIN) + INT
self._dash_f_e_parser = (Group(OneOrMore(model)) +
likelihood +
Group(OneOrMore(Group(description +
alpha +
Suppress(TREELENGTH_LEADIN) +
Suppress(FLOAT) +
Group(OneOrMore(rates)) +
Group(OneOrMore(freqs))
))))
def parse(self, filename):
with open(filename) as fl:
s = fl.read()
try:
best_index = self.best.parseString(s)[0]
except ParseException as err:
logger.error(err)
best_index = 0
try:
n_partitions = max(self.partition.parseString(s).asList()) + 1
except ParseException as err:
logger.error(err)
n_partitions = 1
try:
n_inferences = max(self.inference.parseString(s).asList()) + 1
except ParseException as err:
logger.error(err)
n_inferences = 1
try:
alphas = self.alpha.parseString(s).asList()
except ParseException as err:
logger.error(err)
alphas = [None]
try:
freqs = self.frq.parseString(s).asList()
except ParseException as err:
logger.error(err)
freqs = [None]
try:
names = self.names.parseString(s).asList()
except ParseException as err:
logger.error(err)
names = [None]
try:
rates = self.rates.parseString(s).asList()
except ParseException:
rates = None
try:
lnl = self.lnl.parseString(s).asList()
except ParseException as err:
logger.error(err)
lnl = [0]
#.........这里部分代码省略.........
示例5: Word
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import parseString [as 别名]
while site_contents.find('\r\n', starting_day, ending_day) != -1:
end_line = site_contents.find('\r\n', starting_day)
unparsed.append(site_contents[starting_day:end_line])
starting_day = end_line+2
cattle_slaughter = (Word(alphas) + Word(printables)) | (Word(alphas) + Literal("-")) # grammar for daily cattle slaughter
# Loops through each unparsed line and parses it, appending to number_cattle_slaughter
z = 0
while z < len(unparsed):
parsed.append(cattle_slaughter.parseString(unparsed[z]))
day.append(parsed[z][0])
number_cattle_slaughter.append(parsed[z][1])
z = z + 1
number_cattle_slaughter = [float(g.replace(',','').replace('-','0')) for g in number_cattle_slaughter] # remove commas and convert each value to a float
starting = site_contents.find('Beef', site_contents.find('Meat Production, Live Weight and Dressed Weight')) # store index of beginning of second data section
weight = Suppress(Literal('Beef')) + Word(printables) # grammar for finding weight of beef production
weight = float((weight.parseString(site_contents[starting:]))[0])
starting = site_contents.find('Cattle', starting)
word = Suppress(Word(alphas)) + Word(nums)
weights = Suppress(Word(alphas)) + Word(printables) + Word(nums) + word*4
average_live_weight = float((weights.parseString(site_contents[starting:]))[0].replace(',',''))
average_dressed_weight = float((weights.parseString(site_contents[starting:]))[1])
average_weights = weights.parseString(site_contents[starting:])[2:]
starting = site_contents.find('Cattle', site_contents.find('Federally Inspected Slaughter Head & Percentage by Class'))
suppress = Suppress(Word(printables))
word = Word(alphas) + ZeroOrMore(Word(alphas))
number = Word(printables)
cattle_head = suppress + Suppress(ZeroOrMore(Literal(':'))) + (word + Suppress(ZeroOrMore(Literal(':'))) + number) + ( Suppress(ZeroOrMore(Literal(':'))) + word + Suppress(ZeroOrMore(Literal(':'))) + number + Suppress(ZeroOrMore(Literal(':'))) + suppress ) * 5
y = cattle_head.parseString(site_contents[starting:])
names = [y[0], y[2], y[4], y[6] + ' ' + y[7], y[9] + ' ' + y[10], y[12]]
total_head = [y[1],y[3],y[5],y[8], y[11], y[13]]
total_head = [float(i.replace(',','.')) for i in total_head]
示例6: Lindenmayer
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import parseString [as 别名]
#.........这里部分代码省略.........
z2 = z
#for h in range(maxx):
r2 = int(r2/(2))
dd = int(r*1.0)
for i in range(2):
x3 = x2+randint(-dd,dd)
y3 = y2+randint(-dd,dd)
z3 = z2+randint(-dd,dd)
self.drawShape(field,x3,y3,z3,r2,c-1)
def rotate(self):
ang = self.angle#+random.random()/10
self.x = self.xparent + np.int32(fdist(self.r)*np.cos(ang))+randint(-int(self.r),int(self.r))
self.y = self.yparent + np.int32(fdist(self.r)*np.sin(ang))+randint(-int(self.r),int(self.r))
self.z = self.zparent
def rotate2(self):
ang = self.angle2#+random.random()/10
self.x = self.xparent
self.y = self.yparent + np.int32(fdist(self.r)*np.cos(ang))+randint(-int(self.r),int(self.r))
self.z = self.zparent + np.int32(fdist(self.r)*np.sin(ang))+randint(-int(self.r),int(self.r))
def moveX(self):
self.x += self.r
def mmoveX(self):
self.x -= self.r
def moveY(self):
self.y += self.r
def mmoveY(self):
self.y -= self.r
def initialize(self):
ParserElement.setDefaultWhitespaceChars(' \t\r')
integer = Regex(r"[+-]?\d+") \
.setParseAction(lambda s,l,t: [ int(t[0]) ])
number = Regex(r"[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?") \
.setParseAction(lambda s,l,t: [ float(t[0]) ])
color = Regex(r"#([0-9a-fA-F]{6})")
angle = "'" + Regex(r"(360|3[0-5][0-9]|[12][0-9]{2}|[0-9]{1,2})") \
.setParseAction(lambda s,l,t: [ int(t[0]) ])
alpha = "'" + Regex(r"(360|3[0-5][0-9]|[12][0-9]{2}|[0-9]{1,2})") \
.setParseAction(lambda s,l,t: [ int(t[0]) ])
variable = Word(alphas, exact=1).setParseAction(self.addVar)
colon = Literal(":").suppress()
comma = Literal(",")
lBrace = Literal("(")
rBrace = Literal(")")
lBracket = Literal("[")
rBracket = Literal("]")
lAngle = Literal("<")
rAngle = Literal(">")
plus = Literal("+")
minus = Literal("-")
FTerm = Literal("F")
fTerm = Literal("f")
ZTerm = Literal("Z")
zTerm = Literal("z")
xTerm = Literal("x")
cTerm = Literal("c")
eol = OneOrMore(LineEnd()).suppress()
param = ( angle | color | "!" + number | "|" + number )
self.pList = lBrace + param + ZeroOrMore(comma + param) + rBrace
literal = ((lBracket + ( variable + Optional(self.pList)
| plus + Optional(self.pList) | minus + Optional(self.pList) ) + rBracket)
| (variable + Optional(self.pList) | plus + Optional(self.pList)
| minus + Optional(self.pList)))
terminal = (ZTerm | zTerm | FTerm | fTerm | xTerm | cTerm
| plus | minus | lBracket | rBracket)
lprod = (
(OneOrMore(terminal) + lAngle + variable + rAngle + OneOrMore(terminal))
| (OneOrMore(terminal) + lAngle + variable)
| (variable + rAngle + OneOrMore(terminal))
| variable )
rProd = OneOrMore(literal | terminal)
comment = Suppress((LineStart() + "#" + SkipTo(eol, include=True)))
rules = (
(lprod + Literal("=") + rProd + eol).setParseAction(self.addRule) \
| comment )
defaults = ( ( ("Dimensions" + colon + integer + comma + integer)
| ("Position" + colon + integer + comma + integer)
| ("Iterations" + colon + integer)
| ("Angle" + colon + angle)
| ("Linelength" + colon + number)
| ("Linewidth" + colon + number)
| ("Linecolor" + colon + color)
| ("Background" + colon + color)
| ("Axiom" + colon + rProd) ) + eol ).setParseAction(self.setAttribute)
header = ( defaults | comment )
self.grammar = Suppress(ZeroOrMore(LineEnd())) \
+ ZeroOrMore(header) \
+ OneOrMore(rules)
try:
L = self.grammar.parseString( self.stream )
except ParseException, err:
print err.line
print " "*(err.column-1) + "^"
print err
示例7: Lindenmayer
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import parseString [as 别名]
class Lindenmayer(object):
def __init__(self, stream):
# Set the default image dimensions ...
self.width = 500
self.height = 500
# ... and the number of iterations.
self.iterations = 5
# Set the default rotation angle in degrees.
self.alpha = 90
# Initialize the branch stack, ...
self.stack = []
# ... the constants, the rules, the variables and the axiom ...
self.const = {'+':'+', '-':'-', '[':'[', ']':']'}
self.rules = {}
self.vars = []
self.axiom = None
# ... and drawing settings.
self.bgcolor = (1.0, 1.0, 1.0)
self.lineLength = 20
self.lineWidth = 5
self.lineColor = (0, 0, 0)
# Calculate the starting position.
self.offset = (0, -self.height*0.5)
print 'Offset :', self.offset
# Finally store the stream ...
self.stream = stream
# ... and initialize the parser.
self.initialize()
def initialize(self):
ParserElement.setDefaultWhitespaceChars(' \t\r')
integer = Regex(r"[+-]?\d+") \
.setParseAction(lambda s,l,t: [ int(t[0]) ])
number = Regex(r"[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?") \
.setParseAction(lambda s,l,t: [ float(t[0]) ])
color = Regex(r"#([0-9a-fA-F]{6})")
angle = "'" + Regex(r"(360|3[0-5][0-9]|[12][0-9]{2}|[0-9]{1,2})") \
.setParseAction(lambda s,l,t: [ int(t[0]) ])
variable = Word(alphas, exact=1).setParseAction(self.addVar)
colon = Literal(":").suppress()
comma = Literal(",")
lBrace = Literal("(")
rBrace = Literal(")")
lBracket = Literal("[")
rBracket = Literal("]")
lAngle = Literal("<")
rAngle = Literal(">")
plus = Literal("+")
minus = Literal("-")
FTerm = Literal("F")
fTerm = Literal("f")
ZTerm = Literal("Z")
zTerm = Literal("z")
xTerm = Literal("x")
cTerm = Literal("c")
eol = OneOrMore(LineEnd()).suppress()
param = ( angle | color | "!" + number | "|" + number )
self.pList = lBrace + param + ZeroOrMore(comma + param) + rBrace
literal = ((lBracket + ( variable + Optional(self.pList)
| plus + Optional(self.pList) | minus + Optional(self.pList) ) + rBracket)
| (variable + Optional(self.pList) | plus + Optional(self.pList)
| minus + Optional(self.pList)))
terminal = (ZTerm | zTerm | FTerm | fTerm | xTerm | cTerm
| plus | minus | lBracket | rBracket)
lprod = (
(OneOrMore(terminal) + lAngle + variable + rAngle + OneOrMore(terminal))
| (OneOrMore(terminal) + lAngle + variable)
| (variable + rAngle + OneOrMore(terminal))
| variable )
rProd = OneOrMore(literal | terminal)
comment = Suppress((LineStart() + "#" + SkipTo(eol, include=True)))
rules = (
(lprod + Literal("=") + rProd + eol).setParseAction(self.addRule) \
| comment )
defaults = ( ( ("Dimensions" + colon + integer + comma + integer)
| ("Position" + colon + integer + comma + integer)
| ("Iterations" + colon + integer)
| ("Angle" + colon + angle)
| ("Linelength" + colon + number)
| ("Linewidth" + colon + number)
| ("Linecolor" + colon + color)
| ("Background" + colon + color)
| ("Axiom" + colon + rProd) ) + eol ).setParseAction(self.setAttribute)
header = ( defaults | comment )
self.grammar = Suppress(ZeroOrMore(LineEnd())) \
+ ZeroOrMore(header) \
+ OneOrMore(rules)
try:
L = self.grammar.parseString( self.stream )
#.........这里部分代码省略.........
示例8: Suppress
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import parseString [as 别名]
)
)
NIL
NIL
)
"MIXED"
(
"BOUNDARY"
"Boundary-00=_H2YnIG887ejM4hn"
)
NIL
NIL
NIL
)
)
"""
parse = Suppress(Word(nums)) + Suppress("(") + Group(OneOrMore( Suppress("(") + Group(OneOrMore(Word(printables))) + Suppress(")") )) + Suppress(")")
for folder in folderlist:
tmp = parse.parseString( folder )
if type in tmp[2][1]:
result.append(tmp[0])
return result
@staticmethod
def folderAnnotation(folder):
pass
示例9: RaxmlParser
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import parseString [as 别名]
class RaxmlParser(object):
def __init__(self):
self.ALPHA_LABEL = Regex(r"alpha\[\d+\]:")
self.LNL_LABEL = Literal("Final GAMMA-based Score of best tree")
self.FRQ_LABEL = Regex(r"Base frequencies: (?=\d+)") ^ Regex(r"ML estimate base freqs\[\d+\]:")
self.NAMES_LABEL = Regex(r"Partition: \d+ with name:\s+")
self.RATES_LABEL = Regex(r"rates\[\d+\].+?:")
self.MODEL_LABEL = Literal("Substitution Matrix:")
self.alpha = OneOrMore(Suppress(SkipTo(self.ALPHA_LABEL)) + Suppress(self.ALPHA_LABEL) + FLOAT)
self.lnl = Suppress(SkipTo(self.LNL_LABEL)) + Suppress(self.LNL_LABEL) + FLOAT
self.frq = OneOrMore(Group(Suppress(SkipTo(self.FRQ_LABEL)) + Suppress(self.FRQ_LABEL) + OneOrMore(FLOAT)))
self.names = OneOrMore(
Suppress(SkipTo(self.NAMES_LABEL)) + Suppress(self.NAMES_LABEL) + CharsNotIn("\n") + Suppress(LineEnd())
)
self.rates = OneOrMore(
Group(Suppress(SkipTo(self.RATES_LABEL)) + Suppress(self.RATES_LABEL) + OneOrMore(FLOAT))
)
self.model = Suppress(SkipTo(self.MODEL_LABEL)) + Suppress(self.MODEL_LABEL) + WORD
MODEL_LABEL = Literal("Substitution Matrix:")
SCORE_LABEL = Literal("Final GAMMA likelihood:")
DESC_LABEL = Literal("Model Parameters of Partition")
NAME_LEADIN = Literal(", Name:")
DATATYPE_LEADIN = Literal(", Type of Data:")
ALPHA_LEADIN = Literal("alpha:")
TREELENGTH_LEADIN = Literal("Tree-Length:")
RATES_LABEL = Regex(r"rate \w <-> \w:")
FREQS_LABEL = Regex(r"freq pi\(\w\):")
model = Suppress(SkipTo(MODEL_LABEL)) + Suppress(MODEL_LABEL) + WORD
likelihood = Suppress(SkipTo(SCORE_LABEL)) + Suppress(SCORE_LABEL) + FLOAT
description = (
Suppress(SkipTo(DESC_LABEL))
+ Suppress(DESC_LABEL)
+ INT
+ Suppress(NAME_LEADIN)
+ SPACEDWORD
+ Suppress(DATATYPE_LEADIN)
+ WORD
)
alpha = Suppress(ALPHA_LEADIN) + FLOAT
rates = Suppress(RATES_LABEL) + FLOAT
freqs = Suppress(FREQS_LABEL) + FLOAT
self._dash_f_e_parser = (
Group(OneOrMore(model))
+ likelihood
+ Group(
OneOrMore(
Group(
description
+ alpha
+ Suppress(TREELENGTH_LEADIN)
+ Suppress(FLOAT)
+ Group(OneOrMore(rates))
+ Group(OneOrMore(freqs))
)
)
)
)
def parse(self, filename):
with open(filename) as fl:
s = fl.read()
try:
alphas = self.alpha.parseString(s).asList()
except ParseException as err:
logger.error(err)
alphas = [None]
try:
freqs = self.frq.parseString(s).asList()
except ParseException as err:
logger.error(err)
freqs = [None]
try:
names = self.names.parseString(s).asList()
except ParseException as err:
logger.error(err)
names = [None]
try:
rates = self.rates.parseString(s).asList()
except ParseException:
rates = None
try:
lnl = self.lnl.parseString(s).asList()
except ParseException as err:
logger.error(err)
lnl = [0]
return alphas, freqs, names, rates, lnl
def _dash_f_e_to_dict(self, info_filename, tree_filename):
"""
Raxml provides an option to fit model params to a tree,
selected with -f e.
The output is different and needs a different parser.
"""
with open(info_filename) as fl:
models, likelihood, partition_params = self._dash_f_e_parser.parseFile(fl).asList()
#.........这里部分代码省略.........