Commit aefe3f1b authored by Elad Noor's avatar Elad Noor

Merge branch 'flake8' into 'develop'

Flake8

See merge request !5
parents 911597ee 6cd003e9
Pipeline #47478717 (#126) passed with stage
in 18 minutes and 21 seconds
......@@ -12,7 +12,7 @@ test36:
image: python:3.6
script:
- tox -e isort
# - tox -e flake8
- tox -e flake8
- tox -e safety
- tox -e py36 -- --cov-report xml --cov-report term
......
"""Command-line script for estimating dGs in batch."""
# The MIT License (MIT)
#
# Copyright (c) 2013 Weizmann Institute of Science
......@@ -40,11 +41,12 @@ if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Calculate potentials for a number of reactions.')
parser.add_argument('infile', type=argparse.FileType('r'),
help='path to input file containing reactions')
help='path to input file containing reactions')
parser.add_argument('outfile', type=argparse.FileType('w'),
help='path to output file')
help='path to output file')
parser.add_argument('--plaintext', action='store_true',
help='indicate that reactions are given in plain text (not accessions)')
help="'indicate that reactions are given in plain text"
" (not accessions)")
parser.add_argument('--ph', type=str,
help='pH level',
default="7.0")
......@@ -80,11 +82,8 @@ if __name__ == '__main__':
infile_lines = list(filter(None, map(str.strip, args.infile.readlines())))
if args.plaintext:
raise Exception("ReactionMatcher needs to be reimplemented")
#reaction_matcher = ReactionMatcher()
#reactions = list(map(reaction_matcher.match, infile_lines))
raise NotImplementedError("ReactionMatcher needs to be reimplemented")
else:
reactions = list(map(Reaction.parse_formula, infile_lines))
......@@ -105,10 +104,11 @@ if __name__ == '__main__':
result_df["comment"] = ""
non_balanced = result_df["reaction (parsed)"].apply(
lambda r: r.is_balanced(raise_exception=False) == False
lambda r: not r.is_balanced(raise_exception=False)
)
result_df.loc[non_balanced, "ln(Reversibility index)"] = np.nan
result_df.loc[non_balanced, "comment"] = "reaction is not chemically balanced"
result_df.loc[non_balanced, "comment"] = ("reaction is not chemically "
"balanced")
result_df.to_csv(args.outfile)
args.outfile.flush()
"""Command-line script for estimating dG of single reactions."""
# The MIT License (MIT)
#
# Copyright (c) 2013 Weizmann Institute of Science
......@@ -37,6 +38,7 @@ from equilibrator_api import Q_, ComponentContribution, Reaction
def MakeParser():
"""Parser for equilibrator_cmd."""
parser = argparse.ArgumentParser(
description=('Estimate the Gibbs energy of a reaction. For example,'
'the following calculates dGr0 for ATP hydrolysis '
......@@ -76,9 +78,9 @@ if temperature.check(None):
else:
assert temperature.check("[temperature]")
sys.stderr.write('pH = %s\n' % p_h)
sys.stderr.write('I = %s\n' % ionic_strength)
sys.stderr.write('T = %s\n' % temperature)
sys.stderr.write(f"pH = {p_h}\n")
sys.stderr.write(f"I = {ionic_strength}\n")
sys.stderr.write(f"T = {temperature}\n")
sys.stderr.flush()
# parse the reaction
......
"""Command-line script for pathway analysis."""
# The MIT License (MIT)
#
# Copyright (c) 2013 Weizmann Institute of Science
......@@ -28,7 +29,6 @@
import argparse
import logging
import pandas as pd
from matplotlib.backends.backend_pdf import PdfPages
from equilibrator_api import Pathway
......@@ -56,7 +56,6 @@ if __name__ == '__main__':
pdf.savefig(mdf_res.compound_plot)
pdf.savefig(mdf_res.reaction_plot)
net_rxn = pp.net_reaction()
rxn_df = mdf_res.reaction_df
cpd_df = mdf_res.compound_df
......@@ -62,6 +62,7 @@ universal = 1
max-line-length = 80
exclude =
__init__.py
_version.py
[pydocstyle]
match_dir = equilibrator_api
......
......@@ -28,11 +28,27 @@ from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
import numpy as np
from equilibrator_cache import Compound, ureg, Q_, R
from equilibrator_cache.compound_cache import ccache
from equilibrator_cache.thermodynamic_constants import (
FARADAY, POSSIBLE_REACTION_ARROWS, Q_, R, default_I, default_pH,
default_pMg, default_T, physiological_concentration,
standard_concentration, ureg)
default_pMg = Q_("14.0")
default_phase = 'aqueous'
default_conc_lb = Q_("1e-6 M")
default_conc_ub = Q_("1e-2 M")
def strip_units(v: np.array) -> np.array:
return np.array(list(map(float, v.flat))).reshape(v.shape)
from equilibrator_api.bounds import Bounds
from equilibrator_api.pathway import Pathway
from equilibrator_api.phased_reaction import PhasedReaction as Reaction
from equilibrator_api.component_contribution import ComponentContribution
from equilibrator_api.thermo_models import PathwayThermoModel
This diff is collapsed.
"""A wrapper for the GibbeEnergyPredictor in component-contribution."""
# The MIT License (MIT)
#
# Copyright (c) 2013 Weizmann Institute of Science
......@@ -29,17 +30,16 @@ from typing import Dict, List, Tuple
import numpy as np
from component_contribution import GibbsEnergyPredictor
from equilibrator_cache.reaction import Reaction
from . import Compound, ureg
from .phased_reaction import AQUEOUS_PHASE, PHASED_COMPOUND_DICT, PhasedReaction
from .settings import FARADAY, R, default_I, default_pH, default_pMg, default_T
from . import (
FARADAY, Compound, R, default_I, default_pH, default_pMg, default_T, ureg)
from .phased_reaction import PhasedReaction
class ComponentContribution(object):
"""
This class is basically a wrapper for GibbsEnergyPredictor that also
holds default conditions for compounds in the different phases,
"""A wrapper class for GibbsEnergyPredictor.
Also holds default conditions for compounds in the different phases.
"""
@ureg.check(None, None, None, '[concentration]', '[temperature]')
......@@ -50,7 +50,13 @@ class ComponentContribution(object):
ionic_strength: float = default_I,
temperature: float = default_T
) -> object:
"""Create a ComponentContribution object.
:param p_h:
:param p_mg:
:param ionic_strength:
:param temperature:
"""
self.predictor = GibbsEnergyPredictor()
self.p_h = p_h
self.ionic_strength = ionic_strength
......@@ -59,6 +65,7 @@ class ComponentContribution(object):
@property
def RT(self) -> float:
"""Get the value of RT."""
return R * self.temperature
def standard_dg_prime_multi(
......@@ -75,12 +82,10 @@ class ComponentContribution(object):
U as the covariance of a Gaussian used for sampling
(where dG0_cc is the mean of that Gaussian).
"""
rxn_aquoues, dg_prime_nonaq = zip(*
[reaction.split_aqueous_phase(
p_h=self.p_h,
ionic_strength=self.ionic_strength,
temperature=self.temperature)
for reaction in reactions])
rxn_dg_pairs = map(lambda r: r.split_aqueous_phase(
p_h=self.p_h, ionic_strength=self.ionic_strength,
temperature=self.temperature), reactions)
rxn_aquoues, dg_prime_nonaq = zip(*rxn_dg_pairs)
dg_prime_nonaq = np.array(dg_prime_nonaq)
standard_dg_prime, dg_sigma = self.predictor.standard_dg_prime_multi(
......@@ -122,20 +127,16 @@ class ComponentContribution(object):
reaction: PhasedReaction,
compound_to_conc: Dict[Compound, float]
) -> Tuple[float, float]:
"""Calculate the dG'0 of a single reaction.
:param reaction: an object of type Reaction
:param compound_to_conc: a dictionary mapping Compound objects to
concentration in M (default is 1M)
:return: a tuple of (dG_r_prime, dG_uncertainty) where dG_r_prime is
the estimated Gibbs free energy of reaction and dG_uncertainty is the
standard deviation of estimation. Multiply it by 1.96 to get a 95%
confidence interval (which is the value shown on eQuilibrator).
"""
Calculate the dG'0 of a single reaction
Arguments:
reaction - an object of type Reaction
compound_to_conc - a dictionary mapping Compound objects
to concentration in M (default is 1M)
Returns:
dG_r_prime - estimated Gibbs free energy of reaction
dG_uncertainty - standard deviation of estimation, multiply
by 1.96 to get a 95% confidence interval
(which is the value shown on eQuilibrator)
"""
dg_prime, dg_uncertainty = self.standard_dg_prime(reaction)
dg_prime += self.RT * reaction.dg_correction(compound_to_conc)
return dg_prime, dg_uncertainty
......@@ -144,32 +145,27 @@ class ComponentContribution(object):
self,
reaction: PhasedReaction
) -> Tuple[float, float]:
"""
Calculate the dG'm of a single reaction (i.e. if all reactants are
at 1 mM, except H2O)
"""Calculate the dG'm of a single reaction.
Arguments:
reaction - an object of type Reaction
Assume all aqueous reactants are at 1 mM, gas reactants at 1 mbar and
the rest at their standard concentration.
Returns:
physiological_dg_prime - estimated Gibbs free energy of reaction
dg_uncertainty - standard deviation of estimation, multiply
by 1.96 to get a 95% confidence interval
(which is the value shown on eQuilibrator)
:param reaction: an object of type PhasedReaction
:return: a tuple (dG_r_prime, dG_uncertainty) where dG_r_prime is
the estimated Gibbs free energy of reaction and dG_uncertainty is the
standard deviation of estimation. Multiply it by 1.96 to get a 95%
confidence interval (which is the value shown on eQuilibrator).
"""
physiological_dg_prime, dg_uncertainty = self.standard_dg_prime(
reaction)
physiological_dg_prime += self.RT * \
reaction.physiological_dg_correction()
physiological_dg_prime += \
self.RT * reaction.physiological_dg_correction()
return physiological_dg_prime, dg_uncertainty
def ln_reversibility_index(self, reaction: PhasedReaction) -> float:
"""
Calculate the reversibility index (ln Gamma) of a single reaction
"""Calculate the reversibility index (ln Gamma) of a single reaction.
Returns:
ln_RI - The reversibility index (in natural log scale)
:return: ln_RI - The reversibility index (in natural log scale).
"""
physiological_dg_prime, _ = self.physiological_dg_prime(reaction)
......@@ -180,8 +176,14 @@ class ComponentContribution(object):
return ln_RI
def standard_e_prime(self, reaction: PhasedReaction) -> Tuple[float, float]:
"""
Calculate the E'0 of a single half-reaction
"""Calculate the E'0 of a single half-reaction.
:param reaction: a PhasedReaction object
:return: a tuple (E0_prime, E0_uncertainty) where E0_prime is
the estimated standard electrostatic potential of reaction and
E0_uncertainty is the standard deviation of estimation. Multiply it
by 1.96 to get a 95% confidence interval (which is the value shown on
eQuilibrator).
"""
n_e = reaction.check_half_reaction_balancing()
if n_e is None:
......@@ -192,13 +194,26 @@ class ComponentContribution(object):
dG0_prime, dG0_uncertainty = self.standard_dg_prime(reaction)
E0_prime = -dG0_prime / (n_e*FARADAY) # in Volts
E0_uncertainty = dG0_uncertainty / (n_e*FARADAY) # in Volts
E0_prime = -dG0_prime / (n_e*FARADAY) # in Volts
E0_uncertainty = dG0_uncertainty / (n_e*FARADAY) # in Volts
return E0_prime, E0_uncertainty
def dG0_analysis(self, reaction: PhasedReaction) -> List[Dict[str, object]]:
def dg_analysis(
self,
reaction: PhasedReaction
) -> List[Dict[str, object]]:
"""Get the analysis of the component contribution estimation process.
:param reaction: a PhasedReaction object.
:return: the analysis results as a list of dictionaries
"""
return self.predictor.get_dg_analysis(reaction)
def IsUsingGroupContributions(self, reaction: PhasedReaction) -> bool:
"""Check whether group contribution is needed to get this reactions' dG.
:param reaction: a PhasedReaction object.
:return: true iff group contribution is needed
"""
return self.predictor.is_using_group_contribution(reaction)
"""analyze pathways using thermodynamic models."""
# The MIT License (MIT)
#
# Copyright (c) 2013 Weizmann Institute of Science
......@@ -37,29 +38,12 @@ from equilibrator_cache.reaction import (
from sbtab import SBtab
from scipy.linalg import fractional_matrix_power
from . import Compound
from . import (
Q_, Compound, R, default_I, default_pH, default_pMg, default_T, strip_units)
from .bounds import Bounds
from .component_contribution import ComponentContribution
from .phased_reaction import PhasedReaction
from .settings import (
Q_, R, default_I, default_pH, default_pMg, default_T, strip_units)
from .thermo_models import PathwayThermoModel
class PathwayParseError(Exception):
pass
class InvalidReactionFormula(PathwayParseError):
pass
class UnbalancedReaction(PathwayParseError):
pass
class ViolatesFirstLaw(PathwayParseError):
pass
from .thermo_models import PathwayMDFData, PathwayThermoModel
class Pathway(object):
......@@ -120,10 +104,10 @@ class Pathway(object):
S_inv = np.linalg.pinv(S_T)
null_proj = np.eye(self.S.shape[1]) - S_T @ S_inv
projected = null_proj @ standard_dg_primes.T
if (projected > Q_("1e-8 kJ/mol")).any():
raise ViolatesFirstLaw(
'Supplied reaction dG values are inconsistent '
'with the stoichiometric matrix.')
assert (projected < Q_("1e-8 kJ/mol")).all(), (
"Supplied reaction standard deltaG values are inconsistent "
"with the stoichiometric matrix."
)
self.standard_dg_primes = standard_dg_primes
......@@ -144,6 +128,13 @@ class Pathway(object):
ionic_strength: float = None,
temperature: float = None
) -> None:
"""Set the aqueous conditions and recalculate the standard dG' values.
:param p_h:
:param p_mg:
:param ionic_strength:
:param temperature:
"""
if self.comp_contrib is None:
p_h = p_h or default_pH
p_mg = p_mg or default_pMg
......@@ -178,32 +169,48 @@ class Pathway(object):
self,
mapping: Callable[[Compound], str]
) -> None:
"""Use alternative compound names for outputs such as plots
Args:
mapping: a dictionary mapping compounds to their names in the model
"""Use alternative compound names for outputs such as plots.
:param mapping: a dictionary mapping compounds to their names in the
model
"""
self.compound_names = list(map(mapping, self.S.index))
@property
def bounds(self) -> Tuple[Iterable[float], Iterable[float]]:
"""Get the concentration bounds.
The order of compounds is according to the stoichiometric matrix index.
:return: tuple of (lower bounds, upper bounds)
"""
return self._bounds.GetBounds(self.S.index)
@property
def ln_conc_lb(self) -> np.array:
"""Get the log lower bounds on the concentrations.
The order of compounds is according to the stoichiometric matrix index.
:return: a NumPy array of the log lower bounds
"""
return np.array(list(map(float,
self._bounds.GetLnLowerBounds(self.S.index))))
@property
def ln_conc_ub(self) -> np.array:
"""Get the log upper bounds on the concentrations.
The order of compounds is according to the stoichiometric matrix index.
:return: a NumPy array of the log upper bounds
"""
return np.array(list(map(float,
self._bounds.GetLnUpperBounds(self.S.index))))
@staticmethod
def get_compounds(reactions: List[PhasedReaction]) -> List[Compound]:
"""
Returns a unique list of all compounds in all reactions
def get_compounds(reactions: Iterable[PhasedReaction]) -> List[Compound]:
"""Get a unique list of all compounds in all reactions.
:param reactions: an iterator of reactions
:return: a list of unique compounds
"""
compounds = set()
for r in reactions:
......@@ -211,16 +218,36 @@ class Pathway(object):
return sorted(compounds)
def calc_mdf(self, stdev_factor: float = 1.0) -> object:
def calc_mdf(self, stdev_factor: float = 1.0) -> PathwayMDFData:
"""Calculate the Max-min Driving Force.
:param stdev_factor: the factor by which to multiply the uncertainties
:return: a PathwayMDFData object with the results
"""
return PathwayThermoModel(self, stdev_factor).FindMDF()
@property
def reaction_ids(self) -> Iterable[str]:
"""Iterate through all the reaction IDs.
:return: the reaction IDs
"""
return map(lambda rxn: rxn.reaction_id, self.reactions)
@property
def reaction_formulas(self) -> Iterable[str]:
"""Iterate through all the reaction formulas.
:return: the reaction formulas
"""
return map(str, self.reactions)
@property
def net_reaction(self) -> PhasedReaction:
"""Calculate the sum of all the reactions in the pathway.
:return: the net reaction
"""
v = np.array(list(map(float, self.fluxes)))
net_rxn_stoich = self.S @ v
net_rxn_stoich = net_rxn_stoich[net_rxn_stoich != 0]
......@@ -235,12 +262,17 @@ class Pathway(object):
p_mg: float = default_pMg,
ionic_strength: float = default_I,
temperature: float = default_T) -> object:
"""Returns a pathway parsed from an input file.
"""Parse a CSV file and return a Pathway object.
Caller responsible for closing f.
Args:
f: file-like object containing CSV data describing the pathway.
:param f: file-like object containing CSV data describing the pathway
:param bounds: a Bounds object
:param p_h:
:param p_mg:
:param ionic_strength:
:param: temperature:
:return: a Pathway object
"""
reactions = []
fluxes = []
......@@ -264,24 +296,34 @@ class Pathway(object):
return pp
@classmethod
def from_sbtab(self, sbtab) -> object:
"""
read the sbtab file (can be a filename or file handel)
and use it to initialize the Pathway
def open_sbtab(cls, sbtab) -> SBtab.SBtabDocument:
"""Open an SBtabDocument.
:param sbtab: a file name, stream, or SBtabDocument to open
:return: an SBtabDocument object
"""
if type(sbtab) == SBtab.SBtabDocument:
sbtabdoc = sbtab
return sbtab
elif type(sbtab) == str:
sbtabdoc = SBtab.read_csv(sbtab, "pathway")
return SBtab.read_csv(sbtab, "pathway")
elif isinstance(sbtab, IOBase):
sbtab_contents = sbtab.read()
if type(sbtab_contents) == bytes:
sbtab_contents = sbtab_contents.decode('utf-8')
sbtabdoc = SBtab.SBtabDocument("pathway", sbtab_contents,
"unnamed_sbtab.tsv")
else:
raise ValueError("sbtab must be either a file name or a Stream "
"object")
return SBtab.SBtabDocument("pathway", sbtab_contents,
"unnamed_sbtab.tsv")
raise ValueError("sbtab must be either a file name or a Stream "
"object")
@classmethod
def from_sbtab(cls, sbtab) -> object:
"""Parse and SBtabDocument and return a Pathway.
:param sbtab: a file name, stream, or SBtabDocument to open
:return: a Pathway object
"""
sbtabdoc = cls.open_sbtab(sbtab)
table_ids = ['ConcentrationConstraint', 'Reaction', 'RelativeFlux',
'Parameter']
dfs = []
......@@ -290,10 +332,10 @@ class Pathway(object):
sbtab = sbtabdoc.get_sbtab_by_id(table_id)
if sbtab is None:
tables = ', '.join(map(lambda s: s.table_id, sbtabdoc.sbtabs))
raise PathwayParseError(f"The SBtabDocument must have a table "
f"with the following ID: {table_id}, "
f"however, only these tables were "
f"found: {tables}")
raise ValueError(f"The SBtabDocument must have a table "
f"with the following ID: {table_id}, "
f"however, only these tables were "
f"found: {tables}")
dfs.append(sbtab.to_data_frame())
bounds_df, reaction_df, flux_df, param_df = dfs
......
"""inherit from equilibrator_cache.reaction.Reaction an add phases."""
# The MIT License (MIT)
#
# Copyright (c) 2013 Weizmann Institute of Science
......@@ -42,12 +43,13 @@ SOLID_PHASE = 's'
LIQUID_PHASE = 'l'
PhaseInfo = namedtuple("phase_info", "name "
"standard_abundance "
"physiolical_abundance "
"dimensionality")
"standard_abundance "
"physiolical_abundance "
"dimensionality")
PHASE_INFO_DICT = {
AQUEOUS_PHASE: PhaseInfo("aqueous",Q_("1 M"),Q_("1 mM"),"[concentration]"),
AQUEOUS_PHASE: PhaseInfo("aqueous", Q_("1 M"), Q_("1 mM"),
"[concentration]"),
GAS_PHASE: PhaseInfo("gas", Q_("1 bar"), Q_("1 mbar"), "[pressure]"),
SOLID_PHASE: PhaseInfo("solid", None, None, "[dimensionless]"),
LIQUID_PHASE: PhaseInfo("liquid", None, None, "[dimensionless]")
......@@ -73,21 +75,22 @@ MicroSpecie = namedtuple("microspecie", "standard_dgf num_protons charge")
# None, use the value from component_contribution
PHASED_COMPOUND_DICT = {
("MNXM4", GAS_PHASE): MicroSpecie(
standard_dgf=Q_("0 kJ/mol"), num_protons=0, charge=0), # O2
standard_dgf=Q_("0 kJ/mol"), num_protons=0, charge=0), # O2
("MNXM195", GAS_PHASE): MicroSpecie(
standard_dgf=Q_("0 kJ/mol"), num_protons=2, charge=0), # H2
standard_dgf=Q_("0 kJ/mol"), num_protons=2, charge=0), # H2
("MNXM724", GAS_PHASE): MicroSpecie(
standard_dgf=Q_("0 kJ/mol"), num_protons=0, charge=0), # N2
standard_dgf=Q_("0 kJ/mol"), num_protons=0, charge=0), # N2
("MNXM13", GAS_PHASE): MicroSpecie(
standard_dgf=Q_("-394.36 kJ/mol"), num_protons=0, charge=0), # CO2
standard_dgf=Q_("-394.36 kJ/mol"), num_protons=0, charge=0), # CO2
("MNXM10881", GAS_PHASE): MicroSpecie(
standard_dgf=Q_("-137.17 kJ/mol"), num_protons=0, charge=0), # CO
standard_dgf=Q_("-137.17 kJ/mol"), num_protons=0, charge=0), # CO
("MNXM89", SOLID_PHASE): MicroSpecie(
standard_dgf=Q_("0 kJ/mol"), num_protons=0, charge=0), # S8
standard_dgf=Q_("0 kJ/mol"), num_protons=0, charge=0), # S8
}
class PhasedReaction(Reaction):
"""A daughter class of Reaction that adds phases to each compound."""
REACTION_COUNTER = 0
......@@ -97,6 +100,12 @@ class PhasedReaction(Reaction):
arrow: str = "<=>",
rid: str = None
) -> object:
"""Create a PhasedReaction object.
:param sparse: a dictionary of Compounds to stoichiometric coefficients
:param arrow: a string representing the arrow in the chemical formula
:param rid: a string of the reaction ID
"""
super(PhasedReaction, self).__init__(sparse, arrow, rid)
if rid is not None:
......@@ -110,16 +119,33 @@ class PhasedReaction(Reaction):
@staticmethod
def get_default_phase(compound: Compound):
"""Get the default phase of a compound.
:param compound: a Compound
:return: the default phase
"""
if compound.mnx_id in NON_AQUEOUS_COMPOUND_DICT:
return NON_AQUEOUS_COMPOUND_DICT[compound.mnx_id][0]
else:
return AQUEOUS_PHASE
def change_phase(self, compound: Compound, phase: str) -> None:
"""Change the phase of a specific compound.
:param compound:
:param phase:
:return:
"""
if compound.mnx_id in NON_AQUEOUS_COMPOUND_DICT:
assert phase in NON_AQUEOUS_COMPOUND_DICT[compound.mnx_id]
possible_phases = NON_AQUEOUS_COMPOUND_DICT[compound.mnx_id]
assert phase in possible_phases, (
f"The phase of {compound} must be one of the following: "
f"{str(possible_phases)}."
)
else:
assert phase == AQUEOUS_PHASE
assert phase == AQUEOUS_PHASE, (
f"The phase of {compound} can only by aqueous."
)
self.compound_to_phase[compound] = phase
......@@ -130,7 +156,7 @@ class PhasedReaction(Reaction):
ionic_strength: float,
temperature: float
) -> Tuple[Reaction, float]:
"""
"""Split the PhasedReaction to aqueous phase and all the rest.
:param p_h:
:param ionic_strength:
......@@ -163,16 +189,12 @@ class PhasedReaction(Reaction):
self,
compound_to_conc: Dict[Compound, float]
) -> float:
"""
Calculate the concentration adjustment in the dG' of reaction.
Arguments:
compound_to_conc - a dictionary mapping Compound objects
to concentration in M (default is 1M)
"""Calculate the concentration adjustment in the dG' of reaction.
Returns:
ddg_over_rt - correction for delta G in units of RT
:param compound_to_conc: a dictionary mapping Compound objects to
concentration in M (default is 1M)
:return: the correction for delta G in units of RT
"""
# here we check that each concentration is in suitable units,
# depending on the phase of that compound
ddg_over_rt = Q_(0.0)
......@@ -199,13 +221,12 @@ class PhasedReaction(Reaction):
return ddg_over_rt
def physiological_dg_correction(self) -> float:
"""
Calculate the concentration adjustment in the dG' of reaction
assuming all reactants are in the default physiological
concentrations (i.e. 1 mM)
"""Calculate the concentration adjustment in the dG' of reaction.
Assuming all reactants are in the default physiological
concentrations (i.e. 1 mM)
Returns:
ddg_over_rt - correction for delta G in units of RT
:return: the correction for delta G in units of RT
"""
compound_to_conc = {}
for compound, phase in self.compound_to_phase.items():
......@@ -215,15 +236,15 @@ class PhasedReaction(Reaction):
return self.dg_correction(compound_to_conc)
def balance_by_oxidation(self):
"""Convert an unbalanced reaction into oxidation.
By adding H2O, O2, Pi, CO2, and NH4+ to both sides.
"""