Commit 9bc433d2 by Victor Shnayder

Actually implement exact vs factors-don't-matter comparisons in chemcalc

parent 5f816597
......@@ -312,12 +312,14 @@ def divide_chemical_expression(s1, s2, ignore_state=False):
return Fraction(treedic['1 factors'][0] / treedic['2 factors'][0])
def chemical_equations_equal(eq1, eq2, ignoreFactor=True):
def chemical_equations_equal(eq1, eq2, exact=False):
"""
Check whether two chemical equations are the same. If ignoreFactor is True,
then they are considered equal if they differ by a constant factor.
Check whether two chemical equations are the same.
arrows matter: ->, and <-> are different.
If exact is False, then they are considered equal if they differ by a
constant factor.
arrows matter: -> and <-> are different.
e.g.
chemical_equations_equal('H2 + O2 -> H2O2', 'O2 + H2 -> H2O2') -> True
......@@ -325,6 +327,10 @@ def chemical_equations_equal(eq1, eq2, ignoreFactor=True):
chemical_equations_equal('H2 + O2 -> H2O2', 'O2 + H2 <-> H2O2') -> False
chemical_equations_equal('H2 + O2 -> H2O2', '2 H2 + 2 O2 -> 2 H2O2') -> True
chemical_equations_equal('H2 + O2 -> H2O2', '2 H2 + 2 O2 -> 2 H2O2', exact=True) -> False
If there's a syntax error, we raise pyparsing.ParseException.
"""
# for now, we do a manual parse for the arrow.
......@@ -359,4 +365,8 @@ def chemical_equations_equal(eq1, eq2, ignoreFactor=True):
# factors don't match (molecule counts to add up)
return False
if exact and factor_left != 1:
# want an exact match.
return False
return True
......@@ -44,6 +44,17 @@ class Test_Compare_Equations(unittest.TestCase):
self.assertFalse(chemical_equations_equal('H2 + O2 -> H2O2',
'O2 + H2 <-> 2H2O2'))
def test_exact_match(self):
self.assertTrue(chemical_equations_equal('H2 + O2 -> H2O2',
'2O2 + 2H2 -> 2H2O2'))
self.assertFalse(chemical_equations_equal('H2 + O2 -> H2O2',
'2O2 + 2H2 -> 2H2O2', exact=True))
# order still doesn't matter
self.assertTrue(chemical_equations_equal('H2 + O2 -> H2O2',
'O2 + H2 -> H2O2', exact=True))
def test_syntax_errors(self):
self.assertRaises(ParseException, chemical_equations_equal,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment