Example #1
0
def output_crn(enumerator,
               filename,
               output_condensed=False,
               output_rates=True,
               condense_options={}):
    output_file = open(filename, 'w')

    def write_reaction(output_file, reaction):
        reactants = map(str, reaction.reactants)
        products = map(str, reaction.products)
        reac_string_list = [
            " + ".join(reactants), "->", " + ".join(products), "\n"
        ]
        reac_string = ' '.join(reac_string_list)
        output_file.write(reac_string)

    reactions = enumerator.reactions
    if (output_condensed):
        condensed = condense_resting_states(enumerator, **condense_options)
        reactions = condensed['reactions']

    for reaction in sorted(reactions):  # utils.natural_sort(reactions):
        write_reaction(output_file, reaction)

    output_file.close()
Example #2
0
def output_k(enumerator,
             filename,
             output_condensed=False,
             output_rates=True,
             condense_options={}):
    output_file = open(filename, 'w')

    def write_reaction(output_file, reaction, reversible=True):
        reactants = sorted([
            str(count) + '*' + str(x) if count > 1 else str(x) for (x, count)
            in collections.Counter(sorted(reaction.reactants)).iteritems()
        ])
        products = sorted([
            str(count) + '*' + str(x) if count > 1 else str(x) for (x, count)
            in collections.Counter(sorted(reaction.products)).iteritems()
        ])

        if reversible:
            arrow = '<->'
        else:
            arrow = '->'

        rxn = [" + ".join(reactants), arrow, " + ".join(products), "\n"]
        output_file.write(' '.join(rxn))

    reactions = enumerator.reactions
    if (output_condensed):
        condensed = condense_resting_states(enumerator, **condense_options)
        reactions = condensed['reactions']

    for reaction in sorted(reactions):  # utils.natural_sort(reactions):
        write_reaction(output_file, reaction, True)

    output_file.close()
Example #3
0
def output_condensed_dotfile(enumerator, filename):
    fout = open(filename + ".dot", "w")
    fout.write("digraph G {\n")
    fout.write('size="7,10"\n')
    fout.write('page="8.5,11"\n')
    fout.write('node[width=0.25,height=0.375,fontsize=9]\n')

    condensed_graph = condense_resting_states(enumerator, **condense_options)

    # We loop through all resting states, drawing them on the graph
    for state in condensed_graph['resting_states']:
        fout.write('%s [label="%s"]\n' % (str(state), str(state)))

    # We now add reactions. We always create a reaction node.
    for (i, reaction) in enumerate(condensed_graph['reactions']):
        reaction_label = "R_%d" % i
        fout.write(
            '%s [label="",shape=circle,height=0.12,width=0.12,fontsize=1,style=filled,color=red];\n'
            % reaction_label)

        for reagent in reaction.reactants:
            fout.write("%s -> %s\n" % (str(reagent), reaction_label))

        for product in reaction.products:
            fout.write("%s -> %s\n" % (reaction_label, str(product)))

    fout.write("}\n")
    fout.close()
Example #4
0
  def test_peppercorn_interface(self):
    """ Make sure peppercorn.utils did not change """

    t0  = peputils.Domain('t0', 5, sequence='H'*5)
    t0_ = peputils.Domain('t0', 5, sequence='D'*5, is_complement=True)
    d1  = peputils.Domain('d1', 15, sequence='H'*15)
    d1_ = peputils.Domain('d1', 15, sequence='D'*15, is_complement=True)
    domains = [t0,t0_,d1,d1_]

    s0  = peputils.Strand('s0', [t0, d1])
    s1  = peputils.Strand('s1', [d1])
    s2  = peputils.Strand('s2', [d1_, t0_])
    strands = [s0,s1,s2]

    c1s = peputils.parse_dot_paren('..')
    c1  = peputils.Complex('c1', [s0], c1s)
    c1.check_structure()

    c2s = peputils.parse_dot_paren('(+).')
    c2  = peputils.Complex('c2', [s1,s2], c2s)
    c2.check_structure()
    complexes = [c1,c2]

    enum = Enumerator(domains, strands, complexes)

    enum.enumerate()

    ###########################
    # Get full output CRN
    reactions = enum.reactions

    self.assertEqual(len(reactions), 3)

    r1_kernel = 't0 d1  +  d1( + ) t0*  ->  t0( d1 + d1( + ) )'
    r2_kernel = 't0( d1 + d1( + ) )  ->  t0( d1( + ) )  +  d1'
    r3_kernel = 't0( d1 + d1( + ) )  ->  t0 d1  +  d1( + ) t0*'

    p_cntr = Counter()
    r_cntr = Counter()
    for r in sorted(reactions):
      #print r.kernel_string()
      for cx in r.reactants :
        p_cntr += Counter(map(str, cx.strands))
      for cx in r.products:
        r_cntr += Counter(map(str, cx.strands))

      self.assertEqual(p_cntr, r_cntr)
      self.assertTrue(r.kernel_string() in [r1_kernel, r2_kernel, r3_kernel])

    ###########################
    # Get condensed output CRN
    condensed = condense_resting_states(enum, compute_rates=True, k_fast = 0.)
    reactions = condensed['reactions']

    self.assertEqual(len(reactions), 1)

    result_kernel = 't0 d1  +  d1( + ) t0*  ->  t0( d1( + ) )  +  d1'
    self.assertEqual(reactions[0].kernel_string(), result_kernel)
Example #5
0
  def test_under_the_hood2(self):
    domstring = """
    sequence tf : 5
    sequence bm : 15
    
    A :
    tf bm
    . .

    B :
    bm tf + tf* bm* tf*
    ( ( + ) ) .
    """
    
    solution = self._TestTube_from_DOM(domstring)
    peppercorn = ne.TestTubePeppercornIO(testtube=solution, pargs=self.args)
    self.assertIsInstance(pep.enumerator, Enumerator)

    pep.enumerate()

    ###########################
    # Get full output CRN
    reactions = pep.enumerator.reactions
    r1 = 'tf bm  +  tf( bm( + tf* ) )  ->  tf( bm( + tf( bm + ) ) )'
    r2 = 'tf bm  +  bm( tf( + ) ) tf*  ->  tf( bm + bm( tf( + ) ) )'
    r3 = 'tf( bm( + tf* ) )  +  bm tf  ->  tf( bm( + bm tf( + ) ) )'
    r4 = 'bm tf  +  bm( tf( + ) ) tf*  ->  bm tf( + bm( tf( + ) ) )'
    r5 = 'tf( bm + bm( tf( + ) ) )  ->  tf( bm( + bm tf( + ) ) )'
    r6 = 'tf( bm( + bm tf( + ) ) )  ->  tf( bm + bm( tf( + ) ) )'
    r7 = 'tf( bm( + tf( bm + ) ) )  ->  tf bm  +  tf( bm( + tf* ) )'
    r8 = 'tf( bm + bm( tf( + ) ) )  ->  tf bm  +  bm( tf( + ) ) tf*'
    r9 = 'tf( bm( + bm tf( + ) ) )  ->  tf( bm( + tf* ) )  +  bm tf'
    r10 = 'bm tf( + bm( tf( + ) ) )  ->  bm tf  +  bm( tf( + ) ) tf*'

    self.assertEqual(len(reactions), 10)
    for r in sorted(reactions):
      self.assertTrue(r.kernel_string() in [
        r1, r2, r3, r4, r5, r6, r7, r8, r9, r10])

    ###########################
    # Get condensed output CRN
    condensed = condense_resting_states(pep.enumerator)
    reactions = condensed['reactions']

    rc1 = 'tf bm  +  bm( tf( + ) ) tf*  ->  tf( bm( + tf* ) )  +  bm tf'
    rc2 = 'tf( bm( + tf* ) )  +  bm tf  ->  tf bm  +  bm( tf( + ) ) tf*'

    self.assertEqual(len(reactions), 2)
    for r in sorted(reactions):
      self.assertTrue(r.kernel_string() in [rc1, rc2])
Example #6
0
  def test_under_the_hood1(self):
    # A test function that checks enumerated reaction networks by directly
    # calling the Enumerator object, not the output of the TestTubePeppercornIO
    # wrapper.
    domstring = """
    sequence tf : 5
    sequence bm : 15
    sequence tb : 5
    
    A :
    tf bm
    . .

    B :
    bm tb + tb* bm* tf*
    ( ( + ) ) .
    """
    
    solution = self._TestTube_from_DOM(domstring)
    peppercorn = ne.TestTubePeppercornIO(testtube=solution, pargs=self.args)
    self.assertIsInstance(pep.enumerator, Enumerator)

    pep.enumerate()

    ###########################
    # Get full output CRN
    reactions = pep.enumerator.reactions
    r1 = 'tf bm  +  bm( tb( + ) ) tf*  ->  tf( bm + bm( tb( + ) ) )'
    r2 = 'tf( bm( + tb* ) )  +  bm tb  ->  tf( bm( + bm tb( + ) ) )'
    r3 = 'tf( bm + bm( tb( + ) ) )  ->  tf( bm( + bm tb( + ) ) )'
    r4 = 'tf( bm( + bm tb( + ) ) )  ->  tf( bm + bm( tb( + ) ) )'
    r5 = 'tf( bm + bm( tb( + ) ) )  ->  tf bm  +  bm( tb( + ) ) tf*'
    r6 = 'tf( bm( + bm tb( + ) ) )  ->  tf( bm( + tb* ) )  +  bm tb'

    for r in sorted(reactions):
      print r.kernel_string()
      self.assertTrue(r.kernel_string() in [r1, r2, r3, r4, r5, r6])

    ###########################
    # Get condensed output CRN
    condensed = condense_resting_states(pep.enumerator)
    reactions = condensed['reactions']

    rc1 = 'tf bm  +  bm( tb( + ) ) tf*  ->  tf( bm( + tb* ) )  +  bm tb'
    rc2 = 'tf( bm( + tb* ) )  +  bm tb  ->  tf bm  +  bm( tb( + ) ) tf*'

    for r in sorted(reactions):
      self.assertTrue(r.kernel_string() in [rc1, rc2])
Example #7
0
    def enumerator_to_testtube(self, enumerator):
        """Merge Enumerator() complexes into the TestTube() object. 

    Note that the enumerator cannot generate new domains or new strands, it
    only finds new complexes. This function adds all complexes that are
    present in resting states in the system. Transient states are ignored.
    """
        condensed = TestTubePeppercornIO.condensed
        ttcomplexes = dict()

        domains = enumerator.domains
        # The enumerator cannot find new domains, so if there is a testtube object
        # already, then we might as well save some effort and use the testtube
        # domains directly
        if self._testtube:
            dNames = map(lambda x: x.name, domains)
            tDomains = self._testtube.domains
            assert all(map(lambda d: d in tDomains, dNames))
            domains = tDomains
        else:
            # translate domains to nuskell.Domain format, easy...
            raise NotImplementedError

        if condensed:
            enum_complexes = enumerator.resting_complexes
        else:
            # resting_complexes + transient_complexes
            enum_complexes = enumerator.complexes

        for cx in enum_complexes:
            if cx.name in self._enumN_to_ttubeO:
                ttcplx = self._enumN_to_ttubeO[cx.name]
                ttcomplexes[cx.name] = (ttcplx, None, None)
                continue
            domseq = []
            for sd in cx.strands:
                domseq.append('+')
                for do in sd.domains:
                    assert (do.name in domains)
                    dom = domains[do.name]
                    domseq.append(dom)
            # remove the first '+' again
            if len(domseq) > 0: domseq = domseq[1:]
            domstr = list(cx.dot_paren_string())
            cplxname = self._ecplx_rename(cx.name)
            if cplxname in ttcomplexes:
                raise ValueError("Complex found in muliple resting states?")
            ttcplx = Complex(sequence=domseq, structure=domstr, name=cplxname)

            ttcomplexes[ttcplx.name] = (ttcplx, None, None)
            self._enumN_to_ttubeO[cx.name] = ttcplx
            self._ttubeN_to_enumO[ttcplx.name] = cx

        crn = dict()
        if condensed:
            condensed = condense_resting_states(enumerator,
                                                compute_rates=True,
                                                k_fast=enumerator.k_fast)
            reactions = condensed['reactions']
            for r in reactions:
                # NOTE: takes only the *first complex* of resting states as representative
                react = []
                for rs in r.reactants:
                    react.append(self._enumN_to_ttubeO[rs.complexes[0].name])
                prod = []
                for rs in r.products:
                    prod.append(self._enumN_to_ttubeO[rs.complexes[0].name])
                rxn = Reaction(react, prod, rate=r.rate(), rtype=r.name)
                crn[rxn.name] = rxn
        else:
            for r in enumerator.reactions:
                react = []
                for re in r.reactants:
                    react.append(self._enumN_to_ttubeO[re.name])
                prod = []
                for pr in r.products:
                    prod.append(self._enumN_to_ttubeO[pr.name])
                rxn = Reaction(react, prod, rate=r.rate(), rtype=r.name)
                crn[rxn.name] = rxn

        return TestTube(complexes=ttcomplexes, reactions=crn)
Example #8
0
def output_case(enumerator,
                filename,
                output_condensed=False,
                condense_options={}):
    def tab(x):
        return "\t" * x

    of = open(filename, 'w')
    of.write("def test_%s(enumerator):\n" % filename)

    # Domains
    of.write(tab(1) + "# Domains \n")
    of.write(tab(1) + "domains = { \n")
    lines = []
    for domain in utils.natural_sort(enumerator.domains):
        #  name, length, is_complement=False, sequence=None
        lines.append(
            tab(2) +
            "'%s' : Domain('%s', %d, is_complement=%s, sequence='%s')" %
            (domain.name, domain.identity, domain.length, domain.is_complement,
             domain.sequence))

    of.write(",\n".join(lines) + "\n")
    of.write(tab(1) + "}\n")
    of.write(
        tab(1) + "assert set(domains.values()) == set(enumerator.domains)\n\n")

    # Strands
    of.write(tab(1) + "# Strands \n")
    of.write(tab(1) + "strands = { \n")
    lines = []
    for strand in utils.natural_sort(enumerator.strands):
        doms = ", ".join("domains['%s']" % dom.name for dom in strand.domains)
        lines.append(
            tab(2) + "'%s' : Strand('%s', [%s])" %
            (strand.name, strand.name, doms))
    of.write(",\n".join(lines) + "\n")
    of.write(tab(1) + "}\n")
    of.write(
        tab(1) + "assert set(strands.values()) == set(enumerator.strands)\n\n")

    # Complexes
    of.write(tab(1) + "# Complexes \n")
    of.write(tab(1) + "complexes = { \n")
    lines = []
    for complex in utils.natural_sort(enumerator.complexes):
        strands = ", ".join("strands['%s']" % strand.name
                            for strand in complex.strands)
        lines.append(
            tab(2) + "'%s' : Complex('%s', [%s], %r)" %
            (complex.name, complex.name, strands, complex.structure))
    of.write(",\n".join(lines) + "\n")
    of.write(tab(1) + "}\n")
    of.write(
        tab(1) +
        "assert set(complexes.values()) == set(enumerator.complexes)\n\n")

    # Reactions
    of.write(tab(1) + "# Reactions \n")
    of.write(tab(1) + "reactions = { \n")
    lines = []
    for reaction in utils.natural_sort(enumerator.reactions):
        reactants = ", ".join("complexes['%s']" % complex.name
                              for complex in reaction.reactants)
        products = ", ".join("complexes['%s']" % complex.name
                             for complex in reaction.products)
        lines.append(
            tab(2) + "ReactionPathway('%s', [%s], [%s])" %
            (reaction.name, reactants, products))
    of.write(",\n".join(lines) + "\n")
    of.write(tab(1) + "}\n")
    of.write(tab(1) + "assert set(reactions) == set(enumerator.reactions)\n\n")

    if (output_condensed):
        condensed = condense_resting_states(enumerator, **condense_options)

        # Resting states
        of.write(tab(1) + "# Resting states \n")
        of.write(tab(1) + "resting_states = { \n")
        lines = []
        for rs in utils.natural_sort(condensed['resting_states']):
            complexes = ", ".join("complexes['%s']" % complex.name
                                  for complex in rs.complexes)
            lines.append(
                tab(2) + "'%s' : RestingState('%s', [%s])" %
                (rs.name, rs.name, complexes))

        of.write(",\n".join(lines) + "\n")
        of.write(tab(1) + "}\n")
        of.write(
            tab(1) +
            "assert set(resting_states.values()) == set(condensed['resting_states'])\n\n"
        )

        # Condensed reactions
        of.write(tab(1) + "# Condensed Reactions \n")
        of.write(tab(1) + "condensed_reactions = { \n")
        lines = []
        for reaction in utils.natural_sort(condensed['reactions']):
            reactants = ", ".join("resting_states['%s']" % species.name
                                  for species in reaction.reactants)
            products = ", ".join("resting_states['%s']" % species.name
                                 for species in reaction.products)
            lines.append(
                tab(2) + "ReactionPathway('%s', [%s], [%s])" %
                (reaction.name, reactants, products))
        of.write(",\n".join(lines) + "\n")
        of.write(tab(1) + "}\n")
        of.write(
            tab(1) +
            "assert set(condensed_reactions) == set(condensed['reactions'])\n\n"
        )

    of.close()
Example #9
0
def output_sbml(enumerator,
                filename,
                output_condensed=False,
                output_rates=True,
                condense_options={}):
    # # default initial concentration of all species is 100 nM
    # initial_concentration = 10e-7

    import xml.dom.minidom
    header = '<?xml version="1.0" encoding="UTF-8"?>'
    out = [
        header,
        '<sbml level="2" version="3" xmlns="http://www.sbml.org/sbml/level2/version3">',
        '<model name="%s">' % filename, '<listOfUnitDefinitions>',
        '<unitDefinition id="per_second">', '<listOfUnits>',
        '<unit kind="second" exponent="-1"/>', ' </listOfUnits>',
        '</unitDefinition>', '<unitDefinition id="litre_per_mole_per_second">',
        '<listOfUnits>', '<unit kind="mole"   exponent="-1"/>',
        '<unit kind="litre"  exponent="1"/>',
        '<unit kind="second" exponent="-1"/>', '</listOfUnits>',
        '</unitDefinition>', '</listOfUnitDefinitions>',
        '<listOfCompartments>', '<compartment id="reaction" size="1e-3" />',
        '</listOfCompartments>', '<listOfSpecies>'
    ]

    if (output_condensed):
        condensed = condense_resting_states(enumerator, **condense_options)
        complexes = condensed['resting_states']
        reactions = condensed['reactions']
    else:
        complexes = enumerator.complexes
        reactions = enumerator.reactions

    def id(species):
        return "s_" + species.name

    # build elements for each species
    if (output_condensed):
        for resting_state in complexes:
            # is_initial = any(c in enumerator.initial_complexes for c in resting_state.complexes)
            initial_concentration = sum(
                (c.concentration if c.concentration is not None else 0.0)
                for c in resting_state.complexes)
            out.append(
                '<species compartment="reaction" id="%(id)s" name="%(name)s" initialConcentration="%(initial)g"/>'
                % {
                    "name": resting_state.name,
                    "id": id(resting_state),
                    "initial": initial_concentration
                })
    else:
        for complex in complexes:
            # is_initial = (complex in enumerator.initial_complexes)
            initial_concentration = complex.concentration if complex.concentration is not None else 0.0
            out.append(
                '<species compartment="reaction" id="%(id)s" name="%(name)s" initialConcentration="%(initial)g"/>'
                % {
                    "name": complex.name,
                    "id": id(complex),
                    "initial": initial_concentration
                })

    out += ['</listOfSpecies>', '<listOfReactions>']

    # list reactions
    for (i, reaction) in enumerate(reactions):
        out += ['<reaction id="r_%d" reversible="false">' % i,
                '<listOfReactants>'] + \
            ['<speciesReference species="%s"/>' % id(species) for species in reaction.reactants] + \
            ['</listOfReactants>',
             '<listOfProducts>'] + \
            ['<speciesReference species="%s"/>' % id(species) for species in reaction.products] + \
            ['</listOfProducts>']

        # unimolecular rate constants have units 1/s, bimolecular rate
        # constants have units 1/M/s
        units = 'per_second' if reaction.arity[
            0] == 1 else 'litre_per_mole_per_second'

        out += ['<kineticLaw>',
                '<math xmlns="http://www.w3.org/1998/Math/MathML">',
                '<apply>',
                '<times />',
                '<ci>k</ci>'] + \
            ['<ci>' + id(s) + '</ci>' for s in reaction.reactants] + \
            ['</apply>',
             '</math>',
             '<listOfParameters>',
             '<parameter id="k"  value="%.10f" units="%s"/>' % (
                 reaction.rate(), units),
             '</listOfParameters>',
             '</kineticLaw>',
             '</reaction>']

    out.extend(['</listOfReactions>', '</model>', '</sbml>'])

    doc = xml.dom.minidom.parseString("".join(out))

    fout = open(filename, "w")
    fout.write(header + '\n' + doc.documentElement.toprettyxml(indent="\t"))
    fout.close()
Example #10
0
def output_json(enumerator,
                filename,
                output_condensed=False,
                output_rates=True,
                condense_options={}):
    """
    JSON-based output schema intended to be easily machine parsable. Uses
    python's JSON serialization libraries.
    """
    def serializeComplex(complex):
        temp_strands = []
        for strand in complex.strands:
            temp_strands.append(strand.name)
        return {
            'name': complex.name,
            'strands': temp_strands,
            'structure': complex.structure,
            'dot-paren': complex.dot_paren_string(),
            'dot-paren-full': complex.dot_paren_string_full(),
        }

    def serializeReaction(reaction):
        # temp_reactants = []
        # for reactant in reaction.reactants:
        # 	temp_reactants.append(reactant.name)
        # temp_products = []
        # for product in reaction.products:
        # 	temp_products.append(product.name)
        reactants = map(str, reaction.reactants)
        products = map(str, reaction.products)
        return {
            "name": reaction.name,
            "reactants": reactants,  # temp_reactants,
            "products": products  # temp_products
        }

    def serializeDomain(domain):
        temp_domain = {
            "name": domain.name,
            "length": domain.length,
            "is_complement": domain.is_complement
        }

        # temp_domain = {}
        # temp_domain['name'] = domain.name
        # temp_domain['length'] = domain.length
        # temp_domain['is_complement'] = domain.is_complement
        if domain.sequence is not None:
            temp_domain['sequence'] = domain.sequence
        return temp_domain

    def serializeStrand(strand):
        return {
            "name": strand.name,
            "domains": [domain.name for domain in strand.domains]
        }
        # temp_strand = {}
        # temp_strand['name'] = strand.name
        # temp_domains = []
        # for domain in strand.domains:
        # 	temp_domains.append(domain.name)
        # temp_strand['domains'] = temp_domains
        # return temp_strand

    def serializeRestingState(resting_state):
        return {
            "name": str(resting_state),
            "complexes": [complex.name for complex in resting_state.complexes]
        }
        # temp_resting_state = {}
        # temp_complexes = []
        # for complex in resting_state.complexes:
        # 	temp_complexes.append(complex.name)
        # temp_resting_state['name'] = resting_state.name
        # temp_resting_state['complexes'] = temp_complexes
        # return temp_resting_state

    object_out = {}

    object_out['domains'] = map(serializeDomain, enumerator.domains)
    object_out['strands'] = map(serializeStrand, enumerator.strands)
    object_out['resting_complexes'] = map(serializeComplex,
                                          enumerator.resting_complexes)
    object_out['transient_complexes'] = map(serializeComplex,
                                            enumerator.transient_complexes)
    object_out['resting_states'] = map(serializeRestingState,
                                       enumerator.resting_states)
    object_out['initial_complexes'] = map(serializeComplex,
                                          enumerator.initial_complexes)
    object_out['reactions'] = map(serializeReaction, enumerator.reactions)

    if output_condensed:
        condensed = condense_resting_states(enumerator, **condense_options)
        object_out['condensed_reactions'] = map(serializeReaction,
                                                condensed['reactions'])

    fout = open(filename, 'w')
    json.dump(object_out, fout, indent=4)
    fout.close()
Example #11
0
def output_kernel(enumerator,
                  filename,
                  output_condensed=False,
                  output_rates=True,
                  condense_options={}):
    """
    Text-based output using the Pepper Intermediate Language (PIL)
    """
    def write_complex(output_file, complex):
        params = ""
        if complex.concentration is not None:
            params = "[@ %g %sM] " % utils.format_si(complex.concentration)
        output_file.write(
            str(complex) + params + " = " + complex.kernel_string() + "\n")

    def write_reaction(output_file, reaction):
        if output_rates:
            rate_units = "/M" * (reaction.arity[0] - 1) + "/s"
            rate_const = "[%f %s]" % (reaction.rate(), rate_units)
        else:
            rate_const = ""
        reac_string_list = [rate_const, reaction.kernel_string()]
        reac_string = ' '.join(reac_string_list)

        reactants = map(str, reaction.reactants)
        products = map(str, reaction.products)
        prefix = " ".join([
            "# ",
            str(reaction), " + ".join(reactants), "->", " + ".join(products)
        ])

        output_file.write(prefix + "\n" + reac_string + "\n")

    complexes = enumerator.complexes
    transient_complexes = enumerator.transient_complexes
    resting_complexes = enumerator.resting_complexes
    reactions = enumerator.reactions
    resting_states = enumerator.resting_states

    output_file = open(filename, 'w')
    output_file.write("###### Enumerated Output ######\n")
    output_file.write("\n# Domains \n")

    def seq(dom):
        if (dom.sequence is not None):
            return dom.sequence
        else:
            return "N" * len(dom)

    for domain in utils.natural_sort(enumerator.domains):
        if (not domain.is_complement):
            output_file.write("sequence " + domain.name + " = " + seq(domain) +
                              " : " + str(domain.length) + "\n")

    output_file.write("\n# Strands \n")
    for strand in utils.natural_sort(enumerator.strands):
        output_file.write("strand " + strand.name + " = " +
                          " ".join(map(lambda dom: dom.name, strand.domains)) +
                          "\n")

    output_file.write("\n# Resting-state Complexes \n")
    for complex in utils.natural_sort(resting_complexes):
        write_complex(output_file, complex)

    if (output_condensed):
        condensed = condense_resting_states(enumerator, **condense_options)

        output_file.write("\n# Resting-state sets \n")
        resting_states = condensed['resting_states']
        for resting_state in utils.natural_sort(resting_states):
            output_file.write("# state " + str(resting_state) + " = { " +
                              " ".join(map(str, resting_state.complexes)) +
                              " }\n")

        output_file.write("\n# Condensed Reactions \n")
        new_reactions = condensed['reactions']
        for reaction in sorted(new_reactions):
            write_reaction(output_file, reaction)
    else:
        output_file.write("\n# Transient Complexes \n")
        for complex in utils.natural_sort(transient_complexes):
            write_complex(output_file, complex)
        output_file.write("\n# Detailed Reactions \n")
        for reaction in sorted(reactions):  # utils.natural_sort(reactions):
            write_reaction(output_file, reaction)

    output_file.close()
Example #12
0
def output_legacy(enumerator,
                  filename,
                  output_condensed=False,
                  output_rates=False,
                  condense_options={}):
    """
    Legacy text-based output scheme similar to that used in the original
    enumerator. Designed to be simultaneously parsable and human-readable.
    Supports output of condensed graph in addition to the full graph. Does
    not support strands.
    """
    def write_complex(output_file, complex):
        output_file.write(str(complex) + "\n")
        names = []
        for strand in complex.strands:
            names.append(" ".join(map(str, strand.domains)))
        strands_string = " + ".join(names)
        output_file.write(strands_string + "\n")
        output_file.write(str(complex.dot_paren_string()) + "\n")
        output_file.write("\n")

    def write_reaction(output_file, reaction):
        reactants = map(str, reaction.reactants)
        products = map(str, reaction.products)
        reac_string_list = [
            " + ".join(reactants), "->", " + ".join(products), "\n"
        ]
        reac_string = ' '.join(reac_string_list)
        output_file.write(reac_string)

#	def write_reaction(output_file,reaction):
#		reactants = reaction.reactants
#		products = reaction.products
#		reac_string_list = [reactants[0].name]
#		for reactant in reactants[1:]:
#			reac_string_list.append(" + " + reactant.name)
#		reac_string_list.append(" -> ")
#		reac_string_list.append(products[0].name)
#		for product in products[1:]:
#			reac_string_list.append(" + " + product.name)
#		reac_string_list.append("\n")
#		reac_string = ''.join(reac_string_list)
#		output_file.write(reac_string)

    complexes = enumerator.complexes
    transient_complexes = enumerator.transient_complexes
    resting_complexes = enumerator.resting_complexes
    reactions = enumerator.reactions
    resting_states = enumerator.resting_states

    output_file = open(filename, 'w')
    output_file.write("###### Enumerated Output ######\n")
    output_file.write("\n\n# Domains \n")
    for domain in sorted(enumerator.domains):
        if (not domain.is_complement):
            output_file.write("sequence " + domain.name + " = : " +
                              str(domain.length) + "\n")

    output_file.write("\n\n# End-state Complexes \n")
    for complex in sorted(resting_complexes):
        write_complex(output_file, complex)

    # Not part of the original output; omitting


#	output_file.write("###############################\n")
#	output_file.write("\n\n# Resting-state sets \n")
#	for resting_state in sorted(resting_states):
#		output_file.write("state " + resting_state.name + " = : ")
#		output_file.write(str(resting_state.complexes[0]))
#		for complex in resting_state.complexes[1:]:
#			output_file.write(" %s" % complex)
#		output_file.write("\n")
    output_file.write("###############################\n")
    output_file.write("\n\n# Fast (Transition) Complexes \n")
    for complex in sorted(transient_complexes):
        write_complex(output_file, complex)
    output_file.write("###############################\n")
    output_file.write("\n\n# Reactions \n")
    for reaction in sorted(reactions):
        write_reaction(output_file, reaction)

    if (output_condensed):
        output_file.write("###############################\n")
        output_file.write("\n\n# Condensed Reactions \n")
        condensed = condense_resting_states(enumerator, **condense_options)
        new_reactions = condensed['reactions']
        for reaction in sorted(new_reactions):
            write_reaction(output_file, reaction)

    output_file.close()
Example #13
0
  def test_under_the_hood3(self):
    # Here we have a test example that illustrates the condese function of the
    # enumerator. The example uses complexes from the Soloveichik scheme,
    # reaction B+B->B. Note that some of these complexes are commented out! 
    # It turns out that the enumerator does the correct thing, and the test is
    # kind of pointless. But it is nice to understand what is going on under the
    # hood of the condese function, and what problems you might find when
    # looking at the return statements.
    domstring = """
    sequence a : 6
    sequence x : 15
    sequence b : 6
    sequence y : 15

    B :
    y a x b
    . . . .

    #C_1_ :
    #x b a
    #. . .

    #C_2_ :
    #y a x b + a* y* b*
    #( ( . . + ) ) .

    C_3_ :
    x b a + x b y a + b* x* a* b* x* a*
    ( ( ( + ( ( . . + ) ) ) ) ) .
    """
    
    solution = self._TestTube_from_DOM(domstring)
    #self.args.reject_remote = False
    self.args.MAX_COMPLEX_SIZE = 4
    self.args.MAX_COMPLEX_COUNT = 9
    self.args.MAX_REACTION_COUNT = 10
    self.args.REJECT_REMOTE = False
    self.args.ignore_branch_4way = True
 
    peppercorn = ne.TestTubePeppercornIO(testtube=solution, pargs=self.args)
    self.assertIsInstance(pep.enumerator, Enumerator)

    pep.enumerate()
    ###########################
    # Get full output CRN
    reactions = pep.enumerator.reactions

    count = 0
    ks_t_cp = dict()
    for r in sorted(reactions):
      print map(str, r.reactants), '->', map(str, r.products)
      print r.kernel_string()

    print '--'
    ###########################
    # Get condensed output CRN
    condensed = condense_resting_states(pep.enumerator)
    reactions = condensed['reactions']

    for r in sorted(reactions):
      print map(str, map(lambda x: x.complexes, r.reactants)), '->', 
      print map(str, map(lambda x: x.complexes, r.products))
      print r.kernel_string()
      for rs in r.reactants :
        if len(rs.complexes) == 1 :
          print rs.complexes[0],
        else :
          print 'rs' + str(rs),
      print '->',
      for rs in r.products:
        if len(rs.complexes) == 1 :
          print rs.complexes[0],
        else :
          print 'rs' + str(rs),
      print
 
    ## INCORRECT (misses resting state)
    for r in condensed['resting_states']:
      print 'r', r

    ## CORRECT (frozensets)
    for m in condensed['resting_state_map']:
      print 'm', m

    ## CORRECT (all species)
    for t in condensed['resting_state_targets']:
      print 't', t

    ## CORRECT (all resting states)
    for s in condensed['complexes_to_resting_states']:
      print 's', s