Skip to content

Commit

Permalink
Merge branch 'devel' into metadata_fbc3_group
Browse files Browse the repository at this point in the history
  • Loading branch information
Hemant27031999 authored Aug 27, 2020
2 parents c8b850a + ad49414 commit e77f9ab
Show file tree
Hide file tree
Showing 21 changed files with 198 additions and 96 deletions.
9 changes: 6 additions & 3 deletions src/cobra/core/metabolite.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ def constraint(self):

@property
def elements(self):
""" Dictionary of elements as keys and their count in the metabolite
as integer. When set, the `formula` property is update accordingly """
"""Dictionary of elements as keys and their count in the metabolite
as integer. When set, the `formula` property is update accordingly"""
tmp_formula = self.formula
if tmp_formula is None:
return {}
Expand Down Expand Up @@ -246,7 +246,10 @@ def summary(self, solution=None, fva=None):
from cobra.summary import MetaboliteSummary

return MetaboliteSummary(
metabolite=self, model=self._model, solution=solution, fva=fva,
metabolite=self,
model=self._model,
solution=solution,
fva=fva,
)

def _repr_html_(self):
Expand Down
3 changes: 1 addition & 2 deletions src/cobra/core/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,7 @@ class Model(Object):
"""

def __setstate__(self, state):
"""Make sure all cobra.Objects in the model point to the model.
"""
"""Make sure all cobra.Objects in the model point to the model."""
self.__dict__.update(state)
for y in ["reactions", "genes", "metabolites"]:
for x in getattr(self, y):
Expand Down
11 changes: 7 additions & 4 deletions src/cobra/core/reaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def flux_expression(self):
The expression representing the the forward flux (if associated
with model), otherwise None. Representing the net flux if
model.reversible_encoding == 'unsplit' or None if reaction is
not associated with a model """
not associated with a model"""
if self.model is not None:
return 1.0 * self.forward_variable - 1.0 * self.reverse_variable
else:
Expand Down Expand Up @@ -169,7 +169,7 @@ def reverse_variable(self):

@property
def objective_coefficient(self):
""" Get the coefficient for this reaction in a linear
"""Get the coefficient for this reaction in a linear
objective (float)
Assuming that the objective of the associated model is summation of
Expand Down Expand Up @@ -294,7 +294,7 @@ def upper_bound(self, value):

@property
def bounds(self):
""" Get or set the bounds directly from a tuple
"""Get or set the bounds directly from a tuple
Convenience method for setting upper and lower bounds in one line
using a tuple of lower and upper bound. Invalid bounds will raise an
Expand Down Expand Up @@ -1174,7 +1174,10 @@ def summary(self, solution=None, fva=None):
from cobra.summary import ReactionSummary

return ReactionSummary(
reaction=self, model=self._model, solution=solution, fva=fva,
reaction=self,
model=self._model,
solution=solution,
fva=fva,
)

def __str__(self):
Expand Down
9 changes: 8 additions & 1 deletion src/cobra/flux_analysis/deletion.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,14 @@ def _multi_deletion(

def extract_knockout_results(result_iter):
result = pd.DataFrame(
[(set(ids), growth, status,) for (ids, growth, status) in result_iter],
[
(
set(ids),
growth,
status,
)
for (ids, growth, status) in result_iter
],
columns=["ids", "growth", "status"],
)
return result
Expand Down
97 changes: 48 additions & 49 deletions src/cobra/flux_analysis/gapfilling.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class GapFiller(object):
e1004808. doi:10.1371/journal.pcbi.1004808.
[5] Diener, Christian https://github.com/cdiener/corda
"""
"""

def __init__(
self,
Expand Down Expand Up @@ -178,8 +178,7 @@ def update_costs(self):
self.model.objective.set_linear_coefficients(self.costs)

def add_switches_and_objective(self):
""" Update gapfilling model with switches and the indicator objective.
"""
"""Update gapfilling model with switches and the indicator objective."""
constraints = list()
big_m = max(max(abs(b) for b in r.bounds) for r in self.model.reactions)
prob = self.model.problem
Expand Down Expand Up @@ -291,54 +290,54 @@ def gapfill(
):
"""Perform gapfilling on a model.
See documentation for the class GapFiller.
See documentation for the class GapFiller.
Parameters
----------
model : cobra.Model
The model to perform gap filling on.
universal : cobra.Model, None
A universal model with reactions that can be used to complete the
model. Only gapfill considering demand and exchange reactions if
left missing.
lower_bound : float
The minimally accepted flux for the objective in the filled model.
penalties : dict, None
A dictionary with keys being 'universal' (all reactions included in
the universal model), 'exchange' and 'demand' (all additionally
added exchange and demand reactions) for the three reaction types.
Can also have reaction identifiers for reaction specific costs.
Defaults are 1, 100 and 1 respectively.
iterations : int
The number of rounds of gapfilling to perform. For every iteration,
the penalty for every used reaction increases linearly. This way,
the algorithm is encouraged to search for alternative solutions
which may include previously used reactions. I.e., with enough
iterations pathways including 10 steps will eventually be reported
even if the shortest pathway is a single reaction.
exchange_reactions : bool
Consider adding exchange (uptake) reactions for all metabolites
in the model.
demand_reactions : bool
Consider adding demand reactions for all metabolites.
Parameters
----------
model : cobra.Model
The model to perform gap filling on.
universal : cobra.Model, None
A universal model with reactions that can be used to complete the
model. Only gapfill considering demand and exchange reactions if
left missing.
lower_bound : float
The minimally accepted flux for the objective in the filled model.
penalties : dict, None
A dictionary with keys being 'universal' (all reactions included in
the universal model), 'exchange' and 'demand' (all additionally
added exchange and demand reactions) for the three reaction types.
Can also have reaction identifiers for reaction specific costs.
Defaults are 1, 100 and 1 respectively.
iterations : int
The number of rounds of gapfilling to perform. For every iteration,
the penalty for every used reaction increases linearly. This way,
the algorithm is encouraged to search for alternative solutions
which may include previously used reactions. I.e., with enough
iterations pathways including 10 steps will eventually be reported
even if the shortest pathway is a single reaction.
exchange_reactions : bool
Consider adding exchange (uptake) reactions for all metabolites
in the model.
demand_reactions : bool
Consider adding demand reactions for all metabolites.
Returns
-------
iterable
list of lists with on set of reactions that completes the model per
requested iteration.
Examples
--------
import cobra as ct
>>> from cobra import Model
>>> from cobra.flux_analysis import gapfill
>>> model = ct.create_test_model("salmonella")
>>> universal = Model('universal')
>>> universal.add_reactions(model.reactions.GF6PTA.copy())
>>> model.remove_reactions([model.reactions.GF6PTA])
>>> gapfill(model, universal)
Returns
-------
iterable
list of lists with on set of reactions that completes the model per
requested iteration.
Examples
--------
import cobra as ct
>>> from cobra import Model
>>> from cobra.flux_analysis import gapfill
>>> model = ct.create_test_model("salmonella")
>>> universal = Model('universal')
>>> universal.add_reactions(model.reactions.GF6PTA.copy())
>>> model.remove_reactions([model.reactions.GF6PTA])
>>> gapfill(model, universal)
"""
gapfiller = GapFiller(
model,
Expand Down
4 changes: 3 additions & 1 deletion src/cobra/flux_analysis/loopless.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,9 @@ def loopless_solution(model, fluxes=None):
prob = model.problem
# Needs one fixed bound for cplex...
loopless_obj_constraint = prob.Constraint(
model.objective.expression, lb=-1e32, name="loopless_obj_constraint",
model.objective.expression,
lb=-1e32,
name="loopless_obj_constraint",
)
model.add_cons_vars([loopless_obj_constraint])
_add_cycle_free(model, fluxes)
Expand Down
9 changes: 7 additions & 2 deletions src/cobra/flux_analysis/variability.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,8 @@ def flux_variability_analysis(
if pfba_factor is not None:
if pfba_factor < 1.0:
warn(
"The 'pfba_factor' should be larger or equal to 1.", UserWarning,
"The 'pfba_factor' should be larger or equal to 1.",
UserWarning,
)
with model:
add_pfba(model, fraction_of_optimum=0)
Expand Down Expand Up @@ -227,7 +228,11 @@ def flux_variability_analysis(


def find_blocked_reactions(
model, reaction_list=None, zero_cutoff=None, open_exchanges=False, processes=None,
model,
reaction_list=None,
zero_cutoff=None,
open_exchanges=False,
processes=None,
):
"""
Find reactions that cannot carry any flux.
Expand Down
5 changes: 3 additions & 2 deletions src/cobra/io/sbml.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ class CobraSBMLError(Exception):

def _escape_non_alphanum(nonASCII):
"""converts a non alphanumeric character to a string representation of
its ascii number """
its ascii number"""
return "__" + str(ord(nonASCII.group())) + "__"


Expand Down Expand Up @@ -544,7 +544,7 @@ def _sbml_to_model(

# GPR rules
def process_association(ass):
""" Recursively convert gpr association to a gpr string.
"""Recursively convert gpr association to a gpr string.
Defined as inline functions to not pass the replacement dict around.
"""
if ass.isFbcOr():
Expand Down Expand Up @@ -1352,6 +1352,7 @@ def _check(value, message):
# -----------------------------------------------------------------------------
# Notes
# -----------------------------------------------------------------------------

def _parse_notes_info(sbase: libsbml.SBase) -> Notes:
""" Creates Notes object.
Expand Down
3 changes: 2 additions & 1 deletion src/cobra/sampling/achr.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,8 @@ def sample(self, n, fluxes=True):
names = [r.id for r in self.model.reactions]

return pandas.DataFrame(
samples[:, self.fwd_idx] - samples[:, self.rev_idx], columns=names,
samples[:, self.fwd_idx] - samples[:, self.rev_idx],
columns=names,
)
else:
names = [v.name for v in self.model.variables]
Expand Down
66 changes: 57 additions & 9 deletions src/cobra/sampling/hr_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,9 @@ def generate_fva_warmup(self):

primals = self.model.solver.primal_values
sol = [primals[v.name] for v in self.model.variables]
self.warmup[self.n_warmup,] = sol
self.warmup[
self.n_warmup,
] = sol
self.n_warmup += 1

# Reset objective
Expand Down Expand Up @@ -391,13 +393,33 @@ def _bounds_dist(self, p):
"""Get the lower and upper bound distances. Negative is bad."""

prob = self.problem
lb_dist = (p - prob.variable_bounds[0,]).min()
ub_dist = (prob.variable_bounds[1,] - p).min()
lb_dist = (
p
- prob.variable_bounds[
0,
]
).min()
ub_dist = (
prob.variable_bounds[
1,
]
- p
).min()

if prob.bounds.shape[0] > 0:
const = prob.inequalities.dot(p)
const_lb_dist = (const - prob.bounds[0,]).min()
const_ub_dist = (prob.bounds[1,] - const).min()
const_lb_dist = (
const
- prob.bounds[
0,
]
).min()
const_ub_dist = (
prob.bounds[
1,
]
- const
).min()
lb_dist = min(lb_dist, const_lb_dist)
ub_dist = min(ub_dist, const_ub_dist)

Expand Down Expand Up @@ -486,13 +508,39 @@ def validate(self, samples):
)

feasibility = np.abs(S.dot(samples.T).T - b).max(axis=1)
lb_error = (samples - bounds[0,]).min(axis=1)
ub_error = (bounds[1,] - samples).min(axis=1)
lb_error = (
samples
- bounds[
0,
]
).min(axis=1)
ub_error = (
bounds[
1,
]
- samples
).min(axis=1)

if samples.shape[1] == len(self.model.variables) and prob.inequalities.shape[0]:
consts = prob.inequalities.dot(samples.T)
lb_error = np.minimum(lb_error, (consts - prob.bounds[0,]).min(axis=1))
ub_error = np.minimum(ub_error, (prob.bounds[1,] - consts).min(axis=1))
lb_error = np.minimum(
lb_error,
(
consts
- prob.bounds[
0,
]
).min(axis=1),
)
ub_error = np.minimum(
ub_error,
(
prob.bounds[
1,
]
- consts
).min(axis=1),
)

valid = (
(feasibility < self.feasibility_tol)
Expand Down
3 changes: 2 additions & 1 deletion src/cobra/sampling/optgp.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,8 @@ def sample(self, n, fluxes=True):
names = [r.id for r in self.model.reactions]

return pandas.DataFrame(
chains[:, self.fwd_idx] - chains[:, self.rev_idx], columns=names,
chains[:, self.fwd_idx] - chains[:, self.rev_idx],
columns=names,
)
else:
names = [v.name for v in self.model.variables]
Expand Down
Loading

0 comments on commit e77f9ab

Please sign in to comment.