Skip to content

Commit

Permalink
Fix plotting stuff (#95)
Browse files Browse the repository at this point in the history
* fix: phenotypic phase plane labels
* fix: yields are only for objective
* fix: 3d plot only with objective upper value
  • Loading branch information
the-code-magician authored and hredestig committed Jan 13, 2017
1 parent af01eff commit 93f64fa
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 36 deletions.
28 changes: 19 additions & 9 deletions cameo/flux_analysis/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import itertools
import logging
import re
from collections import OrderedDict
from functools import partial, reduce

Expand All @@ -42,6 +43,8 @@
__all__ = ['find_blocked_reactions', 'flux_variability_analysis', 'phenotypic_phase_plane',
'flux_balance_impact_degree']

_BIOMASS_RE_ = re.compile("biomass", re.IGNORECASE)


def find_blocked_reactions(model):
"""Determine reactions that cannot carry steady-state flux.
Expand Down Expand Up @@ -622,12 +625,12 @@ def plot(self, grid=None, width=None, height=None, title=None, axis_font_size=No
'[mmol gDW^-1 h^-1]'),
'mass_yield': ('mass_yield_upper_bound',
'mass_yield_lower_bound',
'mass yield, source={}'.format(self.source_reaction),
'[g(product) g(source)^-1 h^-1]'),
'mass yield, src={}'.format(self.source_reaction),
'[g/g(src) h^-1]'),
'c_yield': ('c_yield_upper_bound',
'c_yield_lower_bound',
'carbon yield, source={}'.format(self.source_reaction),
'[mmol(C(product)) mmol(C(source))^-1 h^-1]')}
'carbon yield, src={}'.format(self.source_reaction),
'[mmol(C)/mmol(C(src)) h^-1]')}
if estimate not in possible_estimates:
raise Exception('estimate must be one of %s' %
', '.join(possible_estimates.keys()))
Expand All @@ -637,8 +640,8 @@ def plot(self, grid=None, width=None, height=None, title=None, axis_font_size=No
if len(self.variable_ids) == 1:

variable = self.variable_ids[0]
y_axis_label = '{} [h^-1]'.format(self.nice_objective_id)
x_axis_label = '{} {}'.format(self.nice_variable_ids[0], unit)
y_axis_label = self._axis_label(self.objective, self.nice_objective_id, unit)
x_axis_label = self._axis_label(variable, self.nice_variable_ids[0], '[mmol gDW^-1 h^-1]')

dataframe = pandas.DataFrame(columns=["ub", "lb", "value", "strain"])
for _, row in self.iterrows():
Expand All @@ -653,9 +656,9 @@ def plot(self, grid=None, width=None, height=None, title=None, axis_font_size=No
elif len(self.variable_ids) == 2:
var_1 = self.variable_ids[0]
var_2 = self.variable_ids[1]
x_axis_label = '{} {}'.format(self.nice_variable_ids[0], unit)
y_axis_label = '{} {}'.format(self.nice_variable_ids[1], unit)
z_axis_label = '{} [h^-1]'.format(self.nice_objective_id)
x_axis_label = self._axis_label(var_1, self.nice_variable_ids[0], '[mmol gDW^-1 h^-1]')
y_axis_label = self._axis_label(var_2, self.nice_variable_ids[1], '[mmol gDW^-1 h^-1]')
z_axis_label = self._axis_label(self.objective, self.nice_objective_id, unit)

dataframe = pandas.DataFrame(columns=["ub", "lb", "value1", "value2", "strain"])
for _, row in self.iterrows():
Expand All @@ -676,6 +679,13 @@ def plot(self, grid=None, width=None, height=None, title=None, axis_font_size=No
if grid is None:
plotter.display(plot)

@staticmethod
def _axis_label(variable_id, nice_variable_id, unit):
if re.search(_BIOMASS_RE_, variable_id):
return '{} [h^-1]'.format(nice_variable_id)
else:
return '{} {}'.format(nice_variable_id, unit)

def __getitem__(self, item):
return self._phase_plane[item]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ def __init__(self, color_map={}, *args, **kwargs):
self.color_map = color_map
self.data_frame = DataFrame(columns=['iteration', 'island', 'color', 'fitness'])
self.plotted = False
self.handle = None

def _create_client(self, i):
self.clients[i] = IPythonNotebookBokehMultiprocessPlotObserverClient(queue=self.queue, index=i)
Expand All @@ -52,7 +53,7 @@ def _plot(self):
self.ds = ColumnDataSource(data=dict(x=[], y=[], island=[]))
self.plot.circle('x', 'y', source=self.ds)

show(self.plot)
self.handle = show(self.plot, notebook_handle=True)
self.plotted = True

def _process_message(self, message):
Expand All @@ -76,7 +77,7 @@ def _update_plot(self):
self.ds.data['fill_color'] = self.data_frame['color']
self.ds.data['line_color'] = self.data_frame['color']
self.ds._dirty = True
push_notebook()
push_notebook(handle=self.handle)

def stop(self):
self.data_frame = DataFrame(columns=['iteration', 'island', 'color', 'fitness'])
Expand Down
27 changes: 14 additions & 13 deletions cameo/strain_design/heuristic/evolutionary/optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@
from __future__ import absolute_import, print_function

import logging
import time
import types
from functools import reduce

import inspyred
import time
from pandas import DataFrame

from cameo import config
Expand Down Expand Up @@ -372,7 +372,8 @@ def run(self, view=config.default_view, max_size=10, variable_size=True, **kwarg
target_type=self._target_type,
decoder=self._decoder,
seed=kwargs['seed'],
metadata=self.metadata)
metadata=self.metadata,
view=view)


class KnockoutOptimization(TargetOptimization):
Expand All @@ -386,22 +387,20 @@ def __init__(self, simulation_method=pfba, wt_reference=None, *args, **kwargs):


class TargetOptimizationResult(Result):
def __init__(self, model=None, heuristic_method=None, simulation_method=None,
simulation_kwargs=None, solutions=None, objective_function=None,
target_type=None, decoder=None, seed=None, metadata=None, *args, **kwargs):
def __init__(self, model=None, heuristic_method=None, simulation_method=None, simulation_kwargs=None,
solutions=None, objective_function=None, target_type=None, decoder=None,
seed=None, metadata=None, view=None, *args, **kwargs):
super(TargetOptimizationResult, self).__init__(*args, **kwargs)
self.seed = seed
self.model = model
self.heuristic_method = heuristic_method
self.simulation_method = simulation_method
self.simulation_kwargs = simulation_kwargs or {}
if isinstance(objective_function, list):
self.objective_functions = objective_function
else:
self.objective_functions = [objective_function]
self.objective_functions = objective_function
self.target_type = target_type
self._decoder = decoder
self._metadata = metadata
self._view = view
self._solutions = self._decode_solutions(solutions)

def __len__(self):
Expand All @@ -410,6 +409,7 @@ def __len__(self):
def __getstate__(self):
state = super(TargetOptimizationResult, self).__getstate__()
state.update({'model': self.model,
'view': self._view,
'decoder': self._decoder,
'simulation_method': self.simulation_method,
'simulation_kwargs': self.simulation_kwargs,
Expand All @@ -435,6 +435,7 @@ def __setstate__(self, state):
self.simulation_method = state['simulation_method']
self.simulation_kwargs = state['simulation_kwargs']
self.seed = state['seed']
self.view = state['view']
random = state['heuristic_method._random']
self.heuristic_method = state['heuristic_method.__class__'](random)
self.heuristic_method.maximize = state['heuristic_method.maximize']
Expand All @@ -447,9 +448,9 @@ def __setstate__(self, state):
self.target_type = state['target_type']
self._solutions = state['solutions']
self._metadata = state['metadata']
self._decoder = state['decoder']

def _repr_html_(self):

template = """
<h4>Result:</h4>
<ul>
Expand Down Expand Up @@ -509,9 +510,9 @@ def data_frame(self):
def _decode_solutions(self, solutions):
decoded_solutions = DataFrame(columns=["targets", "fitness"])
for index, solution in enumerate(solutions):
knockouts = self._decoder(solution.candidate, flat=True)
if len(knockouts) > 0:
decoded_solutions.loc[index] = [knockouts, solution.fitness]
targets = self._decoder(solution.candidate, flat=True)
if len(targets) > 0:
decoded_solutions.loc[index] = [targets, solution.fitness]

return decoded_solutions

Expand Down
12 changes: 8 additions & 4 deletions cameo/strain_design/heuristic/evolutionary/plotters.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,15 @@ def __init__(self, window_size=1000):
self.fitness = []
self.uuid = None
self.plotted = False
self.handle = None

def _set_plot(self):
self.plot = figure(title="Fitness plot", tools='', plot_height=400, plot_width=650)
self.plot.xaxis.axis_label = "Iteration"
self.plot.yaxis.axis_label = "Fitness"
self.ds = ColumnDataSource(data=dict(x=[], y=[]))
self.plot.circle('x', 'y', source=self.ds)
show(self.plot)
self.handle = show(self.plot, notebook_handle=True)
self.plotted = True

def __call__(self, population, num_generations, num_evaluations, args):
Expand All @@ -62,13 +63,14 @@ def __call__(self, population, num_generations, num_evaluations, args):
def _update(self):
self.ds.data['x'] = self.iterations[-self.window_size:]
self.ds.data['y'] = self.fitness[-self.window_size:]
push_notebook()
push_notebook(handle=self.handle)

def reset(self):
self.iteration = 0
self.iterations = []
self.fitness = []
self.plotted = False
self.handle = None

def end(self):
if self.plotted:
Expand All @@ -86,6 +88,7 @@ def __init__(self, objective_function=None, x=0, y=1):
self.fitness = []
self.uuid = None
self.plotted = False
self.handle = None

def _set_plot(self):
self.plot = figure(title="Multi-objective Fitness Plot", tools='', plot_height=400, plot_width=650)
Expand All @@ -94,7 +97,7 @@ def _set_plot(self):
self.ds = ColumnDataSource(data=dict(x=[], y=[]))
self.plot.circle('x', 'y', source=self.ds)

show(self.plot)
self.handle = show(self.plot, notebook_handle=True)
self.plotted = True

def __call__(self, population, num_generations, num_evaluations, args):
Expand All @@ -108,11 +111,12 @@ def __call__(self, population, num_generations, num_evaluations, args):
def _update(self):
self.ds.data['x'] = [e[self.x] for e in self.fitness]
self.ds.data['y'] = [e[self.y] for e in self.fitness]
push_notebook()
push_notebook(handle=self.handle)

def reset(self):
self.fitness = []
self.plotted = False
self.handle = None

def end(self):
if self.plotted:
Expand Down
12 changes: 4 additions & 8 deletions cameo/visualization/plotting/with_plotly.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,10 @@
from __future__ import absolute_import

import math
import six

import plotly.graph_objs as go
import six
from plotly import tools

from numpy import concatenate

from cameo.util import zip_repeat, in_ipnb, inheritdocstring, partition
from cameo.visualization.plotting.abstract import AbstractPlotter

Expand Down Expand Up @@ -170,12 +167,11 @@ def production_envelope(self, dataframe, grid=None, width=None, height=None, tit
return plot

def _make_production_envelope_3d(self, dataframe, variable, color=None):
lb_data = dataframe.pivot('value1', 'value2', 'lb')
ub_data = dataframe.pivot('value1', 'value2', 'ub')

surface = go.Surface(x=lb_data.index.tolist(),
y=lb_data.columns.tolist() + ub_data.columns.tolist(),
z=concatenate([ub_data.as_matrix(), lb_data.as_matrix()]),
surface = go.Surface(x=ub_data.index.tolist(),
y=ub_data.columns.tolist(),
z=ub_data.as_matrix(),
name=variable,
hoverinfo='none',
surfacecolor=color)
Expand Down

0 comments on commit 93f64fa

Please sign in to comment.