Пример #1
0
def dom_document_setup():
    crn_DWC = "".join(
        [x for x in ParseElementEnhance.DEFAULT_WHITE_CHARS if x != "\n"])
    ParseElementEnhance.setDefaultWhitespaceChars(crn_DWC)

    W = Word
    G = Group
    S = Suppress
    O = Optional
    L = Literal

    identifier = W(alphas, alphanums + "_")
    number = W(nums, nums)
    domain = G(OneOrMore((G(identifier + O("*")) | "?" | "+")))
    dotparen = G(OneOrMore(W("().+", max=1)))
    structure = domain + OneOrMore(LineEnd().suppress()) + dotparen
    sequence = G(
        S("sequence") + identifier + S(":") + number +
        OneOrMore(LineEnd().suppress()))
    molecule = G(identifier + S(":") + OneOrMore(LineEnd().suppress()) +
                 structure)

    document = StringStart() + ZeroOrMore(LineEnd().suppress()) + G(
        ZeroOrMore(sequence)) + G(
            OneOrMore(molecule +
                      OneOrMore(LineEnd().suppress()))) + StringEnd()
    document.ignore(pythonStyleComment)
    return document
Пример #2
0
def crn_document_setup(modular = False):
  """Parse a formal chemical reaction network. 

  Args: 
    modular <optional:bool>: Adds an additional nesting for modules within a
      CRN. Use one line per module (';' separates reactions).

  Format:
    # A list of reactions, optionally with reaction rates:
    # <- this is a comment!
    B + B -> C    # [k = 1]
    C + A <=> D   # [kf = 1, kr = 1]
    <=> A  [kf = 15, kr = 6]

    # Note that you can write multiple reactions in one line:
    A + 2C -> E [k = 13.78]; E + F <=> 2A  [kf = 13, kr = 14]

  Returns:

  """
  # NOTE: If you want to add support for multiple modules per line, you can use
  # the '|' character.
  
  W = Word
  G = Group
  S = Suppress
  O = Optional
  C = Combine
  L = Literal
  
  def T(x, tag):
    """ Return a *Tag* to distinguish (ir)reversible reactions """
    def TPA(tag):
      return lambda s, l, t: t.asList() + [tag]
    return x.setParseAction(TPA(tag))
  
  crn_DWC = "".join(
      [x for x in ParseElementEnhance.DEFAULT_WHITE_CHARS if x != "\n"])
  ParseElementEnhance.setDefaultWhitespaceChars(crn_DWC)
  
  identifier = W(alphas, alphanums+"_")

  multiplier = W(nums)
  species = G(O(multiplier) + identifier)

  rate = C(W(nums) + O((L('.') + W(nums)) | (L('e') + O('-') + W(nums))))

  k = G(S('[') + S('k') + S('=') + rate + S(']'))
  rev_k = G(S('[') + S('kf') + S('=') + rate + S(',') + \
                     S('kr') + S('=') + rate + S(']'))

  reaction = T(G(O(delimitedList(species, "+"))) + \
             S("->") + \
             G(O(delimitedList(species, "+"))) + O(k), 'irreversible')

  rev_reaction = T(G(O(delimitedList(species, "+"))) + \
                 S("<=>") + \
                 G(O(delimitedList(species, "+"))) + O(rev_k), 'reversible')
  

  expr = G(reaction | rev_reaction) 

  if modular :
    module = G(expr + ZeroOrMore(S(";") + expr))
  else :
    module = expr + ZeroOrMore(S(";") + expr)

  formal = G(O(S(";")) + L("formals") + S(L("=") + \
             L("{")) + O(delimitedList(identifier)) + S("}"))

  signal = G(O(S(";")) + L("signals") + S(L("=") + \
             L("{")) + O(delimitedList(identifier)) + S("}"))

  fuel = G(O(S(";")) + L("fuels") + S(L("=") + \
               L("{")) + O(delimitedList(identifier)) + S("}"))

  addon = formal | signal | fuel

  crn = OneOrMore(module + ZeroOrMore(S(LineEnd()))) + ZeroOrMore(addon + ZeroOrMore(S(LineEnd())))

  document = StringStart() + ZeroOrMore(S(LineEnd())) + crn + StringEnd()
  document.ignore(pythonStyleComment)
  return document
def crn_document_setup(modular = False):
    """Parse a formal chemical reaction network.

    Args:
      modular <optional:bool>: Adds an additional nesting for modules within a
        CRN. Use one line per module (';' separates reactions).

    Format:
      # A list of reactions, optionally with reaction rates:
      # <- this is a comment!
      B + B -> C    # [k = 1]
      C + A <=> D   # [kf = 1, kr = 1]
      <=> A  [kf = 15, kr = 6]

      # Note that you can write multiple reactions in one line:
      A + 2C -> E [k = 13.78]; E + F <=> 2A  [kf = 13, kr = 14]

    Returns:

    """
    # NOTE: If you want to add support for multiple modules per line, you can use
    # the '|' character.

    W = Word
    G = Group
    S = Suppress
    O = Optional
    C = Combine
    L = Literal

    def T(x, tag):
        """ Return a *Tag* to distinguish (ir)reversible reactions """
        def TPA(tag):
            return lambda s, l, t: [tag] + t.asList()
        return x.setParseAction(TPA(tag))

    crn_DWC = "".join(
        [x for x in ParseElementEnhance.DEFAULT_WHITE_CHARS if x != "\n"])
    ParseElementEnhance.setDefaultWhitespaceChars(crn_DWC)

    identifier = W(alphas, alphanums + "_")

    multiplier = W(nums)
    species = G(O(multiplier) + identifier)

    number = W(nums, nums)
    num_flt = C(number + O(L('.') + number))
    num_sci = C(number + O(L('.') + number) + L('e') + O(L('-') | L('+')) + W(nums))
    gorf = num_sci | num_flt

    # Make specification of forward, backward, reverse more flexible
    kf = S('kf') | S('fw')
    kr = S('kr') | S('bw') | S('rv')

    k = G(S('[') + O(S('k') + S('=')) + gorf + S(']'))
    rev_k = G(S('[') + kf + S('=') + gorf + S(',') + kr + S('=') + gorf + S(']')) | G(S('[') + gorf + S(',') + gorf + S(']'))

    concentration = T(species + S('@') + G(L("initial") | L("i") | L("constant") | L("c")) + G(gorf), 'concentration')

    reaction = T(G(O(delimitedList(species, "+"))) +
                 S("->") +
                 G(O(delimitedList(species, "+"))) + O(k), 'irreversible')

    rev_reaction = T(G(O(delimitedList(species, "+"))) +
                     S("<=>") +
                     G(O(delimitedList(species, "+"))) + O(rev_k), 'reversible')

    expr = G(reaction | rev_reaction | concentration)

    if modular:
        module = G(expr + ZeroOrMore(S(";") + expr))
    else:
        module = expr + ZeroOrMore(S(";") + expr)

    crn = OneOrMore(module + ZeroOrMore(S(LineEnd())))

    document = StringStart() + ZeroOrMore(S(LineEnd())) + crn + StringEnd()
    document.ignore(pythonStyleComment)
    return document
Пример #4
0
def ts_document_setup():
    """The gramar to parse a translation scheme."""
    ParserElement.enablePackrat()
    ParseElementEnhance.setDefaultWhitespaceChars(" \n\t\r")

    W = Word
    G = Group
    S = Suppress
    O = Optional
    L = Literal

    def TPAOp(s, l, t):
        """ """
        def helper(t):
            if len(t) == 1:
                return t[0]
            else:
                return [t[1], t[0], helper(t[2:])]

        return [helper((t.asList())[0])]

    def T(x, tag):
        def TPA(tag):
            return lambda s, l, t: [tag] + t.asList()

        return x.setParseAction(TPA(tag))

    expr = Forward()
    exprlist = delimitedList(expr)

    paren = S("(") + expr + S(")")
    list = G(T(S("[") + O(exprlist) + S("]"), "list"))
    identifier = G(T(W(alphas, alphanums + "_"), "id"))
    number = G(T(W(nums), "num"))
    domains = G(S('"') + \
                OneOrMore(G(identifier + O("*")) | "?" | "+") + \
                S('"'))
    dotparen = G(S('"') + OneOrMore(W("().~+", max=1)) + S('"'))
    dna = G(T(domains + S("|") + dotparen, "dna"))
    quote = G(T(S('"') + W(alphas, alphanums + "_") + S('"'), "quote")) | \
            G(T(S('\'') + W(alphas, alphanums + "_") + S('\''), "quote"))

    atom = paren | list | identifier | number | dna | quote

    function_call = G(T(S("(") + O(exprlist) + S(")"), "apply"))
    index = G(T(S("[") + expr + S("]"), "index"))
    attribute = G(T(S(".") + identifier, "attribute"))
    trailer = function_call | index | attribute
    atom_trailers = G(T(atom + ZeroOrMore(trailer), "trailer"))

    factor = Forward()
    factor << (G(T(S("-") + factor, "uminus")) | atom_trailers)

    test = operatorPrecedence(factor,
        [(W("*/",max=1), 2, opAssoc.LEFT, TPAOp),
         (W("+-",max=1), 2, opAssoc.LEFT, TPAOp),
         ((L("==") | L(">=") | L("<=") | L(">") | L("<") | L("!=")), \
             2, opAssoc.LEFT, TPAOp),
         ((L("and") | L("or")), 2, opAssoc.LEFT, TPAOp)])

    id_list = Forward()
    id_list << (G(T(S("[") + delimitedList(id_list) + S("]"), "idlist")) \
             | identifier)

    asgn = G(id_list + S("=") + expr)
    where_clause = G(S("where") + S("{") + \
        delimitedList(asgn, ";") + S("}")) | G(S("where") + asgn)

    quote_expr = G(T(quotedString, 'quote'))
    dict_expr = G(
        T(
            OneOrMore(
                O(S(',')) + G(identifier + S(':') + (quote_expr | number))),
            'dict'))

    where_expr = G(T(test + O(where_clause), "where"))
    if_expr = G("if" + expr + S("then") + expr + \
        ZeroOrMore(S("elseif") + expr + S("then") + expr) + \
        S("else") + expr)

    expr << (dict_expr | if_expr | where_expr | quote_expr)

    class_def    = G("class" + identifier + \
        G(S("(") + O(delimitedList(identifier)) + S(")")) + S("=") + expr)
    function_def = G("function" + identifier + \
        G(S("(") + O(delimitedList(identifier)) + S(")")) + S("=") + expr)
    module_def   = G("module" + identifier + \
        G(S("(") + O(delimitedList(identifier)) + S(")")) + S("=") + expr)
    macro_def    = G("macro" + identifier + \
        G(S("(") + O(delimitedList(identifier)) + S(")")) + S("=") + expr)
    global_def = G("global" + id_list + S("=") + expr)

    stmt = class_def | function_def | module_def | macro_def | global_def

    # Make ';' also an optional delimiter for the main() statement. That will make the
    # documentation easier, while keeping backward-compatibility
    document = StringStart() + stmt + ZeroOrMore(S(";") + stmt) + O(
        S(";")) + StringEnd()
    document.ignore(pythonStyleComment)
    return document
Пример #5
0
def pil_document_setup():
    crn_DWC = "".join(
        [x for x in ParseElementEnhance.DEFAULT_WHITE_CHARS if x != "\n"])
    ParseElementEnhance.setDefaultWhitespaceChars(crn_DWC)

    # letter = (* any alphanumeric character *)
    # identifier = letter, {letter}, [*]
    # pattern = expression, {space, expression}
    # expression = domain | loop | wildcard | break
    # domain = identifier
    # loop = identifier, "(", [pattern] ,")"
    # wildcard = "?" | "_" | "~" (* ... etc.*)
    # break = "+"

    def T(x, tag):
        def TPA(tag):
            return lambda s, l, t: [tag] + t.asList()

        return x.setParseAction(TPA(tag))

    W = Word
    G = Group
    S = Suppress
    O = Optional
    C = Combine
    L = Literal

    # NOTE: Exchange comment to forbid/allow names starting with digits
    #identifier = W(alphanums + "_-")
    identifier = W(alphas, alphanums + "_-")
    number = W(nums, nums)
    gorf = C(W(nums) + O((L('.') + W(nums)) | (L('e') + O('-') + W(nums))))
    domain = G(
        T(
            S("length") + identifier + S("=") + number +
            OneOrMore(LineEnd().suppress()), 'domain'))

    # NOTE: exchange the comment for asense if you want to allow input in form of "x( ... y)",
    # but also double-check if that really works...
    sense = Combine(identifier + O(L("^")) + O(L("*")))
    #asense = (Combine(sense + S(")")) | S(")"))
    asense = S(")")

    sbreak = L("+")

    pattern = Forward()
    # NOTE: Remove S(White()) for backward compatiblility: )) is not allowed anymore.
    #loop = (Combine(sense + S("(")) + O(pattern) + asense)
    loop = (Combine(sense + S("(")) + S(White()) + O(pattern) + S(White()) +
            asense)
    pattern << G(OneOrMore(loop | sbreak | sense))

    unit = L('M') | L('mM') | L('uM') | L('nM') | L('pM')
    conc = G(S('@') + L('initial') + gorf +
             unit) | G(S('@') + L('constant') + gorf + unit)

    cplx = G(
        T(
            identifier + S("=") + OneOrMore(pattern) + O(conc) +
            OneOrMore(LineEnd().suppress()), 'complex'))

    stmt = domain | cplx

    document = StringStart() + ZeroOrMore(
        LineEnd().suppress()) + OneOrMore(stmt) + StringEnd()
    document.ignore(pythonStyleComment)

    return document
Пример #6
0
def pil_document_setup():
    crn_DWC = "".join(
        [x for x in ParseElementEnhance.DEFAULT_WHITE_CHARS if x != "\n"])
    ParseElementEnhance.setDefaultWhitespaceChars(crn_DWC)

    def T(x, tag):
        def TPA(tag):
            return lambda s, l, t: [tag] + t.asList()

        return x.setParseAction(TPA(tag))

    W = Word
    G = Group
    S = Suppress
    O = Optional
    C = Combine
    L = Literal

    identifier = W(alphanums + "_-")
    number = W(nums, nums)

    num_flt = C(number + O(L('.') + number))
    num_sci = C(number + O(L('.') + number) + L('e') + O(L('-') | L('+')) +
                W(nums))
    gorf = num_sci | num_flt
    ginf = gorf | L('inf')

    domain = C(identifier + O('*'))
    constraint = W(alphas)
    assign = L("=") | L(":")
    dotbracket = W("(.)+ ")
    dlength = number | L('short') | L('long')

    dl_domain = G(T(S("length") + domain + S(assign) + dlength + OneOrMore(LineEnd().suppress()), 'dl-domain')) \
              | G(T(S("domain") + domain + S(assign) + dlength + OneOrMore(LineEnd().suppress()), 'dl-domain')) \
              | G(T(S("sequence") + domain + S(assign) + dlength + OneOrMore(LineEnd().suppress()), 'dl-domain'))

    sl_domain = G(
        T(
            S("sequence") + domain + S(assign) + constraint +
            O(S(assign) + number) + OneOrMore(LineEnd().suppress()),
            'sl-domain'))

    # strand and sup-sequence are the same thing ...
    comp_domain = G(T(S("sup-sequence") + identifier + S(assign) \
            + G(OneOrMore(domain)) + O(S(assign) + number) \
            + OneOrMore(LineEnd().suppress()), 'composite-domain'))
    strand = G(T(S("strand") + identifier + S(assign) \
            + G(OneOrMore(domain)) + O(S(assign) + number) \
            + OneOrMore(LineEnd().suppress()), 'composite-domain'))

    strandcomplex = G(T(S("complex") + identifier + S(assign) + O(LineEnd().suppress()) \
                    + G(OneOrMore(domain)) + O(LineEnd().suppress()) \
                    + dotbracket + OneOrMore(LineEnd().suppress()), 'strand-complex')) \
                  | G(T(S("structure") + identifier + S(assign) \
                    + G(OneOrMore(domain | S('+'))) + S(assign) \
                    + dotbracket + OneOrMore(LineEnd().suppress()), 'strand-complex'))

    species = delimitedList(identifier, '+')
    cunit = L('M') | L('mM') | L('uM') | L('nM') | L('pM')
    tunit = L('s') | L('m') | L('h')
    runit = C(ZeroOrMore('/' + cunit) + L('/') + tunit)
    infobox = S('[') + G(
        O(identifier +
          S(assign))) + G(gorf + O(S(L('+/-')) + ginf)) + G(runit) + S(']')

    reaction = G(T(S("kinetic") + G(O(infobox)) + G(species) + S('->') + G(species) + OneOrMore(LineEnd().suppress()), 'reaction')) \
             | G(T(S("reaction") + G(O(infobox)) + G(species) + S('->') + G(species) + OneOrMore(LineEnd().suppress()), 'reaction'))

    restingset = G(T(S("state") + identifier + S("=") + S('[') + G(delimitedList(identifier)) + S(']') + OneOrMore(LineEnd().suppress()), 'resting-macrostate')) \
               | G(T(S("macrostate") + identifier + S("=") + S('[') + G(delimitedList(identifier)) + S(']') + OneOrMore(LineEnd().suppress()), 'resting-macrostate'))

    # kernel notation
    sense = Combine(identifier + O(L("^")) + O(L("*")))

    pattern = Forward()
    innerloop = pattern | S(White())
    loop = (Combine(sense + S("(")) + G(O(innerloop)) + S(")"))
    pattern << OneOrMore(loop | L("+") | sense)

    conc = G( S('@') + (L('initial')  | L('i')) + gorf + cunit) \
         | G( S('@') + (L('constant') | L('c')) + gorf + cunit)

    cplx = G(
        T(
            identifier + S("=") + OneOrMore(G(pattern)) + O(conc) +
            OneOrMore(LineEnd().suppress()), 'kernel-complex'))

    stmt = sl_domain | dl_domain | comp_domain | strand | strandcomplex | reaction | cplx | restingset

    document = StringStart() + ZeroOrMore(LineEnd().suppress()) + \
        OneOrMore(stmt) + StringEnd()
    document.ignore(pythonStyleComment)

    return document
def ssw_document_setup():
    crn_DWC = "".join(
        [x for x in ParseElementEnhance.DEFAULT_WHITE_CHARS if x != "\n"])
    ParseElementEnhance.setDefaultWhitespaceChars(crn_DWC)

    def T(x, tag):
        def TPA(tag):
            return lambda s, l, t: [tag] + t.asList()

        return x.setParseAction(TPA(tag))

    W = Word
    G = Group
    S = Suppress
    O = Optional
    L = Literal
    C = Combine

    identifier = W(alphas, alphanums + "_-")
    number = W(nums, nums)
    num_flt = C(number + O(L('.') + number))
    num_sci = C(number + O(L('.') + number) + L('e') + O(L('-') | L('+')) +
                W(nums))
    gorf = num_sci | num_flt

    wire = G('w' + S('[') + G(number + S(',') + (number | L('f'))) + S(']'))
    gateO = G('g' + S('[') + G(wire + S(',') + number) + S(']'))
    gateI = G('g' + S('[') + G(number + S(',') + wire) + S(']'))
    thshO = G('th' + S('[') + G(wire + S(',') + number) + S(']'))
    thshI = G('th' + S('[') + G(number + S(',') + wire) + S(']'))

    fluor = G('Fluor' + S('[') + number + S(']'))

    inp = "INPUT" + S(L("(")) + G(number | identifier) + S(")") + S("=") + wire
    out = "OUTPUT" + S("(") + G(number | identifier) + S(")") + S("=") + (
        fluor | wire)

    inputs = G(S("{") + delimitedList(number, ",") + S("}"))
    outputs = G(S("{") + delimitedList((number | L('f')), ",") + S("}"))
    seesaw = 'seesaw' + S('[') + G(number + S(',') + inputs + S(',') +
                                   outputs) + S(']')

    conc = gorf + S(L('*') + L('c'))
    wireconc = 'conc' + S('[') + wire + S(',') + conc + S(']')
    outpconc = 'conc' + S('[') + (gateO | gateI) + S(',') + conc + S(']')
    thshconc = 'conc' + S('[') + (thshO | thshI) + S(',') + conc + S(']')

    # MACROS:
    reporter = 'reporter' + S('[') + G(number + S(',') + number) + S(']')
    inputfanout = 'inputfanout' + S('[') + G(number + S(',') + number +
                                             S(',') + inputs) + S(']')
    seesawOR = 'seesawOR' + S('[') + \
        G(number + S(',') + number + S(',') + inputs + S(',') + inputs) + S(']')
    seesawAND = 'seesawAND' + S('[') + \
        G(number + S(',') + number + S(',') + inputs + S(',') + inputs) + S(']')

    macros = reporter | inputfanout | seesawOR | seesawAND
    stmt = G(inp | out | seesaw | wireconc | outpconc | thshconc
             | macros) + OneOrMore(LineEnd().suppress())

    document = StringStart() + ZeroOrMore(
        LineEnd().suppress()) + OneOrMore(stmt) + StringEnd()
    document.ignore(pythonStyleComment)

    return document