├── requirements.txt ├── docs ├── source │ └── quickstart.rst ├── installation.rst ├── dependencis.rst ├── index.rst └── conf.py ├── README.md ├── setup.cfg ├── .travis.yml ├── driven ├── generic │ ├── __init__.py │ └── normalization.py ├── flux_analysis │ ├── __init__.py │ ├── metrics.py │ ├── tn_seq.py │ ├── fit_objective │ │ ├── __init__.py │ │ ├── generators.py │ │ ├── variators.py │ │ ├── evaluators.py │ │ └── optimization.py │ ├── proteomics.py │ ├── fluxomics.py │ ├── profiling.py │ ├── thermodynamics.py │ ├── results.py │ └── transcriptomics.py ├── vizualization │ ├── __init__.py │ ├── utils.py │ ├── plotting │ │ ├── __init__.py │ │ ├── abstract.py │ │ ├── with_plotly.py │ │ ├── with_ggplot.py │ │ └── with_bokeh.py │ └── escher_viewer.py ├── network_analysis │ └── __init__.py ├── sensitivity_analysis │ ├── __init__.py │ └── flux_analysis.py ├── __init__.py ├── data_sets │ ├── pax_db.py │ ├── __init__.py │ ├── normalization.py │ ├── fluxes.py │ └── expression_profile.py ├── config.py ├── stats.py ├── _cobra_ext.py └── utils.py ├── .gitignore ├── tests ├── test_data_sets.py ├── assets │ ├── blazier_et_al_2012.py │ └── zur_et_al_2010.py └── test_flux_analysis.py ├── setup.py ├── notebooks └── 13C_based_lMOMA_ROOM.ipynb └── LICENSE /requirements.txt: -------------------------------------------------------------------------------- 1 | -e . 2 | -------------------------------------------------------------------------------- /docs/source/quickstart.rst: -------------------------------------------------------------------------------- 1 | Quick start 2 | =========== -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Driven 2 | ====== 3 | 4 | Data-Driven Constraint-based analysis -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [wheel] 2 | universal = 1 3 | 4 | [isort] 5 | not_skip = __init__.py 6 | indent = 4 7 | line_length = 120 8 | multi_line_output = 4 9 | known_third_party = future,six 10 | known_first_party = driven 11 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | Installation 2 | ============ 3 | 4 | Install driven is easy. First it needs a linear programming solver - *glpk*. And it also support **CPLEX**. 5 | For more information about that see [*optlang* documentation](http://github.com/biosustain/optlang). 6 | 7 | Next, use pip: 8 | 9 | `pip install driven` 10 | 11 | And you are read to go. -------------------------------------------------------------------------------- /docs/dependencis.rst: -------------------------------------------------------------------------------- 1 | Dependencies 2 | ============ 3 | 4 | Driven currently depends on the following packages: 5 | 6 | * cobra 7 | * ipython[all] 8 | * sympy 9 | * optlang 10 | * swiglpk 11 | * numpy 12 | * cameo 13 | * pandas 14 | * ipywidgets 15 | 16 | Optional packages: 17 | 18 | * cplex - enables CPLEX solver 19 | * ipyparallel - enables parallel computing on IPython -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | sudo: false 4 | 5 | python: 6 | - '2.7' 7 | - '3.4' 8 | - '3.5' 9 | - '3.6' 10 | 11 | branches: 12 | only: 13 | - master 14 | - devel 15 | - /^[0-9]+\.[0-9]+\.[0-9]+[.0-9ab]*$/ 16 | 17 | cache: 18 | - pip: true 19 | 20 | git: 21 | depth: 3 22 | 23 | before_install: 24 | - travis_retry pip install --upgrade pip setuptools wheel pytest pytest-cov 25 | 26 | install: 27 | - pip install . 28 | 29 | script: 30 | - pytest -v -rsx --cov --cov-report=xml 31 | 32 | after_success: 33 | - codecov 34 | 35 | notifications: 36 | slack: biosustain:8QjrEi8U59rrS3W8CtvOwc5T 37 | -------------------------------------------------------------------------------- /driven/generic/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /driven/flux_analysis/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /driven/vizualization/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /driven/network_analysis/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /driven/sensitivity_analysis/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /driven/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from driven import _cobra_ext 16 | -------------------------------------------------------------------------------- /driven/data_sets/pax_db.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | -------------------------------------------------------------------------------- /driven/flux_analysis/metrics.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | -------------------------------------------------------------------------------- /driven/flux_analysis/tn_seq.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | -------------------------------------------------------------------------------- /driven/config.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from driven.vizualization.plotting import plotting 15 | 16 | __all__ = ['plotting'] 17 | -------------------------------------------------------------------------------- /driven/data_sets/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from driven.data_sets.expression_profile import ExpressionProfile 17 | -------------------------------------------------------------------------------- /driven/flux_analysis/fit_objective/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from driven.flux_analysis.fit_objective.optimization import FitProfileStrategy 16 | -------------------------------------------------------------------------------- /driven/flux_analysis/proteomics.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | from driven.flux_analysis.transcriptomics import gimme, imat 18 | 19 | __all__ = ["gimme", "imat"] 20 | -------------------------------------------------------------------------------- /driven/stats.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | import math 15 | 16 | import numpy as np 17 | 18 | 19 | def iqr(sample): 20 | q75, q25 = np.percentile(sample, [75, 25]) 21 | return q75 - q25 22 | 23 | 24 | def freedman_diaconis(sample): 25 | n = len(sample) 26 | return 2 * iqr(sample) * math.pow(n, -1/3) 27 | -------------------------------------------------------------------------------- /driven/vizualization/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | GOLDEN_NUMBER = 1.618033988 16 | 17 | 18 | def golden_ratio(width, height): 19 | if width is None: 20 | width = int(height + height/GOLDEN_NUMBER) 21 | 22 | elif height is None: 23 | height = int(width/GOLDEN_NUMBER) 24 | 25 | return width, height 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | 47 | # Translations 48 | *.mo 49 | *.pot 50 | 51 | # Django stuff: 52 | *.log 53 | 54 | # Sphinx documentation 55 | docs/_build/ 56 | 57 | # PyBuilder 58 | target/ 59 | 60 | # PyCharm config 61 | .idea/ 62 | .env/ -------------------------------------------------------------------------------- /driven/generic/normalization.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | from math import log 18 | 19 | 20 | def log_plus_one(value, threshold=1e-6): 21 | if abs(value) <= threshold: 22 | return float(0) 23 | elif value > threshold: 24 | return float(log(value + 1)) 25 | elif value < threshold: 26 | return float(-log(abs(value) + 1)) 27 | -------------------------------------------------------------------------------- /driven/_cobra_ext.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | from sympy import Symbol 18 | from sympy.parsing.ast_parser import parse_expr 19 | 20 | from cobra import Reaction 21 | 22 | 23 | def __gene_to_expression__(reaction): 24 | local_dict = {g.id: Symbol(g.id) for g in reaction.genes} 25 | rule = reaction._gene_reaction_rule.replace("and", "+").replace("or", "*") 26 | return parse_expr(rule, local_dict) 27 | 28 | Reaction.gene_expression = __gene_to_expression__ 29 | -------------------------------------------------------------------------------- /driven/data_sets/normalization.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | from sympy import Add, Mul 18 | from sympy.functions.elementary.miscellaneous import Max, Min 19 | 20 | from cobra import Reaction 21 | 22 | 23 | def or2min_and2max(reaction, gene_values): 24 | assert isinstance(reaction, Reaction) 25 | assert isinstance(gene_values, dict) 26 | expression = reaction.gene_expression() 27 | expression = expression.replace(Mul, Max).replace(Add, Min) 28 | return expression.subs(gene_values).evalf() 29 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Driven 2 | ===== 3 | 4 | |Documentation Status||Build Status||Coverage Status| 5 | 6 | **Driven** is a high-level python library developed to integrate and 7 | analyze *omics* data using constraint-based modeling. The library provides 8 | a state-of-the-art simulation methods, access to models and workflows to 9 | easy analyze the most common data-types. 10 | 11 | Integration with **escher** allows easy visualization of results, comparison 12 | between different conditions or methods. 13 | 14 | Table of Contents 15 | ----------------- 16 | 17 | .. toctree:: 18 | :maxdepth: 2 19 | 20 | dependencies 21 | installation 22 | API 23 | 24 | Indices and tables 25 | ------------------ 26 | 27 | * :ref:`genindex` 28 | * :ref:`modindex` 29 | * :ref:`search` 30 | 31 | 32 | .. |Documentation Status| image:: https://readthedocs.org/projects/driven/badge/?version=master 33 | :target: https://readthedocs.org/projects/driven/?badge=master 34 | .. |Build Status| image:: https://travis-ci.org/biosustain/driven.svg?branch=master 35 | :target: https://travis-ci.org/biosustain/driven 36 | .. |Coverage Status| image:: https://coveralls.io/repos/biosustain/driven/badge.svg?branch=master 37 | :target: https://coveralls.io/r/biosustain/driven?branch=master 38 | -------------------------------------------------------------------------------- /driven/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | def all_same(seq): 17 | """ 18 | Determines whether all the elements in a sequence are the same. 19 | 20 | seq: list 21 | """ 22 | 23 | # Compare all the elements to the first in the sequence, 24 | # then do a logical and (min) to see if they all matched. 25 | return min([elem == seq[0] for elem in seq]+[True]) 26 | 27 | 28 | def get_common_start(*seq_list): 29 | """ 30 | Returns the common prefix of a list of sequences. 31 | 32 | Raises 33 | an exception if the list is empty. 34 | """ 35 | m = [all_same(seq) for seq in zip(*seq_list)] # Map the matching elements 36 | m.append(False) # Guard in case all the sequences match 37 | return seq_list[0][0:m.index(False)] # Truncate before first mismatch 38 | -------------------------------------------------------------------------------- /driven/flux_analysis/fit_objective/generators.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | __all__ = ["zero_one_binary_generator", "zero_one_linear_generator"] 18 | 19 | 20 | def zero_one_binary_generator(random, args): 21 | max_objectives = args.get('max_objectives', 5) 22 | representation = args.get('representation') 23 | individual = [0 for _ in representation] 24 | for i in range(len(representation) - 1): 25 | individual[i] = 0 if random.random() < 0.5 else 1 if individual.count(1) <= max_objectives else 0 26 | 27 | return individual 28 | 29 | 30 | def zero_one_linear_generator(random, args): 31 | max_objectives = args.get('max_objectives', 5) 32 | representation = args.get('representation') 33 | individual = [0 for _ in representation] 34 | for i in range(len(representation) - 1): 35 | individual[i] = 0 if random.random() < 0.5 else random.random() if individual.count(1) <= max_objectives else 0 36 | 37 | return individual 38 | -------------------------------------------------------------------------------- /driven/flux_analysis/fit_objective/variators.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | __all__ = ["zero_one_binary_variator", "zero_one_linear_variator"] 18 | 19 | 20 | def zero_one_binary_variator(random, candidates, args): 21 | mutation_rate = args.get("mutation_rate", 0.15) 22 | new_candidates = [None for _ in candidates] 23 | for i, c in enumerate(candidates): 24 | new_candidate = [0 for _ in c] 25 | for j, v in enumerate(c): 26 | new_candidate[j] = v if random.random() < mutation_rate else 1 if random.random() < 0.5 else 0 27 | new_candidates[i] = new_candidate 28 | 29 | return new_candidates 30 | 31 | 32 | def zero_one_linear_variator(random, candidates, args): 33 | mutation_rate = args.get("mutation_rate", 0.15) 34 | new_candidates = [None for _ in candidates] 35 | for i, c in enumerate(candidates): 36 | new_candidates[i] = [v if random.random() < mutation_rate else random.random() for j, v in enumerate(c)] 37 | 38 | return new_candidates 39 | -------------------------------------------------------------------------------- /driven/vizualization/plotting/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from __future__ import absolute_import 15 | 16 | import six 17 | 18 | from driven.vizualization.plotting.abstract import Plotter 19 | 20 | __all__ = ["plotting"] 21 | 22 | _engine = None 23 | _engines = {} 24 | 25 | try: 26 | from driven.vizualization.plotting.with_bokeh import BokehPlotter 27 | _engine = BokehPlotter() 28 | _engines["bokeh"] = BokehPlotter 29 | except ImportError: 30 | pass 31 | 32 | try: 33 | from driven.vizualization.plotting.with_ggplot import GGPlotPlotter 34 | _engine = GGPlotPlotter() if _engine is None else _engine 35 | _engines["ggplot"] = GGPlotPlotter 36 | except (ImportError, RuntimeError): 37 | pass 38 | 39 | 40 | class _plotting: 41 | def __init__(self, engine): 42 | self.__dict__['_engine'] = engine 43 | 44 | def __getattr__(self, item): 45 | if item not in ["_engine", "engine"]: 46 | return getattr(self.__dict__['_engine'], item) 47 | else: 48 | return self.__dict__['_engine'] 49 | 50 | def __setattr__(self, key, item): 51 | if key not in ["_engine", "engine"]: 52 | raise KeyError(key) 53 | else: 54 | if isinstance(item, six.string_types): 55 | item = _engines[item]() 56 | 57 | if not isinstance(item, Plotter): 58 | raise AssertionError("Invalid engine %s" % item) 59 | 60 | self.__dict__['_engine'] = item 61 | 62 | 63 | plotting = _plotting(_engine) 64 | -------------------------------------------------------------------------------- /driven/flux_analysis/fluxomics.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | from cobra import Model 18 | from driven.data_sets.fluxes import FluxConstraints 19 | from driven.flux_analysis.results import FluxBasedFluxDistribution 20 | 21 | 22 | def fba(model, objective=None, distribution=None, relax=0.01, *args, **kwargs): 23 | """ 24 | Runs a Flux Balance Analysis using a set of measured fluxes. 25 | 26 | Arguments 27 | --------- 28 | 29 | model : cobra.Model 30 | A constraint-based model 31 | distribution : FluxConstraints 32 | A set of experimental or computational determined flux constraints 33 | objective : objective 34 | Optional objective for the model 35 | relax : float 36 | A relax value to make the computation feasible 37 | """ 38 | if not isinstance(model, Model): 39 | raise ValueError("Argument model must be instance of SolverBasedModel, not %s" % model.__class__) 40 | if not isinstance(distribution, FluxConstraints): 41 | raise ValueError("Argument distribution must be instance of FluxConstraints, not %s" % distribution.__class__) 42 | 43 | with model: 44 | for reaction_id in distribution: 45 | reaction = model.reactions.get_by_id(reaction_id) 46 | bounds = distribution[reaction_id] 47 | reaction.bounds = bounds[0] - bounds[0] * relax, bounds[1] + bounds[1] * relax 48 | if objective is not None: 49 | model.objective = objective 50 | 51 | solution = model.optimize() 52 | 53 | return FluxBasedFluxDistribution(solution.fluxes, distribution) # TODO bug here, missing arg 54 | -------------------------------------------------------------------------------- /driven/vizualization/plotting/abstract.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from driven.vizualization.utils import golden_ratio 15 | 16 | 17 | class Plotter(object): 18 | __default_options__ = { 19 | 'palette': 'Spectral', 20 | 'width': 800, 21 | 'color': "#AFDCEC", 22 | } 23 | 24 | def __init__(self, **defaults): 25 | self.__default_options__.update(defaults) 26 | 27 | def _palette(self, palette, *args, **kwargs): 28 | raise NotImplementedError 29 | 30 | def histogram(self, dataframe, bins=100, width=None, height=None, palette=None, title='Histogram', values=None, 31 | groups=None, legend=True): 32 | raise NotImplementedError 33 | 34 | def scatter(self, dataframe, x=None, y=None, width=None, height=None, color=None, title='Scatter', 35 | xaxis_label=None, yaxis_label=None, label=None): 36 | raise NotImplementedError 37 | 38 | def heatmap(self, dataframe, y=None, x=None, values=None, width=None, height=None, 39 | max_color=None, min_color=None, mid_color=None, title='Heatmap'): 40 | raise NotImplementedError 41 | 42 | def line(self, dataframe, x=None, y=None, width=None, height=None, groups=None, title="Line"): 43 | raise NotImplementedError 44 | 45 | def boxplot(self, dataframe, values='value', groups=None, width=None, height=None, palette=None, 46 | title="BoxPlot", legend=True): 47 | raise NotImplementedError 48 | 49 | @staticmethod 50 | def _width_height(width, height): 51 | if width is None or height is None: 52 | return golden_ratio(width, height) 53 | else: 54 | return width, height 55 | 56 | @classmethod 57 | def display(cls, plot): 58 | raise NotImplementedError 59 | -------------------------------------------------------------------------------- /tests/test_data_sets.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | import unittest 15 | 16 | import numpy as np 17 | 18 | from driven.data_sets.expression_profile import ExpressionProfile 19 | from driven.data_sets.fluxes import FluxConstraints 20 | 21 | 22 | class ExpressionProfileTestCase(unittest.TestCase): 23 | def test_difference(self): 24 | genes = ["G1"] 25 | conditions = ["T1", "T2", "T3", "T4"] 26 | 27 | expression = np.zeros((1, 4)) 28 | expression[0] = [10, 11, 65, 109] 29 | pvalues = np.zeros((1, 3)) 30 | pvalues[0] = [0.02, 0.048, 0.0012] 31 | 32 | profile = ExpressionProfile(genes, conditions, expression, pvalues) 33 | 34 | self.assertEqual(profile.differences(), {"G1": [0, 0, 1]}) 35 | 36 | def test_export_import(self): 37 | genes = ["G1"] 38 | 39 | conditions = ["T1", "T2", "T3", "T4"] 40 | 41 | expression = np.zeros((1, 4)) 42 | expression[0] = [10, 11, 65, 109] 43 | 44 | profile = ExpressionProfile(genes, conditions, expression) 45 | data_frame = profile.data_frame 46 | 47 | new_profile = ExpressionProfile.from_data_frame(data_frame) 48 | 49 | self.assertEqual(profile, new_profile) 50 | 51 | 52 | class FluxConstraintsTestCase(unittest.TestCase): 53 | def test_export_import(self): 54 | reaction_ids = ["R1", "R2", "R3"] 55 | limits = np.zeros((3, 2)) 56 | limits[0] = [0, 10] 57 | limits[1] = [0.5, 0.7] 58 | limits[2] = [5.1, 5.2] 59 | flux_constraints = FluxConstraints(reaction_ids, limits) 60 | 61 | new_flux_constraints = FluxConstraints.from_data_frame(flux_constraints.data_frame, type="constraints") 62 | 63 | print(new_flux_constraints.data_frame) 64 | 65 | self.assertEqual(flux_constraints, new_flux_constraints) 66 | 67 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2013 Novo Nordisk Foundation Center for Biosustainability, 3 | # Technical University of Denmark. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from __future__ import absolute_import, print_function 18 | 19 | from setuptools import setup, find_packages 20 | import os 21 | 22 | on_rtd = os.environ.get('READTHEDOCS', None) == 'True' 23 | if on_rtd: 24 | requirements = ["numpydoc>=0.5"] 25 | else: 26 | requirements = [ 27 | 'cameo>=0.11.0', 28 | 'sympy>=0.7.5', 29 | 'cobra>=0.6.2', 30 | 'ipython>=4.0', 31 | 'numpy>=1.9.2', 32 | 'ggplot', 33 | 'six>=1.9.0', 34 | 'pandas>=0.16.2' 35 | ] 36 | 37 | setup( 38 | name='driven', 39 | version="0.0.3", 40 | packages=find_packages(), 41 | install_requires=requirements, 42 | include_package_data=True, 43 | author='Joao Cardoso', 44 | author_email='jooaaoo@gmail.com', 45 | description='driven - data-driven constraint-based analysis', 46 | license='Apache License Version 2.0', 47 | keywords='biology metabolism bioinformatics high-throughput omics', 48 | url='http://driven.bio', 49 | long_description="A package for data-driven modeling and analysis. It implements novel and state-of-the-art methods" 50 | " to integrate 'omics' data in genome-scale methods.", 51 | classifiers=[ 52 | 'Development Status :: 4 - Beta', 53 | 'Intended Audience :: Education', 54 | 'Intended Audience :: Healthcare Industry', 55 | 'Intended Audience :: Science/Research', 56 | 'Topic :: Scientific/Engineering :: Bio-Informatics', 57 | 'Topic :: Utilities', 58 | 'Programming Language :: Python :: 2.6', 59 | 'Programming Language :: Python :: 2.7', 60 | 'Programming Language :: Python :: 3.4', 61 | 'License :: OSI Approved :: Apache Software License' 62 | ], 63 | ) 64 | -------------------------------------------------------------------------------- /driven/vizualization/plotting/with_plotly.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from warnings import warn 15 | 16 | from plotly.graph_objs import Figure, Layout, Scatter 17 | 18 | from driven.vizualization.plotting import Plotter 19 | 20 | 21 | class PlotlyPlotter(Plotter): 22 | 23 | def __init__(self, **defaults): 24 | warn("Plotly requires configuration before start (https://plot.ly/python/getting-started/)") 25 | super(PlotlyPlotter, self).__init__(**defaults) 26 | 27 | def scatter(self, dataframe, x=None, y=None, width=None, height=None, color=None, title='Scatter', xaxis_label=None, 28 | yaxis_label=None, label=None): 29 | 30 | color = self.__default_options__.get('color', None) if color is None else color 31 | width = self.__default_options__.get('width', None) if width is None else width 32 | 33 | scatter = Scatter(x=dataframe[x], 34 | y=dataframe[y], 35 | mode='markers', 36 | marker=dict(color=color)) 37 | 38 | if label: 39 | scatter['text'] = dataframe[label] 40 | 41 | width, height = self._width_height(width, height) 42 | 43 | layout = Layout(title=title, 44 | width=width, 45 | height=height) 46 | 47 | if xaxis_label: 48 | layout['xaxis'] = dict(title=xaxis_label) 49 | 50 | if yaxis_label: 51 | layout['yaxis'] = dict(title=yaxis_label) 52 | 53 | return Figure(data=[scatter], layout=layout) 54 | 55 | def histogram(self, dataframe, bins=100, width=None, height=None, palette=None, title='Histogram', values=None, 56 | groups=None, legend=True): 57 | pass 58 | 59 | @classmethod 60 | def display(cls, plot): 61 | pass 62 | 63 | def heatmap(self, dataframe, y=None, x=None, values=None, width=None, height=None, max_color=None, min_color=None, 64 | mid_color=None, title='Heatmap'): 65 | pass 66 | 67 | def _palette(self, palette, *args, **kwargs): 68 | pass 69 | -------------------------------------------------------------------------------- /driven/flux_analysis/fit_objective/evaluators.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | import sympy 18 | 19 | from cobra import Reaction 20 | from cobra.flux_analysis import find_essential_genes 21 | 22 | __all__ = ["essential_genes_profile_evaluator", "essential_reactions_profile_evaluator"] 23 | 24 | One = sympy.singleton.S.One 25 | Add = sympy.Add._from_args 26 | Mul = sympy.Mul._from_args 27 | Real = sympy.RealNumber 28 | 29 | 30 | def _essential_profile_assertion_score(actual, expected): 31 | score = 0 32 | for key in actual: 33 | exp = expected.get(key, False) 34 | if exp == actual[key]: 35 | score += 1 36 | return float(score) 37 | 38 | 39 | def essential_genes_profile_evaluator(model, coefficients, candidates, essential, use_reactions=True): 40 | total = float(len(model.genes)) 41 | with model: 42 | _set_objective(model, coefficients, candidates, use_reactions) 43 | predicted_essential = find_essential_genes(model) 44 | actual = {g.id: g in predicted_essential for g in model.genes} 45 | return total - _essential_profile_assertion_score(actual, essential) 46 | 47 | 48 | def essential_reactions_profile_evaluator(model, coefficients, candidates, essential, use_reactions=True): 49 | total = float(len(model.reactions) - len(model.exchanges)) 50 | with model: 51 | _set_objective(model, coefficients, candidates, use_reactions) 52 | predicted_essential = model.essential_reactions() 53 | actual = {r.id: r in predicted_essential for r in model.reactions if r not in model.exchanges} 54 | return total - _essential_profile_assertion_score(actual, essential) 55 | 56 | 57 | def _set_objective(model, coefficients, candidates, use_reactions): 58 | if use_reactions: 59 | obj = Add([Mul([Real(coeff), react.flux_expression]) for react, coeff in zip(candidates, coefficients)]) 60 | else: 61 | obj = Reaction("make_metabolites") 62 | obj.add_metabolites({met: coeff for met, coeff in zip(candidates, coefficients) if coeff != 0}) 63 | model.add_reactions([obj]) 64 | model.objective = obj 65 | -------------------------------------------------------------------------------- /driven/vizualization/escher_viewer.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | import os 18 | 19 | import numpy as np 20 | import six 21 | from IPython.display import display 22 | from pandas import DataFrame 23 | 24 | from cameo.visualization.escher_ext import NotebookBuilder 25 | 26 | 27 | class EscherViewer(object): 28 | def __init__(self, data_frame, map_name, color_scales, normalization_functions): 29 | assert isinstance(data_frame, DataFrame) 30 | self.data_frame = data_frame 31 | self.map_name = map_name 32 | self.builder = None 33 | self.color_scales = color_scales 34 | self.normalization_functions = normalization_functions 35 | 36 | def __call__(self, column): 37 | reaction_data = dict(self.data_frame.dropna()[column].apply(self.normalization_functions[column])) 38 | reaction_data = {r: v for r, v in six.iteritems(reaction_data) if v is not None} 39 | reaction_data = {r: v for r, v in six.iteritems(reaction_data) if v is not np.nan} 40 | reaction_scale = self.color_scales[column] 41 | if self.builder is None: 42 | self._init_builder(reaction_data, reaction_scale) 43 | else: 44 | self.builder.update(reaction_data=reaction_data, reaction_scale=reaction_scale) 45 | 46 | def _init_builder(self, reaction_data, reaction_scale): 47 | if os.path.isfile(self.map_name): 48 | self.builder = NotebookBuilder(map_json=self.map_name, 49 | reaction_data=reaction_data, 50 | reaction_scale=reaction_scale, 51 | reaction_no_data_color="lightgray", 52 | reaction_no_data_size=5) 53 | else: 54 | self.builder = NotebookBuilder(map_name=self.map_name, 55 | reaction_data=reaction_data, 56 | reaction_scale=reaction_scale, 57 | reaction_no_data_color="lightgray", 58 | reaction_no_data_size=5) 59 | display(self.builder.display_in_notebook()) 60 | -------------------------------------------------------------------------------- /driven/data_sets/fluxes.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | from numpy import ndarray 18 | from pandas import DataFrame 19 | 20 | 21 | class FluxConstraints(object): 22 | 23 | @classmethod 24 | def from_csv(cls, file_path, type="measurement"): 25 | return cls.from_data_frame(DataFrame.from_csv(file_path), type=type) 26 | 27 | @classmethod 28 | def from_data_frame(cls, data_frame, type="measurement"): 29 | reaction_ids = list(data_frame.index.values) 30 | if type == "measurement": 31 | limits = data_frame.apply(lambda x: [x["value"]-x["deviation"], x["value"]+x["deviation"]], axis=1).values 32 | elif type == "constraints": 33 | limits = data_frame.apply(lambda x: [x["lower_limit"], x["upper_limit"]], axis=1).values 34 | else: 35 | raise ValueError("Invalid input type %s" % type) 36 | 37 | return FluxConstraints(reaction_ids, limits) 38 | 39 | def __init__(self, reaction_ids, limits): 40 | assert isinstance(reaction_ids, list), "Invalid class for reactions_ids %s" % type(reaction_ids) 41 | assert isinstance(limits, ndarray), "Invalid class for limits %s" % type(limits) 42 | assert limits.shape == (len(reaction_ids), 2) 43 | self.reaction_ids = reaction_ids 44 | self._reaction_id_index = {rid: i for i, rid in enumerate(reaction_ids)} 45 | self.limits = limits 46 | 47 | def __getitem__(self, item): 48 | if isinstance(item, int): 49 | index = item 50 | elif isinstance(item, str): 51 | index = self._reaction_id_index[item] 52 | else: 53 | raise ValueError("Invalid value %s for retrieving reaction limits. Use either index or key" % item) 54 | 55 | return self.limits[index, :] 56 | 57 | def __iter__(self): 58 | return iter(self.reaction_ids) 59 | 60 | def __eq__(self, other): 61 | if not isinstance(other, FluxConstraints): 62 | return False 63 | else: 64 | return self.reaction_ids == other.reaction_ids and (self.limits == other.limits).all() 65 | 66 | def _repr_html_(self): 67 | return self.data_frame._repr_html_() 68 | 69 | @property 70 | def data_frame(self): 71 | return DataFrame(self.limits, index=self.reaction_ids, columns=["lower_limit", "upper_limit"]) 72 | -------------------------------------------------------------------------------- /driven/flux_analysis/profiling.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | from cobra.manipulation.delete import find_gene_knockout_reactions 18 | 19 | __all__ = ["ReactionKnockoutProfiler", "GeneKnockoutProfiler"] 20 | 21 | 22 | class KnockoutProfiler(object): 23 | def __init__(self, model=None, simulation_method=None): 24 | self._model = model 25 | self._simulation_method = simulation_method 26 | 27 | def profile(self, elements, *args, **kwargs): 28 | return {e.id: self.simulate_knockout(e, *args, **kwargs) for e in elements} 29 | 30 | def simulate_knockout(self, to_knockout, *args, **kwargs): 31 | raise NotImplementedError 32 | 33 | 34 | class ReactionKnockoutProfiler(KnockoutProfiler): 35 | def __init__(self, *args, **kwargs): 36 | super(ReactionKnockoutProfiler, self).__init__(*args, **kwargs) 37 | 38 | def simulate_knockout(self, to_knockout, *args, **kwargs): 39 | cache = { 40 | "variables": {}, 41 | "constraints": {}, 42 | "first_run": True 43 | } 44 | 45 | with self._model: 46 | to_knockout.knock_out() 47 | return self._simulation_method(self._model, 48 | volatile=False, 49 | cache=cache, 50 | *args, 51 | **kwargs)[cache['original_objective']] 52 | 53 | 54 | class GeneKnockoutProfiler(KnockoutProfiler): 55 | def __init__(self, *args, **kwargs): 56 | super(GeneKnockoutProfiler, self).__init__(*args, **kwargs) 57 | 58 | def simulate_knockout(self, to_knockout, *args, **kwargs): 59 | reactions = find_gene_knockout_reactions(self._model, [to_knockout]) 60 | cache = { 61 | "variables": {}, 62 | "constraints": {}, 63 | "first_run": True 64 | } 65 | 66 | with self._model: 67 | for reaction in reactions: 68 | reaction.knock_out() 69 | 70 | return self._simulation_method(self._model, 71 | volatile=False, 72 | cache=cache, 73 | *args, 74 | **kwargs)[cache['original_objective']] 75 | -------------------------------------------------------------------------------- /driven/flux_analysis/thermodynamics.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 3 | 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from __future__ import absolute_import, print_function 17 | 18 | 19 | def tmfa(model, objective=None, delta_gs=None, K=None, *args, **kwargs): 20 | """ 21 | Thermodynamics-based Metabolic Flux Analysis. [1] 22 | 23 | Arguments 24 | --------- 25 | 26 | objective: a compatible objective 27 | The objective function of the simulation 28 | delta_gs: dict 29 | The Gibbs energy of the reactions 30 | K: number 31 | The feasible Gibbs energy 32 | 33 | References 34 | ---------- 35 | .. [1] Henry, C. S., Broadbelt, L. J. and Hatzimanikatis, V. (2007). Thermodynamics-based metabolic flux analysis. 36 | Biophysical Journal, 92(5), 1792–1805. doi:10.1529/biophysj.106.093138 37 | """ 38 | variables = [] 39 | constraints = [] 40 | original_objective = model.objective.expression 41 | try: 42 | for reaction in model.reactions: 43 | if reaction.id in delta_gs: 44 | z = model.solver.interface.Variable("z_%s" % reaction.id, type='binary') 45 | variables.append(z) 46 | 47 | k_constraint = model.solver.interface.Constraint(delta_gs[reaction.id] - K + K*z, 48 | ub=0, 49 | name="second_law_constraint_%s" % reaction.id, 50 | sloppy=True) 51 | 52 | flux_constraint = model.solver.interface.Constraint(z * reaction.upper_bound - reaction.flux_expression, 53 | lb=0, 54 | name="thermo_flux_constraint_%s" % reaction.id, 55 | sloppy=True) 56 | 57 | constraints.append([k_constraint, flux_constraint]) 58 | # TODO: Not sure what this is meant to do.. 59 | # with TimeMachine() as tm: 60 | # tm(do=partial(setattr, model, 'objective', objective), 61 | # undo=partial(setattr, model, 'objective', model.objective.expression)) 62 | # tm(do=partial(model.solver.add, variables), 63 | # undo=partial(model.solver.remove, variables)) 64 | # tm(do=partial(model.solver.add, constraints), 65 | # undo=partial(model.solver.remove, constraints)) 66 | 67 | finally: 68 | model.solver._remove_constraints(constraints) 69 | model.solver._remove_variables(variables) 70 | model.objective = original_objective 71 | -------------------------------------------------------------------------------- /tests/assets/blazier_et_al_2012.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Model and expression sets used by Anna S. Blazier and Jason A. Papin in their review. 17 | 18 | Blazier AS and Papin JA (2012) Integration of expression data in genome-scale metabolic network reconstructions. 19 | Front. Physio. 3:299. doi: 10.3389/fphys.2012.00299 20 | """ 21 | 22 | 23 | from cobra import Model, Reaction 24 | from cobra import Metabolite 25 | from driven.data_sets.expression_profile import ExpressionProfile 26 | import numpy as np 27 | 28 | 29 | def build_model(): 30 | m = Model("Blazier et al 2012") 31 | m1_e = Metabolite("M1_e") 32 | m1 = Metabolite("M1") 33 | m2 = Metabolite("M2") 34 | m3 = Metabolite("M3") 35 | m4_e = Metabolite("M4_e") 36 | m4 = Metabolite("M4") 37 | m5 = Metabolite("M5") 38 | 39 | r1 = Reaction("R1") 40 | r1.add_metabolites({m1_e: -1, m1: 1}) 41 | 42 | r2 = Reaction("R2") 43 | r2.add_metabolites({m1: -1, m2: 1}) 44 | r2.gene_reaction_rule = "Gene2" 45 | 46 | r3 = Reaction("R3") 47 | r3.add_metabolites({m2: -1, m3: 1}) 48 | r3.gene_reaction_rule = "Gene3" 49 | 50 | r4 = Reaction("R4") 51 | r4.add_metabolites({m3: -1}) 52 | 53 | r5 = Reaction("R5") 54 | r5.add_metabolites({m4_e: -1, m4: 1}) 55 | 56 | r6 = Reaction("R6") 57 | r6.add_metabolites({m4: -1, m5: 1}) 58 | r6.gene_reaction_rule = "Gene6" 59 | 60 | r7 = Reaction("R7") 61 | r7.add_metabolites({m5: -1, m2: 1}) 62 | r7.lower_bound = -r7.upper_bound 63 | r7.gene_reaction_rule = "Gene7" 64 | 65 | r8 = Reaction("R8") 66 | r8.add_metabolites({m5: -1}) 67 | 68 | m.add_reactions([r1, r2, r3, r4, r5, r6, r7, r8]) 69 | 70 | EX_M1_e = m.add_boundary(m1_e) 71 | EX_M1_e.lower_bound = -10 72 | 73 | EX_M4_e = m.add_boundary(m4_e) 74 | EX_M4_e.lower_bound = -10 75 | 76 | m.objective = r4 77 | 78 | return m 79 | 80 | 81 | def build_expression_profile(): 82 | expression = np.zeros((4, 3)) 83 | expression[0, 0] = 0.17 84 | expression[0, 1] = 0.20 85 | expression[0, 2] = 0.93 86 | expression[1, 0] = 0.36 87 | expression[1, 1] = 0.83 88 | expression[1, 2] = 0.77 89 | expression[2, 0] = 0.87 90 | expression[2, 1] = 0.65 91 | expression[2, 2] = 0.07 92 | expression[3, 0] = 0.55 93 | expression[3, 1] = 0.49 94 | expression[3, 2] = 0.52 95 | 96 | genes = ["Gene2", "Gene3", "Gene6", "Gene7"] 97 | conditions = ["Exp#1", "Exp#2", "Exp#3"] 98 | 99 | return ExpressionProfile(genes, conditions, expression) 100 | 101 | model = build_model() 102 | 103 | expression_profile = build_expression_profile() 104 | 105 | -------------------------------------------------------------------------------- /driven/sensitivity_analysis/flux_analysis.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | from functools import partial as p 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | import six 17 | from pandas import DataFrame 18 | 19 | from cameo.util import TimeMachine 20 | from cobra import Model 21 | from driven.data_sets.expression_profile import ExpressionProfile 22 | from driven.vizualization.plotting import plotting 23 | 24 | 25 | def expression_sensitivity_analysis(method, model, expression_profile, metrics, condition_exchanges=None, 26 | condition_knockouts=None, growth_rates=None, growth_rates_std=None, 27 | growth_reaction=None, **kwargs): 28 | 29 | assert isinstance(model, Model) 30 | assert isinstance(expression_profile, ExpressionProfile) 31 | if condition_exchanges is None: 32 | condition_exchanges = {} 33 | if condition_knockouts is None: 34 | condition_knockouts = {} 35 | 36 | data_frames = [DataFrame(columns=["x", "y", "condition"]) for _ in metrics] 37 | 38 | for condition in expression_profile.conditions: 39 | with TimeMachine() as tm: 40 | for exchange_condition, ex in six.iteritems(condition_exchanges): 41 | if exchange_condition == condition: 42 | tm(do=p(setattr, ex, "lower_bound", -10), undo=p(setattr, ex, "lower_bound", ex.lower_bound)) 43 | else: 44 | tm(do=p(setattr, ex, "lower_bound", 0), undo=p(setattr, ex, "lower_bound", ex.lower_bound)) 45 | 46 | for knockout in condition_knockouts.get(condition, []): 47 | model.reactions.get_by_id(knockout).knock_out(tm) 48 | 49 | if growth_reaction is not None: 50 | growth_rate = growth_rates[condition] 51 | growth_std = growth_rates_std[condition] 52 | if isinstance(growth_reaction, str): 53 | growth_reaction = model.reactions.get_by_id(growth_reaction) 54 | 55 | tm(do=p(setattr, growth_reaction, "lower_bound", growth_rate-growth_std), 56 | undo=p(setattr, growth_reaction, "lower_bound", growth_reaction.upper_bound)) 57 | tm(do=p(setattr, growth_reaction, "upper_bound", growth_rate+growth_std), 58 | undo=p(setattr, growth_reaction, "upper_bound", growth_reaction.upper_bound)) 59 | min_val, max_val = expression_profile.minmax(condition) 60 | binwidth = expression_profile.binwidth(condition) 61 | 62 | for i, exp in enumerate(range(min_val, max_val, binwidth)): 63 | res = method(model, expression_profile=expression_profile, condition=condition, cutoff=exp, **kwargs) 64 | for j, metric in enumerate(metrics): 65 | data_frames[j].loc[i] = [exp, getattr(res, metric), metric] 66 | 67 | for i, metric in enumerate(metrics): 68 | plotting.line(data_frames[i], x=metric, y="cutoff") 69 | -------------------------------------------------------------------------------- /tests/assets/zur_et_al_2010.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Model and expression sets used by Hadas Zur, Eytan Ruppin and Tomer Shlomi in iMAT publication. 17 | 18 | Zur, Hadas; Ruppin, Eytan and Shlomi, Tomer (2010) iMAT: an integrative metabolic analysis tool. 19 | Bioinformatics 26 (24): 3140-3142. doi: 10.1093/bioinformatics/btq602 20 | """ 21 | 22 | from __future__ import print_function, absolute_import 23 | from warnings import warn 24 | 25 | from cobra import Model, Reaction, Metabolite 26 | from driven.data_sets.expression_profile import ExpressionProfile 27 | import numpy as np 28 | 29 | 30 | def build_model(): 31 | m = Model("Zur et al 2012") 32 | 33 | m1 = Metabolite("M1") 34 | m2 = Metabolite("M2") 35 | m3 = Metabolite("M3") 36 | m4 = Metabolite("M4") 37 | m5 = Metabolite("M5") 38 | m6 = Metabolite("M6") 39 | m7 = Metabolite("M7") 40 | m8 = Metabolite("M8") 41 | m9 = Metabolite("M9") 42 | m10 = Metabolite("M10") 43 | 44 | r1 = Reaction("R1") 45 | r1.add_metabolites({m3: 1}) 46 | 47 | r2 = Reaction("R2") 48 | r2.add_metabolites({m1: 1}) 49 | r2.gene_reaction_rule = "G1 or G2" 50 | 51 | r3 = Reaction("R3") 52 | r3.add_metabolites({m2: 1}) 53 | r3.gene_reaction_rule = "G5" 54 | 55 | r4 = Reaction("R4") 56 | r4.add_metabolites({m1: -1, m10: 1}) 57 | r4.lower_bound = -r4.upper_bound 58 | 59 | r5 = Reaction("R5") 60 | r5.add_metabolites({m10: -1, m4: 1}) 61 | r5.lower_bound = -r5.upper_bound 62 | 63 | r6 = Reaction("R6") 64 | r6.add_metabolites({m1: -1, m4: 1}) 65 | 66 | r7 = Reaction("R7") 67 | r7.add_metabolites({m1: -1, m2: -1, m5: 1, m6: 1}) 68 | r7.gene_reaction_rule = "G6" 69 | 70 | r8 = Reaction("R8") 71 | r8.add_metabolites({m3: -1, m4: -1, m7: 1, m8: 1}) 72 | r8.gene_reaction_rule = "G3" 73 | 74 | r9 = Reaction("R9") 75 | r9.add_metabolites({m5: -1}) 76 | 77 | r10 = Reaction("R10") 78 | r10.add_metabolites({m6: -1, m9: 1}) 79 | r10.gene_reaction_rule = "G7" 80 | 81 | r11 = Reaction("R11") 82 | r11.add_metabolites({m7: -1}) 83 | 84 | r12 = Reaction("R12") 85 | r12.add_metabolites({m8: -1}) 86 | r12.gene_reaction_rule = "G4" 87 | 88 | r13 = Reaction("R13") 89 | r13.add_metabolites({m9: -1}) 90 | 91 | m.add_reactions([r1, r2, r3, r4, r5, r6, r7, r8]) 92 | 93 | m.objective = r4 94 | 95 | return m 96 | 97 | 98 | def build_expression_profile(): 99 | warn("The profile is not correct because the picture is black and white (do not use this profile for testing)") 100 | expression = np.zeros((7, 1)) 101 | expression[0, 0] = .0 102 | expression[1, 0] = .0 103 | expression[2, 0] = .0 104 | expression[3, 0] = .0 105 | expression[4, 0] = .0 106 | expression[5, 0] = .0 107 | expression[6, 0] = .0 108 | 109 | genes = ["G1", "G2", "G3", "G4", "G5", "G6", "G7"] 110 | conditions = ["Exp"] 111 | 112 | return ExpressionProfile(genes, conditions, expression) 113 | 114 | model = build_model() 115 | 116 | expression_profile = build_expression_profile() -------------------------------------------------------------------------------- /driven/flux_analysis/fit_objective/optimization.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | from random import Random 18 | 19 | import sympy 20 | from inspyred.ec.emo import NSGA2, Pareto 21 | 22 | from cameo import config 23 | from driven.flux_analysis.fit_objective.generators import zero_one_binary_generator, zero_one_linear_generator 24 | from driven.flux_analysis.fit_objective.variators import zero_one_binary_variator, zero_one_linear_variator 25 | 26 | __all__ = ["FitProfileStrategy"] 27 | 28 | One = sympy.singleton.S.One 29 | Add = sympy.Add._from_args 30 | Mul = sympy.Mul._from_args 31 | Real = sympy.RealNumber 32 | 33 | 34 | def evaluate(model, candidates, coefficients, profiles, evaluators, **kwargs): 35 | if all(map(lambda v: v == 0, coefficients)): 36 | return Pareto([1000000] + [100000 for _ in profiles]) 37 | else: 38 | fitness_list = [f(model, coefficients, candidates, profile, **kwargs) for f, profile in zip(evaluators, profiles)] 39 | coefficient_sum = sum(coefficients) 40 | return Pareto([coefficient_sum] + fitness_list) 41 | 42 | 43 | def zero_one_bounder(candidate, args): 44 | for i, v in enumerate(candidate): 45 | candidate[i] = min(v, 1) if v >= 0 else 0 46 | return candidate 47 | 48 | 49 | class FitProfileStrategy(object): 50 | def __init__(self, profiles=None, evaluators=None, binary=True, use_reactions=True, model=None, 51 | heuristic_method=NSGA2, **kwargs): 52 | self._heuristic_method = heuristic_method(Random()) 53 | self.model = model 54 | 55 | if use_reactions: 56 | self.candidates = [r for r in self.model.exchanges if r.lower_bound >= 0] 57 | else: 58 | self.candidates = self.model.metabolites 59 | 60 | self.kwargs = dict(use_reactions=use_reactions) 61 | self.kwargs.update(kwargs) 62 | self.profiles = profiles or [] 63 | self.evaluators = evaluators or [] 64 | self.binary = binary 65 | if binary: 66 | self._heuristic_method.variator = zero_one_binary_variator 67 | self._generator = zero_one_binary_generator 68 | else: 69 | self._heuristic_method.variator = zero_one_linear_variator 70 | self._generator = zero_one_linear_generator 71 | 72 | def _evaluator(self, candidates, args): 73 | return [evaluate(self.model, self.candidates, coeffs, self.profiles, self.evaluators, **self.kwargs) 74 | for coeffs in candidates] 75 | 76 | def run(self, view=config.default_view, maximize=False, **kwargs): 77 | res = self._heuristic_method.evolve(generator=self._generator, 78 | maximize=maximize, 79 | representation=self.candidates, 80 | bounder=zero_one_bounder, 81 | evaluator=self._evaluator, 82 | binary=self.binary, 83 | view=view, 84 | **kwargs) 85 | return res 86 | -------------------------------------------------------------------------------- /driven/vizualization/plotting/with_ggplot.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | import collections 15 | 16 | import six 17 | from ggplot import ( 18 | aes, geom_histogram, geom_point, geom_tile, ggplot, ggtitle, scale_color_brewer, scale_colour_gradient2, 19 | scale_colour_manual, scale_x_continuous, scale_y_continuous) 20 | from matplotlib.ticker import Locator 21 | 22 | from driven.vizualization.plotting.abstract import Plotter 23 | 24 | Locator.MAXTICKS = 15000 25 | 26 | class gradient: 27 | def __init__(self, low, mid, high): 28 | self.low = low 29 | self.mid = mid 30 | self.high = high 31 | 32 | 33 | class GGPlotPlotter(Plotter): 34 | def __init__(self, **defaults): 35 | super(GGPlotPlotter, self).__init__(**defaults) 36 | 37 | def histogram(self, dataframe, bins=100, width=None, height=None, palette=None, title='Histogram', values=None, 38 | groups=None, legend=True): 39 | palette = self.__default_options__.get('palette', None) if palette is None else palette 40 | 41 | return ggplot(dataframe, aes(x=values, fill=groups, color=groups)) + \ 42 | geom_histogram(alpha=0.6, breaks=bins, position="fill") + \ 43 | self._palette(palette) + \ 44 | ggtitle(title) + \ 45 | scale_y_continuous(name="Count (%s)" % values) 46 | 47 | def scatter(self, dataframe, x=None, y=None, width=None, height=None, color=None, title='Scatter', xaxis_label=None, 48 | yaxis_label=None, label=None): 49 | color = self.__default_options__.get('palette', None) if color is None else color 50 | width = self.__default_options__.get('width', None) if width is None else width 51 | 52 | gg = ggplot(dataframe, aes(x, y)) + geom_point(color=color, alpha=0.6) + ggtitle(title) 53 | if xaxis_label: 54 | gg += scale_x_continuous(name=xaxis_label) 55 | if yaxis_label: 56 | gg += scale_y_continuous(name=xaxis_label) 57 | 58 | return gg 59 | 60 | def heatmap(self, dataframe, y=None, x=None, values=None, width=None, height=None, 61 | max_color=None, min_color=None, mid_color=None, title='Heatmap'): 62 | max_color = self.__default_options__.get('max_color', None) if max_color is None else max_color 63 | min_color = self.__default_options__.get('min_color', None) if min_color is None else min_color 64 | mid_color = self.__default_options__.get('mid_color', None) if mid_color is None else mid_color 65 | width = self.__default_options__.get('width', None) if width is None else width 66 | 67 | palette = gradient(min_color, mid_color, max_color) 68 | return ggplot(dataframe, aes(x=x, y=y, fill=values)) + \ 69 | geom_tile() + \ 70 | self._palette(palette, "div") 71 | 72 | def _palette(self, palette, type="seq", **kwargs): 73 | if isinstance(palette, six.string_types): 74 | return scale_color_brewer(type=type, palette=palette) 75 | elif isinstance(palette, gradient): 76 | return scale_colour_gradient2(low=palette.low, mid=palette.mid, high=palette.high) 77 | elif isinstance(palette, collections.Iterable): 78 | return scale_colour_manual(values=palette) 79 | 80 | @classmethod 81 | def display(cls, plot): 82 | pass 83 | -------------------------------------------------------------------------------- /tests/test_flux_analysis.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | import unittest 15 | import os 16 | from driven.flux_analysis.transcriptomics import gimme, imat 17 | 18 | import six 19 | 20 | if six.PY3: 21 | def execfile(path, globals=None, locals=None): 22 | exec(compile(open(path, "rb").read(), path, 'exec'), globals, locals) 23 | 24 | CUR_DIR = os.path.dirname(__file__) 25 | 26 | 27 | class TranscriptomicsTestCase(unittest.TestCase): 28 | def setUp(self): 29 | variables = {} 30 | 31 | # Blazier et al toy model and mock expression set can be use to test GIMME, iMAT, MADE, E-flux and PROM 32 | execfile(os.path.join(CUR_DIR, "assets", "blazier_et_al_2012.py"), variables) 33 | self._blazier_model = variables["model"] 34 | self._blazier_expression = variables["expression_profile"] 35 | 36 | # Toy model from iMAT publication 37 | execfile(os.path.join(CUR_DIR, "assets", "zur_et_al_2010.py"), variables) 38 | self._zur_et_al_model = variables["model"] 39 | self._zur_et_al_expression = variables["expression_profile"] 40 | 41 | def test_gimme(self): 42 | model = self._blazier_model 43 | gimme_res_025 = gimme(model=model, expression_profile=self._blazier_expression, 44 | cutoff=0.25, fraction_of_optimum=0.4) 45 | 46 | self.assertEqual(gimme_res_025.inconsistency_score, .0) 47 | gimme_res_050 = gimme(model=model, expression_profile=self._blazier_expression, 48 | cutoff=0.5, fraction_of_optimum=0.4) 49 | 50 | self.assertGreater(gimme_res_050.inconsistency_score, .0) 51 | 52 | def test_imat(self): 53 | model = self._blazier_model 54 | 55 | imat_res_025_075 = imat(model, self._blazier_expression, low_cutoff=0.25, high_cutoff=0.75, condition="Exp#2") 56 | 57 | self.assertTrue(all([imat_res_025_075[r] == 0 for r in ["R1", "R2"]])) 58 | # TODO: this failed in master as well, fix 59 | # self.assertTrue(all([imat_res_025_075[r] != 0 for r in ["R3", "R4", "R5", "R6", "R7", "R8"]])) 60 | 61 | imat_res_050_075 = imat(model, self._blazier_expression, low_cutoff=0.50, high_cutoff=0.75, condition="Exp#2") 62 | 63 | # NOTE: There are two states that maximize iMAT result in this model 64 | 65 | # self.assertTrue(all([imat_res_050_075[r] == 0 for r in ["R1", "R2", "R3", "R4"]])) 66 | # self.assertTrue(all([imat_res_050_075[r] != 0 for r in ["R5", "R7", "R6", "R8"]])) 67 | 68 | @unittest.skip("Not implemented") 69 | def test_made(self): 70 | raise NotImplementedError 71 | 72 | @unittest.skip("Not implemented") 73 | def test_eflux(self): 74 | raise NotImplementedError 75 | 76 | @unittest.skip("Not implemented") 77 | def test_relatch(self): 78 | raise NotImplementedError 79 | 80 | @unittest.skip("Not implemented") 81 | def test_gx_fba(self): 82 | raise NotImplementedError 83 | 84 | @unittest.skip("Not implemented") 85 | def test_prom(self): 86 | raise NotImplementedError 87 | 88 | 89 | class ThermodynamicsTestCase(unittest.TestCase): 90 | def setUp(self): 91 | pass 92 | 93 | def test_tmfa(self): 94 | pass 95 | 96 | 97 | class FluxomicsTestCase(unittest.TestCase): 98 | def setUp(self): 99 | pass 100 | 101 | @unittest.skip("Not implemented") 102 | def test_fba(self): 103 | raise 104 | 105 | 106 | class ResultTestCase(unittest.TestCase): 107 | pass 108 | 109 | 110 | -------------------------------------------------------------------------------- /driven/vizualization/plotting/with_bokeh.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import collections 16 | 17 | import six 18 | from bokeh.charts import BoxPlot, HeatMap, Histogram, Line, Scatter 19 | from bokeh.io import show 20 | from bokeh.models import GlyphRenderer, HoverTool 21 | from bokeh.palettes import brewer 22 | 23 | from driven.vizualization.plotting.abstract import Plotter 24 | 25 | TOOLS = 'pan,box_zoom,wheel_zoom,resize,reset,save' 26 | 27 | 28 | class BokehPlotter(Plotter): 29 | def __init__(self, **defaults): 30 | super(BokehPlotter, self).__init__(**defaults) 31 | 32 | def _palette(self, palette, number, **kwargs): 33 | if isinstance(palette, six.string_types): 34 | n = 3 if number < 3 else number 35 | return brewer[palette][n] 36 | elif isinstance(palette, collections.Iterable): 37 | return palette 38 | else: 39 | raise ValueError("Invalid palette %s" % palette) 40 | 41 | def histogram(self, dataframe, bins=None, width=None, height=None, palette=None, title='Histogram', values=None, 42 | groups=None, legend=True): 43 | palette = self.__default_options__.get('palette', None) if palette is None else palette 44 | width = self.__default_options__.get('width', None) if width is None else width 45 | 46 | if values: 47 | unique_values = dataframe[groups].unique() 48 | palette = self._palette(palette, len(unique_values)) 49 | else: 50 | palette = None 51 | 52 | width, height = self._width_height(width, height) 53 | 54 | histogram = Histogram(dataframe, values=values, color=groups, bins=bins, legend=True, width=width, 55 | height=height, palette=palette, title=title) 56 | 57 | return histogram 58 | 59 | def scatter(self, dataframe, x=None, y=None, width=None, height=None, color=None, title=None, 60 | xaxis_label=None, yaxis_label=None, label=None): 61 | color = self.__default_options__.get('color', None) if color is None else color 62 | width = self.__default_options__.get('width', None) if width is None else width 63 | 64 | width, height = self._width_height(width, height) 65 | 66 | scatter = Scatter(dataframe, x=x, y=y, width=width, height=height, color=color, title=title, 67 | tools=TOOLS + ',hover' if label else '') 68 | 69 | if label: 70 | hover = scatter.select_one(dict(type=HoverTool)) 71 | hover.tooltips = [("Id", "@%s" % label)] 72 | renderer = scatter.select_one(dict(type=GlyphRenderer)) 73 | renderer.data_source.data[label] = dataframe[label].tolist() 74 | 75 | if xaxis_label: 76 | scatter._xaxis.axis_label = xaxis_label 77 | if yaxis_label: 78 | scatter._yaxis.axis_label = yaxis_label 79 | 80 | return scatter 81 | 82 | def heatmap(self, dataframe, y=None, x=None, values=None, width=None, height=None, palette=None, 83 | max_color=None, min_color=None, mid_color=None, title='Heatmap', xaxis_label=None, yaxis_label=None): 84 | 85 | palette = self.__default_options__.get('palette', None) if palette is None else palette 86 | width = self.__default_options__.get('width', None) if width is None else width 87 | 88 | width, height = self._width_height(width, height) 89 | 90 | heatmap = HeatMap(dataframe, x=x, y=y, values=values, width=width, height=height, palette=palette, title=title) 91 | if xaxis_label: 92 | heatmap._xaxis.axis_label = xaxis_label 93 | if yaxis_label: 94 | heatmap._yaxis.axis_label = yaxis_label 95 | 96 | return heatmap 97 | 98 | def line(self, dataframe, x=None, y=None, width=None, height=None, groups=None, palette=None, title="Line", 99 | xaxis_label=None, yaxis_label=None): 100 | palette = self.__default_options__.get('palette', None) if palette is None else palette 101 | width = self.__default_options__.get('width', None) if width is None else width 102 | 103 | width, height = self._width_height(width, height) 104 | 105 | line = Line(dataframe, x=x, y=y, color=groups, width=width, height=height, palette=palette, title=title, 106 | legend=True) 107 | 108 | if xaxis_label: 109 | line._xaxis.axis_label = xaxis_label 110 | if yaxis_label: 111 | line._yaxis.axis_label = yaxis_label 112 | 113 | return line 114 | 115 | def boxplot(self, dataframe, values='value', groups=None, width=None, height=None, palette=None, 116 | title="BoxPlot", legend=True): 117 | 118 | palette = self.__default_options__.get('palette', None) if palette is None else palette 119 | width = self.__default_options__.get('width', None) if width is None else width 120 | 121 | if values: 122 | unique_values = dataframe[groups].unique() 123 | palette = self._palette(palette, len(unique_values)) 124 | else: 125 | palette = None 126 | 127 | width, height = self._width_height(width, height) 128 | 129 | boxplot = BoxPlot(dataframe, values=values, label=groups, color=groups, legend=True, width=width, 130 | height=height, palette=palette, title=title) 131 | 132 | return boxplot 133 | 134 | @classmethod 135 | def display(cls, plot): 136 | show(plot) 137 | -------------------------------------------------------------------------------- /notebooks/13C_based_lMOMA_ROOM.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "worksheets": [ 3 | { 4 | "cells": [ 5 | { 6 | "cell_type": "code", 7 | "metadata": {}, 8 | "outputs": [ 9 | { 10 | "output_type": "stream", 11 | "stream": "stdout", 12 | "text": [ 13 | "Last access date & time \n", 14 | "Thu Feb 19 13:07:32 2015\n" 15 | ] 16 | } 17 | ], 18 | "input": [ 19 | "import time\n", 20 | "print \"Last access date & time \\n\" + time.strftime(\"%c\")" 21 | ], 22 | "language": "python", 23 | "prompt_number": 1 24 | }, 25 | { 26 | "cell_type": "heading", 27 | "metadata": {}, 28 | "level": 1, 29 | "source": [ 30 | "This notebook is for calculation the flux distribution of KOs based on 13C flux data through pFBA, lMOMA and ROOM methods" 31 | ] 32 | }, 33 | { 34 | "cell_type": "heading", 35 | "metadata": {}, 36 | "level": 4, 37 | "source": [ 38 | "The flux distribution and setup is based on: Crown, S. B., Long, C. P. & Antoniewicz, M. R. Integrated (13)C-metabolic flux analysis of 14 parallel labeling experiments in Escherichia coli. Metab. Eng. (2015). doi:10.1016/j.ymben.2015.01.001" 39 | ] 40 | }, 41 | { 42 | "cell_type": "heading", 43 | "metadata": {}, 44 | "level": 4, 45 | "source": [ 46 | "Not all flux constrains are applied/can be applied (due to lumped reactions used on 13C experiments, and infeasibility of model with some of the combinations). Flux values can be set as ratios constraints or ub/lb with some room for error." 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "metadata": {}, 52 | "outputs": [], 53 | "input": [ 54 | "from cameo import load_model\n", 55 | "from cameo.flux_analysis.simulation import lmoma, room, pfba\n", 56 | "from cameo.parallel import MultiprocessingView, SequentialView\n", 57 | "from cameo.flux_analysis.analysis import flux_variability_analysis as fva\n", 58 | "\n", 59 | "from cobra.manipulation.delete import find_gene_knockout_reactions\n", 60 | "\n", 61 | "import escher\n", 62 | "\n", 63 | "import pandas as pd\n", 64 | "\n", 65 | "from multiprocessing import Pool\n", 66 | "from functools import partial\n", 67 | "import numpy as np" 68 | ], 69 | "language": "python", 70 | "prompt_number": 2 71 | }, 72 | { 73 | "cell_type": "heading", 74 | "metadata": {}, 75 | "level": 3, 76 | "source": [ 77 | "Load model" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "metadata": {}, 83 | "outputs": [], 84 | "input": [ 85 | "iJO = load_model('../../Models/E.coli/iJO1366_20141021.xml')\n", 86 | "# iJO.solver.configuration.timeout = 120\n", 87 | "# iJO.solver = \"cplex\"" 88 | ], 89 | "language": "python", 90 | "prompt_number": 3 91 | }, 92 | { 93 | "cell_type": "heading", 94 | "metadata": {}, 95 | "level": 4, 96 | "source": [ 97 | "Setup model for bounds version" 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "metadata": {}, 103 | "outputs": [ 104 | { 105 | "output_type": "pyout", 106 | "prompt_number": 4, 107 | "text": [ 108 | "0.7857341104634985" 109 | ], 110 | "metadata": {} 111 | } 112 | ], 113 | "input": [ 114 | "modelB = iJO.copy()\n", 115 | "rxnBound = {\\\n", 116 | " \"EX_glc_lp_e_rp_\": [-10.40965107, -10.4503385],\n", 117 | " \"GLCptspp\": [10.40965107, 10.4503385],\n", 118 | " \"PGI\": [7.35860489, 7.57227387],\n", 119 | " \"PFK\": [8.55935864, 8.67982514],\n", 120 | " \"FBA\": [8.55935864, 8.67982514],\n", 121 | " \"TPI\": [8.55935864, 8.67982514],\n", 122 | " \"GAPD\": [17.6426579, 17.9288571],\n", 123 | " \"PGK\": [-17.6426579, -17.9288571],\n", 124 | " \"PGM\": [-16.1968513, -16.6751711],\n", 125 | " \"ENO\": [16.1968513, 16.6751711],\n", 126 | " \"PYK\": [2.38209727, 3.27936931],\n", 127 | " \"G6PDH2r\": [2.69451749, 2.91458006],\n", 128 | " \"GND\": [2.55020801, 2.76522246],\n", 129 | " \"RPE\": [1.11581183, 1.30394817],\n", 130 | " \"RPI\": [-1.40202146, -1.49203236],\n", 131 | " \"EDD\": [0.112780633, 0.183211294],\n", 132 | " \"EDA\": [0.112780633, 0.183211294],\n", 133 | " \"PDH\": [11.2978803, 12.4997292],\n", 134 | " \"CS\": [1.84921814, 2.11797838],\n", 135 | " \"ACONTa\": [1.84921814, 2.11797838],\n", 136 | " \"ACONTb\": [1.84921814, 2.11797838],\n", 137 | " \"ICDHyr\": [1.56538655, 1.89717528],\n", 138 | " \"AKGDH\": [0.747454477, 1.027061917],\n", 139 | " \"SUCOAS\": [-0.379703107, -0.652958677],\n", 140 | " \"SUCDi\": [1.04795425, 1.23205418],\n", 141 | " \"FUM\": [1.32620579, 1.53493095],\n", 142 | " \"MDH\": [0.976218796, 1.28807371],\n", 143 | " \"ICL\": [0.182467635, 0.325904124],\n", 144 | " \"MALS\": [0.182467635, 0.325904124],\n", 145 | " \"ME2\": [0.000000001043, 0.697007696],\n", 146 | " \"ME1\": [0.000000001043, 0.697009782],\n", 147 | " \"PPC\": [2.54537892, 2.92150558],\n", 148 | " \"PPCK\": [0.0367090108, 0.290508876],\n", 149 | " \"GLUDy\": [-4.74501377, -5.51393423],\n", 150 | "# \"GLNS\": [0.489188903, 0.568338001],\n", 151 | "# \"ASPTA\": [-1.32957468, -1.56318582],\n", 152 | " \"ALATA_L\": [-0.353665655, -0.410886721],\n", 153 | "# \"PGCD\": [0.799934065, 0.934983791],\n", 154 | "# \"PSERT\": [0.799934065, 0.934983791],\n", 155 | "# \"PSP_L\": [0.80311, 0.9387],\n", 156 | " \"EX_ac_lp_e_rp_\": [6.49789, 8.28142],\n", 157 | " \"EX_co2_lp_e_rp_\": [16.13521, 17.29294],\n", 158 | " \"EX_o2_lp_e_rp_\": [-14.20566, -15.62414],\n", 159 | "# \"EX_nh4_lp_e_rp_\": [-5.04812, -5.86166],\n", 160 | " \"EX_so4_lp_e_rp_\": [-0.16688, -0.19817]\n", 161 | " }\n", 162 | "\n", 163 | "for rxn, bounds in rxnBound.iteritems():\n", 164 | " if bounds[0] < bounds[1]: # to fix the issue with negaive values above\n", 165 | " modelB.reactions.get_by_id(rxn).lower_bound = bounds[0]\n", 166 | " modelB.reactions.get_by_id(rxn).upper_bound = bounds[1]\n", 167 | " else:\n", 168 | " modelB.reactions.get_by_id(rxn).upper_bound = bounds[0]\n", 169 | " modelB.reactions.get_by_id(rxn).lower_bound = bounds[1]\n", 170 | "\n", 171 | "modelB.solve().f" 172 | ], 173 | "language": "python", 174 | "prompt_number": 4 175 | }, 176 | { 177 | "cell_type": "heading", 178 | "metadata": {}, 179 | "level": 4, 180 | "source": [ 181 | "Average growth rate on the paper was 0.72" 182 | ] 183 | } 184 | ] 185 | } 186 | ], 187 | "cells": [], 188 | "metadata": { 189 | "name": "", 190 | "signature": "sha256:c97fd6aecb1df26ccceaf15039496f4351fb7f921a7ba74572d5a84b7b882928" 191 | }, 192 | "nbformat": 3, 193 | "nbformat_minor": 0 194 | } -------------------------------------------------------------------------------- /driven/flux_analysis/results.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | from math import sqrt 18 | 19 | import six 20 | from numpy import nan, zeros 21 | from pandas import DataFrame 22 | 23 | from cameo.core.result import Result 24 | from cameo.flux_analysis.simulation import FluxDistributionResult 25 | from cobra import Reaction 26 | 27 | 28 | def _compare_flux_distributions(flux_dist1, flux_dist2, self_key="A", other_key="B"): 29 | assert isinstance(flux_dist1, FluxDistributionResult) 30 | assert isinstance(flux_dist2, FluxDistributionResult) 31 | return FluxDistributionDiff(flux_dist1, flux_dist2, self_key, other_key) 32 | 33 | FluxDistributionResult.__sub__ = lambda self, other: _compare_flux_distributions(self, other) 34 | 35 | 36 | class FluxBasedFluxDistribution(FluxDistributionResult): 37 | def __init__(self, fluxes, objective_value, c13_flux_distribution, *args, **kwargs): 38 | super(FluxBasedFluxDistribution, self).__init__(fluxes, objective_value, *args, **kwargs) 39 | self._c13_fluxes = c13_flux_distribution 40 | 41 | @property 42 | def data_frame(self): 43 | index = list(self.fluxes.keys()) 44 | data = zeros((len(self._fluxes.keys()), 3)) 45 | data[:, 0] = [self._fluxes[r] for r in index] 46 | data[:, 1] = [self._c13_fluxes.get(r, [nan, nan])[0] for r in index] 47 | data[:, 2] = [self._c13_fluxes.get(r, [nan, nan])[1] for r in index] 48 | return DataFrame(data, index=index, columns=["fluxes", "c13_lower_limit", "c13_upper_limit"]) 49 | 50 | 51 | class ExpressionBasedResult(FluxDistributionResult): 52 | def __init__(self, fluxes, objective_value, expression, *args, **kwargs): 53 | super(ExpressionBasedResult, self).__init__(fluxes, objective_value, *args, **kwargs) 54 | self.expression = expression 55 | 56 | 57 | class GimmeResult(ExpressionBasedResult): 58 | def __init__(self, fluxes, objective_value, fba_fluxes, reaction_expression, cutoff, *args, **kwargs): 59 | super(GimmeResult, self).__init__(fluxes, objective_value, reaction_expression, *args, **kwargs) 60 | self._fba_fluxes = fba_fluxes 61 | self.cutoff = cutoff 62 | 63 | @property 64 | def data_frame(self): 65 | index = list(self.fluxes.keys()) 66 | data = zeros((len(self._fluxes.keys()), 4)) 67 | data[:, 0] = [self._fluxes[r] for r in index] 68 | data[:, 1] = [self._fba_fluxes[r] for r in index] 69 | data[:, 2] = [self.expression.get(r, nan) for r in index] 70 | data[:, 3] = [self.reaction_inconsistency_score(r) for r in index] 71 | return DataFrame(data, index=index, columns=["gimme_fluxes", "fba_fluxes", "expression", "inconsistency_scores"]) 72 | 73 | def reaction_inconsistency_score(self, reaction): 74 | if reaction in self.expression: 75 | return abs(self._fluxes[reaction]) * max(self.cutoff - self.expression[reaction], 0) 76 | else: 77 | return 0 78 | 79 | @property 80 | def distance(self): 81 | return sum([abs(self.fluxes[r]-self._fba_fluxes[r]) for r in self.fluxes.keys()]) 82 | 83 | @property 84 | def inconsistency_score(self): 85 | return sum([self.reaction_inconsistency_score(reaction) for reaction in self.expression]) 86 | 87 | def trim_model(self, model, tm=None): 88 | for r_id, flux in six.iteritems(self.fluxes): 89 | expression = self.expression.get(r_id, self.cutoff+1) 90 | if abs(flux) == 0 and expression < self.cutoff and self.reaction_inconsistency_score(r_id) <= 0: 91 | model.reactions.get_by_id(r_id).knock_out(tm) 92 | 93 | 94 | class IMATResult(ExpressionBasedResult): 95 | def __init__(self, fluxes, objective_value, expression, lower_cutoff, higher_cutoff, epsilon, *args, **kwargs): 96 | super(IMATResult, self).__init__(fluxes, objective_value, expression, *args, **kwargs) 97 | self.lower_cutoff = lower_cutoff 98 | self.higher_cutoff = higher_cutoff 99 | self.epsilon = epsilon 100 | 101 | @property 102 | def highly_express(self): 103 | return {r: self._highly_expressed(r) for r in self.fluxes.keys()} 104 | 105 | def _highly_expressed(self, value): 106 | if value in self.expression: 107 | return self.expression[value] >= self.higher_cutoff 108 | else: 109 | return nan 110 | 111 | @property 112 | def lowly_express(self): 113 | return {r: self._lowly_expressed(r) for r in self.fluxes.keys()} 114 | 115 | def _lowly_expressed(self, value): 116 | if value in self.expression: 117 | return self.expression[value] < self.lower_cutoff 118 | else: 119 | return nan 120 | 121 | @property 122 | def data_frame(self): 123 | index = list(self.fluxes.keys()) 124 | columns = ["fluxes", "expression", "highly_express", "lowly_expressed"] 125 | data = zeros((len(self._fluxes.keys()), 4)) 126 | data[:, 0] = [self.fluxes[r] for r in index] 127 | data[:, 1] = [self.expression.get(r, nan) for r in index] 128 | data[:, 2] = [self._highly_expressed(r) for r in index] 129 | data[:, 3] = [self._lowly_expressed(r) for r in index] 130 | return DataFrame(data, columns=columns, index=index) 131 | 132 | 133 | class FluxDistributionDiff(Result): 134 | def __init__(self, flux_dist_a, flux_dist_b, a_key="A", b_key="B", *args, **kwargs): 135 | super(FluxDistributionDiff, self).__init__(*args, **kwargs) 136 | assert isinstance(flux_dist_a, FluxDistributionResult) 137 | assert isinstance(flux_dist_b, FluxDistributionResult) 138 | assert all([rid in flux_dist_a.fluxes.index for rid in flux_dist_b.fluxes.index]) and \ 139 | all([rid in flux_dist_b.fluxes.index for rid in flux_dist_a.fluxes.index]) 140 | 141 | self._a_key = a_key 142 | self._fluxes_a = flux_dist_a.fluxes 143 | 144 | self._b_key = b_key 145 | self._fluxes_b = flux_dist_b.fluxes 146 | 147 | def normalize(self, reaction): 148 | if isinstance(reaction, Reaction): 149 | reaction = reaction.id 150 | 151 | self._fluxes_a = {rid: flux/self._fluxes_a[reaction] for rid, flux in six.iteritems(self._fluxes_a)} 152 | self._fluxes_b = {rid: flux/self._fluxes_b[reaction] for rid, flux in six.iteritems(self._fluxes_b)} 153 | 154 | def _manhattan_distance(self, value): 155 | return abs(self._fluxes_a[value] - self._fluxes_b[value]) 156 | 157 | @property 158 | def manhattan_distance(self): 159 | return sum(self._manhattan_distance(rid) for rid in self._fluxes_a.keys()) 160 | 161 | def _euclidean_distance(self, value): 162 | return (self._fluxes_a[value] - self._fluxes_b[value])**2 163 | 164 | @property 165 | def euclidean_distance(self): 166 | return sqrt(sum(self._euclidean_distance(rid) for rid in self._fluxes_a.keys())) 167 | 168 | def _activity(self, value, threshold=1e-6): 169 | value_a = abs(self._fluxes_a[value]) 170 | value_b = abs(self._fluxes_b[value]) 171 | 172 | if value_a < threshold and value_b < threshold: 173 | return None 174 | 175 | else: 176 | value_a = 1 if value_a > threshold else 0 177 | value_b = 1 if value_b > threshold else 0 178 | 179 | return float(value_a - value_b) 180 | 181 | @property 182 | def activity_profile(self): 183 | return {rid: self._activity(rid) for rid in self._fluxes_a.keys()} 184 | 185 | def _fold_change(self, value): 186 | value_a = self._fluxes_a[value] 187 | value_b = self._fluxes_b[value] 188 | if value_a > 0: 189 | return (value_a - value_b) / value_a 190 | else: 191 | return None 192 | 193 | @property 194 | def data_frame(self): 195 | index = list(self._fluxes_a.keys()) 196 | columns = ["fluxes_%s" % self._a_key, "fluxes_%s" % self._b_key, 197 | "manhattan_distance", "euclidean_distance", 198 | "activity_profile", "fold_change"] 199 | data = zeros((len(self._fluxes_a.keys()), 6)) 200 | data[:, 0] = [self._fluxes_a[r] for r in index] 201 | data[:, 1] = [self._fluxes_b[r] for r in index] 202 | data[:, 2] = [self._manhattan_distance(r) for r in index] 203 | data[:, 3] = [self._euclidean_distance(r) for r in index] 204 | data[:, 4] = [self._activity(r) for r in index] 205 | data[:, 5] = [self._fold_change(r) for r in index] 206 | return DataFrame(data, index=index, columns=columns) 207 | -------------------------------------------------------------------------------- /driven/flux_analysis/transcriptomics.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | import numbers 18 | 19 | import six 20 | from sympy import Add 21 | 22 | from cobra.flux_analysis import flux_variability_analysis as fva 23 | from cobra import Model 24 | from driven.data_sets.expression_profile import ExpressionProfile 25 | from driven.data_sets.normalization import or2min_and2max 26 | from driven.flux_analysis.results import GimmeResult, IMATResult 27 | 28 | 29 | def gimme(model, expression_profile=None, cutoff=None, objective=None, objective_dist=None, fraction_of_optimum=0.9, 30 | normalization=or2min_and2max, condition=None, not_measured_value=None, *args, **kwargs): 31 | """ 32 | Gene Inactivity Moderated by Metabolism and Expression (GIMME)[1] 33 | 34 | Parameters 35 | ---------- 36 | model: cobra.Model 37 | A constraint based model 38 | expression_profile: ExpressionProfile 39 | An expression profile 40 | cutoff: float 41 | inactivity threshold 42 | objective: str or other cameo compatible objective 43 | The Minimal Required Functionalities (MRF) 44 | objective_dist: FluxDistributionResult 45 | A predetermined flux distribution for the objective can be provided (optional) 46 | fraction_of_optimum: float 47 | The fraction of the MRF 48 | normalization: function 49 | expression profile normalization function 50 | condition: str, int or None 51 | The condition from the expression profile. If None (default), the first condition on the profile will be used. 52 | normalization: function 53 | The normalization function to convert the gene expression profile into reaction expression profile (default: max) 54 | 55 | Returns 56 | ------- 57 | GimmeResult 58 | 59 | References 60 | ---------- 61 | .. [1] Becker, S. a and Palsson, B. O. (2008). Context-specific metabolic networks are consistent with experiments. 62 | PLoS Computational Biology, 4(5), e1000082. doi:10.1371/journal.pcbi.1000082 63 | """ 64 | 65 | assert isinstance(model, Model) 66 | assert isinstance(expression_profile, ExpressionProfile) 67 | assert isinstance(fraction_of_optimum, numbers.Number) 68 | assert isinstance(cutoff, numbers.Number) 69 | 70 | with model: 71 | if objective is not None: 72 | model.objective = objective 73 | objective_dist = model.optimize(raise_error=True) if objective_dist is None else objective_dist 74 | 75 | if model.objective.direction == 'max': 76 | fix_obj_constraint = model.problem.Constraint(model.objective.expression, 77 | lb=fraction_of_optimum * objective_dist.objective_value, 78 | name="required metabolic functionalities") 79 | else: 80 | fix_obj_constraint = model.problem.Constraint(model.objective.expression, 81 | ub=fraction_of_optimum * objective_dist.objective_value, 82 | name="required metabolic functionalities") 83 | objective_terms = list() 84 | 85 | condition = expression_profile.conditions[0] if condition is None else condition 86 | not_measured_value = cutoff if not_measured_value is None else not_measured_value 87 | 88 | reaction_profile = expression_profile.to_reaction_dict(condition, model, not_measured_value, normalization) 89 | coefficients = {r: cutoff - exp if cutoff > exp else 0 for r, exp in six.iteritems(reaction_profile)} 90 | 91 | for rid, coefficient in six.iteritems(coefficients): 92 | reaction = model.reactions.get_by_id(rid) 93 | if coefficient > 0: 94 | objective_terms.append(coefficient * (reaction.forward_variable + reaction.reverse_variable)) 95 | 96 | gimme_objective = model.problem.Objective(Add(*objective_terms), direction="min") 97 | model.objective = gimme_objective 98 | model.add_cons_vars(fix_obj_constraint) 99 | solution = model.optimize() 100 | return GimmeResult(solution.fluxes, solution.objective_value, objective_dist.fluxes, reaction_profile, cutoff) 101 | 102 | 103 | def imat(model, expression_profile=None, low_cutoff=0.25, high_cutoff=0.85, epsilon=0.1, condition=None, 104 | normalization=or2min_and2max, fraction_of_optimum=0.99, objective=None, not_measured_value=None, 105 | *args, **kwargs): 106 | """ 107 | Integrative Metabolic Analysis Tool 108 | 109 | Parameters 110 | ---------- 111 | model: cobra.Model 112 | A constraint-based model 113 | expression_profile: ExpressionProfile 114 | The expression profile 115 | low_cutoff: number 116 | The cut off value for low expression values 117 | high_cutoff: number 118 | The cut off value for high expression values 119 | epsilon: float 120 | """ 121 | 122 | assert isinstance(model, Model) 123 | assert isinstance(expression_profile, ExpressionProfile) 124 | assert isinstance(high_cutoff, numbers.Number) 125 | assert isinstance(low_cutoff, numbers.Number) 126 | 127 | condition = expression_profile.conditions[0] if condition is None else condition 128 | not_measured_value = 0 if not_measured_value is None else not_measured_value 129 | 130 | reaction_profile = expression_profile.to_reaction_dict(condition, model, not_measured_value, normalization) 131 | 132 | y_variables = list() 133 | x_variables = list() 134 | constraints = list() 135 | try: 136 | 137 | with model: 138 | if objective is not None: 139 | model.objective = objective 140 | fva_res = fva(model, reactions=list(reaction_profile.keys()), 141 | fraction_of_optimum=fraction_of_optimum) 142 | 143 | for rid, expression in six.iteritems(reaction_profile): 144 | if expression >= high_cutoff: 145 | reaction = model.reactions.get_by_id(rid) 146 | y_pos = model.solver.interface.Variable("y_%s_pos" % rid, type="binary") 147 | y_neg = model.solver.interface.Variable("y_%s_neg" % rid, type="binary") 148 | 149 | y_variables.append([y_neg, y_pos]) 150 | 151 | pos_constraint = model.solver.interface.Constraint( 152 | reaction.flux_expression + y_pos * (fva_res["minimum"][rid] - epsilon), 153 | lb=fva_res["minimum"][rid], name="pos_highly_%s" % rid) 154 | 155 | neg_constraint = model.solver.interface.Constraint( 156 | reaction.flux_expression + y_neg * (fva_res["maximum"][rid] + epsilon), 157 | ub=fva_res["maximum"][rid], name="neg_highly_%s" % rid) 158 | 159 | constraints.extend([pos_constraint, neg_constraint]) 160 | 161 | elif expression < low_cutoff: 162 | reaction = model.reactions.get_by_id(rid) 163 | x = model.solver.interface.Variable("x_%s" % rid, type="binary") 164 | x_variables.append(x) 165 | 166 | pos_constraint = model.solver.interface.Constraint( 167 | (1 - x) * fva_res["maximum"][rid] - reaction.flux_expression, 168 | lb=0, name="x_%s_upper" % rid) 169 | 170 | neg_constraint = model.solver.interface.Constraint( 171 | (1 - x) * fva_res["minimum"][rid] - reaction.flux_expression, 172 | ub=0, name="x_%s_lower" % rid) 173 | 174 | constraints.extend([pos_constraint, neg_constraint]) 175 | 176 | for variable in x_variables: 177 | model.solver.add(variable) 178 | 179 | for variables in y_variables: 180 | model.solver.add(variables[0]) 181 | model.solver.add(variables[1]) 182 | 183 | for constraint in constraints: 184 | model.solver.add(constraint) 185 | 186 | objective = model.solver.interface.Objective(Add(*[(y[0] + y[1]) for y in y_variables]) + Add(*x_variables), 187 | direction="max") 188 | 189 | with model: 190 | model.objective = objective 191 | solution = model.optimize() 192 | return IMATResult(solution.fluxes, solution.f, reaction_profile, low_cutoff, high_cutoff, epsilon) 193 | 194 | finally: 195 | model.solver.remove([var for var in x_variables if var in model.solver.variables]) 196 | model.solver.remove([var for pair in y_variables for var in pair if var in model.solver.variables]) 197 | model.solver.remove([const for const in constraints if const in model.solver.constraints]) 198 | 199 | 200 | def made(model, objective=None, *args, **kwargs): 201 | raise NotImplementedError 202 | 203 | 204 | def eflux(model, objective=None, *args, **kwargs): 205 | raise NotImplementedError 206 | 207 | 208 | def relatch(model, objective=None, *args, **kwargs): 209 | raise NotImplementedError 210 | 211 | 212 | def gx_fba(model, objective=None, *args, **kwargs): 213 | raise NotImplementedError 214 | 215 | 216 | def prom(model, objective=None, *args, **kwargs): 217 | raise NotImplementedError 218 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # cameo documentation build configuration file, created by 4 | # sphinx-quickstart on Mon Aug 25 11:16:27 2014. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | 18 | import sphinx_rtd_theme 19 | 20 | on_rtd = os.environ.get('READTHEDOCS', None) == 'True' 21 | if on_rtd: 22 | from mock import MagicMock 23 | 24 | class Mock(MagicMock): 25 | @classmethod 26 | def __getattr__(cls, name): 27 | return Mock() 28 | 29 | MOCK_MODULES = ['cameo', 'cobra', 'sympy', 'numpy'] 30 | sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) 31 | 32 | # If extensions (or modules to document with autodoc) are in another directory, 33 | # add these directories to sys.path here. If the directory is relative to the 34 | # documentation root, use os.path.abspath to make it absolute, like shown here. 35 | # sys.path.insert(0, os.path.abspath('../../')) 36 | 37 | # -- General configuration ------------------------------------------------ 38 | 39 | # If your documentation needs a minimal Sphinx version, state it here. 40 | # needs_sphinx = '1.0' 41 | 42 | # Add any Sphinx extension module names here, as strings. They can be 43 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 44 | # ones. 45 | extensions = [ 46 | 'sphinx.ext.autodoc', 47 | 'sphinx.ext.doctest', 48 | 'sphinx.ext.intersphinx', 49 | 'sphinx.ext.todo', 50 | 'sphinx.ext.coverage', 51 | 'sphinx.ext.mathjax', 52 | 'sphinx.ext.ifconfig', 53 | 'sphinx.ext.viewcode', 54 | 'sphinx.ext.napoleon' 55 | ] 56 | 57 | # Add any paths that contain templates here, relative to this directory. 58 | templates_path = ['_templates'] 59 | 60 | # The suffix of source filenames. 61 | source_suffix = '.rst' 62 | 63 | # The encoding of source files. 64 | # source_encoding = 'utf-8-sig' 65 | 66 | # The master toctree document. 67 | master_doc = 'index' 68 | 69 | # General information about the project. 70 | project = u'cameo' 71 | copyright = u'2015, João Cardoso' 72 | 73 | # The version info for the project you're documenting, acts as replacement for 74 | # |version| and |release|, also used in various other places throughout the 75 | # built documents. 76 | # 77 | # The short X.Y version. 78 | version = '0.0' 79 | # The full version, including alpha/beta/rc tags. 80 | release = '0.0.beta1' 81 | 82 | # The language for content autogenerated by Sphinx. Refer to documentation 83 | # for a list of supported languages. 84 | # language = None 85 | 86 | # There are two options for replacing |today|: either, you set today to some 87 | # non-false value, then it is used: 88 | # today = '' 89 | # Else, today_fmt is used as the format for a strftime call. 90 | # today_fmt = '%B %d, %Y' 91 | 92 | # List of patterns, relative to source directory, that match files and 93 | # directories to ignore when looking for source files. 94 | exclude_patterns = ['_build'] 95 | 96 | # The reST default role (used for this markup: `text`) to use for all 97 | # documents. 98 | default_role = 'py:obj' 99 | 100 | # If true, '()' will be appended to :func: etc. cross-reference text. 101 | # add_function_parentheses = True 102 | 103 | # If true, the current module name will be prepended to all description 104 | # unit titles (such as .. function::). 105 | # add_module_names = True 106 | 107 | # If true, sectionauthor and moduleauthor directives will be shown in the 108 | # output. They are ignored by default. 109 | # show_authors = False 110 | 111 | # The name of the Pygments (syntax highlighting) style to use. 112 | pygments_style = 'sphinx' 113 | 114 | # A list of ignored prefixes for module index sorting. 115 | # modindex_common_prefix = [] 116 | 117 | # If true, keep warnings as "system message" paragraphs in the built documents. 118 | # keep_warnings = False 119 | 120 | 121 | # -- Options for HTML output ---------------------------------------------- 122 | 123 | # The theme to use for HTML and HTML Help pages. See the documentation for 124 | # a list of builtin themes. 125 | html_theme = "sphinx_rtd_theme" 126 | 127 | # Theme options are theme-specific and customize the look and feel of a theme 128 | # further. For a list of options available for each theme, see the 129 | # documentation. 130 | # html_theme_options = {} 131 | 132 | # Add any paths that contain custom themes here, relative to this directory. 133 | html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] 134 | 135 | # The name for this set of Sphinx documents. If None, it defaults to 136 | # " v documentation". 137 | # html_title = None 138 | 139 | # A shorter title for the navigation bar. Default is the same as html_title. 140 | # html_short_title = None 141 | 142 | # The name of an image file (relative to this directory) to place at the top 143 | # of the sidebar. 144 | # html_logo = None 145 | 146 | # The name of an image file (within the static path) to use as favicon of the 147 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 148 | # pixels large. 149 | # html_favicon = None 150 | 151 | # Add any paths that contain custom static files (such as style sheets) here, 152 | # relative to this directory. They are copied after the builtin static files, 153 | # so a file named "default.css" will overwrite the builtin "default.css". 154 | html_static_path = ['_static'] 155 | 156 | # Add any extra paths that contain custom files (such as robots.txt or 157 | # .htaccess) here, relative to this directory. These files are copied 158 | # directly to the root of the documentation. 159 | # html_extra_path = [] 160 | 161 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 162 | # using the given strftime format. 163 | # html_last_updated_fmt = '%b %d, %Y' 164 | 165 | # If true, SmartyPants will be used to convert quotes and dashes to 166 | # typographically correct entities. 167 | # html_use_smartypants = True 168 | 169 | # Custom sidebar templates, maps document names to template names. 170 | # html_sidebars = {} 171 | 172 | # Additional templates that should be rendered to pages, maps page names to 173 | # template names. 174 | # html_additional_pages = {} 175 | 176 | # If false, no module index is generated. 177 | # html_domain_indices = True 178 | 179 | # If false, no index is generated. 180 | # html_use_index = True 181 | 182 | # If true, the index is split into individual pages for each letter. 183 | # html_split_index = False 184 | 185 | # If true, links to the reST sources are added to the pages. 186 | # html_show_sourcelink = True 187 | 188 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 189 | # html_show_sphinx = True 190 | 191 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 192 | # html_show_copyright = True 193 | 194 | # If true, an OpenSearch description file will be output, and all pages will 195 | # contain a tag referring to it. The value of this option must be the 196 | # base URL from which the finished HTML is served. 197 | # html_use_opensearch = '' 198 | 199 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 200 | # html_file_suffix = None 201 | 202 | # Output file base name for HTML help builder. 203 | htmlhelp_basename = 'cameodoc' 204 | 205 | 206 | # -- Options for LaTeX output --------------------------------------------- 207 | 208 | latex_elements = { 209 | # The paper size ('letterpaper' or 'a4paper'). 210 | # 'papersize': 'letterpaper', 211 | 212 | # The font size ('10pt', '11pt' or '12pt'). 213 | # 'pointsize': '10pt', 214 | 215 | # Additional stuff for the LaTeX preamble. 216 | # 'preamble': '', 217 | } 218 | 219 | # Grouping the document tree into LaTeX files. List of tuples 220 | # (source start file, target name, title, 221 | # author, documentclass [howto, manual, or own class]). 222 | latex_documents = [ 223 | ('index', 'cameo.tex', u'cameo Documentation', 224 | u'Nikolaus Sonnenschein, João Cardoso', 'manual'), 225 | ] 226 | 227 | # The name of an image file (relative to this directory) to place at the top of 228 | # the title page. 229 | # latex_logo = None 230 | 231 | # For "manual" documents, if this is true, then toplevel headings are parts, 232 | # not chapters. 233 | # latex_use_parts = False 234 | 235 | # If true, show page references after internal links. 236 | # latex_show_pagerefs = False 237 | 238 | # If true, show URL addresses after external links. 239 | # latex_show_urls = False 240 | 241 | # Documents to append as an appendix to all manuals. 242 | # latex_appendices = [] 243 | 244 | # If false, no module index is generated. 245 | # latex_domain_indices = True 246 | 247 | 248 | # -- Options for manual page output --------------------------------------- 249 | 250 | # One entry per manual page. List of tuples 251 | # (source start file, name, description, authors, manual section). 252 | man_pages = [ 253 | ('index', 'cameo', u'cameo Documentation', 254 | [u'Nikolaus Sonnenschein, João Cardoso'], 1) 255 | ] 256 | 257 | # If true, show URL addresses after external links. 258 | # man_show_urls = False 259 | 260 | 261 | # -- Options for Texinfo output ------------------------------------------- 262 | 263 | # Grouping the document tree into Texinfo files. List of tuples 264 | # (source start file, target name, title, author, 265 | # dir menu entry, description, category) 266 | texinfo_documents = [ 267 | ('index', 'driven', u'Driven Documentation', 268 | u'João Cardoso', 'driven', 'One line description of project.', 269 | 'Miscellaneous'), 270 | ] 271 | 272 | # Documents to append as an appendix to all manuals. 273 | # texinfo_appendices = [] 274 | 275 | # If false, no module index is generated. 276 | # texinfo_domain_indices = True 277 | 278 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 279 | # texinfo_show_urls = 'footnote' 280 | 281 | # If true, do not generate a @detailmenu in the "Top" node's menu. 282 | # texinfo_no_detailmenu = False 283 | 284 | 285 | # Example configuration for intersphinx: refer to the Python standard library. 286 | intersphinx_mapping = {'http://docs.python.org/': None} 287 | 288 | autodoc_member_order = 'bysource' 289 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /driven/data_sets/expression_profile.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import, print_function 16 | 17 | from itertools import combinations 18 | 19 | from numpy import ndarray 20 | from pandas import DataFrame, melt 21 | 22 | from driven.data_sets.normalization import or2min_and2max 23 | from driven.stats import freedman_diaconis 24 | from driven.utils import get_common_start 25 | from driven.vizualization.plotting import plotting 26 | 27 | 28 | class ExpressionProfile(object): 29 | """ 30 | Representation of an Expression profile. It can be RNA-Seq, Proteomics, TNSeq or any other 31 | profile that links genes/proteins to a value (continuous or discrete). 32 | 33 | It the storage of single or multiple conditions as well as p-values. 34 | 35 | Attributes 36 | ---------- 37 | 38 | identifiers: list 39 | The gene or protein ids 40 | conditions: list 41 | The conditions in the expression profile (time points, media conditions, etc...) 42 | expression: numpy.ndarray 43 | An 2 dimensional array (nxm) where n is the number of genes and m the number of conditions. 44 | p_values: numpy.ndarray 45 | The p-values between conditions. 46 | """ 47 | @classmethod 48 | def from_csv(cls, file_path, sep=",", replicas=None): 49 | """ 50 | Reads and expression profile from a Comma Separated Values (CSV) file. 51 | 52 | Parameters 53 | ---------- 54 | file_path: str 55 | The path to load. 56 | sep: str 57 | Default is "," 58 | replicas: int 59 | number of replicas. It uses the median of the replicas. 60 | 61 | Returns 62 | ------- 63 | ExpressionProfile 64 | An expression profile built from the file. 65 | 66 | """ 67 | data = DataFrame.from_csv(file_path, sep=sep) 68 | if replicas: 69 | columns = data.columns 70 | data = DataFrame([data[columns[i:i+replicas]].median(axis=1) for i in 71 | range(0, len(columns), replicas)]).transpose() 72 | data.columns = [get_common_start(*columns[i:i+replicas].tolist()) for i in 73 | range(0, len(columns), replicas)] 74 | return cls.from_data_frame(data) 75 | 76 | @classmethod 77 | def from_data_frame(cls, data_frame): 78 | """ 79 | Reads and expression profile from a pandas.DataFrame. 80 | 81 | Parameters 82 | ---------- 83 | data_frame: pandas.DataFrame 84 | A DataFrame containing the genes as index and the columns as conditions. 85 | For more information about p-values see @ExpressionProfile.p_value_columns 86 | 87 | Returns 88 | ------- 89 | ExpressionProfile 90 | An expression profile built from the DataFrame. 91 | """ 92 | columns = list(data_frame.columns) 93 | conditions = [c for c in columns if "p-value" not in c] 94 | 95 | p_value_keys = [c for c in columns if "p-value" in c] 96 | if len(p_value_keys) > 0: 97 | p_values = data_frame[p_value_keys].values 98 | else: 99 | p_values = None 100 | 101 | expression = data_frame[conditions].values 102 | identifiers = list(data_frame.index) 103 | return ExpressionProfile(identifiers, conditions, expression, p_values) 104 | 105 | def __init__(self, identifiers, conditions, expression, p_values=None): 106 | assert isinstance(identifiers, list) 107 | assert isinstance(conditions, list) 108 | assert isinstance(expression, ndarray) 109 | assert expression.shape == (len(identifiers), len(conditions)) 110 | 111 | self.conditions = conditions 112 | self._condition_index = dict((c, i) for i, c in enumerate(conditions)) 113 | self.identifiers = identifiers 114 | self._gene_index = dict((g, i) for i, g in enumerate(identifiers)) 115 | self.expression = expression 116 | self._p_values = p_values 117 | 118 | def __getitem__(self, item): 119 | if not isinstance(item, tuple): 120 | raise AttributeError( 121 | "Non supported slicing method. E.g. profile[1,2] or profile[\"id1\", \"condition_a\"]") 122 | 123 | if isinstance(item[0], str): 124 | i = self._gene_index[item[0]] 125 | elif isinstance(item[0], (slice, int)): 126 | i = item[0] 127 | else: 128 | raise AttributeError( 129 | "Non supported slicing value. E.g. profile[1,2] or profile[\"id1\", \"condition_a\"]") 130 | 131 | if isinstance(item[1], str): 132 | j = self._condition_index[item[1]] 133 | elif isinstance(item[1], (slice, int)): 134 | j = item[1] 135 | else: 136 | raise AttributeError( 137 | "Non supported slicing method. E.g. profile[1,2] or profile[\"id1\", \"condition_a\"]") 138 | 139 | return self.expression[i, j] 140 | 141 | def __eq__(self, other): 142 | if not isinstance(other, ExpressionProfile): 143 | return False 144 | else: 145 | if self._p_values is None and other.p_values is None: 146 | return self.identifiers == other.identifiers and \ 147 | self.conditions == other.conditions and \ 148 | self._p_values == other._p_values and \ 149 | (self.expression == other.expression).all() 150 | else: 151 | return self.identifiers == other.identifiers and \ 152 | self.conditions == other.conditions and \ 153 | (self._p_values == other._p_values).all() and \ 154 | (self.expression == other.expression).all() 155 | 156 | def _repr_html_(self): 157 | return self.data_frame._repr_html_() 158 | 159 | @property 160 | def data_frame(self): 161 | """ 162 | Builds a pandas.DataFrame from the ExpressionProfile. 163 | 164 | Returns 165 | ------- 166 | pandas.DataFrame 167 | A DataFrame 168 | """ 169 | if self._p_values is None: 170 | return DataFrame(self.expression, 171 | index=self.identifiers, 172 | columns=self.conditions) 173 | 174 | else: 175 | return DataFrame(self.expression+self.p_values, index=self.identifiers, 176 | columns=self.conditions+self.p_value_columns) 177 | 178 | @property 179 | def p_value_columns(self): 180 | """ 181 | Generates the p-value column names. The p-values are between conditions. 182 | 183 | Returns 184 | ------- 185 | list 186 | A list with p-value column headers. 187 | """ 188 | return ["%s %s p-value" % c for c in combinations(self.conditions, 2)] 189 | 190 | @property 191 | def p_values(self): 192 | return self._p_values 193 | 194 | @p_values.setter 195 | def p_values(self, p_values): 196 | assert isinstance(p_values, (ndarray, type(None))) 197 | if p_values is not None: 198 | if p_values.shape[1] != len(self.p_value_columns): 199 | raise ValueError("Argument p_values does not cover all conditions (expected %s)" % self.p_value_columns) 200 | 201 | self._p_values = p_values 202 | 203 | @p_values.deleter 204 | def p_values(self): 205 | self._p_values = None 206 | 207 | def histogram(self, conditions=None, transform=None, filter=None, bins=None, 208 | width=800, height=None, palette='Spectral'): 209 | 210 | if conditions is None: 211 | conditions = self.conditions 212 | 213 | data = melt(self.data_frame[conditions], var_name='condition') 214 | 215 | if filter: 216 | data = data.query(filter) 217 | if transform: 218 | data['value'] = data['value'].apply(transform) 219 | hist = plotting.histogram(data, values='value', groups='condition', bins=bins, 220 | width=width, height=height, palette=palette, 221 | title="Histogram of expression values", legend=True) 222 | 223 | plotting.display(hist) 224 | return hist 225 | 226 | def scatter(self, condition1=None, condition2=None, transform=float, width=800, height=None, color="#AFDCEC"): 227 | if len(self.conditions) <= 1: 228 | raise AssertionError("Cannot build a scatter with only one condition") 229 | 230 | if condition1 is None: 231 | condition1 = self.conditions[0] 232 | elif isinstance(condition1, int): 233 | condition1 = self.conditions[condition1] 234 | 235 | if condition2 is None: 236 | condition2 = self.conditions[1] 237 | 238 | elif isinstance(condition2, int): 239 | condition2 = self.conditions[condition2] 240 | 241 | if transform: 242 | data = self.data_frame.applymap(transform) 243 | else: 244 | data = self.data_frame 245 | 246 | data = data.reset_index() 247 | scatter = plotting.scatter(data, x=condition1, y=condition2, width=width, height=height, 248 | color=color, label='index', 249 | title="Expression values %s vs. %s" % (condition1, condition2), 250 | xaxis_label="Expression %s" % condition1, 251 | yaxis_label="Expression %s" % condition2) 252 | 253 | plotting.display(scatter) 254 | return scatter 255 | 256 | def heatmap(self, conditions=None, identifiers=None, transform=None, low="green", mid="yellow", high="blue", 257 | width=800, height=None, id_map=None): 258 | 259 | id_map = {} if id_map is None else id_map 260 | identifiers = self.identifiers if identifiers is None else identifiers 261 | conditions = self.conditions if conditions is None else conditions 262 | data = self.data_frame[conditions] 263 | data['y'] = [id_map.get(i, i) for i in identifiers] 264 | data = melt(data, id_vars=['y'], var_name='x') 265 | if transform: 266 | data['value'] = data.values.apply(transform) 267 | 268 | heatmap = plotting.heatmap(data, y='y', x='x', values='value', width=width, height=height, 269 | max_color=high, min_color=low, mid_color=mid, title='Expression profile heatmap') 270 | 271 | plotting.display(heatmap) 272 | return heatmap 273 | 274 | def boxplot(self, conditions=None, transform=None, width=800, height=None, palette='Spectral'): 275 | if conditions is None: 276 | conditions = self.conditions 277 | 278 | data = melt(self.data_frame[conditions], var_name='condition') 279 | 280 | if transform: 281 | data['value'] = data['value'].apply(transform) 282 | hist = plotting.boxplot(data, values='value', groups='condition', width=width, height=height, palette=palette, 283 | title="Box plot of expression values", legend=True) 284 | 285 | plotting.display(hist) 286 | return hist 287 | 288 | def to_dict(self, condition): 289 | """ 290 | Builds a dict with genes as keys and the expression value for the selected condition. 291 | 292 | Parameters 293 | ---------- 294 | condition: str or int1 295 | The condition or the index. 296 | 297 | Returns 298 | ------- 299 | dict 300 | """ 301 | if isinstance(condition, int): 302 | index = condition 303 | else: 304 | index = self._condition_index[condition] 305 | return dict(zip(self.identifiers, self.expression[:, index])) 306 | 307 | def to_reaction_dict(self, condition, model, cutoff, normalization=or2min_and2max): 308 | gene_exp = self.to_dict(condition) 309 | reaction_exp = {} 310 | for r in model.reactions: 311 | if len(r.genes) > 0 and any([identifier.id in self.identifiers for identifier in r.genes]): 312 | reaction_exp[r.id] = normalization(r, {g.id: gene_exp.get(g.id, cutoff) for g in r.genes}) 313 | return reaction_exp 314 | 315 | def differences(self, p_value=0.005): 316 | diff = {} 317 | for index, gene in enumerate(self.identifiers): 318 | diff[gene] = [] 319 | for i in range(1, len(self.conditions)): 320 | start, end = self.expression[index, i-1: i+1] 321 | p = self.p_values[index, i-1] 322 | if p <= p_value: 323 | if start < end: 324 | diff[gene].append(+1) 325 | elif start > end: 326 | diff[gene].append(-1) 327 | else: 328 | diff[gene].append(0) 329 | else: 330 | diff[gene].append(0) 331 | 332 | return diff 333 | 334 | def minmax(self, condition=None): 335 | if condition is None: 336 | values = self[:, :] 337 | else: 338 | values = self[:, condition] 339 | return min(values), max(values) 340 | 341 | def bin_width(self, condition=None, min_val=None, max_val=None): 342 | if condition is None: 343 | values = self[:, :] 344 | else: 345 | values = self[:, condition] 346 | 347 | if min_val: 348 | values = values[values >= min_val] 349 | if max_val: 350 | values = values[values <= max_val] 351 | 352 | values = values[:, condition] 353 | return freedman_diaconis(values) 354 | --------------------------------------------------------------------------------