예제 #1
0
def sp_comm_asyn_fluidc_view(model,
                             k,
                             max_iter=100,
                             random_state=None,
                             layout_name='fcose'):
    """
    Render a visualization of the interactions between the species in a model.
    The species nodes are grouped by the communities detected by the
    asynchronous label propagation algorithm implemented in Networkx.

    Parameters
    ----------
    model: pysb.model or str
        Model to visualize. It can be a pysb model, or the file path to an
        an SBML or BNGL model
    k: int
        The number of communities to be found
    max_iter: int
        The number of maximum iterations allowed
    random_state: int
        Random state seed use by the community detection algorithm
    layout_name: str
        Layout to use

    Returns
    -------

    """
    from pyvipr.pysb_viz.static_viz import PysbStaticViz
    pviz = PysbStaticViz(model, generate_eqs=False)
    data = pviz.sp_comm_asyn_fluidc_view(k, max_iter, random_state)
    return Viz(data=data, type_of_viz='', layout_name=layout_name)
예제 #2
0
def highlight_nodes_view(model,
                         species=None,
                         reactions=None,
                         layout_name='fcose'):
    from pyvipr.pysb_viz.static_viz import PysbStaticViz
    pviz = PysbStaticViz(model)
    data = pviz.highlight_nodes_view(species, reactions)
    return Viz(data=data, type_of_viz='', layout_name=layout_name)
예제 #3
0
    def dynamic_sp_comm_view(self, type_viz='consumption', random_state=None):
        """
        Same as :py:meth:`dynamic_view` but the species nodes are grouped
        by the communities they belong to. Communities are obtained using the 
        Louvain algorithm.

        Parameters
        ----------
        type_viz: str
            Type of visualization. It can be `consumption` to see how species are being consumed
            or `production` to see how the species are being produced.
        random_state: int
            Seed used by the random generator in community detection

        Returns
        -------
        dict
            A Dictionary Object with all nodes and edges information that
            can be converted into Cytoscape.js JSON to be visualized
        """
        self.type_viz = type_viz
        self.sp_graph = PysbStaticViz(self.model).species_graph()
        hf.add_louvain_communities(self.sp_graph,
                                   all_levels=False,
                                   random_state=random_state)
        self.sp_graph.graph['nsims'] = self.nsims
        self.sp_graph.graph['tspan'] = self.tspan.tolist()
        self._add_edge_node_dynamics()
        data = from_networkx(self.sp_graph)
        return data
예제 #4
0
    def dynamic_sp_view(self, type_viz='consumption'):
        """
        Generates a dictionary with the model dynamics data that can be converted in the Cytoscape.js JSON format

        Parameters
        ----------
        type_viz : str
            Type of the dynamic visualization, it can be 'consumption' or 'production'

        Examples
        --------
        >>> from pysb.examples.earm_1_0 import model
        >>> from pysb.simulator import ScipyOdeSimulator
        >>> import pyvipr.pysb_viz.dynamic_viz as viz
        >>> import numpy as np
        >>> tspan = np.linspace(0, 20000)
        >>> sim = ScipyOdeSimulator(model, tspan).run()
        >>> dyn_viz = viz.PysbDynamicViz(sim)
        >>> data = dyn_viz.dynamic_sp_view()

        Returns
        -------
        dict
            A Dictionary Object with all nodes and edges information that
            can be converted into Cytoscape.js JSON to be visualized
        """
        self.type_viz = type_viz
        self.sp_graph = PysbStaticViz(self.model).species_graph()
        self.sp_graph.graph['nsims'] = self.nsims
        self.sp_graph.graph['tspan'] = self.tspan.tolist()
        self._add_edge_node_dynamics()
        data = from_networkx(self.sp_graph)
        return data
예제 #5
0
    def dynamic_sp_comp_view(self, type_viz='consumption'):
        """
        Same as :py:meth:`dynamic_view` but the species nodes are grouped
        by the compartments they belong to

        """
        self.type_viz = type_viz
        self.sp_graph = PysbStaticViz(self.model).compartments_data_graph()
        self.sp_graph.graph['nsims'] = self.nsims
        self.sp_graph.graph['tspan'] = self.tspan.tolist()
        self._add_edge_node_dynamics()
        data = from_networkx(self.sp_graph)
        return data
예제 #6
0
def atom_rules_view(model,
                    visualize_args,
                    rule_name=None,
                    verbose=False,
                    cleanup=True,
                    layout_name='fcose'):
    """
    Uses the BioNetGen atom-rules to visualize large rule-base models. For more
    information regarding atom-rules and its parameters please visit:
    Sekar et al (2017), Automated visualization of rule-based models
    https://doi.org/10.1371/journal.pcbi.1005857

    The visualize_args parameter contains all the arguments that will be passed to the
    BioNetGen visualize function. It is a dictionary and supports the following
    key, value pairs.

      - `type`

        * `conventional` => Conventional rule visualization
        * `compact` => Compact rule visualization (using graph operation nodes)
        * `regulatory` => Rule-derived regulatory graph
        * `opts` => Options template for regulatory graph
        * `contactmap` => Contact map
        * `reaction_network` => Reaction network
      -  `suffix`

        * str => add suffix string to output filename
      - `each`

        * 1 => Show all rules in separate GML files
        * 0 => Show all rules  the same GML file.
      - `opts`

        * file path => import options from file
      - `background`

        * 1 => Enable background
        * 0 => Disable background
      - `groups`

        * 1 => Enable groups
        * 0 => Disable groups
      - `collapse`

        * 1 => Enable collapsing of groups
        * 0 => Disable collapsing of groups
      - `ruleNames`

        * 1 => Enable display of rule names
        * 0 => Disable display of rule names
      - `doNotUseContextWhenGrouping`

        * 1 => Use permissive edge signature
        * 0 => Use strict edge signature
      - `doNotCollapseEdges`:

        * 1 => When collapsing nodes, retain duplicate edges
        * 0 => When collapsing nodes, remove duplicate edges

    Parameters
    ----------
    model: pysb.model or bngl file
        Model to visualize
    visualize_args: dict
        Contains all the arguments that will be passed to the BioNetGen visualize function.
        The following key, value pairs are available

    rule_name : str
       Name of the rule to visualize, when `each` is set to 1 in visualize_args.
    cleanup : bool, optional
        If True (default), delete the temporary files after the simulation is
        finished. If False, leave them in place. Useful for debugging.
    verbose : bool or int, optional (default: False)
        Sets the verbosity level of the logger. See the logging levels and
        constants from Python's logging module for interpretation of integer
        values. False is equal to the PySB default level (currently WARNING),
        True is equal to DEBUG.

    Returns
    -------

    """
    from pyvipr.pysb_viz.static_viz import PysbStaticViz
    from pysb.core import Model
    from pysb.importers.bngl import model_from_bngl
    if isinstance(model, Model):
        pviz = PysbStaticViz(model, generate_eqs=False)
    elif isinstance(model, str):
        pysb_model = model_from_bngl(model)
        pviz = PysbStaticViz(pysb_model, generate_eqs=False)

    else:
        raise TypeError('Only PySB and bngl models are supported')
    data = pviz.atom_rules_view(visualize_args, rule_name, verbose, cleanup)
    return Viz(data=data, type_of_viz='', layout_name=layout_name)
예제 #7
0
def atom_rules_view(model, visualize_args, rule_name=None, verbose=False, cleanup=True, layout_name='fcose'):
    from pyvipr.pysb_viz.static_viz import PysbStaticViz
    pviz = PysbStaticViz(model, generate_eqs=False)
    data = pviz.atom_rules_view(visualize_args, rule_name, verbose, cleanup)
    return Viz(data=data, type_of_viz='', layout_name=layout_name)
예제 #8
0
def data_to_json(value, widget):
    """
    Generate a json file from the data passed to the widget
    Parameters
    ----------
    value: pysb.Model, pysb.SimulationResult, str
        Value passed to the widget that is going to be visualized
    widget: Widget
        Widget instance

    Returns
    -------

    """

    if is_pysb_model(value):
        from pyvipr.pysb_viz.static_viz import PysbStaticViz

        viz = PysbStaticViz(value)
        jsondata = static_data(viz, widget)
        return jsondata

    elif is_pysb_sim(value):
        from pyvipr.pysb_viz.dynamic_viz import PysbDynamicViz

        viz = PysbDynamicViz(value, widget.sim_idx, widget.cmap)
        jsondata = dynamic_data(viz, widget)
        return jsondata

    elif isinstance(value, str):
        file_extension = os.path.splitext(value)[1]
        if file_extension in ['.bngl', '.sbml', '.xml'] and widget.type_of_viz != 'sbgn_xml'\
                or value.startswith('BIOMD'):
            try:
                from pysb.importers.sbml import model_from_sbml, model_from_biomodels
                from pysb.importers.bngl import model_from_bngl
            except ImportError:
                raise Exception(
                    'PySB must be installed to visualize models from files')
            from pyvipr.pysb_viz.static_viz import PysbStaticViz

            if file_extension == '.bngl':
                model = model_from_bngl(value)
            elif file_extension in ['.sbml', '.xml']:
                model = model_from_sbml(value)
            elif value.startswith('BIOMD'):
                model = model_from_biomodels(value)
            viz = PysbStaticViz(model)
            jsondata = static_data(viz, widget)
            return jsondata
        elif file_extension == '.graphml' or widget.type_of_viz == 'sbgn_xml':
            with open(value, 'r') as file:
                data = file.read().replace('\n', '')
            return data
        elif file_extension == '.json':
            import json
            with open(value, 'r') as file:
                data = file.read().replace('\n', '')
            jsondata = json.loads(data)
            return jsondata
        elif file_extension == '.sif':
            with open(value, 'r') as file:
                data = file.read()
            data = data.rstrip('\n')
            return data
        # elif file_extension == '.ka':
        #     subprocess.run(['truml', '-k', value])
        #     bngl_model_path = re.sub('ka', 'bngl', value)
        #     model = model_from_bngl(bngl_model_path)
        #     os.remove(bngl_model_path)

        else:
            raise ValueError('Format not supported')

    elif is_tellurium_model(value):
        if widget.type_of_viz.startswith('dynamic'):
            from pyvipr.tellurium_viz.dynamic_viz import TelluriumDynamicViz
            viz = TelluriumDynamicViz(value, widget.cmap)
            jsondata = dynamic_data(viz, widget)
        else:
            from pyvipr.tellurium_viz.static_viz import TelluriumStaticViz
            viz = TelluriumStaticViz(value)
            jsondata = static_data(viz, widget)
        return jsondata

    elif isinstance(
            value,
        (nx.DiGraph, nx.Graph, nx.MultiDiGraph, nx.MultiGraph, dict)):
        from pyvipr.network_viz.network_viz import NetworkViz
        viz = NetworkViz(value)
        if widget.type_of_viz:
            jsondata = getattr(viz, widget.type_of_viz)()
        else:
            jsondata = value
        return jsondata

    elif is_ecell_model(value):
        try:
            from pysb.importers.sbml import model_from_sbml
        except ImportError:
            raise Exception(
                'PySB must be installed to visualize models from files')
        from pyvipr.pysb_viz.static_viz import PysbStaticViz
        import tempfile
        ecell4 = sys.modules['ecell4']
        f_sbml = tempfile.NamedTemporaryFile(suffix='.sbml')
        # In ecell4 species don't have initial conditions as attributes. Hence, the
        # initial conditions are passed as a dictionary to the save_sbml function.
        # If no initial conditions are passed ecell4 sets the initial condition of the
        # species to 0, and PySB throws an error when the initial condition of all the species
        # are zero. For visualization purposes we then set the initial conditions to 1.
        y0 = {sp.serial(): 1 for sp in value.list_species()}
        ecell4.util.ports.save_sbml(f_sbml.name, value, y0=y0)
        model = model_from_sbml(f_sbml.name)
        viz = PysbStaticViz(model)
        jsondata = static_data(viz, widget)
        return jsondata

    elif is_pysces_model(value):
        try:
            from pysb.importers.sbml import model_from_sbml
        except ImportError:
            raise Exception(
                'PySB must be installed to visualize models from files')
        from pyvipr.pysb_viz.static_viz import PysbStaticViz
        import tempfile
        # Note: Importing a pysces model to sbml doesn't work in python 3.7
        pysces = sys.modules['pysces']
        f_sbml = tempfile.NamedTemporaryFile(suffix='.xml')
        pysces.interface.writeMod2SBML(value, f_sbml.name)
        model = model_from_sbml(f_sbml.name)
        viz = PysbStaticViz(model)
        jsondata = static_data(viz, widget)
        return jsondata

    else:
        raise TypeError(
            'Only pysb Model, pysb SimulationResult, tellurium Model, '
            'PySCeS Model, and networkx graphs are supported')
예제 #9
0
def viz_model():
    viz = PysbStaticViz(model)
    return viz