def check_reaction_consistency(database, solver, exchange=set(),<EOL>checked=set(), zeromass=set(), weights={}):
<EOL>prob = solver.create_problem()<EOL>compound_set = _non_localized_compounds(database)<EOL>mass_compounds = compound_set.difference(zeromass)<EOL>m = prob.namespace(mass_compounds, lower=<NUM_LIT:1>)<EOL>z = prob.namespace(database.reactions, lower=<NUM_LIT:0>)<EOL>r = prob.namespace(database.reactions)<EOL>objective = z.expr((reaction_id, weights.get(reaction_id, <NUM_LIT:1>))<EOL>for reaction_id in database.reactions)<EOL>prob.set_objective(objective)<EOL>rs = r.set(database.reactions)<EOL>zs = z.set(database.reactions)<EOL>prob.add_linear_constraints(zs >= rs, rs >= -zs)<EOL>massbalance_lhs = {reaction_id: <NUM_LIT:0> for reaction_id in database.reactions}<EOL>for (compound, reaction_id), value in iteritems(database.matrix):<EOL><INDENT>if compound not in zeromass:<EOL><INDENT>mass_var = m(compound.in_compartment(None))<EOL>massbalance_lhs[reaction_id] += mass_var * value<EOL><DEDENT><DEDENT>for reaction_id, lhs in iteritems(massbalance_lhs):<EOL><INDENT>if reaction_id not in exchange:<EOL><INDENT>if reaction_id not in checked:<EOL><INDENT>prob.add_linear_constraints(lhs + r(reaction_id) == <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>prob.add_linear_constraints(lhs == <NUM_LIT:0>)<EOL><DEDENT><DEDENT><DEDENT>try:<EOL><INDENT>prob.solve(lp.ObjectiveSense.Minimize)<EOL><DEDENT>except lp.SolverError as e:<EOL><INDENT>raise_from(<EOL>MassConsistencyError('<STR_LIT>'.format(<EOL>e)), e)<EOL><DEDENT>def iterate_reactions():<EOL><INDENT>for reaction_id in database.reactions:<EOL><INDENT>residual = r.value(reaction_id)<EOL>yield reaction_id, residual<EOL><DEDENT><DEDENT>def iterate_compounds():<EOL><INDENT>for compound in mass_compounds:<EOL><INDENT>yield compound, m.value(compound)<EOL><DEDENT><DEDENT>return iterate_reactions(), iterate_compounds()<EOL>
Check inconsistent reactions by minimizing mass residuals

    Return a reaction iterable, and compound iterable. The reaction iterable
    yields reaction ids and mass residuals. The compound iterable yields
    compound ids and mass assignments.

    Each compound is assigned a mass of at least one, and the masses are
    balanced using the stoichiometric matrix. In addition, each reaction has a
    residual mass that is included in the mass balance equations. The L1-norm
    of the residuals is minimized. Reactions in the checked set are assumed to
    have been manually checked and therefore have the residual fixed at zero.