return <NUM_LIT:1> / (exp(z) - <NUM_LIT:1>)<EOL>

Calculate the g0 parameter.

:param z: dimensionless temperature


def _calc_a(self, y_C, y_H, y_O, y_N, y_S):

return <NUM_LIT:1> / (y_C/mm("<STR_LIT:C>") + y_H/mm("<STR_LIT:H>") + y_O/mm("<STR_LIT:O>") + y_N/mm("<STR_LIT:N>") +<EOL>y_S/mm("<STR_LIT:S>"))<EOL>

Calculate the mean atomic weight for the specified element mass
fractions.

:param y_C: Carbon mass fraction
:param y_H: Hydrogen mass fraction
:param y_O: Oxygen mass fraction
:param y_N: Nitrogen mass fraction
:param y_S: Sulphur mass fraction

:returns: [kg/kmol] mean atomic weight

See equation at bottom of page 538 of Merrick1983a.


super().calculate(**state)<EOL>return np.polyval(self._coeffs, state['<STR_LIT:T>'])<EOL>

Calculate the material physical property at the specified temperature
in the units specified by the object's 'property_units' property.

:param T: [K] temperature

:returns: physical property value


@staticmethod<EOL><INDENT>def create(dataset, symbol, degree):<DEDENT>

x_vals = dataset.data['<STR_LIT:T>'].tolist()<EOL>y_vals = dataset.data[symbol].tolist()<EOL>coeffs = np.polyfit(x_vals, y_vals, degree)<EOL>result = PolynomialModelT(dataset.material,<EOL>dataset.names_dict[symbol],<EOL>symbol, dataset.display_symbols_dict[symbol],<EOL>dataset.units_dict[symbol],<EOL>None, [dataset.name], coeffs)<EOL>result.state_schema['<STR_LIT:T>']['<STR_LIT>'] = float(min(x_vals))<EOL>result.state_schema['<STR_LIT:T>']['<STR_LIT>'] = float(max(x_vals))<EOL>return result<EOL>

Create a model object from the data set for the property specified by
the supplied symbol, using the specified polynomial degree.

:param dataset: a DataSet object
:param symbol: the symbol of the property to be described, e.g. 'rho'
:param degree: the polynomial degree to use

:returns: a new PolynomialModelT object


if not self.state_validator.validate(state):<EOL><INDENT>msg = f"<STR_LIT>"<EOL>msg += f"<STR_LIT>"<EOL>for key, value in self.state_validator.errors.items():<EOL><INDENT>msg += '<STR_LIT>' % (key, value)<EOL><DEDENT>msg = msg[<NUM_LIT:0>:-<NUM_LIT:1>]+'<STR_LIT:.>'<EOL>raise ValidationError(msg)<EOL><DEDENT>

Base calculate method for models.
Validates the material state parameter(s).

:param **state: The material state


@staticmethod<EOL><INDENT>def create_template(material, path, show=False):<DEDENT>

file_name = '<STR_LIT>' % material.lower()<EOL>file_path = os.path.join(path, file_name)<EOL>with open(file_path, '<STR_LIT:w>', newline='<STR_LIT>') as csvfile:<EOL><INDENT>writer = csv.writer(csvfile, delimiter='<STR_LIT:U+002C>',<EOL>quotechar='<STR_LIT:">', quoting=csv.QUOTE_MINIMAL)<EOL>writer.writerow(['<STR_LIT:Name>', material])<EOL>writer.writerow(['<STR_LIT>', '<STR_LIT>'<EOL>'<STR_LIT>'])<EOL>writer.writerow(['<STR_LIT>', '<STR_LIT>'<EOL>'<STR_LIT>'])<EOL>writer.writerow(['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'])<EOL>writer.writerow(['<STR_LIT:T>', '<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>writer.writerow(['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'])<EOL>writer.writerow(['<STR_LIT:T>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'])<EOL>for i in range(<NUM_LIT:10>):<EOL><INDENT>writer.writerow([<NUM_LIT> + i*<NUM_LIT:50>, float(i), <NUM_LIT> + i, <NUM_LIT> + i])<EOL><DEDENT><DEDENT>if show is True:<EOL><INDENT>webbrowser.open_new(file_path)<EOL><DEDENT>

Create a template csv file for a data set.

:param material: the name of the material
:param path: the path of the directory where the file must be written
:param show: a boolean indicating whether the created file should be \
displayed after creation


super().calculate(**state)<EOL>return self.mm * self.P / R / state["<STR_LIT:T>"]<EOL>

Calculate the density at the specified temperature.

:param T: [K] temperature

:returns: [kg/m3] density

The **state parameter contains the keyword argument(s) specified above\
that are used to describe the state of the material.


def _create_polynomial_model(<EOL>name: str,<EOL>symbol: str,<EOL>degree: int,<EOL>ds: DataSet,<EOL>dss: dict):

ds_name = ds.name.split("<STR_LIT:.>")[<NUM_LIT:0>].lower()<EOL>file_name = f"<STR_LIT>"<EOL>newmod = PolynomialModelT.create(ds, symbol, degree)<EOL>newmod.plot(dss, _path(f"<STR_LIT>"), False)<EOL>newmod.write(_path(f"<STR_LIT>"))<EOL>

Create a polynomial model to describe the specified property based on the
specified data set, and save it to a .json file.

:param name: material name.
:param symbol: property symbol.
:param degree: polynomial degree.
:param ds: the source data set.
:param dss: dictionary of all datasets.


return {n: DataSet(_path(f"<STR_LIT>")) for n in namelist}<EOL>

Create a data set dictionary from the provided list of data set names.

:param namelist: list of data set names (str).
:return: {str: DataSet}


name = "<STR_LIT>"<EOL>namel = name.lower().replace("<STR_LIT:U+0020>", "<STR_LIT:->")<EOL>mm = M("<STR_LIT>")  <EOL>ds_dict = _create_ds_dict([<EOL>f"<STR_LIT>"])<EOL>active_ds = f"<STR_LIT>"<EOL>model_dict = {<EOL>"<STR_LIT>": IgRhoT(mm, <NUM_LIT>),<EOL>"<STR_LIT>": IgBetaT()}<EOL>model_type = "<STR_LIT>"<EOL>for property in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT:k>"]:<EOL><INDENT>name = f"<STR_LIT>"<EOL>model_dict[property] = PolynomialModelT.read(_path(name))<EOL><DEDENT>material = Material(name, StateOfMatter.gas, model_dict)<EOL>return material, ds_dict<EOL>

Create a dictionary of datasets and a material object for water vapour.

:return: (Material, {str, DataSet})


T = state['<STR_LIT:T>']<EOL>x = state['<STR_LIT:x>']<EOL>x_total = sum([<EOL>x for compound, x in x.items()<EOL>if compound in materials])<EOL>x = {<EOL>compound: x[compound]/x_total<EOL>for compound in x.keys()<EOL>if compound in materials}<EOL>mu = {i: materials[i].mu(T=T) for i in x.keys()}<EOL>result = sum([mu[i] * x[i] * sqrt(M(i)) for i in x.keys()])<EOL>result /= sum([x[i] * sqrt(M(i)) for i in x.keys()])<EOL>return result<EOL>

Calculate dynamic viscosity at the specified temperature and
composition:

:param T: [K] temperature
:param x: [mole fraction] composition dictionary , e.g.
  {'CO': 0.25, 'CO2': 0.25, 'N2': 0.25, 'O2': 0.25}

:returns: [Pa.s] dynamic viscosity

The **state parameter contains the keyword argument(s) specified above
that are used to describe the state of the material.


path = modules[__name__].__file__<EOL>path = realpath(path)<EOL>path = dirname(path)<EOL>return join(path, relative_path)<EOL>

Calculate the full path of the provided relative path.

:param relative_path: relative path (str).
:return: str


name = "<STR_LIT>"<EOL>namel = name.lower().replace("<STR_LIT:U+0020>", "<STR_LIT:->")<EOL>mm = M("<STR_LIT>")  <EOL>ds_dict = _create_ds_dict([<EOL>f"<STR_LIT>"])<EOL>active_ds = f"<STR_LIT>"<EOL>model_dict = {<EOL>"<STR_LIT>": IgBetaT()}<EOL>model_type = "<STR_LIT>"<EOL>for property in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT:k>"]:<EOL><INDENT>name = f"<STR_LIT>"<EOL>model_dict[property] = PolynomialModelT.read(_path(name))<EOL><DEDENT>material = Material(name, StateOfMatter.gas, model_dict)<EOL>return material, ds_dict<EOL>

Create a dictionary of datasets and a material object for carbon dioxide.

:return: (Material, {str, DataSet})


name = "<STR_LIT>"<EOL>namel = name.lower()<EOL>mm = M("<STR_LIT>")  <EOL>ds_dict = _create_ds_dict([<EOL>f"<STR_LIT>"])<EOL>active_ds = f"<STR_LIT>"<EOL>model_dict = {<EOL>"<STR_LIT>": IgBetaT()}<EOL>model_type = "<STR_LIT>"<EOL>for property in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT:k>"]:<EOL><INDENT>name = f"<STR_LIT>"<EOL>model_dict[property] = PolynomialModelT.read(_path(name))<EOL><DEDENT>material = Material(name, StateOfMatter.gas, model_dict)<EOL>return material, ds_dict<EOL>

Create a dictionary of datasets and a material object for ammonia.

:return: (Material, {str, DataSet})


def f_tr_Haaland(Re_D, ɛ, D, warn=True):

if warn:<EOL><INDENT>try:<EOL><INDENT>if (ɛ / D) < <NUM_LIT:0.0> or (ɛ / D) > <NUM_LIT>:<EOL><INDENT>raise Warning(<EOL>f"<STR_LIT>")<EOL><DEDENT><DEDENT>except Warning as w:<EOL><INDENT>ex_type, ex_value, ex_traceback = sys.exc_info()<EOL>print(color_warn("<STR_LIT>"), ex_value)<EOL><DEDENT>try:<EOL><INDENT>if Re_D < <NUM_LIT> or Re_D > <NUM_LIT>:<EOL><INDENT>raise Warning(<EOL>f"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>except Warning as w:<EOL><INDENT>ex_type, ex_value, ex_traceback = sys.exc_info()<EOL>print(color_warn("<STR_LIT>"), ex_value)<EOL><DEDENT><DEDENT>return <NUM_LIT:1> / (<NUM_LIT> * log10((<NUM_LIT> / Re_D) + (ɛ / D / <NUM_LIT>)**<NUM_LIT>))**<NUM_LIT:2><EOL>

Calculate the friction factor of turbulent flow (t) in a rough duct (r) for
the provided conditions with Haaland's equation.

:param Re_D: Reynolds number for the specified hydraulic diameter.
:param ɛ: [m] Surface roughness.
:param D: [m] Duct hydraulic diameter.
:return: Friction factor.

Source: lienhard2018, Eq. 7.50.


return f * (L / D) * (ρ * v**<NUM_LIT:2> / <NUM_LIT:2>)<EOL>

Calculate the pressure drop for turbulent flow in a duct.

:param f: Duct Darcy friction factor.
:param L: [m] Duct length.
:param D: [m] Duct hydraulic diameter.
:param ρ: [kg/m3] Fluid density.
:param v: [m/s] Average fluid velocity.
:return: [Pa] Pressure drop.

Source: lienhard2018, Eq. 3.25.


def cb(f, Re_D, ɛ, D):<EOL><INDENT>"""<STR_LIT>"""<EOL>term1 = ɛ / D / <NUM_LIT><EOL>term2 = <NUM_LIT> / Re_D / sqrt(f)<EOL>return -<NUM_LIT:2> * log10(term1 + term2) - <NUM_LIT:1> / sqrt(f)<EOL><DEDENT>return root(cb, <NUM_LIT>, args=(Re_D, ɛ, D)).x[<NUM_LIT:0>]<EOL>

Calculate the friction factor of turbulent flow (t) a rough duct (r) for
the provided conditions with Colebrook's equation.

:param Re_D: Reynolds number for the specified hydraulic diameter.
:param ɛ: [m] Surface roughness.
:param D: [m] Duct hydraulic diameter.
:return: Friction factor.


return self.Nu_x(L, theta, Ts, **statef) / <NUM_LIT><EOL>

Calculate the average Nusselt number.

:param L: [m] characteristic length of the heat transfer surface
:param theta: [°] angle of the surface with the vertical
:param Ts: [K] heat transfer surface temperature
:param **statef: [K] bulk fluid temperature

:returns: float


Nu_x = self.Nu_x(L, theta, Ts, **statef)<EOL>k = self._fluid.k(T=self.Tr)<EOL>return Nu_x * k / L<EOL>

Calculate the local heat transfer coefficient.

:param L: [m] characteristic length of the heat transfer surface
:param theta: [°] angle of the surface with the vertical
:param Ts: [K] heat transfer surface temperature
:param Tf: [K] bulk fluid temperature

:returns: [W/m2/K] float


Nu_L = self.Nu_L(L, theta, Ts, **statef)<EOL>k = self._fluid.k(T=self.Tr)<EOL>return Nu_L * k / L<EOL>

Calculate the average heat transfer coefficient.

:param L: [m] characteristic length of the heat transfer surface
:param theta: [°] angle of the surface with the vertical
:param Ts: [K] heat transfer surface temperature
:param Tf: [K] bulk fluid temperature

:returns: [W/m2/K] float


def Re(L: float, v: float, nu: float) -> float:

return v * L / nu<EOL>

Calculate the Reynolds number.

:param L: [m] surface characteristic length.
:param v: [m/s] fluid velocity relative to the object.
:param nu: [m2/s] fluid kinematic viscosity.

:returns: float


def Pr(nu: float, alpha: float) -> float:

return nu / alpha<EOL>

Calculate the Prandtl number.

:param nu: [m2/s] fluid kinematic viscosity / momentum diffusivity.
:param alpha: [m2/s] fluid thermal diffusivity.

:returns: float


def Gr(L: float, Ts: float, Tf: float, beta: float, nu: float, g: float):

return g * beta * (Ts - Tf) * L**<NUM_LIT> / nu**<NUM_LIT><EOL>

Calculate the Grashof number.

:param L: [m] heat transfer surface characteristic length.
:param Ts: [K] heat transfer surface temperature.
:param Tf: [K] bulk fluid temperature.
:param beta: [1/K] fluid coefficient of thermal expansion.
:param nu: [m2/s] fluid kinematic viscosity.

:returns: float

.. math::
    \\mathrm{Gr} = \\frac{g \\beta (Ts - Tinf ) L^3}{\\nu ^2}

Characteristic dimensions:
    * vertical plate: vertical length
    * pipe: diameter
    * bluff body: diameter


def Nu(L: float, h: float, k: float) -> float:

return h * L / k<EOL>

Calculate the Nusselt number.

:param L: [m] heat transfer surface characteristic length.
:param h: [W/K/m2] convective heat transfer coefficient.
:param k: [W/K/m] fluid thermal conductivity.

:returns: float


stoichiometry = parse_compound(compound.strip()).count()<EOL>return stoichiometry[element]<EOL>

Determine the stoichiometry coefficient of an element in a chemical
compound.

:param compound: Formula of a chemical compound, e.g. 'SiO2'.
:param element:  Element, e.g. 'Si'.

:returns: Stoichiometry coefficient.


return [element_mass_fraction(compound, element)<EOL>for element in elements]<EOL>

Determine the mass fractions of a list of elements in a chemical compound.

:param compound: Formula and phase of a chemical compound, e.g.
  'Fe2O3[S1]'.
:param elements: List of elements, ['Si', 'O', 'Fe'].

:returns: Mass fractions.


return amount * molar_mass(compound)<EOL>

Calculate the mass of the specified amount of a chemical compound.

:param compound: Formula and phase of a compound, e.g. 'Fe2O3[S1]'. The
  phase may be omitted.
:param amount: [kmol]

:returns: Mass. [kg]


return {compound: amount(compound, masses[compound])<EOL>for compound in masses.keys()}<EOL>

Calculate the amounts from the specified compound masses.

:param masses: [kg] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}

:returns: [kmol] dictionary


def H(compound_string, T, mass=<NUM_LIT:1.0>):

formula, phase = _split_compound_string_(compound_string)<EOL>TK = T + <NUM_LIT><EOL>compound = compounds[formula]<EOL>result = compound.H(phase, TK)<EOL>return _finalise_result_(compound, result, mass)<EOL>

Calculate the enthalpy of the compound for the specified temperature and
mass.

:param compound_string: Formula and phase of chemical compound, e.g.
  'Fe2O3[S1]'.
:param T: [°C] temperature
:param mass: [kg]

:returns: [kWh] Enthalpy.


return <NUM_LIT:0.0><EOL>

Return a zero value for a phase with no magnetic property data.

:param T: [K] temperature

:returns: Zero.


module_path = os.path.dirname(sys.modules[__name__].__file__)<EOL>data_path = os.path.join(module_path, r'<STR_LIT>')<EOL>data_path = os.path.abspath(data_path)<EOL>return data_path<EOL>

Calculate the default path in which thermochemical data is stored.

:returns: Default path.


result = <NUM_LIT:0.0><EOL>for c, e in zip(self._coefficients, self._exponents):<EOL><INDENT>result += c*T**e<EOL><DEDENT>return result<EOL>

Calculate the heat capacity of the compound phase.

:param T: [K] temperature

:returns: [J/mol/K] Heat capacity.


if phase not in self._phases:<EOL><INDENT>raise Exception("<STR_LIT>" %<EOL>(phase, self.formula))<EOL><DEDENT>return self._phases[phase].Cp(T)<EOL>

Calculate the heat capacity of a phase of the compound at a specified
temperature.

:param phase: A phase of the compound, e.g. 'S', 'L', 'G'.
:param T: [K] temperature

:returns: [J/mol/K] Heat capacity.


compounds.clear()<EOL>if path == '<STR_LIT>':<EOL><INDENT>path = default_data_path<EOL><DEDENT>if not os.path.exists(path):<EOL><INDENT>warnings.warn('<STR_LIT>' % path)<EOL>return<EOL><DEDENT>files = glob.glob(os.path.join(path, '<STR_LIT>'))<EOL>for file in files:<EOL><INDENT>compound = Compound(_read_compound_from_factsage_file_(file))<EOL>compounds[compound.formula] = compound<EOL><DEDENT>

Load all the thermochemical data factsage files located at a path.

:param path: Path at which the data files are located.


compounds.clear()<EOL>if path == '<STR_LIT>':<EOL><INDENT>path = default_data_path<EOL><DEDENT>if not os.path.exists(path):<EOL><INDENT>warnings.warn('<STR_LIT>' % path)<EOL>return<EOL><DEDENT>files = glob.glob(os.path.join(path, '<STR_LIT>'))<EOL>for file in files:<EOL><INDENT>compound = Compound.read(file)<EOL>compounds[compound.formula] = compound<EOL><DEDENT>

Load all the thermochemical data auxi files located at a path.

:param path: Path at which the data files are located.


tau = T / self.Tc_mag<EOL>if tau <= <NUM_LIT:1.0>:<EOL><INDENT>g = <NUM_LIT:1> - (self._A_mag/tau +<EOL>self._B_mag*(tau**<NUM_LIT:3>/<NUM_LIT:6> + tau**<NUM_LIT:9>/<NUM_LIT> + tau**<NUM_LIT:15>/<NUM_LIT>)) /self._D_mag<EOL><DEDENT>else:<EOL><INDENT>g = -(tau**-<NUM_LIT:5>/<NUM_LIT:10> + tau**-<NUM_LIT:15>/<NUM_LIT> + tau**-<NUM_LIT>/<NUM_LIT>)/self._D_mag<EOL><DEDENT>return R*T*math.log(self.beta0_mag + <NUM_LIT:1>)*g<EOL>

Calculate the phase's magnetic contribution to Gibbs energy at the
specified temperature.

:param T: [K] temperature

:returns: [J/mol] The magnetic Gibbs energy of the compound phase.

Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
317–425. http://doi.org/10.1016/0364-5916(91)90030-N


with open(file_name) as f:<EOL><INDENT>return json.load(f)<EOL><DEDENT>

Build a dictionary containing the auxi thermochemical data of a compound by
reading the data from a file.

:param file_name: Name of file to read the data from.

:returns: Dictionary containing compound data.


result = self.Sref<EOL>for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]):<EOL><INDENT>result += self._Cp_records[str(Tmax)].S(T)<EOL>if T <= Tmax:<EOL><INDENT>return result + self.S_mag(T)<EOL><DEDENT><DEDENT>Tmax = max([float(TT) for TT in self._Cp_records.keys()])<EOL>result += self.Cp(Tmax)*math.log(T / Tmax)<EOL>return result + self.S_mag(T)<EOL>

Calculate the entropy of the compound phase at the specified
temperature.

:param T: [K] temperature

:returns: [J/mol/K] The entropy of the compound phase.


tau = T / self.Tc_mag<EOL>if tau <= <NUM_LIT:1.0>:<EOL><INDENT>c = (self._B_mag*(<NUM_LIT:2>*tau**<NUM_LIT:3> + <NUM_LIT:2>*tau**<NUM_LIT:9>/<NUM_LIT:3> + <NUM_LIT:2>*tau**<NUM_LIT:15>/<NUM_LIT:5>))/self._D_mag<EOL><DEDENT>else:<EOL><INDENT>c = (<NUM_LIT:2>*tau**-<NUM_LIT:5> + <NUM_LIT:2>*tau**-<NUM_LIT:15>/<NUM_LIT:3> + <NUM_LIT:2>*tau**-<NUM_LIT>/<NUM_LIT:5>)/self._D_mag<EOL><DEDENT>result = R*math.log(self.beta0_mag + <NUM_LIT:1>)*c<EOL>return result<EOL>

Calculate the phase's magnetic contribution to heat capacity at the
specified temperature.

:param T: [K] temperature

:returns: [J/mol/K] The magnetic heat capacity of the compound phase.

Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
317–425. http://doi.org/10.1016/0364-5916(91)90030-N


tau = T / self.Tc_mag<EOL>if tau <= <NUM_LIT:1.0>:<EOL><INDENT>h = (-self._A_mag/tau +<EOL>self._B_mag*(tau**<NUM_LIT:3>/<NUM_LIT:2> + tau**<NUM_LIT:9>/<NUM_LIT:15> + tau**<NUM_LIT:15>/<NUM_LIT>))/self._D_mag<EOL><DEDENT>else:<EOL><INDENT>h = -(tau**-<NUM_LIT:5>/<NUM_LIT:2> + tau**-<NUM_LIT:15>/<NUM_LIT> + tau**-<NUM_LIT>/<NUM_LIT>)/self._D_mag<EOL><DEDENT>return R*T*math.log(self.beta0_mag + <NUM_LIT:1>)*h<EOL>

Calculate the phase's magnetic contribution to enthalpy at the
specified temperature.

:param T: [K] temperature

:returns: [J/mol] The magnetic enthalpy of the compound phase.

Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
317–425. http://doi.org/10.1016/0364-5916(91)90030-N


print('<STR_LIT>')<EOL>for compound in sorted(compounds.keys()):<EOL><INDENT>phases = compounds[compound].get_phase_list()<EOL>print('<STR_LIT>' % (compound, '<STR_LIT:U+002CU+0020>'.join(phases)))<EOL><DEDENT>

List all compounds that are currently loaded in the thermo module, and
their phases.


def G(compound_string, T, mass=<NUM_LIT:1.0>):

formula, phase = _split_compound_string_(compound_string)<EOL>TK = T + <NUM_LIT><EOL>compound = compounds[formula]<EOL>result = compound.G(phase, TK)<EOL>return _finalise_result_(compound, result, mass)<EOL>

Calculate the Gibbs free energy of the compound for the specified
temperature and mass.

:param compound_string: Formula and phase of chemical compound, e.g.
  'Fe2O3[S1]'.
:param T: [°C] temperature
:param mass: [kg]

:returns: [kWh] Gibbs free energy.


def Cp(compound_string, T, mass=<NUM_LIT:1.0>):

formula, phase = _split_compound_string_(compound_string)<EOL>TK = T + <NUM_LIT><EOL>compound = compounds[formula]<EOL>result = compound.Cp(phase, TK)<EOL>return _finalise_result_(compound, result, mass)<EOL>

Calculate the heat capacity of the compound for the specified temperature
and mass.

:param compound_string: Formula and phase of chemical compound, e.g.
  'Fe2O3[S1]'.
:param T: [°C] temperature
:param mass: [kg]

:returns: [kWh/K] Heat capacity.


try:<EOL><INDENT>return self._phases[phase].S(T)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise Exception("<STR_LIT>"<EOL>.format(phase, self.formula))<EOL><DEDENT>

Calculate the enthalpy of a phase of the compound at a specified
temperature.

:param phase: A phase of the compound, e.g. 'S', 'L', 'G'.
:param T: [K] temperature

:returns: [J/mol/K] Entropy.


return sorted(self._phases.keys())<EOL>

Get a list of the compound's phases.

:returns: List of phases.


table = self._generate_table_()<EOL>if format == ReportFormat.printout:<EOL><INDENT>print(tabulate(table, headers="<STR_LIT>", tablefmt="<STR_LIT>"))<EOL><DEDENT>elif format == ReportFormat.latex:<EOL><INDENT>self._render_latex_(table)<EOL><DEDENT>elif format == ReportFormat.txt:<EOL><INDENT>self._render_txt_(table)<EOL><DEDENT>elif format == ReportFormat.csv:<EOL><INDENT>self._render_csv_(table)<EOL><DEDENT>elif format == ReportFormat.string:<EOL><INDENT>return str(tabulate(table, headers="<STR_LIT>", tablefmt="<STR_LIT>"))<EOL><DEDENT>elif format == ReportFormat.matplotlib:<EOL><INDENT>self._render_matplotlib_()<EOL><DEDENT>elif format == ReportFormat.png:<EOL><INDENT>if self.output_path is None:<EOL><INDENT>self._render_matplotlib_()<EOL><DEDENT>else:<EOL><INDENT>self._render_matplotlib_(True)<EOL><DEDENT><DEDENT>

Render the report in the specified format

:param format: The format. The default format is to print
  the report to the console.

:returns: If the format was set to 'string' then a string
  representation of the report is returned.


super(Clock, self).__init__(name, description)<EOL>self.start_datetime = start_datetime<EOL>self.timestep_period_duration = timestep_period_duration<EOL>self.timestep_period_count = timestep_period_count<EOL>self.timestep_ix = <NUM_LIT:0><EOL>

Initialise the object.

        :param name: The name.
        :param description: The description.
        :param start_datetime: The start datetime.
        :param timestep_period_duration: The duration of each time period.
        :param timestep_period_count: The number of periods that makes up a
          timestep.


self.timestep_ix = <NUM_LIT:0><EOL>

Resets the clock's timestep index to '0'.


if self.timestep_period_duration == TimePeriod.millisecond:<EOL><INDENT>return self.start_datetime + timedelta(milliseconds=ix)<EOL><DEDENT>elif self.timestep_period_duration == TimePeriod.second:<EOL><INDENT>return self.start_datetime + timedelta(seconds=ix)<EOL><DEDENT>elif self.timestep_period_duration == TimePeriod.minute:<EOL><INDENT>return self.start_datetime + timedelta(minutes=ix)<EOL><DEDENT>elif self.timestep_period_duration == TimePeriod.hour:<EOL><INDENT>return self.start_datetime + timedelta(hours=ix)<EOL><DEDENT>elif self.timestep_period_duration == TimePeriod.day:<EOL><INDENT>return self.start_datetime + relativedelta(days=ix)<EOL><DEDENT>elif self.timestep_period_duration == TimePeriod.week:<EOL><INDENT>return self.start_datetime + relativedelta(days=ix*<NUM_LIT:7>)<EOL><DEDENT>elif self.timestep_period_duration == TimePeriod.month:<EOL><INDENT>return self.start_datetime + relativedelta(months=ix)<EOL><DEDENT>elif self.timestep_period_duration == TimePeriod.year:<EOL><INDENT>return self.start_datetime + relativedelta(years=ix)<EOL><DEDENT>

Get the datetime at a given period.

:param period: The index of the period.

:returns: The datetime.


module_path = os.path.dirname(module_file_path)<EOL>path = os.path.join(module_path, relative_target_path)<EOL>path = os.path.abspath(path)<EOL>return path<EOL>

Calculate a path relative to the specified module file.

:param module_file_path: The file path to the module.


obj = OrderedDict()<EOL>obj["<STR_LIT>"] = list(map(metabolite_to_dict, model.metabolites))<EOL>obj["<STR_LIT>"] = list(map(reaction_to_dict, model.reactions))<EOL>obj["<STR_LIT>"] = list(map(gene_to_dict, model.genes))<EOL>obj["<STR_LIT:id>"] = model.id<EOL>_update_optional(model, obj, _OPTIONAL_MODEL_ATTRIBUTES,<EOL>_ORDERED_OPTIONAL_MODEL_KEYS)<EOL>if sort:<EOL><INDENT>get_id = itemgetter("<STR_LIT:id>")<EOL>obj["<STR_LIT>"].sort(key=get_id)<EOL>obj["<STR_LIT>"].sort(key=get_id)<EOL>obj["<STR_LIT>"].sort(key=get_id)<EOL><DEDENT>return obj<EOL>

Convert model to a dict.

    Parameters
    ----------
    model : cobra.Model
        The model to reformulate as a dict.
    sort : bool, optional
        Whether to sort the metabolites, reactions, and genes or maintain the
        order defined in the model.

    Returns
    -------
    OrderedDict
        A dictionary with elements, 'genes', 'compartments', 'id',
        'metabolites', 'notes' and 'reactions'; where 'metabolites', 'genes'
        and 'metabolites' are in turn lists with dictionaries holding all
        attributes to form the corresponding object.

    See Also
    --------
    cobra.io.model_from_dict


def _create_parameter(model, pid, value, sbo=None, constant=True, units=None,<EOL>flux_udef=None):

parameter = model.createParameter()  <EOL>parameter.setId(pid)<EOL>parameter.setValue(value)<EOL>parameter.setConstant(constant)<EOL>if sbo:<EOL><INDENT>parameter.setSBOTerm(sbo)<EOL><DEDENT>if units:<EOL><INDENT>parameter.setUnits(flux_udef.getId())<EOL><DEDENT>


annotation = {}<EOL>if sbase.isSetSBOTerm():<EOL><INDENT>annotation["<STR_LIT>"] = sbase.getSBOTermID()<EOL><DEDENT>cvterms = sbase.getCVTerms()<EOL>if cvterms is None:<EOL><INDENT>return annotation<EOL><DEDENT>for cvterm in cvterms:  <EOL><INDENT>for k in range(cvterm.getNumResources()):<EOL><INDENT>uri = cvterm.getResourceURI(k)<EOL>match = URL_IDENTIFIERS_PATTERN.match(uri)<EOL>if not match:<EOL><INDENT>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT>", uri)<EOL>continue<EOL><DEDENT>provider, identifier = match.group(<NUM_LIT:1>), match.group(<NUM_LIT:2>)<EOL>if provider in annotation:<EOL><INDENT>if isinstance(annotation[provider], string_types):<EOL><INDENT>annotation[provider] = [annotation[provider]]<EOL><DEDENT>if identifier not in annotation[provider]:<EOL><INDENT>annotation[provider].append(identifier)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>annotation[provider] = identifier<EOL><DEDENT><DEDENT><DEDENT>return annotation<EOL>

Parses cobra annotations from a given SBase object.

    Annotations are dictionaries with the providers as keys.

    Parameters
    ----------
    sbase : libsbml.SBase
        SBase from which the SBML annotations are read

    Returns
    -------
    dict (annotation dictionary)

    FIXME: annotation format must be updated (this is a big collection of
          fixes) - see: https://github.com/opencobra/cobrapy/issues/684)


package = error.getPackage()<EOL>if package == '<STR_LIT>':<EOL><INDENT>package = '<STR_LIT>'<EOL><DEDENT>template = '<STR_LIT>'<EOL>error_str = template.format(k, error.getSeverityAsString(),<EOL>error.getCategoryAsString(), package,<EOL>error.getLine(), error.getShortMessage(),<EOL>error.getMessage())<EOL>return error_str<EOL>

String representation of SBMLError.

    Parameters
    ----------
    error : libsbml.SBMLError
    k : index of error

    Returns
    -------
    string representation of error


def _check_required(sbase, value, attribute):

if (value is None) or (value == "<STR_LIT>"):<EOL><INDENT>msg = "<STR_LIT>" %(attribute, sbase)<EOL>if hasattr(sbase, "<STR_LIT>") and sbase.getId():<EOL><INDENT>msg += "<STR_LIT>" % sbase.getId()<EOL><DEDENT>elif hasattr(sbase, "<STR_LIT>") and sbase.getName():<EOL><INDENT>msg += "<STR_LIT>" % sbase.getName()<EOL><DEDENT>elif hasattr(sbase, "<STR_LIT>") and sbase.getMetaId():<EOL><INDENT>msg += "<STR_LIT>" % sbase.getName()<EOL><DEDENT>raise CobraSBMLError(msg)<EOL><DEDENT>return value<EOL>

Get required attribute from SBase.

    Parameters
    ----------
    sbase : libsbml.SBase
    value : existing value
    attribute: name of attribute

    Returns
    -------
    attribute value (or value if already set)


if notes and len(notes) > <NUM_LIT:0>:<EOL><INDENT>tokens = ['<STR_LIT>'] +["<STR_LIT>".format(k, v) for (k, v) in notes.items()] +["<STR_LIT>"]<EOL>_check(<EOL>sbase.setNotes("<STR_LIT:\n>".join(tokens)),<EOL>"<STR_LIT>".format(sbase)<EOL>)<EOL><DEDENT>

Set SBase notes based on dictionary.

    Parameters
    ----------
    sbase : libsbml.SBase
        SBML object to set notes on
    notes : notes object
        notes information from cobra object


def write_sbml_model(cobra_model, filename, f_replace=F_REPLACE, **kwargs):

doc = _model_to_sbml(cobra_model, f_replace=f_replace, **kwargs)<EOL>if isinstance(filename, string_types):<EOL><INDENT>libsbml.writeSBMLToFile(doc, filename)<EOL><DEDENT>elif hasattr(filename, "<STR_LIT>"):<EOL><INDENT>sbml_str = libsbml.writeSBMLToString(doc)<EOL>filename.write(sbml_str)<EOL><DEDENT>

Writes cobra model to filename.

    The created model is SBML level 3 version 1 (L1V3) with
    fbc package v2 (fbc-v2).

    If the given filename ends with the suffix ".gz" (for example,
    "myfile.xml.gz"), libSBML assumes the caller wants the file to be
    written compressed in gzip format. Similarly, if the given filename
    ends with ".zip" or ".bz2", libSBML assumes the caller wants the
    file to be compressed in zip or bzip2 format (respectively). Files
    whose names lack these suffixes will be written uncompressed. Special
    considerations for the zip format: If the given filename ends with
    ".zip", the file placed in the zip archive will have the suffix
    ".xml" or ".sbml".  For example, the file in the zip archive will
    be named "test.xml" if the given filename is "test.xml.zip" or
    "test.zip". Similarly, the filename in the archive will be
    "test.sbml" if the given filename is "test.sbml.zip".

    Parameters
    ----------
    cobra_model : cobra.core.Model
        Model instance which is written to SBML
    filename : string
        path to which the model is written
    use_fbc_package : boolean {True, False}
        should the fbc package be used
    f_replace: dict of replacement functions for id replacement


return _clip(sid, prefix)<EOL>


return prefix + sid<EOL>


def _create_bound(model, reaction, bound_type, f_replace, units=None,<EOL>flux_udef=None):

value = getattr(reaction, bound_type)<EOL>if value == config.lower_bound:<EOL><INDENT>return LOWER_BOUND_ID<EOL><DEDENT>elif value == <NUM_LIT:0>:<EOL><INDENT>return ZERO_BOUND_ID<EOL><DEDENT>elif value == config.upper_bound:<EOL><INDENT>return UPPER_BOUND_ID<EOL><DEDENT>elif value == -float("<STR_LIT>"):<EOL><INDENT>return BOUND_MINUS_INF<EOL><DEDENT>elif value == float("<STR_LIT>"):<EOL><INDENT>return BOUND_PLUS_INF<EOL><DEDENT>else:<EOL><INDENT>rid = reaction.id<EOL>if f_replace and F_REACTION_REV in f_replace:<EOL><INDENT>rid = f_replace[F_REACTION_REV](rid)<EOL><DEDENT>pid = rid + "<STR_LIT:_>" + bound_type<EOL>_create_parameter(model, pid=pid, value=value, sbo=SBO_FLUX_BOUND,<EOL>units=units, flux_udef=flux_udef)<EOL>return pid<EOL><DEDENT>

Creates bound in model for given reaction.

    Adds the parameters for the bounds to the SBML model.

    Parameters
    ----------
    model : libsbml.Model
        SBML model instance
    reaction : cobra.core.Reaction
        Cobra reaction instance from which the bounds are read.
    bound_type : {LOWER_BOUND, UPPER_BOUND}
        Type of bound
    f_replace : dict of id replacement functions
    units : flux units

    Returns
    -------
    Id of bound parameter.


def _model_to_sbml(cobra_model, f_replace=None, units=True):

if f_replace is None:<EOL><INDENT>f_replace = {}<EOL><DEDENT>sbml_ns = libsbml.SBMLNamespaces(<NUM_LIT:3>, <NUM_LIT:1>)  <EOL>sbml_ns.addPackageNamespace("<STR_LIT>", <NUM_LIT:2>)  <EOL>doc = libsbml.SBMLDocument(sbml_ns)  <EOL>doc.setPackageRequired("<STR_LIT>", False)<EOL>doc.setSBOTerm(SBO_FBA_FRAMEWORK)<EOL>model = doc.createModel()  <EOL>model_fbc = model.getPlugin("<STR_LIT>")  <EOL>model_fbc.setStrict(True)<EOL>if cobra_model.id is not None:<EOL><INDENT>model.setId(cobra_model.id)<EOL>model.setMetaId("<STR_LIT>" + cobra_model.id)<EOL><DEDENT>else:<EOL><INDENT>model.setMetaId("<STR_LIT>")<EOL><DEDENT>if cobra_model.name is not None:<EOL><INDENT>model.setName(cobra_model.name)<EOL><DEDENT>_sbase_annotations(model, cobra_model.annotation)<EOL>if hasattr(cobra_model, "<STR_LIT>"):<EOL><INDENT>meta = cobra_model._sbml<EOL>if "<STR_LIT>" in meta:<EOL><INDENT>_sbase_annotations(doc, meta["<STR_LIT>"])<EOL><DEDENT>if "<STR_LIT>" in meta:<EOL><INDENT>_sbase_notes_dict(doc, meta["<STR_LIT>"])<EOL><DEDENT>history = libsbml.ModelHistory()  <EOL>if "<STR_LIT>" in meta and meta["<STR_LIT>"]:<EOL><INDENT>history.setCreatedDate(meta["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>time = datetime.datetime.now()<EOL>timestr = time.strftime('<STR_LIT>')<EOL>date = libsbml.Date(timestr)<EOL>_check(history.setCreatedDate(date), '<STR_LIT>')<EOL>_check(history.setModifiedDate(date), '<STR_LIT>')<EOL><DEDENT>if "<STR_LIT>" in meta:<EOL><INDENT>for cobra_creator in meta["<STR_LIT>"]:<EOL><INDENT>creator = libsbml.ModelCreator()  <EOL>if cobra_creator.get("<STR_LIT>", None):<EOL><INDENT>creator.setFamilyName(cobra_creator["<STR_LIT>"])<EOL><DEDENT>if cobra_creator.get("<STR_LIT>", None):<EOL><INDENT>creator.setGivenName(cobra_creator["<STR_LIT>"])<EOL><DEDENT>if cobra_creator.get("<STR_LIT>", None):<EOL><INDENT>creator.setOrganisation(cobra_creator["<STR_LIT>"])<EOL><DEDENT>if cobra_creator.get("<STR_LIT:email>", None):<EOL><INDENT>creator.setEmail(cobra_creator["<STR_LIT:email>"])<EOL><DEDENT>_check(history.addCreator(creator),<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>_check(model.setModelHistory(history), '<STR_LIT>')<EOL><DEDENT>if units:<EOL><INDENT>flux_udef = model.createUnitDefinition()  <EOL>flux_udef.setId(UNITS_FLUX[<NUM_LIT:0>])<EOL>for u in UNITS_FLUX[<NUM_LIT:1>]:<EOL><INDENT>unit = flux_udef.createUnit()  <EOL>unit.setKind(u.kind)<EOL>unit.setExponent(u.exponent)<EOL>unit.setScale(u.scale)<EOL>unit.setMultiplier(u.multiplier)<EOL><DEDENT><DEDENT>if len(cobra_model.reactions) > <NUM_LIT:0>:<EOL><INDENT>min_value = min(cobra_model.reactions.list_attr("<STR_LIT>"))<EOL>max_value = max(cobra_model.reactions.list_attr("<STR_LIT>"))<EOL><DEDENT>else:<EOL><INDENT>min_value = config.lower_bound<EOL>max_value = config.upper_bound<EOL><DEDENT>_create_parameter(model, pid=LOWER_BOUND_ID,<EOL>value=min_value, sbo=SBO_DEFAULT_FLUX_BOUND)<EOL>_create_parameter(model, pid=UPPER_BOUND_ID,<EOL>value=max_value, sbo=SBO_DEFAULT_FLUX_BOUND)<EOL>_create_parameter(model, pid=ZERO_BOUND_ID,<EOL>value=<NUM_LIT:0>, sbo=SBO_DEFAULT_FLUX_BOUND)<EOL>_create_parameter(model, pid=BOUND_MINUS_INF,<EOL>value=-float("<STR_LIT>"), sbo=SBO_FLUX_BOUND)<EOL>_create_parameter(model, pid=BOUND_PLUS_INF,<EOL>value=float("<STR_LIT>"), sbo=SBO_FLUX_BOUND)<EOL>for cid, name in iteritems(cobra_model.compartments):<EOL><INDENT>compartment = model.createCompartment()  <EOL>compartment.setId(cid)<EOL>compartment.setName(name)<EOL>compartment.setConstant(True)<EOL><DEDENT>for metabolite in cobra_model.metabolites:<EOL><INDENT>specie = model.createSpecies()  <EOL>mid = metabolite.id<EOL>if f_replace and F_SPECIE_REV in f_replace:<EOL><INDENT>mid = f_replace[F_SPECIE_REV](mid)<EOL><DEDENT>specie.setId(mid)<EOL>specie.setConstant(False)<EOL>specie.setBoundaryCondition(False)<EOL>specie.setHasOnlySubstanceUnits(False)<EOL>specie.setName(metabolite.name)<EOL>specie.setCompartment(metabolite.compartment)<EOL>s_fbc = specie.getPlugin("<STR_LIT>")  <EOL>if metabolite.charge is not None:<EOL><INDENT>s_fbc.setCharge(metabolite.charge)<EOL><DEDENT>if metabolite.formula is not None:<EOL><INDENT>s_fbc.setChemicalFormula(metabolite.formula)<EOL><DEDENT>_sbase_annotations(specie, metabolite.annotation)<EOL>_sbase_notes_dict(specie, metabolite.notes)<EOL><DEDENT>for cobra_gene in cobra_model.genes:<EOL><INDENT>gp = model_fbc.createGeneProduct()  <EOL>gid = cobra_gene.id<EOL>if f_replace and F_GENE_REV in f_replace:<EOL><INDENT>gid = f_replace[F_GENE_REV](gid)<EOL><DEDENT>gp.setId(gid)<EOL>gname = cobra_gene.name<EOL>if gname is None or len(gname) == <NUM_LIT:0>:<EOL><INDENT>gname = gid<EOL><DEDENT>gp.setName(gname)<EOL>gp.setLabel(gid)<EOL>_sbase_annotations(gp, cobra_gene.annotation)<EOL>_sbase_notes_dict(gp, cobra_gene.notes)<EOL><DEDENT>objective = model_fbc.createObjective()  <EOL>objective.setId("<STR_LIT>")<EOL>objective.setType(SHORT_LONG_DIRECTION[cobra_model.objective.direction])<EOL>model_fbc.setActiveObjectiveId("<STR_LIT>")<EOL>reaction_coefficients = linear_reaction_coefficients(cobra_model)<EOL>for cobra_reaction in cobra_model.reactions:<EOL><INDENT>rid = cobra_reaction.id<EOL>if f_replace and F_REACTION_REV in f_replace:<EOL><INDENT>rid = f_replace[F_REACTION_REV](rid)<EOL><DEDENT>reaction = model.createReaction()  <EOL>reaction.setId(rid)<EOL>reaction.setName(cobra_reaction.name)<EOL>reaction.setFast(False)<EOL>reaction.setReversible((cobra_reaction.lower_bound < <NUM_LIT:0>))<EOL>_sbase_annotations(reaction, cobra_reaction.annotation)<EOL>_sbase_notes_dict(reaction, cobra_reaction.notes)<EOL>for metabolite, stoichiometry in iteritems(cobra_reaction._metabolites):  <EOL><INDENT>sid = metabolite.id<EOL>if f_replace and F_SPECIE_REV in f_replace:<EOL><INDENT>sid = f_replace[F_SPECIE_REV](sid)<EOL><DEDENT>if stoichiometry < <NUM_LIT:0>:<EOL><INDENT>sref = reaction.createReactant()  <EOL>sref.setSpecies(sid)<EOL>sref.setStoichiometry(-stoichiometry)<EOL>sref.setConstant(True)<EOL><DEDENT>else:<EOL><INDENT>sref = reaction.createProduct()  <EOL>sref.setSpecies(sid)<EOL>sref.setStoichiometry(stoichiometry)<EOL>sref.setConstant(True)<EOL><DEDENT><DEDENT>r_fbc = reaction.getPlugin("<STR_LIT>")  <EOL>r_fbc.setLowerFluxBound(_create_bound(model, cobra_reaction,<EOL>"<STR_LIT>",<EOL>f_replace=f_replace, units=units,<EOL>flux_udef=flux_udef))<EOL>r_fbc.setUpperFluxBound(_create_bound(model, cobra_reaction,<EOL>"<STR_LIT>",<EOL>f_replace=f_replace, units=units,<EOL>flux_udef=flux_udef))<EOL>gpr = cobra_reaction.gene_reaction_rule<EOL>if gpr is not None and len(gpr) > <NUM_LIT:0>:<EOL><INDENT>if f_replace and F_GENE_REV in f_replace:<EOL><INDENT>gpr = gpr.replace('<STR_LIT:(>', '<STR_LIT>')<EOL>gpr = gpr.replace('<STR_LIT:)>', '<STR_LIT>')<EOL>tokens = gpr.split('<STR_LIT:U+0020>')<EOL>for k in range(len(tokens)):<EOL><INDENT>if tokens[k] not in ['<STR_LIT:U+0020>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:(>', '<STR_LIT:)>']:<EOL><INDENT>tokens[k] = f_replace[F_GENE_REV](tokens[k])<EOL><DEDENT><DEDENT>gpr_new = "<STR_LIT:U+0020>".join(tokens)<EOL><DEDENT>gpa = r_fbc.createGeneProductAssociation()  <EOL>gpa.setAssociation(gpr_new)<EOL><DEDENT>if reaction_coefficients.get(cobra_reaction, <NUM_LIT:0>) != <NUM_LIT:0>:<EOL><INDENT>flux_obj = objective.createFluxObjective()  <EOL>flux_obj.setReaction(rid)<EOL>flux_obj.setCoefficient(cobra_reaction.objective_coefficient)<EOL><DEDENT><DEDENT>if len(cobra_model.groups) > <NUM_LIT:0>:<EOL><INDENT>doc.enablePackage(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>", True)<EOL>doc.setPackageRequired("<STR_LIT>", False)<EOL>model_group = model.getPlugin("<STR_LIT>")  <EOL>for cobra_group in cobra_model.groups:<EOL><INDENT>group = model_group.createGroup()  <EOL>group.setId(cobra_group.id)<EOL>group.setName(cobra_group.name)<EOL>group.setKind(cobra_group.kind)<EOL>_sbase_notes_dict(group, cobra_group.notes)<EOL>_sbase_annotations(group, cobra_group.annotation)<EOL>for cobra_member in cobra_group.members:<EOL><INDENT>member = group.createMember()  <EOL>mid = cobra_member.id<EOL>m_type = str(type(cobra_member))<EOL>if "<STR_LIT>" in m_type:<EOL><INDENT>if f_replace and F_REACTION_REV in f_replace:<EOL><INDENT>mid = f_replace[F_REACTION_REV](mid)<EOL><DEDENT><DEDENT>if "<STR_LIT>" in m_type:<EOL><INDENT>if f_replace and F_SPECIE_REV in f_replace:<EOL><INDENT>mid = f_replace[F_SPECIE_REV](mid)<EOL><DEDENT><DEDENT>if "<STR_LIT>" in m_type:<EOL><INDENT>if f_replace and F_GENE_REV in f_replace:<EOL><INDENT>mid = f_replace[F_GENE_REV](mid)<EOL><DEDENT><DEDENT>member.setIdRef(mid)<EOL>if cobra_member.name and len(cobra_member.name) > <NUM_LIT:0>:<EOL><INDENT>member.setName(cobra_member.name)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return doc<EOL>

Convert Cobra model to SBMLDocument.

    Parameters
    ----------
    cobra_model : cobra.core.Model
        Cobra model instance
    f_replace : dict of replacement functions
        Replacement to apply on identifiers.
    units : boolean
        Should the FLUX_UNITS be written in the SBMLDocument.

    Returns
    -------
    libsbml.SBMLDocument


if result["<STR_LIT:success>"] is not True:<EOL><INDENT>raise RuntimeError(result["<STR_LIT:content>"]["<STR_LIT>"])<EOL><DEDENT>

ensure success of a pymatbridge operation


def load_matlab_model(infile_path, variable_name=None, inf=inf):

if not scipy_io:<EOL><INDENT>raise ImportError('<STR_LIT>')<EOL><DEDENT>data = scipy_io.loadmat(infile_path)<EOL>possible_names = []<EOL>if variable_name is None:<EOL><INDENT>meta_vars = {"<STR_LIT>", "<STR_LIT>", "<STR_LIT>"}<EOL>possible_names = sorted(i for i in data if i not in meta_vars)<EOL>if len(possible_names) == <NUM_LIT:1>:<EOL><INDENT>variable_name = possible_names[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>if variable_name is not None:<EOL><INDENT>return from_mat_struct(data[variable_name], model_id=variable_name,<EOL>inf=inf)<EOL><DEDENT>for possible_name in possible_names:<EOL><INDENT>try:<EOL><INDENT>return from_mat_struct(data[possible_name], model_id=possible_name,<EOL>inf=inf)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>raise IOError("<STR_LIT>")<EOL>

Load a cobra model stored as a .mat file

    Parameters
    ----------
    infile_path: str
        path to the file to to read
    variable_name: str, optional
        The variable name of the model in the .mat file. If this is not
        specified, then the first MATLAB variable which looks like a COBRA
        model will be used
    inf: value
        The value to use for infinite bounds. Some solvers do not handle
        infinite values so for using those, set this to a high numeric value.

    Returns
    -------
    cobra.core.Model.Model:
        The resulting cobra model


rxns = model.reactions<EOL>mets = model.metabolites<EOL>mat = OrderedDict()<EOL>mat["<STR_LIT>"] = _cell([met_id for met_id in create_mat_metabolite_id(model)])<EOL>mat["<STR_LIT>"] = _cell(mets.list_attr("<STR_LIT:name>"))<EOL>mat["<STR_LIT>"] = _cell([str(m.formula) for m in mets])<EOL>try:<EOL><INDENT>mat["<STR_LIT>"] = array(mets.list_attr("<STR_LIT>")) * <NUM_LIT:1.><EOL><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT>mat["<STR_LIT>"] = _cell(model.genes.list_attr("<STR_LIT:id>"))<EOL>rxn_gene = scipy_sparse.dok_matrix((len(model.reactions),<EOL>len(model.genes)))<EOL>if min(rxn_gene.shape) > <NUM_LIT:0>:<EOL><INDENT>for i, reaction in enumerate(model.reactions):<EOL><INDENT>for gene in reaction.genes:<EOL><INDENT>rxn_gene[i, model.genes.index(gene)] = <NUM_LIT:1><EOL><DEDENT><DEDENT>mat["<STR_LIT>"] = rxn_gene<EOL><DEDENT>mat["<STR_LIT>"] = _cell(rxns.list_attr("<STR_LIT>"))<EOL>mat["<STR_LIT>"] = _cell(rxns.list_attr("<STR_LIT:id>"))<EOL>mat["<STR_LIT>"] = _cell(rxns.list_attr("<STR_LIT:name>"))<EOL>mat["<STR_LIT>"] = _cell(rxns.list_attr("<STR_LIT>"))<EOL>stoich_mat = create_stoichiometric_matrix(model)<EOL>mat["<STR_LIT:S>"] = stoich_mat if stoich_mat is not None else [[]]<EOL>mat["<STR_LIT>"] = array(rxns.list_attr("<STR_LIT>")) * <NUM_LIT:1.><EOL>mat["<STR_LIT>"] = array(rxns.list_attr("<STR_LIT>")) * <NUM_LIT:1.><EOL>mat["<STR_LIT:b>"] = array(mets.list_attr("<STR_LIT>")) * <NUM_LIT:1.><EOL>mat["<STR_LIT:c>"] = array(rxns.list_attr("<STR_LIT>")) * <NUM_LIT:1.><EOL>mat["<STR_LIT>"] = array(rxns.list_attr("<STR_LIT>")) * <NUM_LIT:1><EOL>mat["<STR_LIT:description>"] = str(model.id)<EOL>return mat<EOL>

create a dict mapping model attributes to arrays


content = StringIO(document)<EOL>return model_from_dict(yaml.load(content))<EOL>

Load a cobra model from a YAML document.

Parameters
----------
document : str
    The YAML document representation of a cobra model.

Returns
-------
cobra.Model
    The cobra model as represented in the YAML document.

See Also
--------
load_yaml_model : Load directly from a file.


def to_yaml(model, sort=False, **kwargs):

obj = model_to_dict(model, sort=sort)<EOL>obj["<STR_LIT:version>"] = YAML_SPEC<EOL>return yaml.dump(obj, **kwargs)<EOL>

Return the model as a YAML document.

``kwargs`` are passed on to ``yaml.dump``.

Parameters
----------
model : cobra.Model
    The cobra model to represent.
sort : bool, optional
    Whether to sort the metabolites, reactions, and genes or maintain the
    order defined in the model.

Returns
-------
str
    String representation of the cobra model as a YAML document.

See Also
--------
save_yaml_model : Write directly to a file.
ruamel.yaml.dump : Base function.


def save_json_model(model, filename, sort=False, pretty=False, **kwargs):

obj = model_to_dict(model, sort=sort)<EOL>obj[u"<STR_LIT:version>"] = JSON_SPEC<EOL>if pretty:<EOL><INDENT>dump_opts = {<EOL>"<STR_LIT>": <NUM_LIT:4>, "<STR_LIT>": ("<STR_LIT:U+002C>", "<STR_LIT>"), "<STR_LIT>": True,<EOL>"<STR_LIT>": False}<EOL><DEDENT>else:<EOL><INDENT>dump_opts = {<EOL>"<STR_LIT>": <NUM_LIT:0>, "<STR_LIT>": ("<STR_LIT:U+002C>", "<STR_LIT::>"), "<STR_LIT>": False,<EOL>"<STR_LIT>": False}<EOL><DEDENT>dump_opts.update(**kwargs)<EOL>if isinstance(filename, string_types):<EOL><INDENT>with open(filename, "<STR_LIT:w>") as file_handle:<EOL><INDENT>json.dump(obj, file_handle, **dump_opts)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>json.dump(obj, filename, **dump_opts)<EOL><DEDENT>

Write the cobra model to a file in JSON format.

``kwargs`` are passed on to ``json.dump``.

Parameters
----------
model : cobra.Model
    The cobra model to represent.
filename : str or file-like
    File path or descriptor that the JSON representation should be
    written to.
sort : bool, optional
    Whether to sort the metabolites, reactions, and genes or maintain the
    order defined in the model.
pretty : bool, optional
    Whether to format the JSON more compactly (default) or in a more
    verbose but easier to read fashion. Can be partially overwritten by the
    ``kwargs``.

See Also
--------
to_json : Return a string representation.
json.dump : Base function.


return model_from_dict(json.loads(document))<EOL>

Load a cobra model from a JSON document.

Parameters
----------
document : str
    The JSON document representation of a cobra model.

Returns
-------
cobra.Model
    The cobra model as represented in the JSON document.

See Also
--------
load_json_model : Load directly from a file.


if isinstance(new_members, string_types) orhasattr(new_members, "<STR_LIT:id>"):<EOL><INDENT>warn("<STR_LIT>")<EOL>new_members = [new_members]<EOL><DEDENT>self._members.update(new_members)<EOL>

Add objects to the group.

Parameters
----------
new_members : list
    A list of cobrapy objects to add to the group.


if isinstance(to_remove, string_types) orhasattr(to_remove, "<STR_LIT:id>"):<EOL><INDENT>warn("<STR_LIT>")<EOL>to_remove = [to_remove]<EOL><DEDENT>self._members.difference_update(to_remove)<EOL>

Remove objects from the group.

Parameters
----------
to_remove : list
    A list of cobra objects to remove from the group


total = DictList()<EOL>total.extend(self)<EOL>total.extend(other)<EOL>return total<EOL>

x.__add__(y) <==> x + y

        Parameters
        ----------
        other : iterable
            other must contain only unique id's which do not intersect
            with self


if len(args) > <NUM_LIT:2>:<EOL><INDENT>raise TypeError("<STR_LIT>" % len(args))<EOL><DEDENT>super(DictList, self).__init__(self)<EOL>self._dict = {}<EOL>if len(args) == <NUM_LIT:1>:<EOL><INDENT>other = args[<NUM_LIT:0>]<EOL>if isinstance(other, DictList):<EOL><INDENT>list.extend(self, other)<EOL>self._dict = other._dict.copy()<EOL><DEDENT>else:<EOL><INDENT>self.extend(other)<EOL><DEDENT><DEDENT>

Instantiate a combined dict and list.

        Parameters
        ----------
        args : iterable
            iterable as single argument to create new DictList from


if id in self._dict:<EOL><INDENT>raise ValueError("<STR_LIT>" % str(id))<EOL><DEDENT>

make sure duplicate id's are not added.
        This function is called before adding in elements.


<EOL>if not hasattr(self, "<STR_LIT>") or self._dict is None:<EOL><INDENT>self._dict = {}<EOL><DEDENT>_dict = self._dict<EOL>current_length = len(self)<EOL>list.extend(self, iterable)<EOL>for i, obj in enumerate(islice(self, current_length, None),<EOL>current_length):<EOL><INDENT>the_id = obj.id<EOL>if the_id not in _dict:<EOL><INDENT>_dict[the_id] = i<EOL><DEDENT>else:<EOL><INDENT>self = self[:current_length]<EOL>self._check(the_id)<EOL>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % (str(the_id), i))<EOL><DEDENT><DEDENT>

extend list by appending elements from the iterable


total = DictList()<EOL>total.extend(self)<EOL>for item in other:<EOL><INDENT>total.remove(item)<EOL><DEDENT>return total<EOL>

x.__sub__(y) <==> x - y

        Parameters
        ----------
        other : iterable
            other must contain only unique id's present in the list


the_id = object.id<EOL>self._check(the_id)<EOL>self._dict[the_id] = len(self)<EOL>list.append(self, object)<EOL>


sets internal state

        Ignore the passed in state and recalculate it. This is only for
        compatibility with older pickles which did not correctly specify
        the initialization class


for item in other:<EOL><INDENT>self.remove(item)<EOL><DEDENT>return self<EOL>

x.__sub__(y) <==> x -= y

        Parameters
        ----------
        other : iterable
            other must contain only unique id's present in the list


return {"<STR_LIT>": self._dict}<EOL>

gets internal state

        This is only provided for backwards compatibility so older
        versions of cobrapy can load pickles generated with cobrapy. In
        reality, the "_dict" state is ignored when loading a pickle


self._check(object.id)<EOL>list.insert(self, index, object)<EOL>_dict = self._dict<EOL>for i, j in iteritems(_dict):<EOL><INDENT>if j >= index:<EOL><INDENT>_dict[i] = j + <NUM_LIT:1><EOL><DEDENT><DEDENT>_dict[object.id] = index<EOL>


self.extend(other)<EOL>return self<EOL>

x.__iadd__(y) <==> x += y

        Parameters
        ----------
        other : iterable
            other must contain only unique id's whcih do not intersect
            with self


return list.__getitem__(self, self._dict[id])<EOL>


if self.model is not None:<EOL><INDENT>return self.model.variables[self.id]<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

An optlang variable representing the forward flux

        Returns
        -------
        optlang.interface.Variable
            An optlang variable for the forward flux or None if reaction is
            not associated with a model.


self._genes.discard(cobra_gene)<EOL>cobra_gene._reaction.discard(self)<EOL>

Dissociates a cobra.Gene object with a cobra.Reaction.

        Parameters
        ----------
        cobra_gene : cobra.core.Gene.Gene


try:<EOL><INDENT>check_solver_status(self._model.solver.status)<EOL>return self.forward_variable.primal - self.reverse_variable.primal<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>".format(self.id))<EOL><DEDENT>except (RuntimeError, OptimizationError) as err:<EOL><INDENT>raise_with_traceback(err)<EOL><DEDENT>except Exception as err:<EOL><INDENT>raise_from(OptimizationError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(str(err))), err)<EOL><DEDENT>

The flux value in the most recent solution.

Flux is the primal value of the corresponding variable in the model.

Warnings
--------
* Accessing reaction fluxes through a `Solution` object is the safer,
  preferred, and only guaranteed to be correct way. You can see how to
  do so easily in the examples.
* Reaction flux is retrieved from the currently defined
  `self._model.solver`. The solver status is checked but there are no
  guarantees that the current solver state is the one you are looking
  for.
* If you modify the underlying model after an optimization, you will
  retrieve the old optimization values.

Raises
------
RuntimeError
    If the underlying model was never optimized beforehand or the
    reaction is not part of a model.
OptimizationError
    If the solver status is anything other than 'optimal'.
AssertionError
    If the flux value is not within the bounds.

Examples
--------
>>> import cobra.test
>>> model = cobra.test.create_test_model("textbook")
>>> solution = model.optimize()
>>> model.reactions.PFK.flux
7.477381962160283
>>> solution.fluxes.PFK
7.4773819621602833


if isinstance(metabolite_id, Metabolite):<EOL><INDENT>return self._metabolites[metabolite_id]<EOL><DEDENT>_id_to_metabolites = {m.id: m for m in self._metabolites}<EOL>return self._metabolites[_id_to_metabolites[metabolite_id]]<EOL>

Return the stoichiometric coefficient of a metabolite.

Parameters
----------
metabolite_id : str or cobra.Metabolite


if self.model is not None:<EOL><INDENT>return <NUM_LIT:1.> * self.forward_variable - <NUM_LIT:1.> * self.reverse_variable<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Forward flux expression

        Returns
        -------
        sympy expression
            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


def build_reaction_from_string(self, reaction_str, verbose=True,<EOL>fwd_arrow=None, rev_arrow=None,<EOL>reversible_arrow=None, term_split="<STR_LIT:+>"):

<EOL>forward_arrow_finder = _forward_arrow_finder if fwd_arrow is Noneelse re.compile(re.escape(fwd_arrow))<EOL>reverse_arrow_finder = _reverse_arrow_finder if rev_arrow is Noneelse re.compile(re.escape(rev_arrow))<EOL>reversible_arrow_finder = _reversible_arrow_finderif reversible_arrow is Noneelse re.compile(re.escape(reversible_arrow))<EOL>if self._model is None:<EOL><INDENT>warn("<STR_LIT>")<EOL>model = None<EOL><DEDENT>else:<EOL><INDENT>model = self._model<EOL><DEDENT>found_compartments = compartment_finder.findall(reaction_str)<EOL>if len(found_compartments) == <NUM_LIT:1>:<EOL><INDENT>compartment = found_compartments[<NUM_LIT:0>]<EOL>reaction_str = compartment_finder.sub("<STR_LIT>", reaction_str)<EOL><DEDENT>else:<EOL><INDENT>compartment = "<STR_LIT>"<EOL><DEDENT>arrow_match = reversible_arrow_finder.search(reaction_str)<EOL>if arrow_match is not None:<EOL><INDENT>self.lower_bound = -<NUM_LIT:1000><EOL>self.upper_bound = <NUM_LIT:1000><EOL><DEDENT>else:  <EOL><INDENT>arrow_match = forward_arrow_finder.search(reaction_str)<EOL>if arrow_match is not None:<EOL><INDENT>self.upper_bound = <NUM_LIT:1000><EOL>self.lower_bound = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>arrow_match = reverse_arrow_finder.search(reaction_str)<EOL>if arrow_match is None:<EOL><INDENT>raise ValueError("<STR_LIT>" %<EOL>reaction_str)<EOL><DEDENT>else:<EOL><INDENT>self.upper_bound = <NUM_LIT:0><EOL>self.lower_bound = -<NUM_LIT:1000><EOL><DEDENT><DEDENT><DEDENT>reactant_str = reaction_str[:arrow_match.start()].strip()<EOL>product_str = reaction_str[arrow_match.end():].strip()<EOL>self.subtract_metabolites(self.metabolites, combine=True)<EOL>for substr, factor in ((reactant_str, -<NUM_LIT:1>), (product_str, <NUM_LIT:1>)):<EOL><INDENT>if len(substr) == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>for term in substr.split(term_split):<EOL><INDENT>term = term.strip()<EOL>if term.lower() == "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>if "<STR_LIT:U+0020>" in term:<EOL><INDENT>num_str, met_id = term.split()<EOL>num = float(num_str.lstrip("<STR_LIT:(>").rstrip("<STR_LIT:)>")) * factor<EOL><DEDENT>else:<EOL><INDENT>met_id = term<EOL>num = factor<EOL><DEDENT>met_id += compartment<EOL>try:<EOL><INDENT>met = model.metabolites.get_by_id(met_id)<EOL><DEDENT>except KeyError:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % met_id)<EOL><DEDENT>met = Metabolite(met_id)<EOL><DEDENT>self.add_metabolites({met: num})<EOL><DEDENT><DEDENT>

Builds reaction from reaction equation reaction_str using parser

        Takes a string and using the specifications supplied in the optional
        arguments infers a set of metabolites, metabolite compartments and
        stoichiometries for the reaction.  It also infers the reversibility
        of the reaction from the reaction arrow.

        Changes to the associated model are reverted upon exit when using
        the model as a context.

        Parameters
        ----------
        reaction_str : string
            a string containing a reaction formula (equation)
        verbose: bool
            setting verbosity of function
        fwd_arrow : re.compile
            for forward irreversible reaction arrows
        rev_arrow : re.compile
            for backward irreversible reaction arrows
        reversible_arrow : re.compile
            for reversible reaction arrows
        term_split : string
            dividing individual metabolite entries


<EOL>if "<STR_LIT>" in state:<EOL><INDENT>state.pop("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in state:<EOL><INDENT>state["<STR_LIT>"] = state.pop("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in state:<EOL><INDENT>state['<STR_LIT>'] = state.pop('<STR_LIT>')<EOL><DEDENT>if "<STR_LIT>" in state:<EOL><INDENT>state['<STR_LIT>'] = state.pop('<STR_LIT>')<EOL><DEDENT>self.__dict__.update(state)<EOL>for x in state['<STR_LIT>']:<EOL><INDENT>setattr(x, '<STR_LIT>', self._model)<EOL>x._reaction.add(self)<EOL><DEDENT>for x in state['<STR_LIT>']:<EOL><INDENT>setattr(x, '<STR_LIT>', self._model)<EOL>x._reaction.add(self)<EOL><DEDENT>

Probably not necessary to set _model as the cobra.Model that
        contains self sets the _model attribute for all metabolites and genes
        in the reaction.

        However, to increase performance speed we do want to let the metabolite
        and gene know that they are employed in this reaction


def add_metabolites(self, metabolites_to_add, combine=True,<EOL>reversibly=True):

old_coefficients = self.metabolites<EOL>new_metabolites = []<EOL>_id_to_metabolites = dict([(x.id, x) for x in self._metabolites])<EOL>for metabolite, coefficient in iteritems(metabolites_to_add):<EOL><INDENT>if isinstance(metabolite, Metabolite):<EOL><INDENT>if ((metabolite.model is not None) and<EOL>(metabolite.model is not self._model)):<EOL><INDENT>metabolite = metabolite.copy()<EOL><DEDENT><DEDENT>met_id = str(metabolite)<EOL>if met_id in _id_to_metabolites:<EOL><INDENT>reaction_metabolite = _id_to_metabolites[met_id]<EOL>if combine:<EOL><INDENT>self._metabolites[reaction_metabolite] += coefficient<EOL><DEDENT>else:<EOL><INDENT>self._metabolites[reaction_metabolite] = coefficient<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if self._model:<EOL><INDENT>try:<EOL><INDENT>metabolite =self._model.metabolites.get_by_id(met_id)<EOL><DEDENT>except KeyError as e:<EOL><INDENT>if isinstance(metabolite, Metabolite):<EOL><INDENT>new_metabolites.append(metabolite)<EOL><DEDENT>else:<EOL><INDENT>raise e<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(metabolite, string_types):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% self.id)<EOL><DEDENT>self._metabolites[metabolite] = coefficient<EOL>metabolite._reaction.add(self)<EOL><DEDENT><DEDENT>model = self.model<EOL>if model is not None:<EOL><INDENT>model.add_metabolites(new_metabolites)<EOL>for metabolite, coefficient in self._metabolites.items():<EOL><INDENT>model.constraints[<EOL>metabolite.id].set_linear_coefficients(<EOL>{self.forward_variable: coefficient,<EOL>self.reverse_variable: -coefficient<EOL>})<EOL><DEDENT><DEDENT>for metabolite, the_coefficient in list(self._metabolites.items()):<EOL><INDENT>if the_coefficient == <NUM_LIT:0>:<EOL><INDENT>metabolite._reaction.remove(self)<EOL>self._metabolites.pop(metabolite)<EOL><DEDENT><DEDENT>context = get_context(self)<EOL>if context and reversibly:<EOL><INDENT>if combine:<EOL><INDENT>context(partial(<EOL>self.subtract_metabolites, metabolites_to_add,<EOL>combine=True, reversibly=False))<EOL><DEDENT>else:<EOL><INDENT>mets_to_reset = {<EOL>key: old_coefficients[model.metabolites.get_by_any(key)[<NUM_LIT:0>]]<EOL>for key in iterkeys(metabolites_to_add)}<EOL>context(partial(<EOL>self.add_metabolites, mets_to_reset,<EOL>combine=False, reversibly=False))<EOL><DEDENT><DEDENT>

Add metabolites and stoichiometric coefficients to the reaction.
        If the final coefficient for a metabolite is 0 then it is removed
        from the reaction.

        The change is reverted upon exit when using the model as a context.

        Parameters
        ----------
        metabolites_to_add : dict
            Dictionary with metabolite objects or metabolite identifiers as
            keys and coefficients as values. If keys are strings (name of a
            metabolite) the reaction must already be part of a model and a
            metabolite with the given name must exist in the model.

        combine : bool
            Describes behavior a metabolite already exists in the reaction.
            True causes the coefficients to be added.
            False causes the coefficient to be replaced.

        reversibly : bool
            Whether to add the change to the context to make the change
            reversibly or not (primarily intended for internal use).


return linear_reaction_coefficients(self.model, [self]).get(self, <NUM_LIT:0>)<EOL>

Get the coefficient for this reaction in a linear
        objective (float)

        Assuming that the objective of the associated model is summation of
        fluxes from a set of reactions, the coefficient for each reaction
        can be obtained individually using this property. A more general way
        is to use the `model.objective` property directly.


return self._upper_bound<EOL>

Get or set the upper bound

        Setting the upper bound (float) will also adjust the associated optlang
        variables associated with the reaction. Infeasible combinations,
        such as a upper bound lower than the current lower bound will
        update the other bound.

        When using a `HistoryManager` context, this attribute can be set
        temporarily, reversed when the exiting the context.


warn("<STR_LIT>",<EOL>DeprecationWarning)<EOL>self.remove_from_model(remove_orphans=remove_orphans)<EOL>

Removes the reaction from a model.

        This removes all associations between a reaction the associated
        model, metabolites and genes.

        The change is reverted upon exit when using the model as a context.

        Deprecated, use `reaction.remove_from_model` instead.

        Parameters
        ----------
        remove_orphans : bool
            Remove orphaned genes and metabolites from the model as well


try:<EOL><INDENT>check_solver_status(self._model.solver.status)<EOL>return self.forward_variable.dual - self.reverse_variable.dual<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>".format(self.id))<EOL><DEDENT>except (RuntimeError, OptimizationError) as err:<EOL><INDENT>raise_with_traceback(err)<EOL><DEDENT>except Exception as err:<EOL><INDENT>raise_from(OptimizationError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(str(err))), err)<EOL><DEDENT>

The reduced cost in the most recent solution.

Reduced cost is the dual value of the corresponding variable in the
model.

Warnings
--------
* Accessing reduced costs through a `Solution` object is the safer,
  preferred, and only guaranteed to be correct way. You can see how to
  do so easily in the examples.
* Reduced cost is retrieved from the currently defined
  `self._model.solver`. The solver status is checked but there are no
  guarantees that the current solver state is the one you are looking
  for.
* If you modify the underlying model after an optimization, you will
  retrieve the old optimization values.

Raises
------
RuntimeError
    If the underlying model was never optimized beforehand or the
    reaction is not part of a model.
OptimizationError
    If the solver status is anything other than 'optimal'.

Examples
--------
>>> import cobra.test
>>> model = cobra.test.create_test_model("textbook")
>>> solution = model.optimize()
>>> model.reactions.PFK.reduced_cost
-8.673617379884035e-18
>>> solution.reduced_costs.PFK
-8.6736173798840355e-18


self._metabolites = {<EOL>met: value * coefficient<EOL>for met, value in iteritems(self._metabolites)}<EOL>if coefficient < <NUM_LIT:0>:<EOL><INDENT>self.bounds = (-self.upper_bound, -self.lower_bound)<EOL><DEDENT>if self._model:<EOL><INDENT>self._model._populate_solver([self])<EOL><DEDENT>context = get_context(self)<EOL>if context:<EOL><INDENT>context(partial(self._model._populate_solver, [self]))<EOL>context(partial(self.__imul__, <NUM_LIT:1.>/coefficient))<EOL><DEDENT>return self<EOL>

Scale coefficients in a reaction by a given value

        E.g. A -> B becomes 2A -> 2B.

        If coefficient is less than zero, the reaction is reversed and the
        bounds are swapped.


if self.model is not None:<EOL><INDENT>return self.model.variables[self.reverse_id]<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

An optlang variable representing the reverse flux

        Returns
        -------
        optlang.interface.Variable
            An optlang variable for the reverse flux or None if reaction is
            not associated with a model.


def subtract_metabolites(self, metabolites, combine=True, reversibly=True):

self.add_metabolites({<EOL>k: -v for k, v in iteritems(metabolites)},<EOL>combine=combine, reversibly=reversibly)<EOL>

Subtract metabolites from a reaction.

        That means add the metabolites with -1*coefficient. If the final
        coefficient for a metabolite is 0 then the metabolite is removed from
        the reaction.

        Notes
        -----
        * A final coefficient < 0 implies a reactant.
        * The change is reverted upon exit when using the model as a context.

        Parameters
        ----------
        metabolites : dict
            Dictionary where the keys are of class Metabolite and the values
            are the coefficients. These metabolites will be added to the
            reaction.

        combine : bool
            Describes behavior a metabolite already exists in the reaction.
            True causes the coefficients to be added.
            False causes the coefficient to be replaced.

        reversibly : bool
            Whether to add the change to the context to make the change
            reversibly or not (primarily intended for internal use).


names = {i.id: i.name for i in self._genes}<EOL>ast = parse_gpr(self._gene_reaction_rule)[<NUM_LIT:0>]<EOL>return ast2str(ast, names=names)<EOL>

Display gene_reaction_rule with names intead.

        Do NOT use this string for computation. It is intended to give a
        representation of the rule using more familiar gene names instead of
        the often cryptic ids.


return self.lower_bound, self.upper_bound<EOL>

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
        AssertionError.

        When using a `HistoryManager` context, this attribute can be set
        temporarily, reversed when the exiting the context.


<EOL>model = self._model<EOL>self._model = None<EOL>for i in self._metabolites:<EOL><INDENT>i._model = None<EOL><DEDENT>for i in self._genes:<EOL><INDENT>i._model = None<EOL><DEDENT>new_reaction = deepcopy(self)<EOL>self._model = model<EOL>for i in self._metabolites:<EOL><INDENT>i._model = model<EOL><DEDENT>for i in self._genes:<EOL><INDENT>i._model = model<EOL><DEDENT>return new_reaction<EOL>

Copy a reaction

        The referenced metabolites and genes are also copied.


return self._lower_bound < <NUM_LIT:0> < self._upper_bound<EOL>

Whether the reaction can proceed in both directions (reversible)

        This is computed from the current upper and lower bounds.


return '<STR_LIT:_>'.join((self.id, '<STR_LIT>',<EOL>hashlib.md5(<EOL>self.id.encode('<STR_LIT:utf-8>')).hexdigest()[<NUM_LIT:0>:<NUM_LIT:5>]))<EOL>

Generate the id of reverse_variable from the reaction's id.


new_reaction = self.copy()<EOL>if other == <NUM_LIT:0>:<EOL><INDENT>return new_reaction<EOL><DEDENT>else:<EOL><INDENT>new_reaction += other<EOL><DEDENT>return new_reaction<EOL>

Add two reactions

        The stoichiometry will be the combined stoichiometry of the two
        reactions, and the gene reaction rule will be both rules combined by an
        and. All other attributes (i.e. reaction bounds) will match those of
        the first reaction


return [k for k, v in iteritems(self._metabolites) if v >= <NUM_LIT:0>]<EOL>

Return a list of products for the reaction


tmp_formula = self.formula<EOL>if "<STR_LIT:*>" in tmp_formula:<EOL><INDENT>warn("<STR_LIT>" % self.formula)<EOL>tmp_formula = self.formula.replace("<STR_LIT:*>", "<STR_LIT>")<EOL><DEDENT>if "<STR_LIT:(>" in tmp_formula or "<STR_LIT:)>" in tmp_formula:<EOL><INDENT>warn("<STR_LIT>" % self.formula)<EOL>return<EOL><DEDENT>composition = {}<EOL>parsed = element_re.findall(tmp_formula)<EOL>for (element, count) in parsed:<EOL><INDENT>if count == '<STR_LIT>':<EOL><INDENT>count = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>count = float(count)<EOL>int_count = int(count)<EOL>if count == int_count:<EOL><INDENT>count = int_count<EOL><DEDENT>else:<EOL><INDENT>warn("<STR_LIT>" %<EOL>(count, self.formula))<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>warn("<STR_LIT>" %<EOL>(count, self.formula))<EOL>self.elements = {}<EOL>return<EOL><DEDENT><DEDENT>if element in composition:<EOL><INDENT>composition[element] += count<EOL><DEDENT>else:<EOL><INDENT>composition[element] = count<EOL><DEDENT><DEDENT>self.elements = composition<EOL>

Breaks the chemical formula down by element.


if not hasattr(metabolite_list, '<STR_LIT>'):<EOL><INDENT>metabolite_list = [metabolite_list]<EOL><DEDENT>if len(metabolite_list) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>metabolite_list = [x for x in metabolite_list<EOL>if x.id not in self.metabolites]<EOL>bad_ids = [m for m in metabolite_list<EOL>if not isinstance(m.id, string_types) or len(m.id) < <NUM_LIT:1>]<EOL>if len(bad_ids) != <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(repr(bad_ids)))<EOL><DEDENT>for x in metabolite_list:<EOL><INDENT>x._model = self<EOL><DEDENT>self.metabolites += metabolite_list<EOL>to_add = []<EOL>for met in metabolite_list:<EOL><INDENT>if met.id not in self.constraints:<EOL><INDENT>constraint = self.problem.Constraint(<EOL>Zero, name=met.id, lb=<NUM_LIT:0>, ub=<NUM_LIT:0>)<EOL>to_add += [constraint]<EOL><DEDENT><DEDENT>self.add_cons_vars(to_add)<EOL>context = get_context(self)<EOL>if context:<EOL><INDENT>context(partial(self.metabolites.__isub__, metabolite_list))<EOL>for x in metabolite_list:<EOL><INDENT>context(partial(setattr, x, '<STR_LIT>', None))<EOL><DEDENT><DEDENT>

Will add a list of metabolites to the model object and add new
        constraints accordingly.

        The change is reverted upon exit when using the model as a context.

        Parameters
        ----------
        metabolite_list : A list of `cobra.core.Metabolite` objects


def remove_reactions(self, reactions, remove_orphans=False):

if isinstance(reactions, string_types) or hasattr(reactions, "<STR_LIT:id>"):<EOL><INDENT>warn("<STR_LIT>")<EOL>reactions = [reactions]<EOL><DEDENT>context = get_context(self)<EOL>for reaction in reactions:<EOL><INDENT>try:<EOL><INDENT>reaction = self.reactions[self.reactions.index(reaction)]<EOL><DEDENT>except ValueError:<EOL><INDENT>warn('<STR_LIT>' % (reaction, self))<EOL><DEDENT>else:<EOL><INDENT>forward = reaction.forward_variable<EOL>reverse = reaction.reverse_variable<EOL>if context:<EOL><INDENT>obj_coef = reaction.objective_coefficient<EOL>if obj_coef != <NUM_LIT:0>:<EOL><INDENT>context(partial(<EOL>self.solver.objective.set_linear_coefficients,<EOL>{forward: obj_coef, reverse: -obj_coef}))<EOL><DEDENT>context(partial(self._populate_solver, [reaction]))<EOL>context(partial(setattr, reaction, '<STR_LIT>', self))<EOL>context(partial(self.reactions.add, reaction))<EOL><DEDENT>self.remove_cons_vars([forward, reverse])<EOL>self.reactions.remove(reaction)<EOL>reaction._model = None<EOL>for met in reaction._metabolites:<EOL><INDENT>if reaction in met._reaction:<EOL><INDENT>met._reaction.remove(reaction)<EOL>if context:<EOL><INDENT>context(partial(met._reaction.add, reaction))<EOL><DEDENT>if remove_orphans and len(met._reaction) == <NUM_LIT:0>:<EOL><INDENT>self.remove_metabolites(met)<EOL><DEDENT><DEDENT><DEDENT>for gene in reaction._genes:<EOL><INDENT>if reaction in gene._reaction:<EOL><INDENT>gene._reaction.remove(reaction)<EOL>if context:<EOL><INDENT>context(partial(gene._reaction.add, reaction))<EOL><DEDENT>if remove_orphans and len(gene._reaction) == <NUM_LIT:0>:<EOL><INDENT>self.genes.remove(gene)<EOL>if context:<EOL><INDENT>context(partial(self.genes.add, gene))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>associated_groups = self.get_associated_groups(reaction)<EOL>for group in associated_groups:<EOL><INDENT>group.remove_members(reaction)<EOL><DEDENT><DEDENT><DEDENT>

Remove reactions from the model.

        The change is reverted upon exit when using the model as a context.

        Parameters
        ----------
        reactions : list
            A list with reactions (`cobra.Reaction`), or their id's, to remove

        remove_orphans : bool
            Remove orphaned genes and metabolites from the model as well


warn('<STR_LIT>', DeprecationWarning)<EOL>return self.merge(other_model, objective='<STR_LIT>', inplace=False)<EOL>

Add the content of another model to this model (+).

        The model is copied as a new object, with a new model identifier,
        and copies of all the reactions in the other model are added to this
        model. The objective is the sum of the objective expressions for the
        two models.


def _populate_solver(self, reaction_list, metabolite_list=None):

constraint_terms = AutoVivification()<EOL>to_add = []<EOL>if metabolite_list is not None:<EOL><INDENT>for met in metabolite_list:<EOL><INDENT>to_add += [self.problem.Constraint(<EOL>Zero, name=met.id, lb=<NUM_LIT:0>, ub=<NUM_LIT:0>)]<EOL><DEDENT><DEDENT>self.add_cons_vars(to_add)<EOL>for reaction in reaction_list:<EOL><INDENT>if reaction.id not in self.variables:<EOL><INDENT>forward_variable = self.problem.Variable(reaction.id)<EOL>reverse_variable = self.problem.Variable(reaction.reverse_id)<EOL>self.add_cons_vars([forward_variable, reverse_variable])<EOL><DEDENT>else:<EOL><INDENT>reaction = self.reactions.get_by_id(reaction.id)<EOL>forward_variable = reaction.forward_variable<EOL>reverse_variable = reaction.reverse_variable<EOL><DEDENT>for metabolite, coeff in six.iteritems(reaction.metabolites):<EOL><INDENT>if metabolite.id in self.constraints:<EOL><INDENT>constraint = self.constraints[metabolite.id]<EOL><DEDENT>else:<EOL><INDENT>constraint = self.problem.Constraint(<EOL>Zero,<EOL>name=metabolite.id,<EOL>lb=<NUM_LIT:0>, ub=<NUM_LIT:0>)<EOL>self.add_cons_vars(constraint, sloppy=True)<EOL><DEDENT>constraint_terms[constraint][forward_variable] = coeff<EOL>constraint_terms[constraint][reverse_variable] = -coeff<EOL><DEDENT><DEDENT>self.solver.update()<EOL>for reaction in reaction_list:<EOL><INDENT>reaction = self.reactions.get_by_id(reaction.id)<EOL>reaction.update_variable_bounds()<EOL><DEDENT>for constraint, terms in six.iteritems(constraint_terms):<EOL><INDENT>constraint.set_linear_coefficients(terms)<EOL><DEDENT>

Populate attached solver with constraints and variables that
        model the provided reactions.


warn('<STR_LIT>', DeprecationWarning)<EOL>return self.merge(other_model, objective='<STR_LIT>', inplace=True)<EOL>

Incrementally add the content of another model to this model (+=).

        Copies of all the reactions in the other model are added to this
        model. The objective is the sum of the objective expressions for the
        two models.


<EOL>try:<EOL><INDENT>self._contexts.append(HistoryManager())<EOL><DEDENT>except AttributeError:<EOL><INDENT>self._contexts = [HistoryManager()]<EOL><DEDENT>return self<EOL>

Record all future changes to the model, undoing them when a call to
        __exit__ is received


odict = self.__dict__.copy()<EOL>odict['<STR_LIT>'] = []<EOL>return odict<EOL>

Get state for serialization.

        Ensures that the context stack is cleared prior to serialization,
        since partial functions cannot be pickled reliably.


<EOL>return [g for g in self.groups if element in g.members]<EOL>

Returns a list of groups that an element (reaction, metabolite, gene)
        is associated with.

        Parameters
        ----------
        element: `cobra.Reaction`, `cobra.Metabolite`, or `cobra.Gene`

        Returns
        -------
        list of `cobra.Group`
            All groups that the provided object is a member of


def existing_filter(group):<EOL><INDENT>if group.id in self.groups:<EOL><INDENT>LOGGER.warning(<EOL>"<STR_LIT>", group.id)<EOL>return False<EOL><DEDENT>return True<EOL><DEDENT>if isinstance(group_list, string_types) orhasattr(group_list, "<STR_LIT:id>"):<EOL><INDENT>warn("<STR_LIT>")<EOL>group_list = [group_list]<EOL><DEDENT>pruned = DictList(filter(existing_filter, group_list))<EOL>for group in pruned:<EOL><INDENT>group._model = self<EOL>for member in group.members:<EOL><INDENT>if isinstance(member, Metabolite):<EOL><INDENT>if member not in self.metabolites:<EOL><INDENT>self.add_metabolites([member])<EOL><DEDENT><DEDENT>if isinstance(member, Reaction):<EOL><INDENT>if member not in self.reactions:<EOL><INDENT>self.add_reactions([member])<EOL><DEDENT><DEDENT><DEDENT>self.groups += [group]<EOL><DEDENT>

Add groups to the model.

        Groups with identifiers identical to a group already in the model are
        ignored.

        If any group contains members that are not in the model, these members
        are added to the model as well. Only metabolites, reactions, and genes
        can have groups.

        Parameters
        ----------
        group_list : list
            A list of `cobra.Group` objects to add to the model.


return [rxn for rxn in self.reactions if rxn.boundary]<EOL>

Boundary reactions in the model.
        Reactions that either have no substrate or product.


Get or set the dictionary of current compartment descriptions.

        Assigning a dictionary to this property updates the model's
        dictionary of compartment descriptions with the new values.

        Parameters
        ----------
        value : dict
            Dictionary mapping compartments abbreviations to full names.

        Examples
        --------
        >>> import cobra.test
        >>> model = cobra.test.create_test_model("textbook")
        >>> model.compartments = {'c': 'the cytosol'}
        {'c': 'the cytosol', 'e': 'extracellular'}


return self._solver<EOL>

Get or set the attached solver instance.

        The associated the solver object, which manages the interaction with
        the associated solver, e.g. glpk.

        This property is useful for accessing the optimization problem
        directly and to define additional non-metabolic constraints.

        Examples
        --------
        >>> import cobra.test
        >>> model = cobra.test.create_test_model("textbook")
        >>> new = model.problem.Constraint(model.objective.expression,
        >>> lb=0.99)
        >>> model.solver.add(new)


if isinstance(group_list, string_types) orhasattr(group_list, "<STR_LIT:id>"):<EOL><INDENT>warn("<STR_LIT>")<EOL>group_list = [group_list]<EOL><DEDENT>for group in group_list:<EOL><INDENT>if group.id not in self.groups:<EOL><INDENT>LOGGER.warning("<STR_LIT>", group, self)<EOL><DEDENT>else:<EOL><INDENT>self.groups.remove(group)<EOL>group._model = None<EOL><DEDENT><DEDENT>

Remove groups from the model.

        Members of each group are not removed
        from the model (i.e. metabolites, reactions, and genes in the group
        stay in the model after any groups containing them are removed).

        Parameters
        ----------
        group_list : list
            A list of `cobra.Group` objects to remove from the model.


def set_active_bound(reaction, bound):<EOL><INDENT>if reaction.reactants:<EOL><INDENT>reaction.lower_bound = -bound<EOL><DEDENT>elif reaction.products:<EOL><INDENT>reaction.upper_bound = bound<EOL><DEDENT><DEDENT>media_rxns = list()<EOL>exchange_rxns = frozenset(self.exchanges)<EOL>for rxn_id, bound in iteritems(medium):<EOL><INDENT>rxn = self.reactions.get_by_id(rxn_id)<EOL>if rxn not in exchange_rxns:<EOL><INDENT>LOGGER.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>rxn.id)<EOL><DEDENT>media_rxns.append(rxn)<EOL>set_active_bound(rxn, bound)<EOL><DEDENT>media_rxns = frozenset(media_rxns)<EOL>for rxn in (exchange_rxns - media_rxns):<EOL><INDENT>set_active_bound(rxn, <NUM_LIT:0>)<EOL><DEDENT>

Get or set the constraints on the model exchanges.

        `model.medium` returns a dictionary of the bounds for each of the
        boundary reactions, in the form of `{rxn_id: bound}`, where `bound`
        specifies the absolute value of the bound in direction of metabolite
        creation (i.e., lower_bound for `met <--`, upper_bound for `met -->`)

        Parameters
        ----------
        medium: dictionary-like
            The medium to initialize. medium should be a dictionary defining
            `{rxn_id: bound}` pairs.


def repair(self, rebuild_index=True, rebuild_relationships=True):

if rebuild_index:  <EOL><INDENT>self.reactions._generate_index()<EOL>self.metabolites._generate_index()<EOL>self.genes._generate_index()<EOL>self.groups._generate_index()<EOL><DEDENT>if rebuild_relationships:<EOL><INDENT>for met in self.metabolites:<EOL><INDENT>met._reaction.clear()<EOL><DEDENT>for gene in self.genes:<EOL><INDENT>gene._reaction.clear()<EOL><DEDENT>for rxn in self.reactions:<EOL><INDENT>for met in rxn._metabolites:<EOL><INDENT>met._reaction.add(rxn)<EOL><DEDENT>for gene in rxn._genes:<EOL><INDENT>gene._reaction.add(rxn)<EOL><DEDENT><DEDENT><DEDENT>for l in (self.reactions, self.genes, self.metabolites, self.groups):<EOL><INDENT>for e in l:<EOL><INDENT>e._model = self<EOL><DEDENT><DEDENT>

Update all indexes and pointers in a model

        Parameters
        ----------
        rebuild_index : bool
            rebuild the indices kept in reactions, metabolites and genes
        rebuild_relationships : bool
             reset all associations between genes, metabolites, model and
             then re-add them.


def summary(self, solution=None, threshold=<NUM_LIT>, fva=None, names=False,<EOL>floatfmt='<STR_LIT>'):

from cobra.flux_analysis.summary import model_summary<EOL>return model_summary(self, solution=solution, threshold=threshold,<EOL>fva=fva, names=names, floatfmt=floatfmt)<EOL>

Print a summary of the input and output fluxes of the model.

Parameters
----------
solution: cobra.Solution, optional
    A previously solved model solution to use for generating the
    summary. If none provided (default), the summary method will
    resolve the model. Note that the solution object must match the
    model, i.e., changes to the model such as changed bounds,
    added or removed reactions are not taken into account by this
    method.
threshold : float, optional
    Threshold below which fluxes are not reported.
fva : pandas.DataFrame, float or None, optional
    Whether or not to include flux variability analysis in the output.
    If given, fva should either be a previous FVA solution matching
    the model or a float between 0 and 1 representing the
    fraction of the optimum objective to be searched.
names : bool, optional
    Emit reaction and metabolite names rather than identifiers (default
    False).
floatfmt : string, optional
    Format string for floats (default '.3g').


def add_cons_vars(self, what, **kwargs):

add_cons_vars_to_problem(self, what, **kwargs)<EOL>

Add constraints and variables to the model's mathematical problem.

        Useful for variables and constraints that can not be expressed with
        reactions and simple lower and upper bounds.

        Additions are reversed upon exit if the model itself is used as
        context.

        Parameters
        ----------
        what : list or tuple of optlang variables or constraints.
           The variables or constraints to add to the model. Must be of
           class `optlang.interface.Variable` or
           `optlang.interface.Constraint`.
        **kwargs : keyword arguments
           Passed to solver.add()


def __init__(self, id=None, name="<STR_LIT>"):

self._id = id<EOL>self.name = name<EOL>self.notes = {}<EOL>self.annotation = {}<EOL>

A simple object with an identifier

        Parameters
        ----------
        id: None or a string
            the identifier to associate with the object


state = self.__dict__.copy()<EOL>if '<STR_LIT>' in state:<EOL><INDENT>state['<STR_LIT>'] = None<EOL><DEDENT>return state<EOL>

To prevent excessive replication during deepcopy.


try:<EOL><INDENT>check_solver_status(self._model.solver.status)<EOL>return self._model.constraints[self.id].dual<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>".format(self.id))<EOL><DEDENT>except (RuntimeError, OptimizationError) as err:<EOL><INDENT>raise_with_traceback(err)<EOL><DEDENT>except Exception as err:<EOL><INDENT>raise_from(OptimizationError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(str(err))), err)<EOL><DEDENT>

The shadow price in the most recent solution.

Shadow price is the dual value of the corresponding constraint in the
model.

Warnings
--------
* Accessing shadow prices through a `Solution` object is the safer,
  preferred, and only guaranteed to be correct way. You can see how to
  do so easily in the examples.
* Shadow price is retrieved from the currently defined
  `self._model.solver`. The solver status is checked but there are no
  guarantees that the current solver state is the one you are looking
  for.
* If you modify the underlying model after an optimization, you will
  retrieve the old optimization values.

Raises
------
RuntimeError
    If the underlying model was never optimized beforehand or the
    metabolite is not part of a model.
OptimizationError
    If the solver status is anything other than 'optimal'.

Examples
--------
>>> import cobra
>>> import cobra.test
>>> model = cobra.test.create_test_model("textbook")
>>> solution = model.optimize()
>>> model.metabolites.glc__D_e.shadow_price
-0.09166474637510488
>>> solution.shadow_prices.glc__D_e
-0.091664746375104883


warn("<STR_LIT>", DeprecationWarning)<EOL>return self.shadow_price<EOL>

The shadow price for the metabolite in the most recent solution

        Shadow prices are computed from the dual values of the bounds in
        the solution.


if self.model is not None:<EOL><INDENT>return self.model.constraints[self.id]<EOL><DEDENT>

Get the constraints associated with this metabolite from the solve

        Returns
        -------
        optlang.<interface>.Constraint
            the optlang constraint for this metabolite


from cobra.flux_analysis.summary import metabolite_summary<EOL>return metabolite_summary(self, solution=solution, threshold=threshold,<EOL>fva=fva, names=names, floatfmt=floatfmt)<EOL>

Print a summary of the production and consumption fluxes.

This method requires the model for which this metabolite is a part
to be solved.

Parameters
----------
solution : cobra.Solution, optional
    A previously solved model solution to use for generating the
    summary. If none provided (default), the summary method will
    resolve the model. Note that the solution object must match the
    model, i.e., changes to the model such as changed bounds,
    added or removed reactions are not taken into account by this
    method.
threshold : float, optional
    Threshold below which fluxes are not reported.
fva : pandas.DataFrame, float or None, optional
    Whether or not to include flux variability analysis in the output.
    If given, fva should either be a previous FVA solution matching
    the model or a float between 0 and 1 representing the
    fraction of the optimum objective to be searched.
names : bool, optional
    Emit reaction and metabolite names rather than identifiers (default
    False).
floatfmt : string, optional
    Format string for floats (default '.3g').


return deepcopy(self)<EOL>

When copying a reaction, it is necessary to deepcopy the
        components so the list references aren't carried over.

        Additionally, a copy of a reaction is no longer in a cobra.Model.

        This should be fixed with self.__deepcopy__ if possible


state = Object.__getstate__(self)<EOL>state['<STR_LIT>'] = set()<EOL>return state<EOL>

Remove the references to container reactions when serializing to
        avoid problems associated with recursion.


if isinstance(expr, Expression):<EOL><INDENT>return eval_gpr(expr.body, knockouts)<EOL><DEDENT>elif isinstance(expr, Name):<EOL><INDENT>return expr.id not in knockouts<EOL><DEDENT>elif isinstance(expr, BoolOp):<EOL><INDENT>op = expr.op<EOL>if isinstance(op, Or):<EOL><INDENT>return any(eval_gpr(i, knockouts) for i in expr.values)<EOL><DEDENT>elif isinstance(op, And):<EOL><INDENT>return all(eval_gpr(i, knockouts) for i in expr.values)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" + op.__class__.__name__)<EOL><DEDENT><DEDENT>elif expr is None:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" + repr(expr))<EOL><DEDENT>

evaluate compiled ast of gene_reaction_rule with knockouts

    Parameters
    ----------
    expr : Expression
        The ast of the gene reaction rule
    knockouts : DictList, set
        Set of genes that are knocked out

    Returns
    -------
    bool
        True if the gene reaction rule is true with the given knockouts
        otherwise false


def ast2str(expr, level=<NUM_LIT:0>, names=None):

if isinstance(expr, Expression):<EOL><INDENT>return ast2str(expr.body, <NUM_LIT:0>, names)if hasattr(expr, "<STR_LIT:body>") else "<STR_LIT>"<EOL><DEDENT>elif isinstance(expr, Name):<EOL><INDENT>return names.get(expr.id, expr.id) if names else expr.id<EOL><DEDENT>elif isinstance(expr, BoolOp):<EOL><INDENT>op = expr.op<EOL>if isinstance(op, Or):<EOL><INDENT>str_exp = "<STR_LIT>".join(ast2str(i, level + <NUM_LIT:1>, names)<EOL>for i in expr.values)<EOL><DEDENT>elif isinstance(op, And):<EOL><INDENT>str_exp = "<STR_LIT>".join(ast2str(i, level + <NUM_LIT:1>, names)<EOL>for i in expr.values)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" + op.__class__.__name)<EOL><DEDENT>return "<STR_LIT:(>" + str_exp + "<STR_LIT:)>" if level else str_exp<EOL><DEDENT>elif expr is None:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" + repr(expr))<EOL><DEDENT>

convert compiled ast to gene_reaction_rule str

    Parameters
    ----------
    expr : str
        string for a gene reaction rule, e.g "a and b"
    level : int
        internal use only
    names : dict
        Dict where each element id a gene identifier and the value is the
        gene name. Use this to get a rule str which uses names instead. This
        should be done for display purposes only. All gene_reaction_rule
        strings which are computed with should use the id.

    Returns
    ------
    string
        The gene reaction rule


self.functional = False<EOL>for reaction in self.reactions:<EOL><INDENT>if not reaction.functional:<EOL><INDENT>reaction.bounds = (<NUM_LIT:0>, <NUM_LIT:0>)<EOL><DEDENT><DEDENT>

Knockout gene by marking it as non-functional and setting all
        associated reactions bounds to zero.

        The change is reverted upon exit if executed within the model as
        context.


if self.status != "<STR_LIT>":<EOL><INDENT>return "<STR_LIT>".format(<EOL>self.status, id(self))<EOL><DEDENT>return "<STR_LIT>".format(<EOL>self.f, id(self))<EOL>

String representation of the solution instance.


def __init__(self, f, x=None, x_dict=None, y=None, y_dict=None,<EOL>solver=None, the_time=<NUM_LIT:0>, status='<STR_LIT>', **kwargs):

super(LegacySolution, self).__init__(**kwargs)<EOL>self.solver = solver<EOL>self.f = f<EOL>self.x = x<EOL>self.x_dict = x_dict<EOL>self.status = status<EOL>self.y = y<EOL>self.y_dict = y_dict<EOL>

Initialize a `LegacySolution` from an objective value.

Parameters
----------
f : float
    Objective value.
solver : str, optional
    A string indicating which solver package was used.
x : iterable, optional
    List or Array of the fluxes (primal values).
x_dict : dict, optional
    A dictionary of reaction IDs that maps to the respective primal
    values.
y : iterable, optional
    List or Array of the dual values.
y_dict : dict, optional
    A dictionary of reaction IDs that maps to the respective dual
    values.
the_time : int, optional
status : str, optional

.. warning :: deprecated


assert len(model_1.reactions) == len(model_2.reactions)<EOL>assert len(model_1.metabolites) == len(model_2.metabolites)<EOL>assert len(model_1.genes) == len(model_2.genes)<EOL>assert model_1.objective.direction == model_2.objective.direction<EOL>for attr in ("<STR_LIT:id>", "<STR_LIT:name>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>assert getattr(model_1.reactions[<NUM_LIT:0>], attr) == getattr(<EOL>model_2.reactions[<NUM_LIT:0>], attr)<EOL>assert getattr(model_1.reactions[<NUM_LIT:5>], attr) == getattr(<EOL>model_2.reactions[<NUM_LIT:5>], attr)<EOL>assert getattr(model_1.reactions[-<NUM_LIT:1>], attr) == getattr(<EOL>model_2.reactions[-<NUM_LIT:1>], attr)<EOL><DEDENT>for attr in ("<STR_LIT:id>", "<STR_LIT:name>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>assert getattr(model_1.metabolites[<NUM_LIT:0>], attr) == getattr(<EOL>model_2.metabolites[<NUM_LIT:0>], attr)<EOL>assert getattr(model_1.metabolites[<NUM_LIT:5>], attr) == getattr(<EOL>model_2.metabolites[<NUM_LIT:5>], attr)<EOL>assert getattr(model_1.metabolites[-<NUM_LIT:1>], attr) == getattr(<EOL>model_2.metabolites[-<NUM_LIT:1>], attr)<EOL>assert len(model_1.reactions[<NUM_LIT:0>].metabolites) == len(<EOL>model_2.reactions[<NUM_LIT:0>].metabolites)<EOL><DEDENT>assert len(model_1.reactions[<NUM_LIT:8>].metabolites) == len(<EOL>model_2.reactions[<NUM_LIT:8>].metabolites)<EOL>assert len(model_1.reactions[-<NUM_LIT:1>].metabolites) == len(<EOL>model_2.reactions[-<NUM_LIT:1>].metabolites)<EOL>assert len(model_1.genes) == len(model_2.genes)<EOL>solution_1 = model_1.optimize()<EOL>solution_2 = model_2.optimize()<EOL>assert abs(solution_1.objective_value -<EOL>solution_2.objective_value) == pytest.approx(<NUM_LIT:0.0>)<EOL>assert model_1.metabolites[<NUM_LIT:0>]._model is model_1<EOL>assert model_2.metabolites[<NUM_LIT:0>]._model is model_2<EOL>assert model_1.reactions[<NUM_LIT:0>]._model is model_1<EOL>assert model_2.reactions[<NUM_LIT:0>]._model is model_2<EOL>assert model_1.genes[<NUM_LIT:0>]._model is model_1<EOL>assert model_2.genes[<NUM_LIT:0>]._model is model_2<EOL>

Compare two models (only for testing purposes).


assert model is not None<EOL>annotation = model.annotation<EOL>assert annotation is not None<EOL>assert len(annotation) == <NUM_LIT:3><EOL>for key in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>assert key in annotation<EOL><DEDENT>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>annotation = model.genes.G1.annotation<EOL>assert len(annotation) == <NUM_LIT:5><EOL>for key in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>assert key in annotation<EOL><DEDENT>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>annotation = model.metabolites.A.annotation<EOL>for key in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>assert key in annotation<EOL><DEDENT>assert annotation[<EOL>"<STR_LIT>"] == "<STR_LIT>"  <EOL>annotation = model.reactions.R1.annotation<EOL>for key in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>assert key in annotation<EOL><DEDENT>assert annotation["<STR_LIT>"] == '<STR_LIT>'<EOL>

Checks the annotations from the annotation.xml.


c_elements = [coeff * met.elements.get('<STR_LIT:C>', <NUM_LIT:0>)<EOL>for met, coeff in iteritems(reaction.metabolites)]<EOL>return [elem for elem in c_elements if elem != <NUM_LIT:0>]<EOL>

Split metabolites into the atoms times their stoichiometric coefficients.

Parameters
----------
reaction : Reaction
    The metabolic reaction whose components are desired.

Returns
-------
list
    Each of the reaction's metabolites' desired carbon elements (if any)
    times that metabolite's stoichiometric coefficient.


def total_components_flux(flux, components, consumption=True):

direction = <NUM_LIT:1> if consumption else -<NUM_LIT:1><EOL>c_flux = [elem * flux * direction for elem in components]<EOL>return sum([flux for flux in c_flux if flux > <NUM_LIT:0>])<EOL>

Compute the total components consumption or production flux.

Parameters
----------
flux : float
    The reaction flux for the components.
components : list
    List of stoichiometrically weighted components.
consumption : bool, optional
    Whether to sum up consumption or production fluxes.