Exemplo n.º 1
0
 def __display_pathways_information(predicted_pathways, host,
                                    original_model):
     if util.in_ipnb():
         title = "Production envelopes for %s (%s)" % (host.name,
                                                       original_model.id)
         predicted_pathways.plot_production_envelopes(
             original_model, title=title, objective=original_model.biomass)
Exemplo n.º 2
0
def stop_loader(identifier):
    if util.in_ipnb():
        display(Javascript("""
        jQuery("#%s").remove();
        """ % identifier))
    else:
        logger.debug("loading only works on Jupyter notebooks")
Exemplo n.º 3
0
 def _oflline(self):
     if self._offline_mode:
         return
     if self.get_option('mode') == 'offline' and in_ipnb():
         from plotly.offline import init_notebook_mode
         init_notebook_mode()
     self._offline_mode = True
Exemplo n.º 4
0
 def _oflline(self):
     if self._offline_mode:
         return
     if self.get_option('mode') == 'offline' and in_ipnb():
         from plotly.offline import init_notebook_mode
         init_notebook_mode()
     self._offline_mode = True
Exemplo n.º 5
0
 def _plot_grid(self):
     if util.in_ipnb():
         if config.use_bokeh:
             self._plot_bokeh_grid()
         elif config.use_matplotlib:
             self._plot_matplotlib_grid()
     else:
         self._plot_cli_grid()
Exemplo n.º 6
0
def loading():
    if util.in_ipnb():
        identifier = str(uuid4())
        display(HTML("""
        <img class="loading" id="%s" style="margin:auto; text-align:center;" src="data:image/gif;base64,%s"/>
        """ % (identifier, LOADING_IMAGE)))
        return identifier
    else:
        logger.debug("loading only works on Jupyter notebooks")
Exemplo n.º 7
0
    def stats(self):
        stats_data = None
        if in_ipnb():
            if config.use_bokeh:
                stats_data = stats.BokehStatsData(self)
        else:
            stats_data = stats.CLIStatsData(self)

        stats_data.display()
Exemplo n.º 8
0
    def stats(self):
        stats_data = None
        if in_ipnb():
            if config.use_bokeh:
                stats_data = stats.BokehStatsData(self)
        else:
            stats_data = stats.CLIStatsData(self)

        stats_data.display()
Exemplo n.º 9
0
    def _display_on_map_static(self, index, map_name, palette="RdYlBu", **kwargs):
        try:
            import escher
            if os.path.exists(map_name):
                map_json = map_name
                map_name = None
            else:
                map_json = None

            values = self.normalized_gaps

            values = values[~numpy.isnan(values)]
            values = values[~numpy.isinf(values)]

            data = self.solutions.iloc[index]
            # Find values above decimal precision
            data = data[numpy.abs(data.normalized_gaps.astype(float)) > non_zero_flux_threshold]
            # Remove NaN rows
            data = data[~numpy.isnan(data.normalized_gaps.astype(float))]

            reaction_data = dict(data.normalized_gaps)
            for rid, gap in six.iteritems(reaction_data):
                if numpy.isposinf(gap):
                    gap = numpy.max(values)
                elif numpy.isneginf(gap):
                    gap = numpy.min(values)

                reaction_data[rid] = gap

            scale = self.plot_scale(palette)
            reaction_data['min'] = min(numpy.abs(values) * -1)
            reaction_data['max'] = max(numpy.abs(values))

            reaction_scale = [dict(type='min', color=scale[0][1], size=24),
                              dict(type='value', value=scale[0][0], color=scale[0][1], size=21),
                              dict(type='value', value=scale[1][0], color=scale[1][1], size=16),
                              dict(type='value', value=scale[2][0], color=scale[2][1], size=8),
                              dict(type='value', value=scale[3][0], color=scale[3][1], size=16),
                              dict(type='value', value=scale[4][0], color=scale[4][1], size=21),
                              dict(type='max', color=scale[4][1], size=24)]

            builder = escher.Builder(map_name=map_name, map_json=map_json, reaction_data=reaction_data,
                                     reaction_scale=reaction_scale)

            if in_ipnb():
                from IPython.display import display
                display(builder.display_in_notebook())
            else:
                builder.display_in_browser()

        except ImportError:
            print("Escher must be installed in order to visualize maps")
Exemplo n.º 10
0
    def _display_on_map_static(self, index, map_name, palette="RdYlBu", **kwargs):
        try:
            import escher
            if os.path.exists(map_name):
                map_json = map_name
                map_name = None
            else:
                map_json = None

            values = self.solutions['normalized_gaps'].values
            values = values[numpy.isfinite(values)]

            data = self.nth_panel(index)
            # Find values above decimal precision and not NaN
            data = data.loc[
                ~numpy.isnan(data['normalized_gaps']) & (
                    data['normalized_gaps'].abs() > non_zero_flux_threshold)
            ]
            data.index = data['reaction']

            reaction_data = data['normalized_gaps'].copy()
            reaction_data[numpy.isposinf(reaction_data)] = reaction_data.max()
            reaction_data[numpy.isneginf(reaction_data)] = reaction_data.min()


            reaction_data = dict(reaction_data.iteritems())
            reaction_data['max'] = numpy.abs(values).max()
            reaction_data['min'] = -reaction_data['max']

            scale = self.plot_scale(palette)

            reaction_scale = [dict(type='min', color=scale[0][1], size=24),
                              dict(type='value', value=scale[0][0], color=scale[0][1], size=21),
                              dict(type='value', value=scale[1][0], color=scale[1][1], size=16),
                              dict(type='value', value=scale[2][0], color=scale[2][1], size=8),
                              dict(type='value', value=scale[3][0], color=scale[3][1], size=16),
                              dict(type='value', value=scale[4][0], color=scale[4][1], size=21),
                              dict(type='max', color=scale[4][1], size=24)]

            builder = escher.Builder(map_name=map_name, map_json=map_json, reaction_data=reaction_data,
                                     reaction_scale=reaction_scale)

            if in_ipnb():
                from IPython.display import display
                display(builder.display_in_notebook())
            else:
                builder.display_in_browser()

        except ImportError:
            print("Escher must be installed in order to visualize maps")
Exemplo n.º 11
0
def plot_production_envelope(envelope, objective, key, grid=None, width=None, height=None, title=None,
                             points=None, points_colors=None, axis_font_size=None):
    if util.in_ipnb():
        if config.use_bokeh:
            plot_production_envelope_ipython_bokeh(envelope, objective, key, grid=grid, width=width, height=height,
                                                   title=title, points=points, points_colors=points_colors,
                                                   axis_font_size=axis_font_size)
        elif config.use_matplotlib:
            plot_production_envelope_ipython_matplotlib(envelope, objective, key, grid=grid, width=width, height=height,
                                                        title=title, points=points, points_colors=points_colors,
                                                        axis_font_size=axis_font_size)
    else:
        plot_production_envelope_cli(envelope, objective, key, width=width, height=height, title=title, points=points,
                                     points_colors=points_colors, axis_font_size=axis_font_size)
Exemplo n.º 12
0
    def _display_on_map_static(self, index, map_name, palette="RdYlBu", **kwargs):
        try:
            import escher
            if os.path.exists(map_name):
                map_json = map_name
                map_name = None
            else:
                map_json = None

            values = self.solutions['normalized_gaps'].values
            values = values[numpy.isfinite(values)]

            data = self.nth_panel(index)
            # Find values above decimal precision and not NaN
            data = data.loc[
                ~numpy.isnan(data['normalized_gaps']) &
                (data['normalized_gaps'].abs() > non_zero_flux_threshold)]
            data.index = data['reaction']

            reaction_data = data['normalized_gaps'].copy()
            reaction_data[numpy.isposinf(reaction_data)] = reaction_data.max()
            reaction_data[numpy.isneginf(reaction_data)] = reaction_data.min()


            reaction_data = dict(reaction_data.iteritems())
            reaction_data['max'] = numpy.abs(values).max()
            reaction_data['min'] = -reaction_data['max']

            scale = self.plot_scale(palette)

            reaction_scale = [dict(type='min', color=scale[0][1], size=24),
                              dict(type='value', value=scale[0][0], color=scale[0][1], size=21),
                              dict(type='value', value=scale[1][0], color=scale[1][1], size=16),
                              dict(type='value', value=scale[2][0], color=scale[2][1], size=8),
                              dict(type='value', value=scale[3][0], color=scale[3][1], size=16),
                              dict(type='value', value=scale[4][0], color=scale[4][1], size=21),
                              dict(type='max', color=scale[4][1], size=24)]

            builder = escher.Builder(map_name=map_name, map_json=map_json, reaction_data=reaction_data,
                                     reaction_scale=reaction_scale)

            if in_ipnb():
                from IPython.display import display
                display(builder.display_in_notebook())
            else:
                builder.display_in_browser()

        except ImportError:
            print("Escher must be installed in order to visualize maps")
Exemplo n.º 13
0
    def _set_observer(self):
        self.observers = []

        if in_ipnb() and self.plot:
            if config.use_bokeh:
                if len(self.objective_function) > 1:
                    self.observers.append(plotters.IPythonBokehParetoPlotter(self.objective_function))
                else:
                    self.observers.append(plotters.IPythonBokehFitnessPlotter())

        else:
            if config.use_bokeh:
                pass
            else:
                pass
        if self.progress:
            self.observers.append(observers.ProgressObserver())
Exemplo n.º 14
0
    def _set_observer(self):
        self.observers = []

        if in_ipnb() and self.plot:
            if config.use_bokeh:
                if len(self.objective_function) > 1:
                    self.observers.append(plotters.IPythonBokehParetoPlotter(self.objective_function))
                else:
                    self.observers.append(plotters.IPythonBokehFitnessPlotter())

        else:
            if config.use_bokeh:
                pass
            else:
                pass
        if self.progress:
            self.observers.append(observers.ProgressObserver())
Exemplo n.º 15
0
    def _set_observers(self, number_of_islands):
        observers = []

        plotting_observer = None
        if util.in_ipnb():
            color_map = util.generate_colors(number_of_islands)
            progress_observer = IPythonNotebookMultiprocessProgressObserver(number_of_islands=number_of_islands)
            if config.use_bokeh:
                plotting_observer = IPythonNotebookBokehMultiprocessPlotObserver(number_of_islands=number_of_islands,
                                                                                 color_map=color_map)
        else:
            progress_observer = CliMultiprocessProgressObserver(number_of_islands=number_of_islands)

        if progress_observer is not None:
            observers.append(progress_observer)
        if plotting_observer is not None:
            observers.append(plotting_observer)

        return observers
Exemplo n.º 16
0
    def _set_observers(self, number_of_islands):
        observers = []

        plotting_observer = None
        if util.in_ipnb():
            color_map = util.generate_colors(number_of_islands)
            progress_observer = IPythonNotebookMultiprocessProgressObserver(number_of_islands=number_of_islands)
            if config.use_bokeh:
                plotting_observer = IPythonNotebookBokehMultiprocessPlotObserver(number_of_islands=number_of_islands,
                                                                                 color_map=color_map)
        else:
            progress_observer = CliMultiprocessProgressObserver(number_of_islands=number_of_islands)

        if progress_observer is not None:
            observers.append(progress_observer)
        if plotting_observer is not None:
            observers.append(plotting_observer)

        return observers
Exemplo n.º 17
0
    def display_on_map(self, map_name=None, palette="YlGnBu"):
        try:
            import escher
            if os.path.exists(map_name):
                map_json = map_name
                map_name = None
            else:
                map_json = None

            active_fluxes = {rid: flux for rid, flux in six.iteritems(self.fluxes) if abs(flux) > 10 ** -ndecimals}

            values = [abs(v) for v in active_fluxes.values()]
            values += [-v for v in values]

            scale = self.plot_scale(values, palette)

            reaction_scale = [dict(type='min', color=scale[0][1], size=24),
                              dict(type='value', value=scale[0][0], color=scale[0][1], size=21),
                              dict(type='value', value=scale[1][0], color=scale[1][1], size=16),
                              dict(type='value', value=scale[2][0], color=scale[2][1], size=8),
                              dict(type='value', value=scale[3][0], color=scale[3][1], size=16),
                              dict(type='value', value=scale[4][0], color=scale[4][1], size=21),
                              dict(type='max', color=scale[4][1], size=24)]

            active_fluxes = {rid: round(flux, ndecimals) for rid, flux in six.iteritems(self.fluxes)
                             if abs(flux) > 10 ** -ndecimals}

            active_fluxes['min'] = min(values)
            active_fluxes['max'] = max(values)

            builder = escher.Builder(map_name=map_name, map_json=map_json, reaction_data=active_fluxes,
                                     reaction_scale=reaction_scale)

            if in_ipnb():
                from IPython.display import display
                display(builder.display_in_notebook())
            else:
                builder.display_in_browser()

        except ImportError:
            print("Escher must be installed in order to visualize maps")
Exemplo n.º 18
0
    def display_on_map(self, map_name=None, palette="YlGnBu"):
        try:
            import escher
            if os.path.exists(map_name):
                map_json = map_name
                map_name = None
            else:
                map_json = None

            active_fluxes = {rid: flux for rid, flux in six.iteritems(self.fluxes) if abs(flux) > 10 ** -ndecimals}

            values = [abs(v) for v in active_fluxes.values()]
            values += [-v for v in values]

            scale = self.plot_scale(values, palette)

            reaction_scale = [dict(type='min', color=scale[0][1], size=24),
                              dict(type='value', value=scale[0][0], color=scale[0][1], size=21),
                              dict(type='value', value=scale[1][0], color=scale[1][1], size=16),
                              dict(type='value', value=scale[2][0], color=scale[2][1], size=8),
                              dict(type='value', value=scale[3][0], color=scale[3][1], size=16),
                              dict(type='value', value=scale[4][0], color=scale[4][1], size=21),
                              dict(type='max', color=scale[4][1], size=24)]

            active_fluxes = {rid: round(flux, ndecimals) for rid, flux in six.iteritems(self.fluxes)
                             if abs(flux) > 10 ** -ndecimals}

            active_fluxes['min'] = min(values)
            active_fluxes['max'] = max(values)

            builder = escher.Builder(map_name=map_name, map_json=map_json, reaction_data=active_fluxes,
                                     reaction_scale=reaction_scale)

            if in_ipnb():
                from IPython.display import display
                display(builder.display_in_notebook())
            else:
                builder.display_in_browser()

        except ImportError:
            print("Escher must be installed in order to visualize maps")
Exemplo n.º 19
0
 def __display_pathways_information(predicted_pathways, host, original_model):
     if util.in_ipnb():
         title = "Production envelopes for %s (%s)" % (host.name, original_model.id)
         predicted_pathways.plot_production_envelopes(original_model, title=title, objective=original_model.biomass)
Exemplo n.º 20
0
 def __display_compound(inchi):
     if util.in_ipnb():
         Designer.__display_compound_html(inchi)
Exemplo n.º 21
0
 def __display_product_search_result(search_result):
     if util.in_ipnb():
         Designer.__display_product_search_results_html(search_result)
     else:
         Designer.__display_product_search_results_cli(search_result)
Exemplo n.º 22
0
def delta():
    if util.in_ipnb():
        return "&Delta;"
    else:
        return b'\xce\x94'.decode('utf-8')
Exemplo n.º 23
0
 def __display_compound(inchi):
     if util.in_ipnb():
         Designer.__display_compound_html(inchi)
Exemplo n.º 24
0
    for node in g.nodes():
        if isinstance(node, cameo.Reaction):
            labels[node] = node.name
        else:
            labels[node] = node.name
    nx.draw_networkx_labels(g, labels=labels, pos=layout, font_size=9)
    output = BytesIO()
    fig.savefig(output, format='svg')
    plt.close(fig)
    return output.getvalue()


try:
    import uuid

    if not in_ipnb():
        raise ImportError

    class IPythonProgressBar(object):
        def __init__(self, size=100, label="", color=None, fd=None):
            self.progress = 0
            self.size = size
            self.label = label
            self.color = color
            self.id = None

        def start(self, width='50%'):
            self.id = "progress-bar-%s" % str(uuid.uuid4())
            style = "width:%s;" % width
            if self.color is not None:
                style += "color: %s;" % self.color
Exemplo n.º 25
0
def bold(message):
    if util.in_ipnb():
        display(HTML("<strong>%s</strong>" % message))
    else:
        print("\033[1m" + message + "\033[0m")
Exemplo n.º 26
0
def downreg(coeff):
    if util.in_ipnb():
        return "&darr;%.3f" % coeff
    else:
        return str(b'\xe2\x86\x93') + "%.3f" % coeff
Exemplo n.º 27
0
def knockin():
    if util.in_ipnb():
        return "+"
    else:
        return "+"
Exemplo n.º 28
0
def upreg(coeff):
    if util.in_ipnb():
        return "&uarr;%.3f" % coeff
    else:
        return b'\xe2\x86\x91'.decode('utf-8') + "%.3f" % coeff
Exemplo n.º 29
0
 def __init__(self, **options):
     if in_ipnb():
         from bokeh.io import output_notebook
         output_notebook(hide_banner=True)
     super(BokehPlotter, self).__init__(**options)
Exemplo n.º 30
0
elif sys.version_info[0] == 3:
    if sys.version_info[1] <= 3:
        from importlib import find_loader as _find
    else:
        from importlib.util import find_spec as _find

    def find_module(name):
        return _find(name) is not None


_cameo_path = __path__[0]
_cameo_data_path = os.path.join(_cameo_path, 'data')

# fix - if matplotlib is installed it is not possible to import cameo without importing matplotlib on jupyter notebook.
if find_module("matplotlib") and in_ipnb():
    from IPython import get_ipython

    ipython = get_ipython()
    ipython.magic("matplotlib inline")

system_info = get_system_info()

from ._version import get_versions

__version__ = get_versions()['version']
del get_versions

from cameo.io import load_model

from cameo import models
Exemplo n.º 31
0
def display_pathway(pathway, i):
    notice("Pathway %i" % i)
    if in_ipnb():
        display(pathway.data_frame)
    else:
        print(pathway.data_frame)
Exemplo n.º 32
0
def delta():
    if util.in_ipnb():
        return "&Delta;"
    else:
        return b'\xce\x94'.decode('utf-8')
Exemplo n.º 33
0
def display_pathway(pathway, i):
    notice("Pathway %i" % i)
    if in_ipnb():
        display(pathway.data_frame)
    else:
        print(pathway.data_frame)
Exemplo n.º 34
0
 def _display(self):
     if in_ipnb():
         from IPython.display import display
         return display
Exemplo n.º 35
0
    for node in g.nodes():
        if isinstance(node, cameo.Reaction):
            labels[node] = node.name
        else:
            labels[node] = node.name
    nx.draw_networkx_labels(g, labels=labels, pos=layout, font_size=9)
    output = BytesIO()
    fig.savefig(output, format='svg')
    plt.close(fig)
    return output.getvalue()


try:
    import uuid

    if not in_ipnb():
        raise ImportError

    class IPythonProgressBar(object):
        def __init__(self, size=100, label="", color=None, fd=None):
            self.progress = 0
            self.size = size
            self.label = label
            self.color = color
            self.id = None

        def start(self, width='50%'):
            self.id = "progress-bar-%s" % str(uuid.uuid4())
            style = "width:%s;" % width
            if self.color is not None:
                style += "color: %s;" % self.color
Exemplo n.º 36
0
def downreg(coeff):
    if util.in_ipnb():
        return "&darr;%.3f" % coeff
    else:
        return b'\xe2\x86\x93'.decode('utf-8') + "%.3f" % coeff
Exemplo n.º 37
0
 def __display_product_search_result(search_result):
     if util.in_ipnb():
         Designer.__display_product_search_results_html(search_result)
     else:
         Designer.__display_product_search_results_cli(search_result)
Exemplo n.º 38
0
def upreg(coeff):
    if util.in_ipnb():
        return "&uarr;%.3f" % coeff
    else:
        return str(b'\xe2\x86\x91') + "%.3f" % coeff
Exemplo n.º 39
0
def downreg(coeff):
    if util.in_ipnb():
        return "&darr;%.3f" % coeff
    else:
        return b'\xe2\x86\x93'.decode('utf-8') + "%.3f" % coeff
Exemplo n.º 40
0
def notice(message):
    if util.in_ipnb():
        display(HTML("<span>%s</span>" % message))
    else:
        print(message)
Exemplo n.º 41
0
elif sys.version_info[0] == 3:
    if sys.version_info[1] <= 3:
        from importlib import find_loader as _find
    else:
        from importlib.util import find_spec as _find


    def find_module(name):
        return _find(name) is not None

_cameo_path = __path__[0]
_cameo_data_path = os.path.join(_cameo_path, 'data')

# fix - if matplotlib is installed it is not possible to import cameo without importing matplotlib on jupyter notebook.
if find_module("matplotlib") and in_ipnb():
    from IPython import get_ipython

    ipython = get_ipython()
    ipython.magic("matplotlib inline")

system_info = get_system_info()

from ._version import get_versions

__version__ = get_versions()['version']
del get_versions

from cameo.io import load_model

from cameo import models
Exemplo n.º 42
0
 def __init__(self, **options):
     if in_ipnb():
         from bokeh.io import output_notebook
         output_notebook(hide_banner=True)
     super(BokehPlotter, self).__init__(**options)
Exemplo n.º 43
0
    def _display_on_map_static(self,
                               index,
                               map_name,
                               palette="RdYlBu",
                               **kwargs):
        try:
            import escher
            if os.path.exists(map_name):
                map_json = map_name
                map_name = None
            else:
                map_json = None

            values = self.normalized_gaps

            values = values[~numpy.isnan(values)]
            values = values[~numpy.isinf(values)]

            data = self.solutions.iloc[index]
            # Find values above decimal precision
            data = data[numpy.abs(data.normalized_gaps.astype(float)) >
                        non_zero_flux_threshold]
            # Remove NaN rows
            data = data[~numpy.isnan(data.normalized_gaps.astype(float))]

            reaction_data = dict(data.normalized_gaps)
            for rid, gap in six.iteritems(reaction_data):
                if numpy.isposinf(gap):
                    gap = numpy.max(values)
                elif numpy.isneginf(gap):
                    gap = numpy.min(values)

                reaction_data[rid] = gap

            scale = self.plot_scale(palette)
            reaction_data['min'] = min(numpy.abs(values) * -1)
            reaction_data['max'] = max(numpy.abs(values))

            reaction_scale = [
                dict(type='min', color=scale[0][1], size=24),
                dict(type='value',
                     value=scale[0][0],
                     color=scale[0][1],
                     size=21),
                dict(type='value',
                     value=scale[1][0],
                     color=scale[1][1],
                     size=16),
                dict(type='value',
                     value=scale[2][0],
                     color=scale[2][1],
                     size=8),
                dict(type='value',
                     value=scale[3][0],
                     color=scale[3][1],
                     size=16),
                dict(type='value',
                     value=scale[4][0],
                     color=scale[4][1],
                     size=21),
                dict(type='max', color=scale[4][1], size=24)
            ]

            builder = escher.Builder(map_name=map_name,
                                     map_json=map_json,
                                     reaction_data=reaction_data,
                                     reaction_scale=reaction_scale)

            if in_ipnb():
                from IPython.display import display
                display(builder.display_in_notebook())
            else:
                builder.display_in_browser()

        except ImportError:
            print("Escher must be installed in order to visualize maps")
Exemplo n.º 44
0
def delta():
    if util.in_ipnb():
        return "&Delta;"
    else:
        return str(b'\xce\x94')
Exemplo n.º 45
0
def upreg(coeff):
    if util.in_ipnb():
        return "&uarr;%.3f" % coeff
    else:
        return b'\xe2\x86\x91'.decode('utf-8') + "%.3f" % coeff