Skip to content

Commit

Permalink
Update cmd compare #118
Browse files Browse the repository at this point in the history
  • Loading branch information
cb-Hades committed May 24, 2024
1 parent c12d62c commit 5a4a47a
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 15 deletions.
47 changes: 40 additions & 7 deletions src/refinegems/analysis/comparison.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,21 @@
All other stats are shown in the memote report.
"""

__author__ = "Famke Baeuerle"
__author__ = "Famke Baeuerle, Gwendolyn O. Döbel and Carolin Brune"

################################################################################
# requirements
################################################################################

import pandas as pd
import matplotlib
import matplotlib.colors
import numpy as np
import pandas as pd
import warnings

from cobra import Model as cobraModel
from libsbml import Model as libModel
from typing import Union
from venn import venn

from ..utility.io import search_sbo_label
Expand Down Expand Up @@ -44,7 +48,9 @@ def get_sbo_mapping_multiple(models: list[libModel]) -> pd.DataFrame:
df['SBO-Name'] = df['SBO-Term'].apply(search_sbo_label)
return df

def plot_rea_sbo_multiple(models: list[libModel], rename=None) -> matplotlib.axes.Axes:
def plot_rea_sbo_multiple(models: list[libModel], rename=None,
color_palette:Union[str,list[str]]='Paired',
figsize:tuple=(10,10)) -> matplotlib.figure.Figure:
"""Plots reactions per SBO Term in horizontal bar chart with stacked bars for the models
Args:
Expand All @@ -55,20 +61,47 @@ def plot_rea_sbo_multiple(models: list[libModel], rename=None) -> matplotlib.axe
Defaults to None.
Returns:
matplotlib.axes.Axes:
Pandas stacked barchart
matplotlib.figure.Figure:
The results as a stacked barchart
"""
# set the colours
match color_palette:
case str():
try:
cmap = matplotlib.colormaps[color_palette]
except ValueError:
warnings.warn('Unknown color palette, setting it to "Paired"')
cmap = matplotlib.colormaps['Paired']
#@TODO : make sure all types of colourmaps work
if isinstance(cmap,matplotlib.colors.ListedColormap):
cmap = cmap.colors[0:len(models)]
# @TODO
# alternative, if colour list shorter than model list
else:
cmap = cmap(np.linspace(0,1,len(models)))
case list():
cmap = color_palette
case _:
mes = 'Unkown type for color_palette'
raise TypeError(mes)

# prepare the data
map = get_sbo_mapping_multiple(models)
id_list = [mod.id for mod in models]
map = map[(map[id_list]>3).all(axis=1)]
map = map.drop('SBO-Term', axis=1).sort_values(id_list[0]).set_index('SBO-Name')
if rename is not None:
map = map.rename(rename, axis=1)
fig = map.plot.barh(stacked=True, width=.8, figsize=(8,10))
# make the figure
fig = map.plot.barh(stacked=True, width=.8, figsize=figsize, color=cmap)
for patch in fig.patches:
colour = patch.get_facecolor()
patch.set_edgecolor(colour)
fig.set_ylabel('')
fig.set_xlabel('number of reactions', fontsize=16)
fig.legend(loc='lower right')
return fig
return fig.get_figure()


def plot_venn(models: list[cobraModel], entity: str, perc: bool=False, rename=None) -> matplotlib.axes.Axes:
"""Creates Venn diagram to show the overlap of model entities
Expand Down
19 changes: 14 additions & 5 deletions src/refinegems/cmd_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from pathlib import Path
import pandas as pd
import logging
import sys

from refinegems.curation.db_access import biocyc
from refinegems.utility.io import write_model_to_file
Expand Down Expand Up @@ -406,16 +407,24 @@ def pancore(modelpath, pcpath, based_on,dir):

@analyse.command()
@click.argument('modelpaths', nargs=-1, type=click.Path(exists=True))
@click.option('--type','-t',required=False,type=click.Choice(['sboterm','entities']),
show_default=True, default=None, help='Type of comparison to be performed.')
# @TODO
# extend / add different comparison options
@click.option('--type','-t',required=False,type=click.Choice(['sboterm']), multiple=True,
show_default=True, default=[], help='Type of comparison to be performed.')
@click.option('--all',required=False, is_flag=True, show_default=True, default=False,
help='Shortcut to run all comparisons. Overwrites input of type.')
def compare(modelpaths,type,all):
@click.option('-d', '--dir', required=False, type=click.Path(file_okay=False), show_default=True, default='comparison', help='Path to the output dir.')
@click.option('-c','--colour', required=False, type=str, default='Paired', show_default=True, help='Name of Matplotlib colour palette for the plot.')
def compare(modelpaths,type,all,dir,colour):
"""Compare models.
"""
Path(dir).mkdir(parents=True, exist_ok=True)
# compare SBOterms
if all or 'sboterm' in type:
models = rg.utility.io.load_model(modelpaths)
fig = rg.analysis
models = rg.utility.io.load_model(list(modelpaths),'libsbml')
fig = rg.analysis.comparison.plot_rea_sbo_multiple(models,color_palette=colour)
fig.savefig(Path(dir, 'sboterm'), dpi=400, bbox_inches='tight')


# analyse growth
# --------------
Expand Down
6 changes: 3 additions & 3 deletions src/refinegems/utility/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,11 @@ def load_libsbml_model(modelpath:str) -> libModel:
case list():

loaded_models = []
for modelpath in modelpath:
for m in modelpath:
if package == 'cobra':
loaded_models.append(load_cobra_model(modelpath))
loaded_models.append(load_cobra_model(m))
elif package == 'libsbml':
loaded_models.append(load_libsbml_model(modelpath))
loaded_models.append(load_libsbml_model(m))
return loaded_models

# read in a single model
Expand Down

0 comments on commit 5a4a47a

Please sign in to comment.