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: mass(compound, amounts[compound])<EOL>for compound in amounts.keys()}<EOL>

Calculate the masses from the specified compound amounts.

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

:returns: [kg] dictionary


m = masses(amounts)<EOL>m_total = sum(m.values())<EOL>return {compound: m[compound]/m_total for compound in m.keys()}<EOL>

Calculate the mole fractions from the specified compound amounts.

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

:returns: [mass fractions] dictionary


def convert_compound(mass, source, target, element):

<EOL>target_mass_fraction = element_mass_fraction(target, element)<EOL>if target_mass_fraction == <NUM_LIT:0.0>:<EOL><INDENT>return <NUM_LIT:0.0><EOL><DEDENT>else:<EOL><INDENT>source_mass_fraction = element_mass_fraction(source, element)<EOL>return mass * source_mass_fraction / target_mass_fraction<EOL><DEDENT>

Convert the specified mass of the source compound to the target using
element as basis.

:param mass: Mass of from_compound. [kg]
:param source: Formula and phase of the original compound, e.g.
  'Fe2O3[S1]'.
:param target: Formula and phase of the target compound, e.g. 'Fe[S1]'.
:param element: Element to use as basis for the conversion, e.g. 'Fe' or
  'O'.

:returns: Mass of target. [kg]


coeff = stoichiometry_coefficient(compound, element)<EOL>if coeff == <NUM_LIT:0.0>:<EOL><INDENT>return <NUM_LIT:0.0><EOL><DEDENT>formula_mass = molar_mass(compound)<EOL>element_mass = molar_mass(element)<EOL>return coeff * element_mass / formula_mass<EOL>

Determine the mass fraction of an element in a chemical compound.

:param compound: Formula of the chemical compound, 'FeCr2O4'.
:param element: Element, e.g. 'Cr'.

:returns: Element mass fraction.


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.


elementlist = [parse_compound(compound).count().keys()<EOL>for compound in compounds]<EOL>return set().union(*elementlist)<EOL>

Determine the set of elements present in a list of chemical compounds.

The list of elements is sorted alphabetically.

:param compounds: List of compound formulas and phases, e.g.
  ['Fe2O3[S1]', 'Al2O3[S1]'].

:returns: List of elements.


result = <NUM_LIT:0.0><EOL>if compound is None or len(compound) == <NUM_LIT:0>:<EOL><INDENT>return result<EOL><DEDENT>compound = compound.strip()<EOL>parsed = parse_compound(compound)<EOL>return parsed.molar_mass()<EOL>

Determine the molar mass of a chemical compound.

    The molar mass is usually the mass of one mole of the substance, but here
    it is the mass of 1000 moles, since the mass unit used in auxi is kg.

    :param compound: Formula of a chemical compound, e.g. 'Fe2O3'.

    :returns: Molar mass. [kg/kmol]


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.


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

Determine the stoichiometry coefficients of the specified elements in
the specified chemical compound.

:param compound: Formula of a chemical compound, e.g. 'SiO2'.
:param elements: List of elements, e.g. ['Si', 'O', 'C'].

:returns: List of stoichiometry coefficients.


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.


with open(file_name) as f:<EOL><INDENT>lines = f.readlines()<EOL><DEDENT>compound = {'<STR_LIT>': lines[<NUM_LIT:0>].split('<STR_LIT:U+0020>')[<NUM_LIT:1>]}<EOL>print(compound['<STR_LIT>'])<EOL>compound['<STR_LIT>'] = phs = {}<EOL>started = False<EOL>phaseold = '<STR_LIT>'<EOL>recordold = '<STR_LIT:0>'<EOL>for line in lines:<EOL><INDENT>if started:<EOL><INDENT>if line.startswith('<STR_LIT:_>'):  <EOL><INDENT>break<EOL><DEDENT>line = line.replace('<STR_LIT>', '<STR_LIT>')<EOL>line = line.replace('<STR_LIT>', '<STR_LIT:U+0020>')<EOL>while '<STR_LIT:U+0020>' in line:<EOL><INDENT>line = line.replace('<STR_LIT:U+0020>', '<STR_LIT:U+0020>')<EOL><DEDENT>line = line.replace('<STR_LIT>', '<STR_LIT>')<EOL>line = line.replace('<STR_LIT:\n>', '<STR_LIT>')<EOL>strings = line.split('<STR_LIT:U+0020>')<EOL>if len(strings) < <NUM_LIT:2>:  <EOL><INDENT>continue<EOL><DEDENT>phase = strings[<NUM_LIT:0>]<EOL>if phase != phaseold:  <EOL><INDENT>phaseold = phase<EOL>ph = phs[phase] = {}<EOL>ph['<STR_LIT>'] = phase<EOL>ph['<STR_LIT>'] = float(strings[<NUM_LIT:2>])<EOL>ph['<STR_LIT>'] = float(strings[<NUM_LIT:3>])<EOL>cprecs = ph['<STR_LIT>'] = {}<EOL>record = strings[<NUM_LIT:1>]<EOL>if record != recordold:  <EOL><INDENT>recordold = record<EOL>Tmax = float(strings[len(strings) - <NUM_LIT:1>])<EOL>cprecs[Tmax] = {}<EOL>cprecs[Tmax]['<STR_LIT>'] = float(strings[len(strings) - <NUM_LIT:2>])<EOL>cprecs[Tmax]['<STR_LIT>'] = float(strings[len(strings) - <NUM_LIT:1>])<EOL>cprecs[Tmax]['<STR_LIT>'] = []<EOL>t = {'<STR_LIT>': float(strings[<NUM_LIT:4>]),<EOL>'<STR_LIT>': float(strings[<NUM_LIT:5>])}<EOL>cprecs[Tmax]['<STR_LIT>'].append(t)<EOL>if len(strings) == <NUM_LIT:10>:<EOL><INDENT>t = {'<STR_LIT>': float(strings[<NUM_LIT:6>]),<EOL>'<STR_LIT>': float(strings[<NUM_LIT:7>])}<EOL>cprecs[Tmax]['<STR_LIT>'].append(t)<EOL><DEDENT><DEDENT>else:  <EOL><INDENT>t = {'<STR_LIT>': float(strings[<NUM_LIT:2>]),<EOL>'<STR_LIT>': float(strings[<NUM_LIT:3>])}<EOL>cprecs[Tmax]['<STR_LIT>'].append(t)<EOL>if len(strings) == <NUM_LIT:8>:<EOL><INDENT>t = {'<STR_LIT>': float(strings[<NUM_LIT:4>]),<EOL>'<STR_LIT>': float(strings[<NUM_LIT:5>])}<EOL>cprecs[Tmax]['<STR_LIT>'].append(t)<EOL><DEDENT><DEDENT><DEDENT>else:  <EOL><INDENT>ph = phs[phase]<EOL>record = strings[<NUM_LIT:1>]<EOL>if record != recordold:  <EOL><INDENT>recordold = record<EOL>Tmax = float(strings[len(strings) - <NUM_LIT:1>])<EOL>cprecs = ph['<STR_LIT>']<EOL>cprecs[Tmax] = {}<EOL>cprecs[Tmax]['<STR_LIT>'] = float(strings[len(strings) - <NUM_LIT:2>])<EOL>cprecs[Tmax]['<STR_LIT>'] = float(strings[len(strings) - <NUM_LIT:1>])<EOL>cprecs[Tmax]['<STR_LIT>'] = []<EOL>t = {'<STR_LIT>': float(strings[<NUM_LIT:2>]),<EOL>'<STR_LIT>': float(strings[<NUM_LIT:3>])}<EOL>cprecs[Tmax]['<STR_LIT>'].append(t)<EOL>if len(strings) == <NUM_LIT:8>:<EOL><INDENT>t = {'<STR_LIT>': float(strings[<NUM_LIT:4>]),<EOL>'<STR_LIT>': float(strings[<NUM_LIT:5>])}<EOL>cprecs[Tmax]['<STR_LIT>'].append(t)<EOL><DEDENT><DEDENT>else:  <EOL><INDENT>t = {'<STR_LIT>': float(strings[<NUM_LIT:2>]),<EOL>'<STR_LIT>': float(strings[<NUM_LIT:3>])}<EOL>cprecs[Tmax]['<STR_LIT>'].append(t)<EOL>if len(strings) == <NUM_LIT:8>:<EOL><INDENT>t = {'<STR_LIT>': float(strings[<NUM_LIT:4>]),<EOL>'<STR_LIT>': float(strings[<NUM_LIT:5>])}<EOL>cprecs[Tmax]['<STR_LIT>'].append(t)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if line.startswith('<STR_LIT:_>'):  <EOL><INDENT>started = True<EOL><DEDENT><DEDENT>for name, ph in phs.items():<EOL><INDENT>cprecs = ph['<STR_LIT>']<EOL>first = cprecs[min(cprecs.keys())]<EOL>first['<STR_LIT>'] = <NUM_LIT><EOL><DEDENT>return compound<EOL>

Build a dictionary containing the factsage 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.


formula = compound_string.replace('<STR_LIT:]>', '<STR_LIT>').split('<STR_LIT:[>')[<NUM_LIT:0>]<EOL>phase = compound_string.replace('<STR_LIT:]>', '<STR_LIT>').split('<STR_LIT:[>')[<NUM_LIT:1>]<EOL>return formula, phase<EOL>

Split a compound's combined formula and phase into separate strings for
the formula and phase.

:param compound_string: Formula and phase of a chemical compound, e.g.
  'SiO2[S1]'.

:returns: Formula of chemical compound.
:returns: Phase of chemical compound.


def _finalise_result_(compound, value, mass):

result = value / <NUM_LIT>  <EOL>result = result / compound.molar_mass  <EOL>result = result * mass  <EOL>return result<EOL>

Convert the value to its final form by unit conversions and multiplying
by mass.

:param compound: Compound object.
:param value: [J/mol] Value to be finalised.
:param mass: [kg] Mass of compound.

:returns: [kWh] Finalised value.


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.


file_name = "<STR_LIT>" + compound.formula + "<STR_LIT>"<EOL>with open(os.path.join(directory, file_name), '<STR_LIT:w>') as f:<EOL><INDENT>f.write(str(compound))<EOL><DEDENT>

Writes a compound to an auxi file at the specified directory.

:param dir: The directory.
:param compound: The compound.


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.


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.


with open(get_path(__file__, "<STR_LIT>")) as f:<EOL><INDENT>return json.load(f)<EOL><DEDENT>

Retrieve all the references used by the datafiles.


return mm(compound) / <NUM_LIT><EOL>

Determine the molar mass of a chemical compound.

:param compound: Formula of a chemical compound, e.g. 'Fe2O3'.

:returns: [kg/mol] Molar mass.


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.


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.


def S(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.S(phase, TK)<EOL>return _finalise_result_(compound, result, mass)<EOL>

Calculate the entropy 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] Entropy.


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.


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.


result = <NUM_LIT:0.0><EOL>if T < self.Tmax:<EOL><INDENT>lT = T<EOL><DEDENT>else:<EOL><INDENT>lT = self.Tmax<EOL><DEDENT>Tref = self.Tmin<EOL>for c, e in zip(self._coefficients, self._exponents):<EOL><INDENT>if e == -<NUM_LIT:1.0>:<EOL><INDENT>result += c * math.log(lT/Tref)<EOL><DEDENT>else:<EOL><INDENT>result += c * (lT**(e+<NUM_LIT:1.0>) - Tref**(e+<NUM_LIT:1.0>)) / (e+<NUM_LIT:1.0>)<EOL><DEDENT><DEDENT>return result<EOL>

Calculate the portion of enthalpy of the compound phase covered by this
Cp record.

:param T: [K] temperature

:returns: [J/mol] Enthalpy.


result = <NUM_LIT:0.0><EOL>if T < self.Tmax:<EOL><INDENT>lT = T<EOL><DEDENT>else:<EOL><INDENT>lT = self.Tmax<EOL><DEDENT>Tref = self.Tmin<EOL>for c, e in zip(self._coefficients, self._exponents):<EOL><INDENT>e_modified = e - <NUM_LIT:1.0><EOL>if e_modified == -<NUM_LIT:1.0>:<EOL><INDENT>result += c * math.log(lT/Tref)<EOL><DEDENT>else:<EOL><INDENT>e_mod = e_modified + <NUM_LIT:1.0><EOL>result += c * (lT**e_mod - Tref**e_mod) / e_mod<EOL><DEDENT><DEDENT>return result<EOL>

Calculate the portion of entropy of the compound phase covered by this
Cp record.

:param T: [K] temperature

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


return <NUM_LIT:0.0><EOL>

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

:param T: [K] temperature

:returns: Zero.


<EOL>for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]):<EOL><INDENT>if T < Tmax:<EOL><INDENT>return self._Cp_records[str(Tmax)].Cp(T) + self.Cp_mag(T)<EOL><DEDENT><DEDENT>Tmax = max([float(TT) for TT in self._Cp_records.keys()])<EOL>return self._Cp_records[str(Tmax)].Cp(Tmax) + self.Cp_mag(T)<EOL>

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

:param T: [K] temperature

:returns: [J/mol/K] The heat capacity 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


result = self.DHref<EOL>for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]):<EOL><INDENT>result += self._Cp_records[str(Tmax)].H(T)<EOL>if T <= Tmax:<EOL><INDENT>return result + self.H_mag(T)<EOL><DEDENT><DEDENT>Tmax = max([float(TT) for TT in self._Cp_records.keys()])<EOL>result += self.Cp(Tmax)*(T - Tmax)<EOL>return result + self.H_mag(T)<EOL>

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

:param T: [K] temperature

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


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


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>s = <NUM_LIT:1> - (self._B_mag*(<NUM_LIT:2>*tau**<NUM_LIT:3>/<NUM_LIT:3> + <NUM_LIT:2>*tau**<NUM_LIT:9>/<NUM_LIT> + <NUM_LIT:2>*tau**<NUM_LIT:15>/<NUM_LIT>)) /self._D_mag<EOL><DEDENT>else:<EOL><INDENT>s = (<NUM_LIT:2>*tau**-<NUM_LIT:5>/<NUM_LIT:5> + <NUM_LIT:2>*tau**-<NUM_LIT:15>/<NUM_LIT> + <NUM_LIT:2>*tau**-<NUM_LIT>/<NUM_LIT>)/self._D_mag<EOL><DEDENT>return -R*math.log(self.beta0_mag + <NUM_LIT:1>)*s<EOL>

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

:param T: [K] temperature

:returns: [J/mol/K] The magnetic entropy 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


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

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

        :param T: [K] temperature

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


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


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

Get a list of the compound's phases.

:returns: List of phases.


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.


try:<EOL><INDENT>return self._phases[phase].H(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] Enthalpy.


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.


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

Calculate the Gibbs free energy 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] Gibbs free energy.


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:1><EOL>


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.


return self.get_datetime_at_period_ix(self.timestep_ix)<EOL>

Get the clock's current datetime.

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


if type(date) is str:<EOL><INDENT>return datetime.strptime(date, '<STR_LIT>').date()<EOL><DEDENT>else:<EOL><INDENT>return date<EOL><DEDENT>

Get the date from a value that could be a date object or a string.

:param date: The date object or string.

:returns: The date object.


<EOL>if isinstance(value, string_types):<EOL><INDENT>return str(value)<EOL><DEDENT>if isinstance(value, float_):<EOL><INDENT>return float(value)<EOL><DEDENT>if isinstance(value, bool_):<EOL><INDENT>return bool(value)<EOL><DEDENT>if isinstance(value, set):<EOL><INDENT>return list(value)<EOL><DEDENT>if isinstance(value, dict):<EOL><INDENT>return OrderedDict((key, value[key]) for key in sorted(value))<EOL><DEDENT>if value.__class__.__name__ == "<STR_LIT>":<EOL><INDENT>return str(value)<EOL><DEDENT>if value is None:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>return value<EOL>

convert possible types to str, float, and bool


def _update_optional(cobra_object, new_dict, optional_attribute_dict,<EOL>ordered_keys):

for key in ordered_keys:<EOL><INDENT>default = optional_attribute_dict[key]<EOL>value = getattr(cobra_object, key)<EOL>if value is None or value == default:<EOL><INDENT>continue<EOL><DEDENT>new_dict[key] = _fix_type(value)<EOL><DEDENT>

update new_dict with optional attributes from cobra_object


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


if '<STR_LIT>' not in obj:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>model = Model()<EOL>model.add_metabolites(<EOL>[metabolite_from_dict(metabolite) for metabolite in obj['<STR_LIT>']]<EOL>)<EOL>model.genes.extend([gene_from_dict(gene) for gene in obj['<STR_LIT>']])<EOL>model.add_reactions(<EOL>[reaction_from_dict(reaction, model) for reaction in obj['<STR_LIT>']]<EOL>)<EOL>objective_reactions = [rxn for rxn in obj['<STR_LIT>'] if<EOL>rxn.get('<STR_LIT>', <NUM_LIT:0>) != <NUM_LIT:0>]<EOL>coefficients = {<EOL>model.reactions.get_by_id(rxn['<STR_LIT:id>']): rxn['<STR_LIT>'] for<EOL>rxn in objective_reactions}<EOL>set_objective(model, coefficients)<EOL>for k, v in iteritems(obj):<EOL><INDENT>if k in {'<STR_LIT:id>', '<STR_LIT:name>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'}:<EOL><INDENT>setattr(model, k, v)<EOL><DEDENT><DEDENT>return model<EOL>

Build a model from a dict.

    Models stored in json are first formulated as a dict that can be read to
    cobra model using this function.

    Parameters
    ----------
    obj : dict
        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.

    Returns
    -------
    cora.core.Model
        The generated model.

    See Also
    --------
    cobra.io.model_to_dict


return sid[len(prefix):] if sid.startswith(prefix) else sid<EOL>

Clips a prefix from the beginning of a string if it exists.


sid = sid.replace(SBML_DOT, "<STR_LIT:.>")<EOL>return _clip(sid, prefix)<EOL>


return prefix + sid.replace("<STR_LIT:.>", SBML_DOT)<EOL>


return _clip(sid, prefix)<EOL>


return prefix + sid<EOL>


def read_sbml_model(filename, number=float, f_replace=F_REPLACE,<EOL>set_missing_bounds=False, **kwargs):

try:<EOL><INDENT>doc = _get_doc_from_filename(filename)<EOL>return _sbml_to_model(doc,<EOL>number=number,<EOL>f_replace=f_replace,<EOL>set_missing_bounds=set_missing_bounds,<EOL>**kwargs)<EOL><DEDENT>except IOError as e:<EOL><INDENT>raise e<EOL><DEDENT>except Exception:<EOL><INDENT>LOGGER.error(traceback.print_exc())<EOL>raise CobraSBMLError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>

Reads SBML model from given filename.

    If the given filename ends with the suffix ''.gz'' (for example,
    ''myfile.xml.gz'),' the file is assumed to be compressed in gzip
    format and will be automatically decompressed upon reading. Similarly,
    if the given filename ends with ''.zip'' or ''.bz2',' the file is
    assumed to be compressed in zip or bzip2 format (respectively).  Files
    whose names lack these suffixes will be read uncompressed.  Note that
    if the file is in zip format but the archive contains more than one
    file, only the first file in the archive will be read and the rest
    ignored.

    To read a gzip/zip file, libSBML needs to be configured and linked
    with the zlib library at compile time.  It also needs to be linked
    with the bzip2 library to read files in bzip2 format.  (Both of these
    are the default configurations for libSBML.)

    This function supports SBML with FBC-v1 and FBC-v2. FBC-v1 models
    are converted to FBC-v2 models before reading.

    The parser tries to fall back to information in notes dictionaries
    if information is not available in the FBC packages, e.g.,
    CHARGE, FORMULA on species, or GENE_ASSOCIATION, SUBSYSTEM on reactions.

    Parameters
    ----------
    filename : path to SBML file, or SBML string, or SBML file handle
        SBML which is read into cobra model
    number: data type of stoichiometry: {float, int}
        In which data type should the stoichiometry be parsed.
    f_replace : dict of replacement functions for id replacement
        Dictionary of replacement functions for gene, specie, and reaction.
        By default the following id changes are performed on import:
        clip G_ from genes, clip M_ from species, clip R_ from reactions
        If no replacements should be performed, set f_replace={}, None
    set_missing_bounds : boolean flag to set missing bounds
        Missing bounds are set to default bounds in configuration.

    Returns
    -------
    cobra.core.Model

    Notes
    -----
    Provided file handles cannot be opened in binary mode, i.e., use
        with open(path, "r" as f):
            read_sbml_model(f)
    File handles to compressed files are not supported yet.


if isinstance(filename, string_types):<EOL><INDENT>if ("<STR_LIT>" in platform) and (len(filename) < <NUM_LIT>)and os.path.exists(filename):<EOL><INDENT>doc = libsbml.readSBMLFromFile(filename)  <EOL><DEDENT>elif ("<STR_LIT>" not in platform) and os.path.exists(filename):<EOL><INDENT>doc = libsbml.readSBMLFromFile(filename)  <EOL><DEDENT>else:<EOL><INDENT>if "<STR_LIT>" not in filename:<EOL><INDENT>raise IOError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", filename)<EOL><DEDENT>doc = libsbml.readSBMLFromString(filename)  <EOL><DEDENT><DEDENT>elif hasattr(filename, "<STR_LIT>"):<EOL><INDENT>doc = libsbml.readSBMLFromString(filename.read())  <EOL><DEDENT>else:<EOL><INDENT>raise CobraSBMLError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", type(filename))<EOL><DEDENT>return doc<EOL>

Get SBMLDocument from given filename.

    Parameters
    ----------
    filename : path to SBML, or SBML string, or filehandle

    Returns
    -------
    libsbml.SBMLDocument


def _sbml_to_model(doc, number=float, f_replace=F_REPLACE,<EOL>set_missing_bounds=False, **kwargs):

if f_replace is None:<EOL><INDENT>f_replace = {}<EOL><DEDENT>model = doc.getModel()  <EOL>if model is None:<EOL><INDENT>raise CobraSBMLError("<STR_LIT>")<EOL><DEDENT>model_fbc = model.getPlugin("<STR_LIT>")  <EOL>if not model_fbc:<EOL><INDENT>LOGGER.warning("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>if not model_fbc.isSetStrict():<EOL><INDENT>LOGGER.warning('<STR_LIT>')<EOL><DEDENT>doc_fbc = doc.getPlugin("<STR_LIT>")  <EOL>fbc_version = doc_fbc.getPackageVersion()<EOL>if fbc_version == <NUM_LIT:1>:<EOL><INDENT>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>conversion_properties = libsbml.ConversionProperties()<EOL>conversion_properties.addOption("<STR_LIT>", True,<EOL>"<STR_LIT>")<EOL>result = doc.convert(conversion_properties)<EOL>if result != libsbml.LIBSBML_OPERATION_SUCCESS:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>cobra_model = Model(model.getId())<EOL>cobra_model.name = model.getName()<EOL>meta = {<EOL>"<STR_LIT>": model.getId(),<EOL>"<STR_LIT>": model.getLevel(),<EOL>"<STR_LIT:version>": model.getVersion(),<EOL>"<STR_LIT>": []<EOL>}<EOL>creators = []<EOL>created = None<EOL>if model.isSetModelHistory():<EOL><INDENT>history = model.getModelHistory()  <EOL>if history.isSetCreatedDate():<EOL><INDENT>created = history.getCreatedDate()<EOL><DEDENT>for c in history.getListCreators():  <EOL><INDENT>creators.append({<EOL>"<STR_LIT>": c.getFamilyName() if c.isSetFamilyName() else None,  <EOL>"<STR_LIT>": c.getGivenName() if c.isSetGivenName() else None,<EOL>"<STR_LIT>": c.getOrganisation() if c.isSetOrganisation() else None,  <EOL>"<STR_LIT:email>": c.getEmail() if c.isSetEmail() else None,<EOL>})<EOL><DEDENT><DEDENT>meta["<STR_LIT>"] = creators<EOL>meta["<STR_LIT>"] = created<EOL>meta["<STR_LIT>"] = _parse_notes_dict(doc)<EOL>meta["<STR_LIT>"] = _parse_annotations(doc)<EOL>info = "<STR_LIT>".format(model.getId(),<EOL>model.getLevel(), model.getVersion())<EOL>packages = {}<EOL>for k in range(doc.getNumPlugins()):<EOL><INDENT>plugin = doc.getPlugin(k)  <EOL>key, value = plugin.getPackageName(), plugin.getPackageVersion()<EOL>packages[key] = value<EOL>info += "<STR_LIT>".format(key, value)<EOL>if key not in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT>", key)<EOL><DEDENT><DEDENT>meta["<STR_LIT:info>"] = info<EOL>meta["<STR_LIT>"] = packages<EOL>cobra_model._sbml = meta<EOL>cobra_model.notes = _parse_notes_dict(model)<EOL>cobra_model.annotation = _parse_annotations(model)<EOL>cobra_model.compartments = {c.getId(): c.getName()<EOL>for c in model.getListOfCompartments()}<EOL>metabolites = []<EOL>boundary_metabolites = []<EOL>if model.getNumSpecies() == <NUM_LIT:0>:<EOL><INDENT>LOGGER.warning("<STR_LIT>")<EOL><DEDENT>for specie in model.getListOfSpecies():  <EOL><INDENT>sid = _check_required(specie, specie.getId(), "<STR_LIT:id>")<EOL>if f_replace and F_SPECIE in f_replace:<EOL><INDENT>sid = f_replace[F_SPECIE](sid)<EOL><DEDENT>met = Metabolite(sid)<EOL>met.name = specie.getName()<EOL>met.notes = _parse_notes_dict(specie)<EOL>met.annotation = _parse_annotations(specie)<EOL>met.compartment = specie.getCompartment()<EOL>specie_fbc = specie.getPlugin("<STR_LIT>")  <EOL>if specie_fbc:<EOL><INDENT>met.charge = specie_fbc.getCharge()<EOL>met.formula = specie_fbc.getChemicalFormula()<EOL><DEDENT>else:<EOL><INDENT>if specie.isSetCharge():<EOL><INDENT>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", specie)<EOL>met.charge = specie.getCharge()<EOL><DEDENT>else:<EOL><INDENT>if '<STR_LIT>' in met.notes:<EOL><INDENT>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", specie)<EOL>try:<EOL><INDENT>met.charge = int(met.notes['<STR_LIT>'])<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>if '<STR_LIT>' in met.notes:<EOL><INDENT>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", specie)<EOL>met.formula = met.notes['<STR_LIT>']<EOL><DEDENT><DEDENT>if specie.getBoundaryCondition() is True:<EOL><INDENT>boundary_metabolites.append(met)<EOL><DEDENT>metabolites.append(met)<EOL><DEDENT>cobra_model.add_metabolites(metabolites)<EOL>ex_reactions = []<EOL>for met in boundary_metabolites:<EOL><INDENT>ex_rid = "<STR_LIT>".format(met.id)<EOL>ex_reaction = Reaction(ex_rid)<EOL>ex_reaction.name = ex_rid<EOL>ex_reaction.annotation = {<EOL>'<STR_LIT>': SBO_EXCHANGE_REACTION<EOL>}<EOL>ex_reaction.lower_bound = -float("<STR_LIT>")<EOL>ex_reaction.upper_bound = float("<STR_LIT>")<EOL>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT:%s>" % (ex_reaction.id, met.id))<EOL>ex_reaction.add_metabolites({met: -<NUM_LIT:1>})<EOL>ex_reactions.append(ex_reaction)<EOL><DEDENT>cobra_model.add_reactions(ex_reactions)<EOL>if model_fbc:<EOL><INDENT>for gp in model_fbc.getListOfGeneProducts():  <EOL><INDENT>gid = gp.getId()<EOL>if f_replace and F_GENE in f_replace:<EOL><INDENT>gid = f_replace[F_GENE](gid)<EOL><DEDENT>cobra_gene = Gene(gid)<EOL>cobra_gene.name = gp.getName()<EOL>if cobra_gene.name is None:<EOL><INDENT>cobra_gene.name = gid<EOL><DEDENT>cobra_gene.annotation = _parse_annotations(gp)<EOL>cobra_gene.notes = _parse_notes_dict(gp)<EOL>cobra_model.genes.append(cobra_gene)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for cobra_reaction in model.getListOfReactions():  <EOL><INDENT>notes = _parse_notes_dict(cobra_reaction)<EOL>if "<STR_LIT>" in notes:<EOL><INDENT>gpr = notes['<STR_LIT>']<EOL><DEDENT>elif "<STR_LIT>" in notes:<EOL><INDENT>gpr = notes['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>gpr = '<STR_LIT>'<EOL><DEDENT>if len(gpr) > <NUM_LIT:0>:<EOL><INDENT>gpr = gpr.replace("<STR_LIT:(>", "<STR_LIT:;>")<EOL>gpr = gpr.replace("<STR_LIT:)>", "<STR_LIT:;>")<EOL>gpr = gpr.replace("<STR_LIT>", "<STR_LIT:;>")<EOL>gpr = gpr.replace("<STR_LIT>", "<STR_LIT:;>")<EOL>gids = [t.strip() for t in gpr.split('<STR_LIT:;>')]<EOL>for gid in gids:<EOL><INDENT>if f_replace and F_GENE in f_replace:<EOL><INDENT>gid = f_replace[F_GENE](gid)<EOL><DEDENT>if gid not in cobra_model.genes:<EOL><INDENT>cobra_gene = Gene(gid)<EOL>cobra_gene.name = gid<EOL>cobra_model.genes.append(cobra_gene)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>def process_association(ass):<EOL><INDENT>"""<STR_LIT>"""<EOL>if ass.isFbcOr():<EOL><INDENT>return "<STR_LIT:U+0020>".join(<EOL>["<STR_LIT:(>", '<STR_LIT>'.join(process_association(c)<EOL>for c in ass.getListOfAssociations()), "<STR_LIT:)>"]<EOL>)<EOL><DEDENT>elif ass.isFbcAnd():<EOL><INDENT>return "<STR_LIT:U+0020>".join(<EOL>["<STR_LIT:(>", '<STR_LIT>'.join(process_association(c)<EOL>for c in ass.getListOfAssociations()), "<STR_LIT:)>"])<EOL><DEDENT>elif ass.isGeneProductRef():<EOL><INDENT>gid = ass.getGeneProduct()<EOL>if f_replace and F_GENE in f_replace:<EOL><INDENT>return f_replace[F_GENE](gid)<EOL><DEDENT>else:<EOL><INDENT>return gid<EOL><DEDENT><DEDENT><DEDENT>missing_bounds = False<EOL>reactions = []<EOL>if model.getNumReactions() == <NUM_LIT:0>:<EOL><INDENT>LOGGER.warning("<STR_LIT>")<EOL><DEDENT>for reaction in model.getListOfReactions():  <EOL><INDENT>rid = _check_required(reaction, reaction.getId(), "<STR_LIT:id>")<EOL>if f_replace and F_REACTION in f_replace:<EOL><INDENT>rid = f_replace[F_REACTION](rid)<EOL><DEDENT>cobra_reaction = Reaction(rid)<EOL>cobra_reaction.name = reaction.getName()<EOL>cobra_reaction.annotation = _parse_annotations(reaction)<EOL>cobra_reaction.notes = _parse_notes_dict(reaction)<EOL>p_ub, p_lb = None, None<EOL>r_fbc = reaction.getPlugin("<STR_LIT>")  <EOL>if r_fbc:<EOL><INDENT>lb_id = r_fbc.getLowerFluxBound()<EOL>if lb_id:<EOL><INDENT>p_lb = model.getParameter(lb_id)  <EOL>if p_lb and p_lb.getConstant() and(p_lb.getValue() is not None):<EOL><INDENT>cobra_reaction.lower_bound = p_lb.getValue()<EOL><DEDENT>else:<EOL><INDENT>raise CobraSBMLError("<STR_LIT>"<EOL>"<STR_LIT>" % (p_lb, reaction))<EOL><DEDENT><DEDENT>ub_id = r_fbc.getUpperFluxBound()<EOL>if ub_id:<EOL><INDENT>p_ub = model.getParameter(ub_id)  <EOL>if p_ub and p_ub.getConstant() and(p_ub.getValue() is not None):<EOL><INDENT>cobra_reaction.upper_bound = p_ub.getValue()<EOL><DEDENT>else:<EOL><INDENT>raise CobraSBMLError("<STR_LIT>"<EOL>"<STR_LIT>" % (p_ub, reaction))<EOL><DEDENT><DEDENT><DEDENT>elif reaction.isSetKineticLaw():<EOL><INDENT>klaw = reaction.getKineticLaw()  <EOL>p_lb = klaw.getParameter("<STR_LIT>")  <EOL>if p_lb:<EOL><INDENT>cobra_reaction.lower_bound = p_lb.getValue()<EOL><DEDENT>p_ub = klaw.getParameter("<STR_LIT>")  <EOL>if p_ub:<EOL><INDENT>cobra_reaction.upper_bound = p_ub.getValue()<EOL><DEDENT>if p_ub is not None or p_lb is not None:<EOL><INDENT>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", reaction)<EOL><DEDENT><DEDENT>if p_lb is None:<EOL><INDENT>missing_bounds = True<EOL>if set_missing_bounds:<EOL><INDENT>lower_bound = config.lower_bound<EOL><DEDENT>else:<EOL><INDENT>lower_bound = -float("<STR_LIT>")<EOL><DEDENT>cobra_reaction.lower_bound = lower_bound<EOL>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT>", lower_bound, reaction)<EOL><DEDENT>if p_ub is None:<EOL><INDENT>missing_bounds = True<EOL>if set_missing_bounds:<EOL><INDENT>upper_bound = config.upper_bound<EOL><DEDENT>else:<EOL><INDENT>upper_bound = float("<STR_LIT>")<EOL><DEDENT>cobra_reaction.upper_bound = upper_bound<EOL>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT>", upper_bound, reaction)<EOL><DEDENT>reactions.append(cobra_reaction)<EOL>stoichiometry = defaultdict(lambda: <NUM_LIT:0>)<EOL>for sref in reaction.getListOfReactants():  <EOL><INDENT>sid = sref.getSpecies()<EOL>if f_replace and F_SPECIE in f_replace:<EOL><INDENT>sid = f_replace[F_SPECIE](sid)<EOL><DEDENT>stoichiometry[sid] -= number(<EOL>_check_required(sref, sref.getStoichiometry(),<EOL>"<STR_LIT>"))<EOL><DEDENT>for sref in reaction.getListOfProducts():  <EOL><INDENT>sid = sref.getSpecies()<EOL>if f_replace and F_SPECIE in f_replace:<EOL><INDENT>sid = f_replace[F_SPECIE](sid)<EOL><DEDENT>stoichiometry[sid] += number(<EOL>_check_required(sref, sref.getStoichiometry(),<EOL>"<STR_LIT>"))<EOL><DEDENT>object_stoichiometry = {}<EOL>for met_id in stoichiometry:<EOL><INDENT>metabolite = cobra_model.metabolites.get_by_id(met_id)<EOL>object_stoichiometry[metabolite] = stoichiometry[met_id]<EOL><DEDENT>cobra_reaction.add_metabolites(object_stoichiometry)<EOL>if r_fbc:<EOL><INDENT>gpr = '<STR_LIT>'<EOL>gpa = r_fbc.getGeneProductAssociation()  <EOL>if gpa is not None:<EOL><INDENT>association = gpa.getAssociation()  <EOL>gpr = process_association(association)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>notes = cobra_reaction.notes<EOL>if "<STR_LIT>" in notes:<EOL><INDENT>gpr = notes['<STR_LIT>']<EOL><DEDENT>elif "<STR_LIT>" in notes:<EOL><INDENT>gpr = notes['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>gpr = '<STR_LIT>'<EOL><DEDENT>if len(gpr) > <NUM_LIT:0>:<EOL><INDENT>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", reaction)<EOL>if f_replace and F_GENE in f_replace:<EOL><INDENT>gpr = "<STR_LIT:U+0020>".join(<EOL>f_replace[F_GENE](t) for t in gpr.split('<STR_LIT:U+0020>')<EOL>)<EOL><DEDENT><DEDENT><DEDENT>if gpr.startswith("<STR_LIT:(>") and gpr.endswith("<STR_LIT:)>"):<EOL><INDENT>gpr = gpr[<NUM_LIT:1>:-<NUM_LIT:1>].strip()<EOL><DEDENT>cobra_reaction.gene_reaction_rule = gpr<EOL><DEDENT>cobra_model.add_reactions(reactions)<EOL>obj_direction = "<STR_LIT>"<EOL>coefficients = {}<EOL>if model_fbc:<EOL><INDENT>obj_list = model_fbc.getListOfObjectives()  <EOL>if obj_list is None:<EOL><INDENT>LOGGER.warning("<STR_LIT>")<EOL><DEDENT>elif obj_list.size() == <NUM_LIT:0>:<EOL><INDENT>LOGGER.warning("<STR_LIT>")<EOL><DEDENT>elif not obj_list.getActiveObjective():<EOL><INDENT>LOGGER.warning("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>obj_id = obj_list.getActiveObjective()<EOL>obj = model_fbc.getObjective(obj_id)  <EOL>obj_direction = LONG_SHORT_DIRECTION[obj.getType()]<EOL>for flux_obj in obj.getListOfFluxObjectives():  <EOL><INDENT>rid = flux_obj.getReaction()<EOL>if f_replace and F_REACTION in f_replace:<EOL><INDENT>rid = f_replace[F_REACTION](rid)<EOL><DEDENT>try:<EOL><INDENT>objective_reaction = cobra_model.reactions.get_by_id(rid)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise CobraSBMLError("<STR_LIT>"<EOL>"<STR_LIT>" % rid)<EOL><DEDENT>try:<EOL><INDENT>coefficients[objective_reaction] = number(<EOL>flux_obj.getCoefficient()<EOL>)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>LOGGER.warning(str(e))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for reaction in model.getListOfReactions():  <EOL><INDENT>if reaction.isSetKineticLaw():<EOL><INDENT>klaw = reaction.getKineticLaw()  <EOL>p_oc = klaw.getParameter(<EOL>"<STR_LIT>")  <EOL>if p_oc:<EOL><INDENT>rid = reaction.getId()<EOL>if f_replace and F_REACTION in f_replace:<EOL><INDENT>rid = f_replace[F_REACTION](rid)<EOL><DEDENT>try:<EOL><INDENT>objective_reaction = cobra_model.reactions.get_by_id(<EOL>rid)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise CobraSBMLError("<STR_LIT>"<EOL>"<STR_LIT>", rid)<EOL><DEDENT>try:<EOL><INDENT>coefficients[objective_reaction] = number(<EOL>p_oc.getValue())<EOL><DEDENT>except ValueError as e:<EOL><INDENT>LOGGER.warning(str(e))<EOL><DEDENT>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", cobra_reaction)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if len(coefficients) == <NUM_LIT:0>:<EOL><INDENT>LOGGER.error("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>set_objective(cobra_model, coefficients)<EOL>cobra_model.solver.objective.direction = obj_direction<EOL>model_groups = model.getPlugin("<STR_LIT>")  <EOL>groups = []<EOL>if model_groups:<EOL><INDENT>sid_map = {}<EOL>metaid_map = {}<EOL>for obj_list in [model.getListOfCompartments(),<EOL>model.getListOfSpecies(),<EOL>model.getListOfReactions(),<EOL>model_groups.getListOfGroups()]:<EOL><INDENT>for sbase in obj_list:  <EOL><INDENT>if sbase.isSetId():<EOL><INDENT>sid_map[sbase.getId()] = sbase<EOL><DEDENT>if sbase.isSetMetaId():<EOL><INDENT>metaid_map[sbase.getMetaId()] = sbase<EOL><DEDENT><DEDENT><DEDENT>for group in model_groups.getListOfGroups():  <EOL><INDENT>cobra_group = Group(group.getId())<EOL>cobra_group.name = group.getName()<EOL>if group.isSetKind():<EOL><INDENT>cobra_group.kind = group.getKindAsString()<EOL><DEDENT>cobra_group.annotation = _parse_annotations(group)<EOL>cobra_group.notes = _parse_notes_dict(group)<EOL>cobra_members = []<EOL>for member in group.getListOfMembers():  <EOL><INDENT>if member.isSetIdRef():<EOL><INDENT>obj = sid_map[member.getIdRef()]<EOL><DEDENT>elif member.isSetMetaIdRef():<EOL><INDENT>obj = metaid_map[member.getMetaIdRef()]<EOL><DEDENT>typecode = obj.getTypeCode()<EOL>obj_id = obj.getId()<EOL>cobra_member = None<EOL>if typecode == libsbml.SBML_SPECIES:<EOL><INDENT>if f_replace and F_SPECIE in f_replace:<EOL><INDENT>obj_id = f_replace[F_SPECIE](obj_id)<EOL><DEDENT>cobra_member = cobra_model.metabolites.get_by_id(obj_id)<EOL><DEDENT>elif typecode == libsbml.SBML_REACTION:<EOL><INDENT>if f_replace and F_REACTION in f_replace:<EOL><INDENT>obj_id = f_replace[F_REACTION](obj_id)<EOL><DEDENT>cobra_member = cobra_model.reactions.get_by_id(obj_id)<EOL><DEDENT>elif typecode == libsbml.SBML_FBC_GENEPRODUCT:<EOL><INDENT>if f_replace and F_GENE in f_replace:<EOL><INDENT>obj_id = f_replace[F_GENE](obj_id)<EOL><DEDENT>cobra_member = cobra_model.genes.get_by_id(obj_id)<EOL><DEDENT>else:<EOL><INDENT>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT:%s>" % (member, group, typecode))<EOL><DEDENT>if cobra_member:<EOL><INDENT>cobra_members.append(cobra_member)<EOL><DEDENT><DEDENT>cobra_group.add_members(cobra_members)<EOL>groups.append(cobra_group)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>groups_dict = {}<EOL>for cobra_reaction in cobra_model.reactions:<EOL><INDENT>if "<STR_LIT>" in cobra_reaction.notes:<EOL><INDENT>g_name = cobra_reaction.notes["<STR_LIT>"]<EOL>if g_name in groups_dict:<EOL><INDENT>groups_dict[g_name].append(cobra_reaction)<EOL><DEDENT>else:<EOL><INDENT>groups_dict[g_name] = [cobra_reaction]<EOL><DEDENT><DEDENT><DEDENT>for gid, cobra_members in groups_dict.items():<EOL><INDENT>cobra_group = Group(gid, name=gid, kind="<STR_LIT>")<EOL>cobra_group.add_members(cobra_members)<EOL>groups.append(cobra_group)<EOL><DEDENT><DEDENT>cobra_model.add_groups(groups)<EOL>if missing_bounds and not set_missing_bounds:<EOL><INDENT>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return cobra_model<EOL>

Creates cobra model from SBMLDocument.

    Parameters
    ----------
    doc: libsbml.SBMLDocument
    number: data type of stoichiometry: {float, int}
        In which data type should the stoichiometry be parsed.
    f_replace : dict of replacement functions for id replacement
    set_missing_bounds : flag to set missing bounds

    Returns
    -------
    cobra.core.Model


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


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


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 _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>


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 value is None:<EOL><INDENT>LOGGER.error('<STR_LIT>'<EOL>'<STR_LIT>' + message + '<STR_LIT>')<EOL><DEDENT>elif type(value) is int:<EOL><INDENT>if value == libsbml.LIBSBML_OPERATION_SUCCESS:<EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>LOGGER.error('<STR_LIT>' + message + '<STR_LIT>')<EOL>LOGGER.error('<STR_LIT>'.format(str(value),<EOL>libsbml.OperationReturnValue_toString(value).strip()))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT>

Checks the libsbml return value and logs error messages.

If 'value' is None, logs an error message constructed using
  'message' and then exits with status code 1. If 'value' is an integer,
  it assumes it is a libSBML return status code. If the code value is
  LIBSBML_OPERATION_SUCCESS, returns without further action; if it is not,
  prints an error message constructed using 'message' along with text from
  libSBML explaining the meaning of the code, and exits with status code 1.


notes = sbase.getNotesString()<EOL>if notes and len(notes) > <NUM_LIT:0>:<EOL><INDENT>pattern = r"<STR_LIT>"<EOL>matches = re.findall(pattern, notes)<EOL>d = {k.strip(): v.strip() for (k, v) in matches}<EOL>return {k: v for k, v in d.items() if len(v) > <NUM_LIT:0>}<EOL><DEDENT>else:<EOL><INDENT>return {}<EOL><DEDENT>

Creates dictionary of COBRA notes.

    Parameters
    ----------
    sbase : libsbml.SBase

    Returns
    -------
    dict of notes


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


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)


if not annotation or len(annotation) == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>annotation_data = deepcopy(annotation)<EOL>for key, value in annotation_data.items():<EOL><INDENT>if isinstance(value, (float, int)):<EOL><INDENT>value = str(value)<EOL><DEDENT>if isinstance(value, string_types):<EOL><INDENT>annotation_data[key] = [("<STR_LIT>", value)]<EOL><DEDENT><DEDENT>for key, value in annotation_data.items():<EOL><INDENT>for idx, item in enumerate(value):<EOL><INDENT>if isinstance(item, string_types):<EOL><INDENT>value[idx] = ("<STR_LIT>", item)<EOL><DEDENT><DEDENT><DEDENT>meta_id = "<STR_LIT>".format(sbase.getId())<EOL>sbase.setMetaId(meta_id)<EOL>for provider, data in iteritems(annotation_data):<EOL><INDENT>if provider in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>if provider == "<STR_LIT>":<EOL><INDENT>LOGGER.warning("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>sbo_term = data[<NUM_LIT:0>][<NUM_LIT:1>]<EOL>_check(sbase.setSBOTerm(sbo_term),<EOL>"<STR_LIT>".format(sbo_term))<EOL>continue<EOL><DEDENT>for item in data:<EOL><INDENT>qualifier_str, entity = item[<NUM_LIT:0>], item[<NUM_LIT:1>]<EOL>qualifier = QUALIFIER_TYPES.get(qualifier_str, None)<EOL>if qualifier is None:<EOL><INDENT>qualifier = libsbml.BQB_IS<EOL>LOGGER.error("<STR_LIT>"<EOL>"<STR_LIT>".format(qualifier_str))<EOL><DEDENT>qualifier_type = libsbml.BIOLOGICAL_QUALIFIER<EOL>if qualifier_str.startswith("<STR_LIT>"):<EOL><INDENT>qualifier_type = libsbml.MODEL_QUALIFIER<EOL><DEDENT>cv = libsbml.CVTerm()  <EOL>cv.setQualifierType(qualifier_type)<EOL>if qualifier_type == libsbml.BIOLOGICAL_QUALIFIER:<EOL><INDENT>cv.setBiologicalQualifierType(qualifier)<EOL><DEDENT>elif qualifier_type == libsbml.MODEL_QUALIFIER:<EOL><INDENT>cv.setModelQualifierType(qualifier)<EOL><DEDENT>else:<EOL><INDENT>raise CobraSBMLError('<STR_LIT>'<EOL>'<STR_LIT:%s>' % qualifier)<EOL><DEDENT>resource = "<STR_LIT>" % (URL_IDENTIFIERS_PREFIX, provider, entity)<EOL>cv.addResource(resource)<EOL>_check(sbase.addCVTerm(cv),<EOL>"<STR_LIT>".format(cv, resource))<EOL><DEDENT><DEDENT>

Set SBase annotations based on cobra annotations.

    Parameters
    ----------
    sbase : libsbml.SBase
        SBML object to annotate
    annotation : cobra annotation structure
        cobra object with annotation information

    FIXME: annotation format must be updated
        (https://github.com/opencobra/cobrapy/issues/684)


<EOL>keys = (<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>)<EOL>errors = {key: [] for key in keys}<EOL>doc = _get_doc_from_filename(filename)  <EOL>doc.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY,<EOL>check_units_consistency)<EOL>doc.setConsistencyChecks(libsbml.LIBSBML_CAT_MODELING_PRACTICE,<EOL>check_modeling_practice)<EOL>if internal_consistency:<EOL><INDENT>doc.checkInternalConsistency()<EOL><DEDENT>doc.checkConsistency()<EOL>for k in range(doc.getNumErrors()):<EOL><INDENT>e = doc.getError(k)  <EOL>msg = _error_string(e, k=k)<EOL>sev = e.getSeverity()<EOL>if sev == libsbml.LIBSBML_SEV_FATAL:<EOL><INDENT>errors["<STR_LIT>"].append(msg)<EOL><DEDENT>elif sev == libsbml.LIBSBML_SEV_ERROR:<EOL><INDENT>errors["<STR_LIT>"].append(msg)<EOL><DEDENT>elif sev == libsbml.LIBSBML_SEV_SCHEMA_ERROR:<EOL><INDENT>errors["<STR_LIT>"].append(msg)<EOL><DEDENT>elif sev == libsbml.LIBSBML_SEV_WARNING:<EOL><INDENT>errors["<STR_LIT>"].append(msg)<EOL><DEDENT><DEDENT>log_stream = StringIO()<EOL>stream_handler = logging.StreamHandler(log_stream)<EOL>formatter = logging.Formatter('<STR_LIT>')<EOL>stream_handler.setFormatter(formatter)<EOL>stream_handler.setLevel(logging.INFO)<EOL>LOGGER.addHandler(stream_handler)<EOL>LOGGER.propagate = False<EOL>try:<EOL><INDENT>model = _sbml_to_model(doc, **kwargs)<EOL><DEDENT>except CobraSBMLError as e:<EOL><INDENT>errors["<STR_LIT>"].append(str(e))<EOL>return None, errors<EOL><DEDENT>except Exception as e:<EOL><INDENT>errors["<STR_LIT>"].append(str(e))<EOL>return None, errors<EOL><DEDENT>cobra_errors = log_stream.getvalue().split("<STR_LIT:\n>")<EOL>for cobra_error in cobra_errors:<EOL><INDENT>tokens = cobra_error.split("<STR_LIT::>")<EOL>error_type = tokens[<NUM_LIT:0>]<EOL>error_msg = "<STR_LIT::>".join(tokens[<NUM_LIT:1>:])<EOL>if error_type == "<STR_LIT>":<EOL><INDENT>errors["<STR_LIT>"].append(error_msg)<EOL><DEDENT>elif error_type == "<STR_LIT>":<EOL><INDENT>errors["<STR_LIT>"].append(error_msg)<EOL><DEDENT><DEDENT>LOGGER.removeHandler(stream_handler)<EOL>LOGGER.propagate = True<EOL>if check_model:<EOL><INDENT>errors["<STR_LIT>"].extend(<EOL>check_metabolite_compartment_formula(model)<EOL>)<EOL><DEDENT>for key in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>if len(errors[key]) > <NUM_LIT:0>:<EOL><INDENT>LOGGER.error("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>break<EOL><DEDENT><DEDENT>for key in ["<STR_LIT>"]:<EOL><INDENT>if len(errors[key]) > <NUM_LIT:0>:<EOL><INDENT>LOGGER.error("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>break<EOL><DEDENT><DEDENT>for key in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>if len(errors[key]) > <NUM_LIT:0>:<EOL><INDENT>LOGGER.error("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>break<EOL><DEDENT><DEDENT>for key in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>if len(errors[key]) > <NUM_LIT:0>:<EOL><INDENT>LOGGER.error("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>break<EOL><DEDENT><DEDENT>return model, errors<EOL>

Validate SBML model and returns the model along with a list of errors.

    Parameters
    ----------
    filename : str
        The filename (or SBML string) of the SBML model to be validated.
    internal_consistency: boolean {True, False}
        Check internal consistency.
    check_units_consistency: boolean {True, False}
        Check consistency of units.
    check_modeling_practice: boolean {True, False}
        Check modeling practise.
    check_model: boolean {True, False}
        Whether to also check some basic model properties such as reaction
        boundaries and compartment formulas.

    Returns
    -------
    (model, errors)
    model : :class:`~cobra.core.Model.Model` object
        The cobra model if the file could be read successfully or None
        otherwise.
    errors : dict
        Warnings and errors grouped by their respective types.

    Raises
    ------
    CobraSBMLError


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


bracket_search = _bracket_re.findall(id)<EOL>if len(bracket_search) == <NUM_LIT:1>:<EOL><INDENT>return bracket_search[<NUM_LIT:0>][<NUM_LIT:1>]<EOL><DEDENT>underscore_search = _underscore_re.findall(id)<EOL>if len(underscore_search) == <NUM_LIT:1>:<EOL><INDENT>return underscore_search[<NUM_LIT:0>][<NUM_LIT:1>]<EOL><DEDENT>return None<EOL>

extract the compartment from the id string


x_no_none = [i if i is not None else "<STR_LIT>" for i in x]<EOL>return array(x_no_none, dtype=np_object)<EOL>

translate an array x into a MATLAB cell array


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


def save_matlab_model(model, file_name, varname=None):

if not scipy_io:<EOL><INDENT>raise ImportError('<STR_LIT>')<EOL><DEDENT>if varname is None:<EOL><INDENT>varname = str(model.id)if model.id is not None and len(model.id) > <NUM_LIT:0>else "<STR_LIT>"<EOL><DEDENT>mat = create_mat_dict(model)<EOL>scipy_io.savemat(file_name, {varname: mat},<EOL>appendmat=True, oned_as="<STR_LIT>")<EOL>

Save the cobra model as a .mat file.

    This .mat file can be used directly in the MATLAB version of COBRA.

    Parameters
    ----------
    model : cobra.core.Model.Model object
        The model to save
    file_name : str or file-like object
        The file to save to
    varname : string
       The name of the variable within the workspace


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


def from_mat_struct(mat_struct, model_id=None, inf=inf):

m = mat_struct<EOL>if m.dtype.names is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not {"<STR_LIT>", "<STR_LIT>", "<STR_LIT:S>", "<STR_LIT>", "<STR_LIT>"} <= set(m.dtype.names):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT:c>" in m.dtype.names:<EOL><INDENT>c_vec = m["<STR_LIT:c>"][<NUM_LIT:0>, <NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>c_vec = None<EOL>warn("<STR_LIT>")<EOL><DEDENT>model = Model()<EOL>if model_id is not None:<EOL><INDENT>model.id = model_id<EOL><DEDENT>elif "<STR_LIT:description>" in m.dtype.names:<EOL><INDENT>description = m["<STR_LIT:description>"][<NUM_LIT:0>, <NUM_LIT:0>][<NUM_LIT:0>]<EOL>if not isinstance(description, string_types) and len(description) > <NUM_LIT:1>:<EOL><INDENT>model.id = description[<NUM_LIT:0>]<EOL>warn("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>model.id = description<EOL><DEDENT><DEDENT>else:<EOL><INDENT>model.id = "<STR_LIT>"<EOL><DEDENT>for i, name in enumerate(m["<STR_LIT>"][<NUM_LIT:0>, <NUM_LIT:0>]):<EOL><INDENT>new_metabolite = Metabolite()<EOL>new_metabolite.id = str(name[<NUM_LIT:0>][<NUM_LIT:0>])<EOL>if all(var in m.dtype.names for var in<EOL>['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>comp_index = m["<STR_LIT>"][<NUM_LIT:0>, <NUM_LIT:0>][i][<NUM_LIT:0>] - <NUM_LIT:1><EOL>new_metabolite.compartment = m['<STR_LIT>'][<NUM_LIT:0>, <NUM_LIT:0>][comp_index][<NUM_LIT:0>][<NUM_LIT:0>]<EOL>if new_metabolite.compartment not in model.compartments:<EOL><INDENT>comp_name = m['<STR_LIT>'][<NUM_LIT:0>, <NUM_LIT:0>][comp_index][<NUM_LIT:0>][<NUM_LIT:0>]<EOL>model.compartments[new_metabolite.compartment] = comp_name<EOL><DEDENT><DEDENT>else:<EOL><INDENT>new_metabolite.compartment = _get_id_compartment(new_metabolite.id)<EOL>if new_metabolite.compartment not in model.compartments:<EOL><INDENT>model.compartments[<EOL>new_metabolite.compartment] = new_metabolite.compartment<EOL><DEDENT><DEDENT>try:<EOL><INDENT>new_metabolite.name = str(m["<STR_LIT>"][<NUM_LIT:0>, <NUM_LIT:0>][i][<NUM_LIT:0>][<NUM_LIT:0>])<EOL><DEDENT>except (IndexError, ValueError):<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>new_metabolite.formula = str(m["<STR_LIT>"][<NUM_LIT:0>][<NUM_LIT:0>][i][<NUM_LIT:0>][<NUM_LIT:0>])<EOL><DEDENT>except (IndexError, ValueError):<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>new_metabolite.charge = float(m["<STR_LIT>"][<NUM_LIT:0>, <NUM_LIT:0>][i][<NUM_LIT:0>])<EOL>int_charge = int(new_metabolite.charge)<EOL>if new_metabolite.charge == int_charge:<EOL><INDENT>new_metabolite.charge = int_charge<EOL><DEDENT><DEDENT>except (IndexError, ValueError):<EOL><INDENT>pass<EOL><DEDENT>model.add_metabolites([new_metabolite])<EOL><DEDENT>new_reactions = []<EOL>coefficients = {}<EOL>for i, name in enumerate(m["<STR_LIT>"][<NUM_LIT:0>, <NUM_LIT:0>]):<EOL><INDENT>new_reaction = Reaction()<EOL>new_reaction.id = str(name[<NUM_LIT:0>][<NUM_LIT:0>])<EOL>new_reaction.lower_bound = float(m["<STR_LIT>"][<NUM_LIT:0>, <NUM_LIT:0>][i][<NUM_LIT:0>])<EOL>new_reaction.upper_bound = float(m["<STR_LIT>"][<NUM_LIT:0>, <NUM_LIT:0>][i][<NUM_LIT:0>])<EOL>if isinf(new_reaction.lower_bound) and new_reaction.lower_bound < <NUM_LIT:0>:<EOL><INDENT>new_reaction.lower_bound = -inf<EOL><DEDENT>if isinf(new_reaction.upper_bound) and new_reaction.upper_bound > <NUM_LIT:0>:<EOL><INDENT>new_reaction.upper_bound = inf<EOL><DEDENT>if c_vec is not None:<EOL><INDENT>coefficients[new_reaction] = float(c_vec[i][<NUM_LIT:0>])<EOL><DEDENT>try:<EOL><INDENT>new_reaction.gene_reaction_rule = str(m['<STR_LIT>'][<NUM_LIT:0>, <NUM_LIT:0>][i][<NUM_LIT:0>][<NUM_LIT:0>])<EOL><DEDENT>except (IndexError, ValueError):<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>new_reaction.name = str(m["<STR_LIT>"][<NUM_LIT:0>, <NUM_LIT:0>][i][<NUM_LIT:0>][<NUM_LIT:0>])<EOL><DEDENT>except (IndexError, ValueError):<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>new_reaction.subsystem = str(m['<STR_LIT>'][<NUM_LIT:0>, <NUM_LIT:0>][i][<NUM_LIT:0>][<NUM_LIT:0>])<EOL><DEDENT>except (IndexError, ValueError):<EOL><INDENT>pass<EOL><DEDENT>new_reactions.append(new_reaction)<EOL><DEDENT>model.add_reactions(new_reactions)<EOL>set_objective(model, coefficients)<EOL>coo = scipy_sparse.coo_matrix(m["<STR_LIT:S>"][<NUM_LIT:0>, <NUM_LIT:0>])<EOL>for i, j, v in zip(coo.row, coo.col, coo.data):<EOL><INDENT>model.reactions[j].add_metabolites({model.metabolites[i]: v})<EOL><DEDENT>return model<EOL>

create a model from the COBRA toolbox struct

    The struct will be a dict read in by scipy.io.loadmat


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 model_to_pymatbridge(model, variable_name="<STR_LIT>", matlab=None):

if scipy_sparse is None:<EOL><INDENT>raise ImportError("<STR_LIT>")<EOL><DEDENT>if matlab is None:  <EOL><INDENT>from IPython import get_ipython<EOL>matlab = get_ipython().magics_manager.registry["<STR_LIT>"].Matlab<EOL><DEDENT>model_info = create_mat_dict(model)<EOL>S = model_info["<STR_LIT:S>"].todok()<EOL>model_info["<STR_LIT:S>"] = <NUM_LIT:0><EOL>temp_S_name = "<STR_LIT>" + uuid4().hex<EOL>_check(matlab.set_variable(variable_name, model_info))<EOL>_check(matlab.set_variable(temp_S_name, S))<EOL>_check(matlab.run_code("<STR_LIT>" % (variable_name, temp_S_name)))<EOL>for i in model_info.keys():<EOL><INDENT>if i == "<STR_LIT:S>":<EOL><INDENT>continue<EOL><DEDENT>_check(matlab.run_code("<STR_LIT>".format(variable_name, i)))<EOL><DEDENT>_check(matlab.run_code("<STR_LIT>" % temp_S_name))<EOL>

send the model to a MATLAB workspace through pymatbridge

    This model can then be manipulated through the COBRA toolbox

    Parameters
    ----------
    variable_name : str
        The variable name to which the model will be assigned in the
        MATLAB workspace

    matlab : None or pymatbridge.Matlab instance
        The MATLAB workspace to which the variable will be sent. If
        this is None, then this will be sent to the same environment
        used in IPython magics.


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.


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 save_yaml_model(model, filename, sort=False, **kwargs):

obj = model_to_dict(model, sort=sort)<EOL>obj["<STR_LIT:version>"] = YAML_SPEC<EOL>if isinstance(filename, string_types):<EOL><INDENT>with io.open(filename, "<STR_LIT:w>") as file_handle:<EOL><INDENT>yaml.dump(obj, file_handle, **kwargs)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yaml.dump(obj, filename, **kwargs)<EOL><DEDENT>

Write the cobra model to a file in YAML format.

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

Parameters
----------
model : cobra.Model
    The cobra model to represent.
filename : str or file-like
    File path or descriptor that the YAML representation should be
    written to.
sort : bool, optional
    Whether to sort the metabolites, reactions, and genes or maintain the
    order defined in the model.

See Also
--------
to_yaml : Return a string representation.
ruamel.yaml.dump : Base function.


if isinstance(filename, string_types):<EOL><INDENT>with io.open(filename, "<STR_LIT:r>") as file_handle:<EOL><INDENT>return model_from_dict(yaml.load(file_handle))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return model_from_dict(yaml.load(filename))<EOL><DEDENT>

Load a cobra model from a file in YAML format.

Parameters
----------
filename : str or file-like
    File path or descriptor that contains the YAML document describing the
    cobra model.

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

See Also
--------
from_yaml : Load from a string.


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

obj = model_to_dict(model, sort=sort)<EOL>obj[u"<STR_LIT:version>"] = JSON_SPEC<EOL>return json.dumps(obj, allow_nan=False, **kwargs)<EOL>

Return the model as a JSON document.

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

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 JSON document.

See Also
--------
save_json_model : Write directly to a file.
json.dumps : 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.


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.


if isinstance(filename, string_types):<EOL><INDENT>with open(filename, "<STR_LIT:r>") as file_handle:<EOL><INDENT>return model_from_dict(json.load(file_handle))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return model_from_dict(json.load(filename))<EOL><DEDENT>

Load a cobra model from a file in JSON format.

Parameters
----------
filename : str or file-like
    File path or descriptor that contains the JSON document describing the
    cobra model.

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

See Also
--------
from_json : Load from a string.


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


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.


self._dict = {v.id: k for k, v in enumerate(self)}<EOL>


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


return [getattr(i, attribute) for i in self]<EOL>

return a list of the given attribute for every object


def get_item(item):<EOL><INDENT>if isinstance(item, int):<EOL><INDENT>return self[item]<EOL><DEDENT>elif isinstance(item, string_types):<EOL><INDENT>return self.get_by_id(item)<EOL><DEDENT>elif item in self:<EOL><INDENT>return item<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" % type(item))<EOL><DEDENT><DEDENT>if not isinstance(iterable, list):<EOL><INDENT>iterable = [iterable]<EOL><DEDENT>return [get_item(item) for item in iterable]<EOL>

Get a list of members using several different ways of indexing

Parameters
----------
iterable : list (if not, turned into single element list)
    list where each element is either int (referring to an index in
    in this DictList), string (a id of a member in this DictList) or
    member of this DictList for pass-through

Returns
-------
list
    a list of members


def query(self, search_function, attribute=None):

def select_attribute(x):<EOL><INDENT>if attribute is None:<EOL><INDENT>return x<EOL><DEDENT>else:<EOL><INDENT>return getattr(x, attribute)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>regex_searcher = re.compile(search_function)<EOL>if attribute is not None:<EOL><INDENT>matches = (<EOL>i for i in self if<EOL>regex_searcher.findall(select_attribute(i)) != [])<EOL><DEDENT>else:<EOL><INDENT>matches = (<EOL>i for i in self if<EOL>regex_searcher.findall(getattr(i, '<STR_LIT:id>')) != [])<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>matches = (<EOL>i for i in self if search_function(select_attribute(i)))<EOL><DEDENT>results = self.__class__()<EOL>results._extend_nocheck(matches)<EOL>return results<EOL>

Query the list

        Parameters
        ----------
        search_function : a string, regular expression or function
            Used to find the matching elements in the list.
            - a regular expression (possibly compiled), in which case the
            given attribute of the object should match the regular expression.
            - a function which takes one argument and returns True for
            desired values

        attribute : string or None
            the name attribute of the object to passed as argument to the
            `search_function`. If this is None, the object itself is used.

        Returns
        -------
        DictList
            a new list of objects which match the query

        Examples
        --------
        >>> import cobra.test
        >>> model = cobra.test.create_test_model('textbook')
        >>> model.reactions.query(lambda x: x.boundary)
        >>> import re
        >>> regex = re.compile('^g', flags=re.IGNORECASE)
        >>> model.metabolites.query(regex, attribute='name')


the_id = new_object.id<EOL>the_index = self._dict[the_id]<EOL>list.__setitem__(self, the_index, new_object)<EOL>

Replace an object by another with the same id.


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


_dict = self._dict<EOL>append = self.append<EOL>for i in iterable:<EOL><INDENT>if i.id not in _dict:<EOL><INDENT>append(i)<EOL><DEDENT><DEDENT>

adds elements with id's not already in the model


<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


current_length = len(self)<EOL>list.extend(self, iterable)<EOL>_dict = self._dict<EOL>if current_length is <NUM_LIT:0>:<EOL><INDENT>self._generate_index()<EOL>return<EOL><DEDENT>for i, obj in enumerate(islice(self, current_length, None),<EOL>current_length):<EOL><INDENT>_dict[obj.id] = i<EOL><DEDENT>

extends without checking for uniqueness

        This function should only be used internally by DictList when it
        can guarantee elements are already unique (as in when coming from
        self or other DictList). It will be faster because it skips these
        checks.


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


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


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


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 {"<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


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


<EOL>if isinstance(id, string_types):<EOL><INDENT>try:<EOL><INDENT>return self._dict[id]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError("<STR_LIT>" % id)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>i = self._dict[id.id]<EOL>if self[i] is not id:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" % id.id)<EOL><DEDENT>return i<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError("<STR_LIT>" % str(id))<EOL><DEDENT>

Determine the position in the list

        id: A string or a :class:`~cobra.core.Object.Object`


if hasattr(object, "<STR_LIT:id>"):<EOL><INDENT>the_id = object.id<EOL><DEDENT>else:<EOL><INDENT>the_id = object<EOL><DEDENT>return the_id in self._dict<EOL>

DictList.__contains__(object) <==> object in DictList

        object: str or :class:`~cobra.core.Object.Object`


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>


value = list.pop(self, *args)<EOL>index = self._dict.pop(value.id)<EOL>if len(args) == <NUM_LIT:0> or args == [-<NUM_LIT:1>]:  <EOL><INDENT>return value<EOL><DEDENT>_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>return value<EOL>

remove and return item at index (default last).


self.extend([x])<EOL>


<EOL>self.pop(self.index(x))<EOL>


list.reverse(self)<EOL>self._generate_index()<EOL>


def sort(self, cmp=None, key=None, reverse=False):

if key is None:<EOL><INDENT>def key(i):<EOL><INDENT>return i.id<EOL><DEDENT><DEDENT>if PY3:<EOL><INDENT>list.sort(self, key=key, reverse=reverse)<EOL><DEDENT>else:<EOL><INDENT>list.sort(self, cmp=cmp, key=key, reverse=reverse)<EOL><DEDENT>self._generate_index()<EOL>

stable sort *IN PLACE*

        cmp(x, y) -> -1, 0, 1


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.


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


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.


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.