Ejemplo n.º 1
0
def build_escher(model=None, fluxes=None, fmt_func=None, **kwargs):
    try:
        import escher
    except ImportError:
        raise RuntimeError("Escher is not installed.")

    js = None
    if isinstance(model, str) and model in escher_maps():
        map_name = model
    else:
        try:
            js = to_json(model)
        except Exception:
            map_name = 'e_coli_core.Core metabolism'

    if fluxes and fmt_func:
        fluxes = {fmt_func(r_id): val for r_id, val in fluxes.items()}
    else:
        fluxes = None
    if js:
        return escher.Builder(model_json=js, reaction_data=fluxes, **kwargs)
    else:
        return escher.Builder(map_name=map_name,
                              reaction_data=fluxes,
                              **kwargs)
Ejemplo n.º 2
0
    def _refresh_map(self, rates):
        """ Refresh the map being displayed

        Generate a map from the set solution
        and metabolite. Only display those
        reactions that are active in the set
        solution if hide_active is set.

        Returns
        -------
        None
        """

        # Generate escher turnover map
        builder = escher.Builder(map_json=setup_turnover_map(
            self.metabolite, rates),
                                 reaction_data=self.solution.fluxes.to_dict())
        html = builder._get_html(**ESCHER_OPTIONS_LOCAL)

        # As Qt does not allow the loading of local files
        # from html set via the setHtml method, write map
        # to file and read it back to webview
        with open(self.temp_file, "w") as ofile:
            ofile.write(replace_css_paths(html))
        self.mapView.load(
            QtCore.QUrl("file:///" + self.temp_file.replace("\\", "/")))
Ejemplo n.º 3
0
def fluxes2escher(fluxes, map_name=None, fmt_func=None, **kwargs):
    """ Build escher map for a given flux distribution

    Args:
        fluxes (dict): flux distribution
        map_name (str): name of **escher** map (for a list of available maps run *escher_maps*)
        fmt_func (str or function): python format string (see Notes)
        kwargs: additional arguments passed to *escher.Builder* (see Escher's documentation for details).

    Notes:
        The format function parameter is used to convert reaction ids to BiGG ids.
        By default it removes the 'R_' prefix ('R_EX_h2o_e' is transformed to 'EX_h2o_e').

    Returns:
        escher.plots.Builder: escher map object
    """

    try:
        import escher
    except ImportError:
        raise RuntimeError("Escher is not installed.")

    if map_name is None:
        map_name = 'e_coli_core.Core metabolism'

    if fmt_func is None:

        def fmt_func(x):
            return x[2:]

    fluxes = {fmt_func(r_id): val for r_id, val in fluxes.items()}

    return escher.Builder(map_name=map_name, reaction_data=fluxes, **kwargs)
Ejemplo n.º 4
0
def show_map(sol, map_loc, color=0):
    ''' Returns an escher Builder object for solution 'sol', map 'map_loc' and the supplied color scheme.
        sol:        the solution object containing the simulation results.
        map_loc:    filename of the map json
        color:      color scheme to use
    '''

    # read css
    script_dir = os.path.dirname(__file__)  #<-- absolute dir the script is in
    with open(script_dir + '/my_escher_css.css', 'r') as myfile:
        my_css = myfile.read().replace('\n', ' ')

    if color == 0:
        # from grey to Green to Orange
        colors = [{
            'type': 'min',
            'color': '#cccccc',
            'size': 5
        }, {
            'type': 'mean',
            'color': '#00CC00',
            'size': 10
        }, {
            'type': 'max',
            'color': '#FFCC00',
            'size': 15
        }]
    else:
        print('Color scheme not defined!')
        return

    if type(sol) != dict:
        try:
            d = sol.fluxes  # it is a cobrapy solution object
        except:
            print('An empty solution was passed.')
            d = {}
    else:
        d = sol  # shorthand

    d2 = {
    }  # for some reason my types (from float 64 to float) were not updating and with a new dictionary they do
    for key in list(d.keys()):  # remove output like this: 1.653e-15
        d2[key] = round(float(d[key]), 6)

    network = escher.Builder(
        map_json=map_loc,
        reaction_data=d2,
        reaction_styles=['color', 'size', 'abs', 'text'],
        # change the default colors, blue to purple to red
        reaction_scale=colors,
        hide_secondary_metabolites=False,
        secondary_metabolite_radius=10,
        highlight_missing=True,
        embedded_css=my_css)
    return network
Ejemplo n.º 5
0
def display_efms_escher(efm):
 """
 Args:
     efm:
 """
	escher_builder = escher.Builder(
		map_name='e_coli_core.Core metabolism',
		hide_secondary_metabolites = True,
		reaction_data = efm
	)
	escher_builder.display_in_notebook(js_source='local')
Ejemplo n.º 6
0
def show_map(sol, map_loc, color=0):
    ''' Returns an escher Builder object for solution 'sol', map 'map_loc' and the supplied color scheme.
        sol:        the solution object containing the simulation results.
        map_loc:    filename of the map json
        color:      color scheme to use
    '''

    if color == 0:
        colors = [
            {
                'type': 'min',
                'color': '#cccccc',
                'size': 5
            },  # grey to green to orange
            {
                'type': 'mean',
                'color': '#007F00',
                'size': 10
            },
            {
                'type': 'max',
                'color': '#f0a900',
                'size': 15
            }
        ]
    else:
        print('Color scheme not defined!')
        return

    if type(sol) != dict:
        try:
            d = sol.x_dict  # it is a cobrapy solution object
        except:
            print('An empty solution was passed.')
            d = {}
    else:
        d = sol  # shorthand

    d2 = {
    }  # for some reason my types (from float 64 to float) were not updating and with a new dictionary they do
    for key in d.keys():  # remove output like this: 1.653e-15
        d2[key] = round(float(d[key]), 6)

    network = escher.Builder(
        map_json=map_loc,
        reaction_data=d2,
        reaction_styles=['color', 'size', 'abs', 'text'],
        # change the default colors, blue to purple to red
        reaction_scale=colors,
        hide_secondary_metabolites=False,
        secondary_metabolite_radius=10,
        highlight_missing=True)
    return network
Ejemplo n.º 7
0
def visualize_flux(reaction_fluxes):
    builder = escher.Builder(map_name='iJO1366.Central metabolism',
                             reaction_scale=[
                                 {'type': 'min', 'color': '#cccccc',
                                  'size': 4},
                                 {'type': 'value', 'value': .01,
                                  'color': '#0000dd', 'size': 20},
                                 {'type': 'max', 'color': '#0000dd',
                                  'size': 20}])
    builder.reaction_data = reaction_fluxes.to_dict()

    return builder.display_in_notebook()
Ejemplo n.º 8
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")
Ejemplo n.º 9
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")
Ejemplo n.º 10
0
    def get_html(self,
                 reaction_data=None,
                 gene_data=None,
                 metabolite_data=None):
        """ Generate the html from map

        Parameters
        ----------
        reaction_data: dict
        metabolite_data: dict
        gene_data: dict

        Returns
        -------
        map_html: str
        """
        builder = escher.Builder(map_json=self._map_json,
                                 reaction_data=reaction_data,
                                 gene_data=gene_data,
                                 metabolite_data=metabolite_data)
        return builder._get_html(**ESCHER_OPTIONS_WEB)
Ejemplo n.º 11
0
def build_escher_map(fluxes, map_name, abstol=1e-6):
    """ Build escher map for a given flux distribution

    Args:
        fluxes (dict): flux distribution
        map_name (str): name of **escher** map (for a list of maps see *list_escher_maps*)
        abstol (float): tolerance to remove residual fluxes for cleaner visualization (default: 1e-6)

    Returns:
        escher.plots.Builder: escher map object
    """

    import escher

    data = {
        r_id[2:]: abs(val) if abs(val) > abstol else 0.0
        for r_id, val in fluxes.items()
    }

    colors = [{
        'type': 'min',
        'color': '#f0f0f0',
        'size': 8
    }, {
        'type': 'mean',
        'color': '#abb7ff',
        'size': 20
    }, {
        'type': 'max',
        'color': '#0f16fb',
        'size': 40
    }]

    emap = escher.Builder(map_name=map_name,
                          reaction_data=data,
                          reaction_scale=colors,
                          reaction_no_data_size=8,
                          reaction_no_data_color='#ffddda')

    return emap
Ejemplo n.º 12
0
def show_escher_map(me, solution=None):
    import escher
    view = escher.Builder("iJO1366.Central metabolism")
    view.reaction_data = me.get_metabolic_flux(solution=solution)
    return view
Ejemplo n.º 13
0
for met in met_count:
    if met_count[met] > 4 and met.id not in included_common_m:
        common_mets.add(met)

# Convert the sets to lists so that they can be iterated over
common_mets, rxn_with_flux, rxn_with_greater_flux = \
    list(common_mets), list(rxn_with_flux), list(rxn_with_greater_flux)


# Get the Escher JSON
escher_map = generate_escher_map.gen_map(
     ecoli_model, rxn_with_greater_flux,  common_mets, 350, met_count
)
escher_json = escher_map.dump_json()
# Currently Escher doesn't accept json strings, needs a file, i assume that's a bug
with open('escher.json', 'w') as f:
    f.write(escher_json)
# See escher documentation for more info on escher.
import escher
ecoli_metabolite_map = escher.Builder(
    #map_json=escher_json,
    map_json='escher.json',
    reaction_data=flux,
    model_json='test.json'
)
import json
parsed_json = json.loads(escher_json)
escher.validate.check_map(parsed_json)
# Use display in browser to get an interactive version of the map.
ecoli_metabolite_map.display_in_browser()
Ejemplo n.º 14
0
print("Model Objective: ", model.objective)

# Escher visualizations #######################################################
escher.list_available_maps()

# available maps for humans:
# {'organism': 'H**o sapiens','map_name': 'RECON1.Amino acid metabolism (partial)'},
# {'organism': 'H**o sapiens','map_name': 'RECON1.Carbohydrate metabolism'},
# {'organism': 'H**o sapiens','map_name': 'RECON1.Glycolysis TCA PPP'},
# {'organism': 'H**o sapiens','map_name': 'RECON1.Inositol retinol metabolism'},
# {'organism': 'H**o sapiens','map_name': 'RECON1.Tryptophan metabolism'},

# We'll build a glycolysis map:

# Only works in Jupyter notebook
b = escher.Builder(map_name='RECON1.Glycolysis TCA PPP')
b.display_in_notebook()

b = escher.Builder(
    map_name='RECON1.Glycolysis TCA PPP',
    reaction_data=dict(solution.fluxes),  # change the default colors
    reaction_scale=[{
        'type': 'min',
        'color': '#cccccc',
        'size': 4
    }, {
        'type': 'value',
        'value': 0.1,
        'color': '#cccccc',
        'size': 8
    }, {
 def read_escher_map(self, map_name):
     return escher.Builder(
         map_json='../dataset/visualizations/%s_map.json' % map_name)
Ejemplo n.º 16
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")
Ejemplo n.º 17
0
 def display_in_notebook(self, enable_editing=False):
     builder = escher.Builder(map_json=json.dumps(self.escher_map))
     return builder.display_in_notebook(enable_editing=enable_editing)
Ejemplo n.º 18
0
 def display_in_notebook(self, enable_editing=False, reaction_data=None):
     builder = escher.Builder(map_json=json.dumps(self.escher_map),
                              reaction_data=reaction_data)
     return builder.display_in_notebook(enable_editing=enable_editing)
Ejemplo n.º 19
0
print('Growth rate: %.2f' % sol.f)
"""

import cobra.test
model = cobra.test.create_test_model("textbook")
ex_oxygen = model.reactions.get_by_id("EX_o2_e")
with model as newModel:
    ex_oxygen.lower_bound = 0
    ex_oxygen.upper_bound = 1
    newSolution = newModel.optimize()
    
    newSolution.fluxes.to_json("solution3.json")
    jsonFile = open("solution3.json","r")
    jsonItem = jsonFile.read()
    testDict = json.loads(jsonItem)
    print(testDict)
    
    

    
    
    b = escher.Builder(map_name='e_coli_core.Core metabolism',
                       reaction_data=testDict,
                       # change the default colors
                       reaction_scale=[{'type': 'min', 'color': '#cccccc', 'size': 4},
                                       {'type': 'mean', 'color': '#0000dd', 'size': 20},
                                       {'type': 'max', 'color': '#ff0000', 'size': 40}],
                       # only show the primary metabolites
                       hide_secondary_metabolites=False)
    #b.display_in_browser(js_source='web')
    b.display_in_browser()