def species_graph(self):

        graph = pygraphviz.AGraph(start=20, directed=True, rankdir="LR", labelloc='t', fontsize=50, label='EARM flux',
                                  bgcolor='gray')
        for idx, cp in enumerate(self.model.species):
            species_node = 's%d' % idx

            graph.add_node(species_node,
                           label=parse_name(self.model.species[idx]),
                           shape="Mrecord",
                           fillcolor="#ccffcc", style="filled", color="transparent",
                           fontsize="35",
                           margin="0.06,0")

        for reaction in self.model.reactions_bidirectional:
            reactants = set(reaction['reactants'])
            products = set(reaction['products'])
            # attr_reversible = {'arrowsize': 2, 'penwidth': 5}
            attr_reversible = {'dir': 'both', 'arrowtail': 'empty', 'arrowsize': 1, 'penwidth': 5} if reaction[
                'reversible'] else {'arrowsize': 1, 'penwidth': 5}
            for s in reactants:
                for p in products:
                    r_link(graph, s, p, **attr_reversible)
        self.sp_graph = graph
        return self.sp_graph
Exemple #2
0
    def visualization2(self, sp_to_vis=None):
        if sp_to_vis:
            species_ready = list(set(sp_to_vis).intersection(self.all_sp_signatures.keys()))
        else:
            raise Exception('list of driver species must be defined')

        if not species_ready:
            raise Exception('None of the input species is a driver')

        for sp in species_ready:
            # Setting up figure
            plt.figure()
            plt.subplot(313)

            mon_val = OrderedDict()
            signature = self.all_sp_signatures[sp]
            for idx, mon in enumerate(list(set(signature))):
                if mon[0] == 'C':
                    mon_val[self.all_comb[sp][mon] + (-1,)] = idx
                else:
                    mon_val[self.all_comb[sp][mon]] = idx

            mon_rep = [0] * len(signature)
            for i, m in enumerate(signature):
                if m[0] == 'C':
                    mon_rep[i] = mon_val[self.all_comb[sp][m] + (-1,)]
                else:
                    mon_rep[i] = mon_val[self.all_comb[sp][m]]
            # mon_rep = [mon_val[self.all_comb[sp][m]] for m in signature]

            y_pos = numpy.arange(len(mon_val.keys()))
            plt.scatter(self.tspan[1:], mon_rep)
            plt.yticks(y_pos, mon_val.keys())
            plt.ylabel('Monomials', fontsize=16)
            plt.xlabel('Time(s)', fontsize=16)
            plt.xlim(0, self.tspan[-1])
            plt.ylim(0, max(y_pos))

            plt.subplot(312)

            for name in self.model.odes[sp].as_coefficients_dict():
                mon = name
                mon = mon.subs(self.param_values)
                var_to_study = [atom for atom in mon.atoms(sympy.Symbol)]
                arg_f1 = [numpy.maximum(self.mach_eps, self.y[str(va)][1:]) for va in var_to_study]
                f1 = sympy.lambdify(var_to_study, mon)
                mon_values = f1(*arg_f1)
                mon_name = str(name).partition('__')[2]
                plt.plot(self.tspan[1:], mon_values, label=mon_name)
            plt.ylabel('Rate(m/sec)', fontsize=16)
            plt.legend(bbox_to_anchor=(-0.1, 0.85), loc='upper right', ncol=1)

            plt.subplot(311)
            plt.plot(self.tspan[1:], self.y['__s%d' % sp][1:], label=parse_name(self.model.species[sp]))
            plt.ylabel('Molecules', fontsize=16)
            plt.legend(bbox_to_anchor=(-0.15, 0.85), loc='upper right', ncol=1)
            plt.suptitle('Tropicalization' + ' ' + str(self.model.species[sp]))

            # plt.show()
            plt.savefig('s%d' % sp + '.png', bbox_inches='tight', dpi=400)
    def species_graph(self):

        graph = pygraphviz.AGraph(directed=True, rankdir="LR", labelloc='t', fontsize=50, label='EARM flux')
        for idx, cp in enumerate(self.model.species):
            species_node = 's%d' % idx
            label = re.sub(r'% ', r'%\\l', str(cp))
            label += '\\l'

            rtn_product = False
            rtn = False
            prdt = False

            all_reactants = []
            for rctn in self.model.reactions:
                if rctn['reverse'][0] is False:
                    all_reactants.append(rctn['reactants'])
            all_reactants_flat = list(set([item for sublist in all_reactants for item in sublist]))

            all_products = []
            for rctn in self.model.reactions:
                if rctn['reverse'][0] is False:
                    all_products.append(rctn['products'])
            all_products_flat = list(set([item for sublist in all_products for item in sublist]))

            if idx in all_reactants_flat:
                rtn = True
            if idx in all_products_flat:
                prdt = True

            if rtn and prdt:
                rtn_product = True

            if rtn_product:
                color = "Cyan"
            elif rtn:
                color = "#FF00F6"
            elif prdt:
                color = "#90EE90"
            else:
                pass

            graph.add_node(species_node,
                           label=parse_name(self.model.species[idx]),
                           shape="Mrecord",
                           fillcolor=color, style="filled", color="transparent",
                           fontsize="35",
                           margin="0.06,0")

        for reaction in self.model.reactions:
            reactants = set(reaction['reactants'])
            products = set(reaction['products'])
            attr_reversible = {'arrowsize': 2, 'penwidth': 5}
            for s in reactants:
                for p in products:
                    r_link(graph, s, p, **attr_reversible)
        self.sp_graph = graph
        return self.sp_graph
Exemple #4
0
 def test_exiled(self):
     """
     Tests that
     :return:
     """
     input_str = 'You exiled playername'
     expected = ['playername']
     result = parse_name(input_str)
     self.assertEqual(result, expected)
Exemple #5
0
    def test_assist(self):
        """

        :return:
        """
        input_str = 'You assisted in exiling playername'
        expected = ['playername']
        result = parse_name(input_str)
        self.assertEqual(result, expected)
Exemple #6
0
    def test_disrupted(self):
        """

        :return:
        """
        input_str = 'You disrupted playername'
        expected = ['playername']
        result = parse_name(input_str)
        self.assertEqual(result, expected)
Exemple #7
0
 async def lookup_enemy(self, name):
     names = parse_name(name)
     users = get_users(names)
     try:
         for user in users['data']:
             clip = create_clip(user['id'])
             await self.get_channel(config.DISCORD_CHANNEL
                                    ).send(clip['data']['edit_url'])
     except Exception as e:
         print('Error: ', e)
    def render_reactions(self):
        pysb.bng.generate_equations(self.model)

        graph = OrderedGraph()
        ic_species = [cp for cp, parameter in self.model.initial_conditions]
        for i, cp in enumerate(self.model.species):
            species_node = 's%d' % i
            color = "#ccffcc"
            # color species with an initial condition differently
            if len([s for s in ic_species if s.is_equivalent_to(cp)]):
                color = "#aaffff"
            graph.add_node(species_node, attr_dict=
            {'label': parse_name(self.model.species[i]),
             'font-size': "35",
             'shape': "roundrectangle",
             'background-color': color})
        for i, reaction in enumerate(self.model.reactions_bidirectional):
            reaction_node = 'r%d' % i
            graph.add_node(reaction_node, attr_dict=
            {'label': reaction_node,
             'font-size': "35",
             'shape': "roundrectangle",
             'background-color': "#D3D3D3"})
            reactants = set(reaction['reactants'])
            products = set(reaction['products'])
            modifiers = reactants & products
            reactants = reactants - modifiers
            products = products - modifiers
            attr_reversible = {'source-arrow-shape': 'DIAMOND', 'target-arrow-shape': 'ARROW',
                               'source-arrow-fill': 'hollow', 'width': 3} if reaction['reversible'] else {
                'source-arrow-shape': 'NONE', 'width': 6, 'target-arrow-shape': 'ARROW'}
            for s in reactants:
                r_link_reactions(graph, s, i, **attr_reversible)
            for s in products:
                r_link_reactions(graph, s, i, _flip=True, **attr_reversible)
            for s in modifiers:
                r_link_reactions(graph, s, i, arrowhead="odiamond")

        self.graph = graph
        return self.graph
    def render_species(self):
        pysb.bng.generate_equations(self.model)
        graph = OrderedGraph()
        for idx, cp in enumerate(self.model.species):
            species_node = 's%d' % idx

            graph.add_node(species_node,
                           {'label': parse_name(self.model.species[idx]),
                            'font-size': "35",
                            'shape': "roundrectangle",
                            'background-color': "#ccffcc"})

        for reaction in self.model.reactions_bidirectional:
            reactants = set(reaction['reactants'])
            products = set(reaction['products'])
            attr_reversible = {'source-arrow-shape': 'DIAMOND', 'target-arrow-shape': 'ARROW',
                               'source-arrow-fill': 'hollow', 'width': 3} if reaction['reversible'] else {
                'source-arrow-shape': 'NONE', 'width': 6, 'target-arrow-shape': 'ARROW'}
            for s in reactants:
                for p in products:
                    r_link_species(graph, s, p, **attr_reversible)
        self.graph = graph
        return self.graph
    def species_graph(self):

        graph = OrderedGraph(ankdir="LR")
        for idx, cp in enumerate(self.model.species):
            species_node = 's%d' % idx

            graph.add_node(species_node,
                           label=parse_name(self.model.species[idx]),
                           shape="Mrecord",
                           fillcolor="#ccffcc", style="filled", color="transparent",
                           fontsize="35",
                           margin="0.06,0", start="1990-01-01", end="1993-01-01")

        for reaction in self.model.reactions_bidirectional:
            reactants = set(reaction['reactants'])
            products = set(reaction['products'])
            attr_reversible = {'dir': 'both', 'arrowtail': 'empty', 'arrowsize': 2, 'penwidth': 5} if reaction[
                'reversible'] else {'arrowsize': 2, 'penwidth': 5}
            for s in reactants:
                for p in products:
                    r_link(graph, s, p, **attr_reversible)
        self.sp_graph = graph
        print(graph.edges(data=True))
        return self.sp_graph
Exemple #11
0
    def visualization(self, driver_species=None):
        # TODO increase figure size when there are too many monomials
        tropical_system = self.tropical_eqs
        if driver_species:
            species_ready = list(set(driver_species).intersection(self.tro_species.keys()))

        else:
            raise Exception('list of driver species must be defined')

        if not species_ready:
            raise Exception('None of the input species is a driver')

        colors = sns.color_palette("Set2", max([len(ode.as_coeff_add()[1]) for ode in self.model.odes]))

        sep = len(self.tspan) / 1

        for sp in species_ready:
            si_flux = 0
            plt.figure()
            plt.subplot(313)
            monomials = []
            monomials_inf = self.mon_names[sp]
            for idx, name in enumerate(self.tro_species[sp].keys()):
                m_value = self.tro_species[sp][name]
                x_concentration = numpy.nonzero(m_value)[0]
                monomials.append(name)
                si_flux += 1
                x_points = [self.tspan[x] for x in x_concentration]
                prueba_y = numpy.repeat(2 * si_flux, len(x_concentration))
                if monomials_inf[sympy.sympify(name)] > 0:
                    plt.scatter(
                        x_points[::int(math.ceil(len(self.tspan) / sep))],
                        prueba_y[::int(math.ceil(len(self.tspan) / sep))],
                        color=colors[idx], marker=r'$\uparrow$',
                        s=numpy.array([200] * len(x_concentration))[
                          ::int(math.ceil(len(self.tspan) / sep))])
                if monomials_inf[sympy.sympify(name)] < 0:
                    plt.scatter(
                        x_points[::int(math.ceil(len(self.tspan) / sep))],
                        prueba_y[::int(math.ceil(len(self.tspan) / sep))],
                        color=colors[idx], marker=r'$\downarrow$',
                        s=numpy.array([200] * len(x_concentration))[
                          ::int(math.ceil(len(self.tspan) / sep))])

            y_pos = numpy.arange(2, 2 * si_flux + 4, 2)
            plt.yticks(y_pos, monomials, fontsize=12)
            plt.ylabel('Monomials', fontsize=16)
            plt.xlabel('Time (s)', fontsize=16)
            plt.xlim(0, self.tspan[-1])
            plt.ylim(0, max(y_pos))

            plt.subplot(312)
            mons = tropical_system[sp].as_coefficients_dict().items()
            mons_matrix = numpy.zeros((len(mons), len(self.tspan[1:])), dtype=float)

            for q, name in enumerate(self.tro_species[sp].keys()):
                j = sympy.sympify(name)
                for par in self.param_values:
                    j = j.subs(par, self.param_values[par])
                var_to_study = [atom for atom in j.atoms(sympy.Symbol)]  # Variables of monomial

                arg_f1 = [numpy.maximum(self.mach_eps, self.y[str(va)][1:]) for va in var_to_study]
                f1 = sympy.lambdify(var_to_study, j,
                                    modules=dict(Heaviside=self._heaviside_num, log=numpy.log, Abs=numpy.abs))
                mon_values = f1(*arg_f1)
                mon_name = name.partition('__')[2]
                plt.plot(self.tspan[1:], mon_values, label=mon_name, color=colors[q])
                mons_matrix[q] = mon_values
            plt.ylabel('Rate(m/sec)', fontsize=16)
            plt.legend(bbox_to_anchor=(-0.1, 0.85), loc='upper right', ncol=1)

            plt.subplot(311)
            plt.plot(self.tspan[1:], self.y['__s%d' % sp][1:], label=parse_name(self.model.species[sp]))
            plt.ylabel('Molecules', fontsize=16)
            plt.legend(bbox_to_anchor=(-0.15, 0.85), loc='upper right', ncol=1)
            plt.suptitle('Tropicalization' + ' ' + str(self.model.species[sp]))

            plt.savefig('s%d' % sp + '.png', bbox_inches='tight', dpi=400)

        # plt.ylim(0, len(monomials)+1)
        return