-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththermoslope.py
executable file
·227 lines (202 loc) · 10.3 KB
/
thermoslope.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!/usr/bin/env python3
__author__ = "Bjarte Aarmo Lund"
import os
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import sys
from statsmodels.regression.rolling import RollingOLS
from scipy.optimize import curve_fit
import statsmodels.api as sm
from matplotlib.figure import Figure
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.style as mplstyle
import base64
from io import BytesIO
mpl.use('agg')
mpl.rcParams['path.simplify'] = True
mpl.rcParams['path.simplify_threshold'] = 1.0
mpl.rcParams['savefig.dpi'] = 50
mplstyle.use('fast')
np.seterr(all='raise')
def MichaelisMenten(x, Km, Vmax):
return (Vmax*x)/(Km+x)
def inversetemp(temperature):
return 1.0/temperature
def logKcat(Kcat):
return np.log(Kcat)
class ThermoSlope:
def __init__(self, datafiles, **kwargs):
self.datafiles = datafiles
# assumes that all files are from the same directory
self.path = os.path.dirname(datafiles[0])
self.ProductAbsorbing = kwargs["ProductAbsorbing"] if "ProductAbsorbing" in kwargs else False
self.EnzymeConcentration = float(
kwargs["EnzymeConcentration"]) if "EnzymeConcentration" in kwargs else 1.0e-9
self.ExtCoeff = float(
kwargs["ExtCoeff"]) if "ExtCoeff" in kwargs else 1.78e4
self.Kmguess = float(
kwargs["Kmguess"]) if "Kmguess" in kwargs else 1e-5
self.Vmaxguess = float(
kwargs["Vmaxguess"]) if "Vmaxguess" in kwargs else 50
self.temperaturebins = int(
kwargs["temperaturebins"]) if "temperaturebins" in kwargs else 12
self.topconcentration = float(
kwargs["topconcentration"]) if "topconcentration" in kwargs else 5e-3
self.dilution = int(kwargs["dilution"]) if "dilution" in kwargs else 2
self.positions = int(kwargs["positions"]
) if "positions" in kwargs else 6
self.lowtempcutoff = float(
kwargs["lowtempcutoff"]) if "lowtempcutoff" in kwargs else 270
self.hightempcutoff = float(
kwargs["hightempcutoff"]) if "hightempcutoff" in kwargs else 373
def fitMichaelisMenten(self, dataframesection):
Concvstime=dataframesection[1]
popt, pcov = curve_fit(MichaelisMenten, Concvstime["Concentration"], Concvstime["Time_regression"], p0=[
self.Kmguess, self.Vmaxguess]) # standard linear regression
return (popt, pcov) # ignore covariances for now
def processcsv(self, datafile):
df = pd.read_csv(datafile, sep=",", header=None, names=(
"Cuvette", "Time", "Temperature", "Absorbance")) # Assumes a csv-file following the named columns
# calculate time in seconds instead of minutes (as the software supplies)
df["Time"] = df["Time"]*60
# calculate temperature in Kelvin instead of degrees Celsius
df["Temperature"] = df["Temperature"]+273.15
if self.ProductAbsorbing:
df["StartingConcentration"] = [self.startingconcentrations[x-1]
for x in df["Cuvette"]]
# calculate concentration depending on start concentration and depletion of substrate
df["Concentration"] = df["StartingConcentration"] - \
df["Absorbance"]/self.ExtCoeff
else:
# calculate concentration directly from absorbance
df["Concentration"] = df["Absorbance"]/self.ExtCoeff
# The rolling regression leaves NaN for the first window,
#I would prefer to have the low temperature points available
#and reverse the dataframe for this reason
df.sort_index(ascending=False, inplace=True)
cuvettes = df.groupby("Cuvette")
regression = pd.DataFrame() # Build up a dataframe cuvette by cuvette
for cuvette in cuvettes:
cuvettedf = cuvette[1]
Velocity = sm.add_constant(cuvettedf["Time"])
Concentration = cuvettedf["Concentration"]
movingregression = RollingOLS(
Concentration, Velocity, window=4).fit(params_only=True)
regression = pd.concat([regression, movingregression.params])
dfwregression = df.join(regression, rsuffix="_regression")
# Repeat rolling regression other direction, double the number of points
df.sort_index(ascending=True, inplace=True)
cuvettes = df.groupby("Cuvette")
regression = pd.DataFrame() # Build up a dataframe cuvette by cuvette
for cuvette in cuvettes:
cuvettedf = cuvette[1]
Velocity = sm.add_constant(cuvettedf["Time"])
Concentration = cuvettedf["Concentration"]
movingregression = RollingOLS(
Concentration, Velocity, window=4).fit(params_only=True)
regression = pd.concat([regression, movingregression.params])
dfwregression = df.join(regression, rsuffix="_regression")
dfwregression.dropna(inplace=True) # Remove the NaN rows
# Whether absorbance is increasing or decreasing, velocities should always be positive.
dfwregression["Time_regression"] = np.abs(
dfwregression["Time_regression"])
return dfwregression
def process(self):
# Should probably not be changed
R = 8.314
T = 298.15
h = 6.626e-34
kb = 1.38e-23
self.startingconcentrations = [
self.topconcentration/self.dilution**x for x in range(0, self.positions)]
# Collect all processed datasets in a single dataframe
mergeddataframes = pd.concat(
[self.processcsv(datafile) for datafile in self.datafiles])
self.mergeddataframes=mergeddataframes
# Show excerpt of data with velocities
# 3D plot of raw data
fig= Figure()
ag = Axes3D(fig)
ag.plot_trisurf(mergeddataframes.Concentration, mergeddataframes.Temperature,
mergeddataframes.Time_regression, cmap=cm.jet)
figdatabuf=BytesIO()
fig.savefig(figdatabuf, format="png")
figdata=base64.b64encode(figdatabuf.getbuffer()).decode("ascii")
self.SurfacePlotImg = f"<img src='data:image/png;base64,{figdata}'/>"
# Bin observations by temperature
temperatures = pd.cut(
mergeddataframes.Temperature, self.temperaturebins)
temperaturesets = mergeddataframes.groupby(temperatures)
# Fit individual bins by classical Michaelis Menten by non-linear regression
temperaturesetslist = []
self.MMplots = []
firstrun=True
fig = Figure()
ax = fig.subplots()
for temperature in temperaturesets: #want to start with the highest one as it presumably has the highest velocity for the graph
temperaturemean = temperature[1]["Temperature"].mean()
if self.lowtempcutoff < temperaturemean < self.hightempcutoff:
if firstrun:
ax.plot(temperature[1].Concentration, temperature[1].Time_regression,
linestyle="None", markersize=10, color="r", marker=11)
else:
ax.set_data(temperature[1].Concentration,temperature[1].Time_regression)
regression, covariance = self.fitMichaelisMenten(temperature)
Km = regression[0]
Vmax = regression[1]
kcat = Vmax/self.EnzymeConcentration
perr = np.sqrt(np.diag(covariance))
kcaterror = perr[1]/self.EnzymeConcentration
Kmerror = perr[0]
ax.plot(temperature[1].Concentration, MichaelisMenten(
temperature[1].Concentration, regression[0], regression[1]), linestyle="None", marker=9)
temperaturesetslist.append(
[temperaturemean, Vmax, kcat, kcaterror,Km,Kmerror])
figdatabuf=BytesIO()
fig.savefig(figdatabuf, format="png")
figdata=base64.b64encode(figdatabuf.getbuffer()).decode("ascii")
self.MMplots.append(f"<img src='data:image/png;base64,{figdata}'/>")
ax.cla()
# Construct Arrhenius-plot
kcatsvstemp = pd.DataFrame(temperaturesetslist, columns=[
"Temperature", "Vmax", "Kcat", "Kcaterror","Km","Kmerror"])
kcatsvstemp["1/T"] = inversetemp(kcatsvstemp["Temperature"])
kcatsvstemp["ln(Kcat)"] = np.log(kcatsvstemp["Kcat"])
kcatsvstemp["ln(Kcaterror)"] = np.log(kcatsvstemp["Kcaterror"])
self.kcatsvstemp = kcatsvstemp # To be used in the report
# Fit ln(kcat) against inverse Temp, weighing the parameters by the stddev of the estimated Kd
Arrheniusmodel = sm.WLS(kcatsvstemp["ln(Kcat)"].values, sm.add_constant(
kcatsvstemp["1/T"].values), weights=1/kcatsvstemp["ln(Kcaterror)"].values**2).fit()
# Fit Arrhenius-equation
slope=Arrheniusmodel.params[1]
A=Arrheniusmodel.params[0]
Ea = -slope*R
lnkcat = (-Ea/R)*(1/T)+A
# Calculate thermodynamic properties
dH = Ea-R*T
dG = R*T*(np.log(kb/h) + np.log(T)-lnkcat)
TdS = (dH-dG)
dS = TdS/T
Parameters = pd.Series(
("dG", "dH", "dS", "TdS","slope","A", "Ea", "ln(kcat) 298K"))
Values = pd.Series((dG, dH, dS, TdS,slope,A, Ea, lnkcat))
frame = {"Parameters": Parameters, "Values": Values}
arrheniusparameters = pd.DataFrame(frame)
arrheniusparameters.loc[arrheniusparameters["Parameters"].isin(("dG","dH","dS","TdS","Ea")),"Values"] = arrheniusparameters.Values/4181
self.arrheniusparameters = arrheniusparameters
fig = Figure()
ax = fig.subplots()
ax.plot(kcatsvstemp["1/T"], kcatsvstemp["ln(Kcat)"],
linestyle="None", marker=11)
ax.plot(kcatsvstemp["1/T"],slope*kcatsvstemp["1/T"]+A,linestyle="dotted")
figdatabuf=BytesIO()
fig.savefig(figdatabuf, format="png")
figdata=base64.b64encode(figdatabuf.getbuffer()).decode("ascii")
self.ArrheniusPlot= f"<img src='data:image/png;base64,{figdata}'/>"
if __name__ == '__main__':
analysis = ThermoSlope(sys.argv[1:],ProductAbsorbing=True)
analysis.process()
analysis.kcatsvstemp.to_csv("kcatsvstemp.csv",index=False,columns=("1/T","ln(Kcat)"))
print(analysis.arrheniusparameters)