Skip to content
Snippets Groups Projects
Commit b415e1b0 authored by Adam Mazur's avatar Adam Mazur
Browse files

simple A->B->C data fitting

parent afcef7e4
No related branches found
No related tags found
No related merge requests found
abc.csv 0 → 100644
time,A,C
0.0,10.024835707650562,0.032384426905034625
0.5,7.8641593252292585,0.09967474037287323
1.0,6.144267227527182,0.37455145447449706
1.5,4.750793515765054,0.7788535105553938
2.0,3.69089252050547,1.194282946202239
2.5,2.836933589827485,1.8169000160323985
3.0,2.1859003968205224,2.4139562376543857
3.5,1.726450627679802,2.8108338229529912
4.0,1.3261337109664588,3.3558694842264747
4.5,1.0727771647059234,3.9119158262286278
5.0,0.7907646738172374,4.415234455686307
5.5,0.5863930839496632,4.81729217625314
6.0,0.5083138804799728,5.245600966261565
6.5,0.39758515566859043,5.724866592805669
7.0,0.2961914367338923,6.0174404020417755
7.5,0.19918526328384978,6.490805091295746
8.0,0.20033731725936038,6.773366500374303
8.5,0.12338823735800432,7.080953314425451
9.0,0.16263995229871547,7.277117637520087
9.5,0.07105634500037562,7.613644911719786
10.0,0.04342076809551818,7.734014850536418
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import least_squares
import kinetic as kn
#%%
df = pd.read_csv('abc.csv')
#%%
plt.plot(df.time, df.A, '.-', label='A')
plt.plot(df.time, df.C, '.-', label='C')
plt.grid()
plt.legend()
plt.show()
#%%
def residuals(p):
global df
k1, k2 = p
rxns = [kn.reaction('A -> B ; k1'),
kn.reaction('B -> C ; k2')]
c0 = {'A': 10.0}
kin = {'k1': k1, 'k2': k2}
ts = np.array(df.time)
spcs, ct = kn.concentration(rxns, c0, kin, ts)
rA = df.A - ct[:, spcs['A']]
rC = df.C - ct[:, spcs['C']]
return np.concatenate([rA, rC])
#%%
p0 = [1.0, 1.0] # k1, k2
print(residuals(p0))
#%%
res = least_squares(residuals, p0)
p_opt = res.x
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import kinetic as kn
#%%
rxns = [kn.reaction('A -> B ; k1'),
kn.reaction('B -> C ; k2')]
c0 = {'A': 10.0}
kin = {'k1': 0.5, 'k2': 0.2}
ts = np.linspace(0.0, 10, 21)
#%%
spcs, ct = kn.concentration(rxns, c0, kin, ts)
#%% randomize
np.random.seed(42)
sigma = 0.05
ct += sigma*np.random.randn(*ct.shape)
#%%
df = pd.DataFrame({'time': ts,
'A': ct[:, spcs['A']],
'C': ct[:, spcs['C']]})
df.to_csv('abc.csv', index=None)
#%%
print(spcs)
for spc in spcs:
plt.plot(ts, ct[:, spcs[spc]], '.-', label=spc)
#%%
plt.grid()
plt.legend()
plt.show()
# for i in range(len(ts)):
# print('%8.3f %12.6e' % (ts[i], ct[i, spcs['S']]))
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment