Plot Entropy
Here’s a full script that you can use to plot the entropy of your trajectories. Note that you must have a model first (otherwise you cannot know the probabilities). In general, you should save this as a .py
file, and use the Scripts
>> Run Scripts
menu option to run that file. You can edit it as you go if you want to change something, and then re-run it. Note that it use’s the current activate model for the calculation.
Save the code below in a file as plot_entropy.py
import numpy as np
import matplotlib.pyplot as plt
def calc_entropy_expected(A,pi):
= -np.sum(pi[:,None]*A*np.log(A))
Hxavg = Hxavg
H_expected return H_expected
= plt.subplots(1,figsize=(3,3),dpi=300)
fig,ax
= maven.modeler.model
m = maven.data.nt
nt = m.nstates
nk = 1.
kb
= m.tmatrix
Tmc = Tmc.copy()
A for i in range(A.shape[0]):
/= A[i].sum()
A[i]
# pi = m.frac
# pi /= pi.sum()
= np.linalg.eig(A.T)
w,v = np.where(w==w.max())[0][0]
ind = v[:,ind]
ss /= ss.sum()
ss = ss
pi
= m.chain
vits = vits.shape
nmol,nt = np.zeros((nmol,nt)) + np.nan
ss = maven.data.pre_list
pre = maven.data.post_list
post = post-pre
dp
for nmoli in range(nmol):
= vits[nmoli]
v if dp[nmoli] > 1:
= m.r[nmoli].copy()
ri
# ## use viterbi instead of the full chain
# v = v[pre[nmoli]:post[nmoli]].copy()
# pij = pi[v[0]]*np.concatenate(([1.],np.exp(np.cumsum(np.log(A[v[:-1],v[1:]])))))
# sij = -kb*np.log(pij)
## use full gamma treatment
= np.zeros((dp[nmoli]))
pij 0] = np.log(np.sum(pi*ri[pre[nmoli]+0]))
pij[for t in range(1,dp[nmoli]):
= np.log(np.sum(A*(ri[pre[nmoli]+t-1][:,None]*ri[pre[nmoli]+t][None,:])))
pij[t] = -kb*(np.cumsum(pij))
sij = np.log(np.finfo(np.float64).max)
sij[np.isinf(sij)] = np.nanmax(sij[np.isfinite(sij)])
sij[np.bitwise_not(np.isfinite(sij))] = sij
ss[nmoli,pre[nmoli]:post[nmoli]]
= maven.prefs['plot.time_dt']
dt = np.arange(nt)
x
for nmoli in range(nmol):
*dt,ss[nmoli],color='k',lw=1,alpha=.05,zorder=1)
ax.plot(x
= calc_entropy_expected(A,pi)
sexp = x*sexp-kb*np.sum(pi*np.log(pi))
theory *dt,theory,color='tab:red',ls='-',lw=1.2,zorder=1)
ax.plot(x= m.description()
desc = desc.split('] ')[1]
desc = ''.join(desc.split(' -')[:-1])
desc
= np.nanpercentile(ss,[2.5,50.,97.5],0)
low,med,high = np.nanstd(ss,axis=0)
std = np.nanmean(ss,axis=0)
mean *dt,mean-std,color="tab:blue",label ='%s'%(desc),ls='-',lw=1.2,zorder=2)
ax.plot(x*dt,mean,color="tab:blue",label ='%s'%(desc),ls='-',lw=1.2,zorder=2)
ax.plot(x*dt,mean+std,color="tab:blue",label ='%s'%(desc),ls='-',lw=1.2,zorder=2)
ax.plot(x
#### order the traces. This destroys the matching w the HMM viterbis so... annoying
# order = np.nanmax(ss,axis=1)
# print(ss.shape,order.shape)
# order[np.isnan(order)] = 0.
# order = np.argsort(order)[::-1]
# print(order)
# maven.data.order(order)
# maven.emit_data_update()
0,np.log(np.finfo(np.float64).max))
ax.set_ylim('Entropy')
ax.set_ylabel('Time')
ax.set_xlabel(
ax.set_title(desc)0,x.max()*dt)
ax.set_xlim(
fig.tight_layout() plt.show()