Search code examples
pythonnumpymatplotlibchemistry

Graphs and Le Chatelier’s Principle


I am try make graphs used scipy and matplotlib, my idea is variable k and concentration in for interactive graphics for equilibrium chemistry. Maybe my equation have error, no make graphics type example bellow, just one example graph finale

Example

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# To reaction A + B <=> C + D
k1=0.05
k2=0.05
tf= 200
dt=0.2
t =  np.arange(0,tf+0.01, dt)
n = len(t)
Ca= np.ones(n)
Ca= np.ones(n)
Cb= np.ones(n)
Cc= np.zeros(n)
Cd= np.zeros(n)

def dC(C,tm):
        Ca,Cb,Cc,Cd =C
        r1 =k1*Ca
        r2 =-k2*Ca
        d1 = -r1
        d2 = -r1 -r2
        d3= r1-r2
        d4= r2
        return [d1,d2,d3,d4]
        
C =odeint(dC,[1,1,0,0], t)
Ca= C[:,0]
Cb= C[:,1]
Cc= C[:,0]
Cd= C[:,1]

plt.plot(t,Ca, 'r--', linewidth=2.0)
plt.plot(t,Cb, 'k--', linewidth=2.0)
plt.plot(t,Cc, 'b--', linewidth=2.0)
plt.plot(t,Cd, 'm--', linewidth=2.0)
plt.show()

Solution

  • I just found a example that can help you.

    Output Graph

    I think that the problem was in your "plot" function. try something like this:

    from scipy.integrate import odeint
    import numpy as np
    
    def myode(C, t):   
    
        k1 = 1   # 1/min;
        k_1 = 0.5   # 1/min;
    
        Ca = C[0]
        Cb = C[1]
    
        ra = -k1 * Ca
        rb = -k_1 * Cb
    
        dCadt =  ra - rb
        dCbdt = -ra + rb
    
        dCdt = [dCadt, dCbdt]
        return dCdt
    
    
    tspan = np.linspace(0, 5)
    
    init = [1, 0]  
    C = odeint(myode, init, tspan)
    
    Ca = C[:,0]
    Cb = C[:,1]
    
    import matplotlib.pyplot as plt
    plt.plot(tspan, Ca, tspan, Cb)