Skip to content

Commit

Permalink
Merge 62d8f6a into 3ea055b
Browse files Browse the repository at this point in the history
  • Loading branch information
the-code-magician committed Mar 14, 2016
2 parents 3ea055b + 62d8f6a commit 026fd22
Show file tree
Hide file tree
Showing 16 changed files with 979 additions and 73 deletions.
29 changes: 28 additions & 1 deletion cameo/__init__.py
Expand Up @@ -50,13 +50,40 @@
from __future__ import absolute_import, print_function

import os
import sys

if sys.version_info[0] == 2:
import imp

def find_module(name):
try:
imp.find_module(name)
return True
except ImportError:
return False

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')


from cameo import config
from .util import get_system_info, in_ipnb

from .util import get_system_info
# 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()

Expand Down
17 changes: 5 additions & 12 deletions cameo/api/designer.py
Expand Up @@ -30,7 +30,7 @@ def HTML(*args, **kwargs):
print(*args, **kwargs)
from pandas import DataFrame

from cameo import Metabolite, Model, phenotypic_phase_plane, fba
from cameo import Metabolite, Model, fba
from cameo import config, util
from cameo.core.result import Result
from cameo.api.hosts import hosts, Host
Expand All @@ -44,7 +44,6 @@ def HTML(*args, **kwargs):
from cameo.models import universal

from cameo.visualization import visualization
from cameo.visualization.plotting import Grid

import logging

Expand Down Expand Up @@ -277,16 +276,10 @@ def __generate_ascii(inchi):

@staticmethod
def __display_pathways_information(predicted_pathways, host, original_model):
# TODO: remove copy hack.
with Grid(nrows=2, title="Production envelopes for %s (%s)" % (host.name, original_model.id)) as grid:
for i, pathway in enumerate(predicted_pathways):
pathway_id = "Pathway %i" % (i + 1)
with TimeMachine() as tm:
pathway.plug_model(original_model, tm)
production_envelope = phenotypic_phase_plane(original_model,
variables=[original_model.biomass],
objective=pathway.product)
production_envelope.plot(grid, title=pathway_id, width=400, height=300)
predicted_pathways.plot_production_envelopes(original_model,
title="Production envelopes for %s (%s)" % (host.name, original_model.id),
variables=[original_model.biomass])


@staticmethod
def calculate_yield(model, source, product):
Expand Down
43 changes: 34 additions & 9 deletions cameo/flux_analysis/analysis.py
Expand Up @@ -34,7 +34,7 @@
from cameo.parallel import SequentialView
from cameo.core.result import Result
from cameo.ui import notice
from cameo.visualization import plotting
from cameo.visualization.plotting import plotter
from cameo.flux_analysis.util import remove_infeasible_cycles

import logging
Expand Down Expand Up @@ -476,13 +476,27 @@ def __init__(self, phase_plane, variable_ids, objective, *args, **kwargs):
def data_frame(self):
return pandas.DataFrame(self._phase_plane)

def plot(self, grid=None, width=None, height=None, title=None, axis_font_size=None, color="lightblue", **kwargs):
def plot(self, grid=None, width=None, height=None, title=None, axis_font_size=None, palette=None,
points=None, points_colors=None, **kwargs):
if len(self.variable_ids) > 1:
notice("Multi-dimensional plotting is not supported")
return
plotting.plot_production_envelope(self._phase_plane, objective=self.objective, key=self.variable_ids[0],
grid=grid, width=width, height=height, title=title, color=color,
axis_font_size=axis_font_size, **kwargs)

if title is None:
title = "Phenotypic Phase Plane"
variable = self.variable_ids[0]

dataframe = pandas.DataFrame(columns=["ub", "lb", "value", "strain"])
for _, row in self.iterrows():
_df = pandas.DataFrame([[row['objective_upper_bound'], row['objective_lower_bound'], row[variable], "WT"]],
columns=dataframe.columns)
dataframe = dataframe.append(_df)

plot = plotter.production_envelope(dataframe, grid=grid, width=width, height=height,
title=title, x_axis_label=str(self.objective), y_axis_label=variable,
palette=palette, points=points, points_colors=points_colors)
if grid is None:
plotter.display(plot)

def __getitem__(self, item):
return self._phase_plane[item]
Expand Down Expand Up @@ -512,13 +526,24 @@ def __init__(self, data_frame, *args, **kwargs):
def data_frame(self):
return self._data_frame

def plot(self, index=None, grid=None, width=None, height=None, title=None, axis_font_size=None, color="lightblue",
**kwargs):
def plot(self, index=None, grid=None, width=None, height=None, title=None, palette=None, **kwargs):
if index is None:
index = self.data_frame.index[0:10]
fva_result = self.data_frame.loc[index]
plotting.plot_flux_variability_analysis(fva_result, grid=grid, width=width, height=height, title=title,
axis_font_size=axis_font_size, color=color)
if title is None:
title = "Flux Variability Analysis"

dataframe = pandas.DataFrame(columns=["lb", "ub", "strain", "reaction"])
for reaction_id, row in fva_result.iterrows():
_df = pandas.DataFrame([[row['lower_bound'], row['upper_bound'], "WT", reaction_id]],
columns=dataframe.columns)
dataframe = dataframe.append(_df)

plot = plotter.flux_variability_analysis(dataframe, grid=grid, width=width, height=height,
title=title, x_axis_label="Reactions", y_axis_label="Flux limits",
palette=palette)
if grid is None:
plotter.display(plot)

def __getitem__(self, item):
return self._data_frame[item]
Expand Down
55 changes: 39 additions & 16 deletions cameo/strain_design/deterministic/flux_variability_based.py
Expand Up @@ -34,7 +34,7 @@

from IProgress import ProgressBar
from pandas import DataFrame, pandas
from cameo.visualization import plotting
from cameo.visualization.plotting import plotter

from cameo import config, flux_variability_analysis
from cameo.flux_analysis.simulation import pfba, fba
Expand Down Expand Up @@ -343,26 +343,49 @@ def __getitem__(self, item):
data["suddenly_essential"] = data["suddenly_essential"].values.astype(np.bool)
return data

def plot(self, index=None, variables=None, grid=None, width=None, height=None, title=None, **kwargs):
def plot(self, index=None, variables=None, grid=None, width=None, height=None, title=None, palette=None, **kwargs):
if len(self.variable_ids) > 1:
notice("Multi-dimensional plotting is not supported")
return
if index is not None:
if variables is None:
variables = self.reference_fva.index[0:10]
title = "Compare WT solution %i" % index
fva_res1 = self.reference_fva.loc[variables]
fva_res2 = self.solutions.iloc[index].loc[variables]
plotting.plot_2_flux_variability_analysis(fva_res1, fva_res2, grid=grid,
width=width, height=height, title=title)
self._plot_flux_variability_analysis(index)
else:
title = "DifferentialFVA Result" if title is None else title
x = [elem[0][1] for elem in list(self.solutions.items)]
y = [elem[1][1] for elem in list(self.solutions.items)]
colors = ["red" for _ in x]
plotting.plot_production_envelope(self._phase_plane, objective=self.objective, key=self.variable_ids[0],
grid=grid, width=width, height=height, title=title,
points=zip(x, y), points_colors=colors)
self._plot_production_envelope(title=title, grid=grid, width=width, height=height)

def _plot_flux_variability_analysis(self, index, variables=None, title=None,
width=None, height=None, palette=None, grid=None):
if variables is None:
variables = self.reference_fva.index[0:10]

title = "Compare WT solution %i" % index if title is None else title

wt_fva_res = self.reference_fva.loc[variables]
strain_fva_res = self.solutions.iloc[index].loc[variables]
dataframe = pandas.DataFrame(columns=["lb", "ub", "strain", "reaction"])
for reaction_id, row in wt_fva_res.iterrows():
_df = pandas.DataFrame([[row['lower_bound'], row['upper_bound'], "WT", reaction_id]],
columns=dataframe.columns)
dataframe = dataframe.append(_df)

for reaction_id, row in strain_fva_res.iterrows():
_df = pandas.DataFrame([[row['lower_bound'], row['upper_bound'], "Striain %i" % index, reaction_id]],
columns=dataframe.columns)
dataframe = dataframe.append(_df)

plot = plotter.flux_variability_analysis(dataframe, grid=grid, width=width, height=height,
title=title, x_axis_label="Reactions", y_axis_label="Flux limits",
palette=palette)

plotter.display(plot)

def _plot_production_envelope(self, title=None, width=None, height=None, grid=None):
title = "DifferentialFVA Result" if title is None else title
x = [elem[0][1] for elem in list(self.solutions.items)]
y = [elem[1][1] for elem in list(self.solutions.items)]
colors = ["red" for _ in x]
points = zip(x, y)
super(DifferentialFVAResult, self).plot(title=title, grid=grid, width=width, heigth=height,
points=points, points_colors=colors)

def _repr_html_(self):
def _data_frame(solution):
Expand Down
31 changes: 22 additions & 9 deletions cameo/strain_design/deterministic/linear_programming.py
Expand Up @@ -18,7 +18,7 @@
import numpy
import logging

from cameo.visualization import plotting
from cameo.visualization.plotting import plotter

from pandas import DataFrame

Expand Down Expand Up @@ -298,12 +298,14 @@ def __init__(self, model, designs, fluxes, production_fluxes, biomass_fluxes, ta
def _process_knockouts(self):
progress = ProgressBar(maxval=len(self._designs), widgets=["Processing solutions: ", Bar(), Percentage()])

self._processed_knockouts = DataFrame(columns=["knockouts", "size", "biomass",
self._processed_knockouts = DataFrame(columns=["reactions", "size", "biomass",
self._target, "fva_min", "fva_max"])

for i, knockouts in progress(enumerate(self._designs)):
try:
fva = flux_variability_analysis(self._model, fraction_of_optimum=0.99, reactions=[self.target])
with TimeMachine() as tm:
[self._model.reactions.get_by_id(ko).knock_out(time_machine=tm) for ko in knockouts]
fva = flux_variability_analysis(self._model, fraction_of_optimum=0.99, reactions=[self.target])
self._processed_knockouts.loc[i] = [knockouts, len(knockouts), self.production[i], self.biomass[i],
fva.lower_bound(self.target), fva.upper_bound(self.target)]
except SolveError:
Expand All @@ -329,18 +331,29 @@ def biomass(self):
def target(self):
return self._target

def plot(self, index, grid=None, width=None, height=None, title=None, *args, **kwargs):
def plot(self, index=0, grid=None, width=None, height=None, title=None, palette=None, **kwargs):
wt_production = phenotypic_phase_plane(self._model, objective=self._target, variables=[self._biomass.id])
with TimeMachine() as tm:
for ko in self._designs[index]:
self._model.reactions.get_by_id(ko).knock_out(tm)

mt_production = phenotypic_phase_plane(self._model, objective=self._target, variables=[self._biomass.id])
plotting.plot_2_production_envelopes(wt_production.data_frame,
mt_production.data_frame,
self._target,
self._biomass.id,
**kwargs)
if title is None:
title = "Production Envelope"

dataframe = DataFrame(columns=["ub", "lb", "value", "strain"])
for _, row in wt_production.iterrows():
_df = DataFrame([[row['objective_upper_bound'], row['objective_lower_bound'], row[self._biomass.id], "WT"]],
columns=dataframe.columns)
dataframe = dataframe.append(_df)
for _, row in mt_production.iterrows():
_df = DataFrame([[row['objective_upper_bound'], row['objective_lower_bound'], row[self._biomass.id], "MT"]],
columns=dataframe.columns)
dataframe = dataframe.append(_df)

plot = plotter.production_envelope(dataframe, grid=grid, width=width, height=height, title=title,
x_axis_label=self._biomass.id, y_axis_label=self._target, palette=palette)
plotter.display(plot)

@property
def data_frame(self):
Expand Down
36 changes: 24 additions & 12 deletions cameo/strain_design/heuristic/evolutionary_based.py
Expand Up @@ -21,7 +21,7 @@
from pandas import DataFrame

from cameo.exceptions import SolveError
from cameo.visualization import plotting
from cameo.visualization.plotting import plotter
from cameo.util import ProblemCache, TimeMachine

from cameo.flux_analysis.simulation import fba
Expand Down Expand Up @@ -96,8 +96,9 @@ def manipulation_type(self, manipulation_type):
else:
raise ValueError("Invalid manipulation type %s" % manipulation_type)

def run(self, target=None, biomass=None, substrate=None, max_knockouts=5, simulation_method=fba, robust=True,
max_evaluations=20000, population_size=100, time_machine=None, max_results=50, **kwargs):
def run(self, target=None, biomass=None, substrate=None, max_knockouts=5, simulation_method=fba,
growth_coupled=True, max_evaluations=20000, population_size=100, time_machine=None,
max_results=50, **kwargs):
"""
Parameters
----------
Expand Down Expand Up @@ -134,7 +135,7 @@ def run(self, target=None, biomass=None, substrate=None, max_knockouts=5, simula
biomass = self._model.reaction_for(biomass, time_machine=time_machine)
substrate = self._model.reaction_for(substrate, time_machine=time_machine)

if robust:
if growth_coupled:
objective_function = biomass_product_coupled_min_yield(biomass, target, substrate)
else:
objective_function = biomass_product_coupled_yield(biomass, target, substrate)
Expand Down Expand Up @@ -231,15 +232,26 @@ def _process_solutions(self):
processed_solutions.drop('genes', axis=1, inplace=True)
self._processed_solutions = processed_solutions

def plot(self, index=None, grid=None, width=None, height=None, title=None, *args, **kwargs):
def plot(self, index=None, grid=None, width=None, height=None, title=None, palette=None, **kwargs):
wt_production = phenotypic_phase_plane(self._model, objective=self._target, variables=[self._biomass])
with TimeMachine() as tm:
for ko in self._designs[index][0]:
for ko in self._processed_solutions.loc[index, "reactions"]:
self._model.reactions.get_by_id(ko).knock_out(tm)

mt_production = phenotypic_phase_plane(self._model, objective=self._target, variables=[self._biomass])
plotting.plot_2_production_envelopes(wt_production.data_frame,
mt_production.data_frame,
self._target,
self._biomass,
**kwargs)

if title is None:
title = "Production Envelope"

dataframe = DataFrame(columns=["ub", "lb", "value", "strain"])
for _, row in wt_production.iterrows():
_df = DataFrame([[row['objective_upper_bound'], row['objective_lower_bound'], row[self._biomass.id], "WT"]],
columns=dataframe.columns)
dataframe = dataframe.append(_df)
for _, row in mt_production.iterrows():
_df = DataFrame([[row['objective_upper_bound'], row['objective_lower_bound'], row[self._biomass.id], "MT"]],
columns=dataframe.columns)
dataframe = dataframe.append(_df)

plot = plotter.production_envelope(dataframe, grid=grid, width=width, height=height, title=title,
x_axis_label=self._biomass.id, y_axis_label=self._target.id, palette=palette)
plotter.display(plot)

0 comments on commit 026fd22

Please sign in to comment.