From 8f65273eb81c4e90987103881d036628f734b7e5 Mon Sep 17 00:00:00 2001 From: "Moritz E. Beber" Date: Mon, 5 Nov 2018 10:06:27 +0100 Subject: [PATCH 1/5] chore: extend gitignore with PyCharm template --- .gitignore | 106 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) diff --git a/.gitignore b/.gitignore index efa6764ea..b9689f9db 100644 --- a/.gitignore +++ b/.gitignore @@ -54,3 +54,109 @@ docs/_build /.DS_Store .cache /coverage.xml +### Python template +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + From 0d08eaab4621dd768226c5ef5f4f23028fe728db Mon Sep 17 00:00:00 2001 From: "Moritz E. Beber" Date: Mon, 5 Nov 2018 10:54:19 +0100 Subject: [PATCH 2/5] style: conform with flake8 settings --- cameo/core/pathway.py | 14 ++--- cameo/core/target.py | 14 +++-- cameo/flux_analysis/analysis.py | 28 ++++++---- .../deterministic/flux_variability_based.py | 52 ++++++++++++------- .../deterministic/linear_programming.py | 6 ++- .../heuristic/evolutionary/optimization.py | 8 ++- 6 files changed, 79 insertions(+), 43 deletions(-) diff --git a/cameo/core/pathway.py b/cameo/core/pathway.py index 70459f6ea..ad9d1af27 100644 --- a/cameo/core/pathway.py +++ b/cameo/core/pathway.py @@ -102,12 +102,14 @@ def to_file(self, file_path, sep="\t"): with open(file_path, "w") as output_file: for reaction in self.reactions: equation = _build_equation(reaction.metabolites) - output_file.write(reaction.id + sep + - equation + sep + - reaction.lower_bound + sep + - reaction.upper_bound + sep + - reaction.name + sep + - reaction.notes.get("pathway_note", "") + "\n") + output_file.write(sep.join(map(str, [ + reaction.id, + equation, + reaction.lower_bound, + reaction.upper_bound, + reaction.name, + reaction.notes.get("pathway_note", "") + ])) + "\n") def plug_model(self, model): """ diff --git a/cameo/core/target.py b/cameo/core/target.py index 308ab14f8..59bcc3bf9 100644 --- a/cameo/core/target.py +++ b/cameo/core/target.py @@ -342,8 +342,11 @@ def __gt__(self, other): def __eq__(self, other): if isinstance(other, GeneModulationTarget): - return (self.id == other.id and self._value == other._value and - self._reference_value == other._reference_value) + return ( + (self.id == other.id) and ( + self._value == other._value) and ( + self._reference_value == other._reference_value) + ) else: return False @@ -425,8 +428,11 @@ def __gt__(self, other): def __eq__(self, other): if isinstance(other, ReactionModulationTarget): - return (self.id == other.id and self._value == other._value and - self._reference_value == other._reference_value) + return ( + (self.id == other.id) and ( + self._value == other._value) and ( + self._reference_value == other._reference_value) + ) else: return False diff --git a/cameo/flux_analysis/analysis.py b/cameo/flux_analysis/analysis.py index 93ccbec2d..742d28cbe 100644 --- a/cameo/flux_analysis/analysis.py +++ b/cameo/flux_analysis/analysis.py @@ -172,9 +172,13 @@ def find_blocked_reactions(model): for exchange in model.exchanges: exchange.bounds = (-9999, 9999) fva_solution = flux_variability_analysis(model) - return frozenset(reaction for reaction in model.reactions - if round(fva_solution.lower_bound(reaction.id), config.ndecimals) == 0 and - round(fva_solution.upper_bound(reaction.id), config.ndecimals) == 0) + return frozenset( + reaction for reaction in model.reactions + if round( + fva_solution.lower_bound(reaction.id), + config.ndecimals) == 0 and round( + fva_solution.upper_bound(reaction.id), config.ndecimals) == 0 + ) def flux_variability_analysis(model, reactions=None, fraction_of_optimum=0., pfba_factor=None, @@ -303,14 +307,16 @@ def phenotypic_phase_plane(model, variables, objective=None, source=None, points nice_variable_ids = [_nice_id(reaction) for reaction in variable_reactions] variable_reactions_ids = [reaction.id for reaction in variable_reactions] - phase_plane = pandas.DataFrame(envelope, - columns=(variable_reactions_ids + - ['objective_lower_bound', - 'objective_upper_bound', - 'c_yield_lower_bound', - 'c_yield_upper_bound', - 'mass_yield_lower_bound', - 'mass_yield_upper_bound'])) + phase_plane = pandas.DataFrame( + envelope, columns=(variable_reactions_ids + [ + 'objective_lower_bound', + 'objective_upper_bound', + 'c_yield_lower_bound', + 'c_yield_upper_bound', + 'mass_yield_lower_bound', + 'mass_yield_upper_bound' + ]) + ) if objective is None: objective = model.objective diff --git a/cameo/strain_design/deterministic/flux_variability_based.py b/cameo/strain_design/deterministic/flux_variability_based.py index 9b972caa6..d5cf4d7b9 100644 --- a/cameo/strain_design/deterministic/flux_variability_based.py +++ b/cameo/strain_design/deterministic/flux_variability_based.py @@ -77,7 +77,7 @@ class DifferentialFVA(StrainDesignMethod): - """Differential flux variability analysis. + r"""Differential flux variability analysis. Compares flux ranges of a reference model to a set of models that have been parameterized to lie on a grid of evenly spaced points in the @@ -354,22 +354,37 @@ def run(self, surface_only=True, improvements_only=True, progress=True, view=Non df['suddenly_essential'] = False df['free_flux'] = False - df.loc[(df.lower_bound == 0) & (df.upper_bound == 0) & - (ref_upper_bound != 0) & (ref_lower_bound != 0), 'KO'] = True - - df.loc[((ref_upper_bound < 0) & (df.lower_bound > 0) | - ((ref_lower_bound > 0) & (df.upper_bound < 0))), 'flux_reversal'] = True - - df.loc[((df.lower_bound <= 0) & (df.lower_bound > 0)) | - ((ref_lower_bound >= 0) & (df.upper_bound <= 0)), 'suddenly_essential'] = True + df.loc[ + (df.lower_bound == 0) & ( + df.upper_bound == 0) & ( + ref_upper_bound != 0) & ( + ref_lower_bound != 0), + 'KO' + ] = True + + df.loc[ + ((ref_upper_bound < 0) & (df.lower_bound > 0) | ( + (ref_lower_bound > 0) & (df.upper_bound < 0))), + 'flux_reversal' + ] = True + + df.loc[ + ((df.lower_bound <= 0) & (df.lower_bound > 0)) | ( + (ref_lower_bound >= 0) & (df.upper_bound <= 0)), + 'suddenly_essential' + ] = True is_reversible = numpy.asarray([ - self.design_space_model.reactions.get_by_id(i).reversibility for i in df.index], dtype=bool) + self.design_space_model.reactions.get_by_id(i).reversibility + for i in df.index], dtype=bool) not_reversible = numpy.logical_not(is_reversible) - df.loc[((df.lower_bound == -1000) & (df.upper_bound == 1000) & is_reversible) | - ((df.lower_bound == 0) & (df.upper_bound == 1000) & not_reversible) | - ((df.lower_bound == -1000) & (df.upper_bound == 0) & not_reversible), 'free_flux'] = True + df.loc[ + ((df.lower_bound == -1000) & (df.upper_bound == 1000) & is_reversible) | ( + (df.lower_bound == 0) & (df.upper_bound == 1000) & not_reversible) | ( + (df.lower_bound == -1000) & (df.upper_bound == 0) & not_reversible), + 'free_flux' + ] = True df['reaction'] = df.index df['excluded'] = df['reaction'].isin(self.exclude) @@ -481,9 +496,9 @@ def _generate_designs(cls, solutions, reference_fva, reference_fluxes): for _, solution in solutions.groupby(('biomass', 'production')): targets = [] relevant_targets = solution.loc[ - (numpy.abs(solution['normalized_gaps']) > non_zero_flux_threshold) & - numpy.logical_not(solution['excluded']) & - numpy.logical_not(solution['free_flux']) + (numpy.abs(solution['normalized_gaps']) > non_zero_flux_threshold) & ( + numpy.logical_not(solution['excluded'])) & ( + numpy.logical_not(solution['free_flux'])) ] for rid, relevant_row in relevant_targets.iterrows(): if relevant_row.KO: @@ -648,8 +663,9 @@ def _display_on_map_static(self, index, map_name, palette="RdYlBu", **kwargs): data = self.nth_panel(index) # Find values above decimal precision and not NaN data = data.loc[ - ~numpy.isnan(data['normalized_gaps']) & - (data['normalized_gaps'].abs() > non_zero_flux_threshold)] + ~numpy.isnan(data['normalized_gaps']) & ( + data['normalized_gaps'].abs() > non_zero_flux_threshold) + ] data.index = data['reaction'] reaction_data = data['normalized_gaps'].copy() diff --git a/cameo/strain_design/deterministic/linear_programming.py b/cameo/strain_design/deterministic/linear_programming.py index 798d3118e..bdb1d3263 100644 --- a/cameo/strain_design/deterministic/linear_programming.py +++ b/cameo/strain_design/deterministic/linear_programming.py @@ -119,10 +119,12 @@ def __init__(self, model, exclude_reactions=None, remove_blocked=True, fraction_ def _remove_blocked_reactions(self): fva_res = flux_variability_analysis(self._model, fraction_of_optimum=0) + # FIXME: Iterate over the index only (reaction identifiers). blocked = [ self._model.reactions.get_by_id(reaction) for reaction, row in fva_res.data_frame.iterrows() - if (round(row["lower_bound"], config.ndecimals) == - round(row["upper_bound"], config.ndecimals) == 0)] + if (round(row["lower_bound"], config.ndecimals) == round( + row["upper_bound"], config.ndecimals) == 0) + ] self._model.remove_reactions(blocked) def _reduce_to_nullspace(self, reactions): diff --git a/cameo/strain_design/heuristic/evolutionary/optimization.py b/cameo/strain_design/heuristic/evolutionary/optimization.py index 39c9ca976..fe88b5f0e 100644 --- a/cameo/strain_design/heuristic/evolutionary/optimization.py +++ b/cameo/strain_design/heuristic/evolutionary/optimization.py @@ -679,8 +679,12 @@ def __init__(self, reactions=None, essential_reactions=None, use_nullspace_simpl ns = nullspace(create_stoichiometric_array(self.model)) dead_ends = set(find_blocked_reactions_nullspace(self.model, ns=ns)) exchanges = set(self.model.exchanges) - reactions = [r for r in self.model.reactions if r not in exchanges and r not in dead_ends and - r.id not in self.essential_reactions] + reactions = [ + r for r in self.model.reactions + if (r not in exchanges) and ( + r not in dead_ends) and ( + r.id not in self.essential_reactions) + ] groups = find_coupled_reactions_nullspace(self.model, ns=ns) groups_keys = [set(group) for group in groups if any(r.id in reactions for r in group)] From 583d03830c123ec595508fd50cff8ef833a09dc7 Mon Sep 17 00:00:00 2001 From: Nikolaus Sonnenschein Date: Wed, 28 Nov 2018 10:59:33 +0100 Subject: [PATCH 3/5] doc: add zenhub badge --- README.rst | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index 48fb16349..e6701c99b 100644 --- a/README.rst +++ b/README.rst @@ -4,7 +4,7 @@ Cameo—Computer Aided Metabolic Engineering and Optimization .. summary-start |Join the chat at https://gitter.im/biosustain/cameo| |PyPI| |License| -|Build Status| |Coverage Status| |DOI| +|Build Status| |Coverage Status| |DOI| |zenhub| What is cameo? ~~~~~~~~~~~~~~ @@ -136,4 +136,6 @@ Contributions .. |Coverage Status| image:: https://coveralls.io/repos/biosustain/cameo/badge.svg?branch=devel :target: https://coveralls.io/r/biosustain/cameo?branch=devel .. |DOI| image:: https://zenodo.org/badge/5031/biosustain/cameo.svg - :target: https://zenodo.org/badge/latestdoi/5031/biosustain/cameo \ No newline at end of file + :target: https://zenodo.org/badge/latestdoi/5031/biosustain/cameo +.. |zenhub| image:: https://img.shields.io/badge/Shipping_faster_with-ZenHub-5e60ba.svg?style=flat-square + :target: https://zenhub.com From e994d07ef085405927d9635924b05edc9b82528b Mon Sep 17 00:00:00 2001 From: Joshua Lerman Date: Tue, 11 Dec 2018 03:11:27 -0800 Subject: [PATCH 4/5] Update simulation.py to use solution.objective_value vs. legacy solution.f (#218) * Update simulation.py to use solution.objective_value vs. legacy solution.f Update simulation.py to use solution.objective_value vs. legacy solution.f * LNT: Lint lines too long. --- cameo/flux_analysis/simulation.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/cameo/flux_analysis/simulation.py b/cameo/flux_analysis/simulation.py index 8a2a9418e..4a7a10584 100644 --- a/cameo/flux_analysis/simulation.py +++ b/cameo/flux_analysis/simulation.py @@ -178,7 +178,8 @@ def create_objective(model, variables): solution = model.optimize(raise_error=True) if reactions is not None: - result = FluxDistributionResult({r: solution.get_primal_by_id(r) for r in reactions}, solution.f) + result = FluxDistributionResult( + {r: solution.get_primal_by_id(r) for r in reactions}, solution.objective_value) else: result = FluxDistributionResult.from_solution(solution) return result @@ -275,7 +276,8 @@ def create_objective(model, variables): solution = model.optimize(raise_error=True) if reactions is not None: - result = FluxDistributionResult({r: solution.get_primal_by_id(r) for r in reactions}, solution.f) + result = FluxDistributionResult( + {r: solution.get_primal_by_id(r) for r in reactions}, solution.objective_value) else: result = FluxDistributionResult.from_solution(solution) return result @@ -369,7 +371,8 @@ def update_lower_constraint(model, constraint, reaction, variable, flux_value, e solution = model.optimize(raise_error=True) if reactions is not None: - result = FluxDistributionResult({r: solution.get_primal_by_id(r) for r in reactions}, solution.f) + result = FluxDistributionResult( + {r: solution.get_primal_by_id(r) for r in reactions}, solution.objective_value) else: result = FluxDistributionResult.from_solution(solution) return result @@ -392,7 +395,7 @@ class FluxDistributionResult(Result): @classmethod def from_solution(cls, solution, *args, **kwargs): - return cls(solution.fluxes, solution.f, *args, **kwargs) + return cls(solution.fluxes, solution.objective_value, *args, **kwargs) def __init__(self, fluxes, objective_value, *args, **kwargs): super(FluxDistributionResult, self).__init__(*args, **kwargs) From c17309fcf5f0fe41a1789227fecdbc0f76956c96 Mon Sep 17 00:00:00 2001 From: Nikolaus Sonnenschein Date: Tue, 11 Dec 2018 16:33:27 +0100 Subject: [PATCH 5/5] Fix copbrapy f and x_dict deprecation (#221) * fix: get rid of all obvious occurrences of `solution.f` * fix: get rid of all obvious occurrences of `solution.f` in tests * fix: get rid of all obvious occurrences of `solution.x_dict` * refactor: use `slim_optimize` insteady of `model.optimize().objective_value` Co-Authored-By: phantomas1234 --- cameo/__init__.py | 2 +- cameo/flux_analysis/analysis.py | 4 +- cameo/flux_analysis/simulation.py | 4 +- cameo/flux_analysis/util.py | 2 +- .../deterministic/linear_programming.py | 4 +- cameo/visualization/visualization.py | 2 +- tests/test_io.py | 10 ++-- tests/test_solver_based_model.py | 48 +++++++++---------- tests/test_targets.py | 6 +-- 9 files changed, 40 insertions(+), 42 deletions(-) diff --git a/cameo/__init__.py b/cameo/__init__.py index 8ea41ac7d..e36886266 100644 --- a/cameo/__init__.py +++ b/cameo/__init__.py @@ -31,7 +31,7 @@ # optimize the model and print the objective value solution = model.optimize() -print 'Objective value:', solution.f +print 'Objective value:', solution.objective_value # Determine a set of gene deletions that will optimize the production # of a desired compound diff --git a/cameo/flux_analysis/analysis.py b/cameo/flux_analysis/analysis.py index 742d28cbe..9e87d87ca 100644 --- a/cameo/flux_analysis/analysis.py +++ b/cameo/flux_analysis/analysis.py @@ -523,7 +523,7 @@ def _cycle_free_fva(model, reactions=None, sloppy=True, sloppy_bound=666): else: logger.debug('Determine if {} with bound {} is a cycle'.format(reaction.id, bound)) solution = get_solution(model) - v0_fluxes = solution.x_dict + v0_fluxes = solution.fluxes v1_cycle_free_fluxes = remove_infeasible_cycles(model, v0_fluxes) if abs(v1_cycle_free_fluxes[reaction.id] - bound) < 10 ** -6: fva_sol[reaction.id]['lower_bound'] = bound @@ -562,7 +562,7 @@ def _cycle_free_fva(model, reactions=None, sloppy=True, sloppy_bound=666): else: logger.debug('Determine if {} with bound {} is a cycle'.format(reaction.id, bound)) solution = get_solution(model) - v0_fluxes = solution.x_dict + v0_fluxes = solution.fluxes v1_cycle_free_fluxes = remove_infeasible_cycles(model, v0_fluxes) if abs(v1_cycle_free_fluxes[reaction.id] - bound) < 1e-6: fva_sol[reaction.id]['upper_bound'] = v0_fluxes[reaction.id] diff --git a/cameo/flux_analysis/simulation.py b/cameo/flux_analysis/simulation.py index 4a7a10584..171d35dd7 100644 --- a/cameo/flux_analysis/simulation.py +++ b/cameo/flux_analysis/simulation.py @@ -541,13 +541,13 @@ def display_on_map(self, map_name=None, palette="YlGnBu"): # print("cobra fba") # tic = time.time() # cb_model.optimize(solver='cglpk') - # print("flux sum:", sum([abs(val) for val in list(cb_model.solution.x_dict.values())])) + # print("flux sum:", sum([abs(val) for val in list(cb_model.solution.fluxes.values())])) # print("cobra fba runtime:", time.time() - tic) # print("cobra pfba") # tic = time.time() # optimize_minimal_flux(cb_model, solver='cglpk') - # print("flux sum:", sum([abs(val) for val in list(cb_model.solution.x_dict.values())])) + # print("flux sum:", sum([abs(val) for val in list(cb_model.solution.fluxes.values())])) # print("cobra pfba runtime:", time.time() - tic) print("pfba") diff --git a/cameo/flux_analysis/util.py b/cameo/flux_analysis/util.py index d9ad89f4a..46489170f 100644 --- a/cameo/flux_analysis/util.py +++ b/cameo/flux_analysis/util.py @@ -77,7 +77,7 @@ def remove_infeasible_cycles(model, fluxes, fix=()): except OptimizationError as e: logger.warning("Couldn't remove cycles from reference flux distribution.") raise e - result = solution.x_dict + result = solution.fluxes return result diff --git a/cameo/strain_design/deterministic/linear_programming.py b/cameo/strain_design/deterministic/linear_programming.py index bdb1d3263..353d28eea 100644 --- a/cameo/strain_design/deterministic/linear_programming.py +++ b/cameo/strain_design/deterministic/linear_programming.py @@ -267,12 +267,12 @@ def run(self, max_knockouts=5, biomass=None, target=None, max_results=1, *args, for kos in combinations: knockout_list.append({r.id for r in kos}) fluxes_list.append(solution.fluxes) - production_list.append(solution.f) + production_list.append(solution.objective_value) biomass_list.append(solution.fluxes[biomass.id]) else: knockout_list.append({r.id for r in knockouts}) fluxes_list.append(solution.fluxes) - production_list.append(solution.f) + production_list.append(solution.objective_value) biomass_list.append(solution.fluxes[biomass.id]) # Add an integer cut diff --git a/cameo/visualization/visualization.py b/cameo/visualization/visualization.py index faab33016..2f19dd85e 100644 --- a/cameo/visualization/visualization.py +++ b/cameo/visualization/visualization.py @@ -102,7 +102,7 @@ def draw_knockout_result(model, map_name, simulation_method, knockouts, *args, * with model: for reaction in model.reactions.get_by_any(knockouts): reaction.knock_out() - solution = simulation_method(model, *args, **kwargs).x_dict + solution = simulation_method(model, *args, **kwargs).fluxes return Builder(map_name, reaction_data=solution) diff --git a/tests/test_io.py b/tests/test_io.py index 3c136d41e..9a67fad71 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -39,25 +39,25 @@ def solver_interface(request): class TestModelLoading(object): def test_load_model_pickle_path(self, solver_interface): model = load_model(os.path.join(TESTDIR, 'data/iJO1366.pickle'), solver_interface=solver_interface) - assert abs(model.optimize().f - 0.9823718127269768) < 10e-6 + assert abs(model.optimize().objective_value - 0.9823718127269768) < 10e-6 def test_load_model_pickle_handle(self, solver_interface): with open(os.path.join(TESTDIR, 'data/iJO1366.pickle'), 'rb') as handle: model = load_model(handle, solver_interface=solver_interface) - assert abs(model.optimize().f - 0.9823718127269768) < 10e-6 + assert abs(model.slim_optimize() - 0.9823718127269768) < 10e-6 def test_load_model_sbml_path(self, solver_interface): model = load_model(os.path.join(TESTDIR, 'data/iJO1366.xml'), solver_interface=solver_interface) - assert abs(model.optimize().f - 0.9823718127269768) < 10e-6 + assert abs(model.slim_optimize() - 0.9823718127269768) < 10e-6 def test_load_model_sbml_handle(self, solver_interface): with open(os.path.join(TESTDIR, 'data/iJO1366.xml')) as handle: model = load_model(handle, solver_interface=solver_interface) - assert abs(model.optimize().f - 0.9823718127269768) < 10e-6 + assert abs(model.slim_optimize() - 0.9823718127269768) < 10e-6 def test_load_model_sbml_path_set_none_interface(self): model = load_model(os.path.join(TESTDIR, 'data/EcoliCore.xml'), solver_interface=None) - assert abs(model.optimize().f - 0.8739215069684306) < 10e-6 + assert abs(model.slim_optimize() - 0.8739215069684306) < 10e-6 assert isinstance(model, cobra.Model) def test_import_model_bigg(self): diff --git a/tests/test_solver_based_model.py b/tests/test_solver_based_model.py index 6004f7e88..5d1f7c491 100644 --- a/tests/test_solver_based_model.py +++ b/tests/test_solver_based_model.py @@ -68,8 +68,7 @@ def tiny_toy_model(request): m1 = Metabolite("M1") d1 = Reaction("ex1") d1.add_metabolites({m1: -1}) - d1.upper_bound = 0 - d1.lower_bound = -1000 + d1.bounds = -1000, 0 tiny.add_reactions([d1]) tiny.solver = request.param return tiny @@ -78,7 +77,7 @@ def tiny_toy_model(request): # class TestLazySolution: # def test_self_invalidation(self, solved_model): # solution, model = solved_model -# assert abs(solution.f - 0.873921506968431) < 0.000001 +# assert abs(solution.objective_value - 0.873921506968431) < 0.000001 # model.optimize() # with pytest.raises(UndefinedSolution): # getattr(solution, 'f') @@ -206,8 +205,7 @@ def test_set_bounds_scenario_1(self, core_model): def test_set_bounds_scenario_3(self, core_model): reac = core_model.reactions.ACALD - reac.upper_bound = -10 - reac.lower_bound = -10 + reac.bounds = -10, -10 assert reac.lower_bound == -10 assert reac.upper_bound == -10 reac.lower_bound = -9 @@ -242,7 +240,7 @@ def test_set_bounds_scenario_4(self, core_model): assert reac.reverse_variable.ub == 2 def test_set_upper_before_lower_bound_to_0(self, core_model): - core_model.reactions.GAPD.upper_bound = 0 + core_model.reactions.GAPD.bounds = 0, 0 core_model.reactions.GAPD.lower_bound = 0 assert core_model.reactions.GAPD.lower_bound == 0 assert core_model.reactions.GAPD.upper_bound == 0 @@ -804,24 +802,24 @@ def test_invalid_objective_raises(self, core_model): # def test_solver_change(self, core_model): # solver_id = id(core_model.solver) # problem_id = id(core_model.solver.problem) - # solution = core_model.optimize().x_dict + # solution = core_model.optimize().fluxes # core_model.solver = 'glpk' # assert id(core_model.solver) != solver_id # assert id(core_model.solver.problem) != problem_id # new_solution = core_model.optimize() # for key in list(solution.keys()): - # assert round(abs(new_solution.x_dict[key] - solution[key]), 7) == 0 + # assert round(abs(new_solution.fluxes[key] - solution[key]), 7) == 0 # # def test_solver_change_with_optlang_interface(self, core_model): # solver_id = id(core_model.solver) # problem_id = id(core_model.solver.problem) - # solution = core_model.optimize().x_dict + # solution = core_model.optimize().fluxes # core_model.solver = optlang.glpk_interface # assert id(core_model.solver) != solver_id # assert id(core_model.solver.problem) != problem_id # new_solution = core_model.optimize() # for key in list(solution.keys()): - # assert round(abs(new_solution.x_dict[key] - solution[key]), 7) == 0 + # assert round(abs(new_solution.fluxes[key] - solution[key]), 7) == 0 def test_invalid_solver_change_raises(self, core_model): with pytest.raises(SolverNotFound): @@ -833,14 +831,14 @@ def test_invalid_solver_change_raises(self, core_model): @pytest.mark.skipif('cplex' not in solvers, reason='no cplex') def test_change_solver_to_cplex_and_check_copy_works(self, core_model): - assert round(abs(core_model.optimize().f - 0.8739215069684306), 7) == 0 + assert round(abs(core_model.slim_optimize() - 0.8739215069684306), 7) == 0 core_model_copy = core_model.copy() - assert round(abs(core_model_copy.optimize().f - 0.8739215069684306), 7) == 0 + assert round(abs(core_model_copy.slim_optimize() - 0.8739215069684306), 7) == 0 # Second, change existing glpk based model to cplex core_model.solver = 'cplex' - assert round(abs(core_model.optimize().f - 0.8739215069684306), 7) == 0 + assert round(abs(core_model.slim_optimize() - 0.8739215069684306), 7) == 0 core_model_copy = copy.copy(core_model) - assert round(abs(core_model_copy.optimize().f - 0.8739215069684306), 7) == 0 + assert round(abs(core_model_copy.slim_optimize() - 0.8739215069684306), 7) == 0 def test_copy_preserves_existing_solution(self, solved_model): solution, model = solved_model @@ -893,37 +891,37 @@ def test_essential_metabolites(self, core_model): # def test_add_ratio_constraint(self, solved_model): # solution, model = solved_model - # assert round(abs(solution.f - 0.873921506968), 7) == 0 - # assert 2 * solution.x_dict['PGI'] != solution.x_dict['G6PDH2r'] + # assert round(abs(solution.objective_value - 0.873921506968), 7) == 0 + # assert 2 * solution.fluxes['PGI'] != solution.fluxes['G6PDH2r'] # cp = model.copy() # ratio_constr = cp.add_ratio_constraint(cp.reactions.PGI, cp.reactions.G6PDH2r, 0.5) # assert ratio_constr.name == 'ratio_constraint_PGI_G6PDH2r' # solution = cp.optimize() - # assert round(abs(solution.f - 0.870407873712), 7) == 0 - # assert round(abs(2 * solution.x_dict['PGI'] - solution.x_dict['G6PDH2r']), 7) == 0 + # assert round(abs(solution.objective_value - 0.870407873712), 7) == 0 + # assert round(abs(2 * solution.fluxes['PGI'] - solution.fluxes['G6PDH2r']), 7) == 0 # cp = model.copy() # # ratio_constr = cp.add_ratio_constraint(cp.reactions.PGI, cp.reactions.G6PDH2r, 0.5) # assert ratio_constr.name == 'ratio_constraint_PGI_G6PDH2r' # solution = cp.optimize() - # assert round(abs(solution.f - 0.870407873712), 7) == 0 - # assert round(abs(2 * solution.x_dict['PGI'] - solution.x_dict['G6PDH2r']), 7) == 0 + # assert round(abs(solution.objective_value - 0.870407873712), 7) == 0 + # assert round(abs(2 * solution.fluxes['PGI'] - solution.fluxes['G6PDH2r']), 7) == 0 # # cp = model.copy() # ratio_constr = cp.add_ratio_constraint('PGI', 'G6PDH2r', 0.5) # assert ratio_constr.name == 'ratio_constraint_PGI_G6PDH2r' # solution = cp.optimize() - # assert abs(solution.f - 0.870407) < 1e-6 - # assert abs(2 * solution.x_dict['PGI'] - solution.x_dict['G6PDH2r']) < 1e-6 + # assert abs(solution.objective_value - 0.870407) < 1e-6 + # assert abs(2 * solution.fluxes['PGI'] - solution.fluxes['G6PDH2r']) < 1e-6 # # cp = model.copy() # ratio_constr = cp.add_ratio_constraint([cp.reactions.PGI, cp.reactions.ACALD], # [cp.reactions.G6PDH2r, cp.reactions.ACONTa], 0.5) # assert ratio_constr.name == 'ratio_constraint_PGI+ACALD_G6PDH2r+ACONTa' # solution = cp.optimize() - # assert abs(solution.f - 0.872959) < 1e-6 - # assert abs((solution.x_dict['PGI'] + solution.x_dict['ACALD']) - - # 0.5 * (solution.x_dict['G6PDH2r'] + solution.x_dict['ACONTa'])) < 1e-5 + # assert abs(solution.objective_value - 0.872959) < 1e-6 + # assert abs((solution.fluxes['PGI'] + solution.fluxes['ACALD']) - + # 0.5 * (solution.fluxes['G6PDH2r'] + solution.fluxes['ACONTa'])) < 1e-5 def test_fix_objective_as_constraint(self, core_model): # with TimeMachine diff --git a/tests/test_targets.py b/tests/test_targets.py index b65913696..93de55ef0 100644 --- a/tests/test_targets.py +++ b/tests/test_targets.py @@ -64,7 +64,7 @@ def test_reaction_down_regulation_target(self, model): down_reg_target.apply(model) assert model.reactions.PGI.upper_bound == 3.4 assert model.reactions.PGI.lower_bound == -1000 - assert abs(model.optimize().f - 0.8706) < 0.0001 + assert abs(model.slim_optimize() - 0.8706) < 0.0001 assert model.reactions.PGI.upper_bound == 1000 assert model.reactions.PGI.lower_bound == -1000 @@ -81,7 +81,7 @@ def test_reaction_down_regulation_target(self, model): down_reg_target.apply(model) assert model.reactions.RPI.lower_bound == -1.5 assert model.reactions.RPI.upper_bound == 1000 - assert abs(model.optimize().f - 0.8691) < 0.0001 + assert abs(model.slim_optimize() - 0.8691) < 0.0001 assert model.reactions.RPI.lower_bound == -1000 assert model.reactions.RPI.upper_bound == 1000 @@ -191,7 +191,7 @@ def test_gene_knockout_target(self, model): knockout_target.apply(model) assert model.reactions.PGI.lower_bound == 0 assert model.reactions.PGI.upper_bound == 0 - assert abs(model.optimize().f - 0.8631) < 0.0001 + assert abs(model.slim_optimize() - 0.8631) < 0.0001 assert model.reactions.PGI.lower_bound == -1000 assert model.reactions.PGI.upper_bound == 1000