Search code examples
pythonequation-solvingchemistrylinear-equation

Programmatically solve for chemical molar ratio between multiple reactions


Consider the reactions:

C6.H12.O6+6O2->6H2.O1+6C1.O2 (glucose + 6oxygen ->6 water + 6carbon dioxide)

2C1.H4.O1+C1.O2->C3.H6.O3+H2.O1 (2*methanol + carbon dioxide -> 1,3-dihydroxypropanone + water)

How can I programmatically figure out the molar ratio of two compounds between two reactions? (For example in this case the molar ratio between glucose and 1,3-dihydroxypropane). With one equation the problem becomes trivial (the ratio is just coefficientofsubstance1/coefficientofsubstance2), but with more than one equation the problem becomes more difficult. I have already implemented the parsing function to parse the chemical reactions (and to balance them). I think the way to go is to set every substance to its own variable and then set all of the substances in one equation with coefficients equal to each other and then solve for the ratio. For example for the upper pair of equations the equations would be:

1*a = 6*b = 6*c = 6*d

2*e = d = f = c

therefore the ratio between glucose (1*a) and 1,3-dihydroxypropanone (f) would be:

1*a=6*d
d=f
a=6*f

therefore the molar ratio is 1/6.

I do not know how to do this programmatically. I would like the solution in python3 preferably, but any help would of course be appreciated no matter the programming language.


Solution

  • For me it looks more like graph problem, not linear equation solving. Coding this would be tedious, but I can provide with simple algorithm, hope this helps.

    1. Build weighted directed graph, where vertices are chemical substances and edges describe reactions with specific molar ratio.

    2. Find path between two substances.

    3. Compute product of path weights, this is your answer.

    Notes:

    • there a lot of path finding algorithms, for example BFS, DFS, Dijkstra's. See https://en.wikipedia.org/wiki/Pathfinding
    • can happen, that there is multiple paths between substances, it means that chemical substance can be synthesised in multiple ways, probably you need path with least weight
    • need to figure out, what to do with cycles

    enter image description here