OSCR

State and parameter estimation for a neural model of local field potentials.

Code ↔ Paper

5 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 5 matches
  1. [1] § Appendix B Robustness › B.2 Noise intensities ↔ NPF.ipynb, lines 381 to 457 · score 0.72 · state weights, particle ensemble, observation noise, intensities, inner, resampling · Report a mismatch
  2. [2] § Problem setting and background › Background on particle filters and Bayesian estimation › Bayesian filtering ↔ NPF.ipynb, lines 235 to 352 · score 0.63 · weighted empirical, updated weights, positions, Gaussian, Particle filters · Report a mismatch
  3. [3] § Problem setting and background › Background on particle filters and Bayesian estimation › Bayesian filtering ↔ NPF.ipynb, lines 381 to 457 · score 0.59 · stratified resampling, particle ensemble, threshold, weights, filtering · Report a mismatch
  4. [4] § Appendix B Robustness › B.4 Tukey window ↔ NPF.ipynb, lines 226 to 233 · score 0.53 · Tukey window, tapering fraction · Report a mismatch
  5. [5] § Nested particle filter for the Radon transformed cortical data › Results ↔ NPF.ipynb, lines 226 to 233 · score 0.51 · tapering fraction, Tukey window · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Jupyter notebook · 574 lines · 17 KB · CC-BY-SA-4.0 · 5 matches

  1. # %% [markdown]
  2. # ##### Import libraries
  3. # %%
  4. import numpy as np
  5. import matplotlib.pyplot as plt
  6. import numpy.random as npr
  7. from math import *
  8. from numpy.fft import ifft,fft,ifftshift,fftshift,rfft,rfftfreq
  9. from numba import jit, njit, prange, objmode, vectorize
  10. from scipy.ndimage import maximum_filter
  11. from scipy.signal.windows import tukey
  12. from scipy.sparse import csr_matrix, random
  13. from scipy.integrate import solve_ivp
  14. from skimage.transform import radon
  15. # %% [markdown]
  16. # ##### Matplotlib settings
  17. # %%
  18. plt.style.use('classic')
  19. plt.rc('xtick', labelsize=8)
  20. plt.rc('ytick', labelsize=8)
  21. plt.rc('axes', labelsize=8)
  22. plt.rc('legend', handlelength=1.0)
  23. plt.rc('axes', titlesize=8)
  24. plt.rc('figure', dpi=400)
  25. plt.rc('lines', linewidth=0.5)
  26. plt.rc('font',**{'family':'serif','serif':['Arial']})
  27. plt.rcParams['axes.spines.top'] = False
  28. plt.rcParams['axes.spines.right'] = False
  29. plt.rcParams['ytick.right']=False
  30. plt.rcParams['xtick.top']=False
  31. plt.rcParams['text.usetex']= False
  32. # %%
  33. Figure_dir='Figures/'
  34. # %% [markdown]
  35. # ##### Helping functions
  36. # %%
  37. # functions for frequency extractions
  38. # numba versions of functions
  39. @njit(fastmath=True)
  40. def numba_sum(arr):
  41. return np.sum(arr)
  42. @njit(fastmath=True)
  43. def numba_mean(x):
  44. return np.mean(x)
  45. @njit(fastmath=True)
  46. def numba_mean_2(x):
  47. '''mean of 2D array along first dimension'''
  48. with objmode(out='float64[:]'):
  49. out=np.mean(x,axis=0)
  50. return out
  51. @njit(fastmath=True)
  52. def numba_mean_3(x):
  53. '''mean of 3D array along the two first dimensions'''
  54. with objmode(out='float64[:]'):
  55. out=np.mean(x,axis=(0,1))
  56. return out
  57. @njit(fastmath=True)
  58. def numba_std(x):
  59. return np.std(x)
  60. @njit(fastmath=True)
  61. def numba_std_2(x):
  62. '''Standard deviation of 2D array along first dimension'''
  63. with objmode(out='float64[:]'):
  64. out=np.std(x,axis=0)
  65. return out
  66. @njit(fastmath=True)
  67. def numba_std_3(x):
  68. '''Standard deviation of 3D array along the two first dimension'''
  69. with objmode(out='float64[:]'):
  70. out=np.std(x,axis=(0,1))
  71. return out
  72. def get_Power(sig,dt):
  73. sig_=sig-np.mean(sig)
  74. fft_=np.fft.rfft(sig_)
  75. freqs=np.fft.rfftfreq(len(sig_), d=dt)
  76. Ny=(2*dt)/len(sig_)
  77. P=Ny*np.real(fft_*np.conj(fft_))
  78. return freqs, P
  79. @njit(fastmath=True)
  80. def numba_random(N):
  81. noise = np.empty(N,dtype=np.float64)
  82. for i in prange(N):
  83. noise[i] = npr.random()
  84. return noise
  85. @njit(parallel=True,fastmath=True)
  86. def noise_2d(n,m):
  87. noise = np.empty((n,m),dtype=np.float64)
  88. for i in prange(n):
  89. for j in range(m):
  90. noise[i,j] = np.random.normal()
  91. return noise
  92. @njit
  93. def seed(a):
  94. np.random.seed(a)
  95. @njit
  96. def numba_ifft(arr):
  97. '''1D ifft'''
  98. with objmode(out='complex128[:]'):
  99. out = np.fft.ifft(arr)
  100. return out
  101. @njit
  102. def numba_ifft2(arr):
  103. '''2D ifft'''
  104. with objmode(out='complex128[:,:]'):
  105. out = np.fft.ifft(arr)
  106. return out
  107. @njit
  108. def numba_fft(arr):
  109. '''1D fft'''
  110. with objmode(out='complex128[:]'):
  111. out = np.fft.fft(arr)
  112. return out
  113. @njit
  114. def numba_fft2(arr):
  115. '''2D fft'''
  116. with objmode(out='complex128[:,:]'):
  117. out = np.fft.fft(arr)
  118. return out
  119. # %% [markdown]
  120. # ##### LFP
  121. # %% [markdown]
  122. # ###### Fetch data
  123. # %%
  124. data_dir=''
  125. R7_A4=
  126. # %%
  127. ''' the dataset used in the paper is called 'R7_A4', it is a dictionary with the following relevant keys:
  128. -'Pos_ch': an array of shape (n_channels,2), give the (x,y) positions of each channel in the 2D grid
  129. -'vsdi_cut': an array of shape (n_channels, time): contains the timeseries of neural activity at each channel
  130. -'REM_0','REM_1','SWS_0' and 'SWS_1': the indices of the start and end of sws and rem stages (Undefined--> SWS--> REM)'''
  131. # %%
  132. #mapping channels to grid
  133. @njit(fastmath=True)
  134. def Square_data(data,channels,Z):
  135. '''maps channels to grid: data is 'vsdi_cut' of shape (channels,time), channels is 'Pos_ch',
  136. Z is a buffer for the output array of shape (time,x,y)'''
  137. for i in prange(len(channels)):
  138. m,n=channels[i]-1
  139. Z[:,m,n]=data[i]
  140. return Z
  141. # %%
  142. Z=np.zeros((R7_A4['vsdi_cut'].shape[1],len(R7_A4['X']),len(R7_A4['Y'])))
  143. data=Square_data(R7_A4['vsdi_cut'],R7_A4['Pos_ch'],Z)
  144. # %%
  145. #get dimensions of measurements (n_t,n_x,ny, dt), sleep stages indices...
  146. t4_sws=20000 #R7_A4['SWS_0']
  147. t4_rem=40533 #R7_A4['REM_0']
  148. # %% [markdown]
  149. # ###### Radon transform
  150. # %%
  151. #angles range, discretisation step
  152. angles=np.arange(0,180,15)
  153. data_r=np.array(list(map(lambda x: radon(x, theta=angles,preserve_range=True,circle=False),data)))
  154. # %%
  155. def get_obs(sig,idx):
  156. '''gets the transformed signal for angles[idx] and removes the extra zero-padding from the radon transform'''
  157. sig=sig[:,:,idx]
  158. obs=sig[:, ~np.all(sig == 0, axis=0)]
  159. return np.hstack([np.zeros((len(obs),1)),obs,np.zeros((len(obs),1))])
  160. # %% [markdown]
  161. # ##### Evolution model
  162. # %%
  163. #Fixed parameters appearing in Table 1
  164. tau_=0.03 #time constant
  165. lambda_,mu=5,0.5 #sigmoid steepness and theshold
  166. A_ex, A_in, l_ex, l_in=10, 6, .5, 1. #synaptic kernel parameters
  167. # %%
  168. @njit(fastmath=True)
  169. def sigmoid_(u,l=lambda_,mu=mu):
  170. x=l*(u-mu)
  171. return 1. / (1 + np.exp(-x))
  172. @njit(fastmath=True)
  173. def w(x,y,a=A_ex,b=l_ex,c=A_in,d=l_in):
  174. z=(x-y)**2
  175. return a*np.exp(-z/(l_ex**2))-c*np.exp(-z/(l_in**2))
  176. @njit(fastmath=True)
  177. def I_trav(x,t,A,nu,f):
  178. '''Space time traveling wave with amplitude A, spatial frequency nu and temporal frequency f'''
  179. return A*np.cos(2*pi*(nu*x-f*t))
  180. # %% [markdown]
  181. # ##### Observation model
  182. # %%
  183. #Tukey window
  184. beta_=0.5 #tapering fraction
  185. def get_TW(J,taper=beta_):
  186. return tukey(J,beta_)
  187. # %% [markdown]
  188. # ##### Nested particle filter
  189. # %%
  190. SQRT_2PI = np.sqrt(2 * np.pi)
  191. @jit(nopython=True, parallel=True)
  192. def normals(x, means, sds):
  193. '''Gaussian PDF evaluated at x'''
  194. result = np.exp(-0.5*((x - means)/sds)**2)
  195. return (1 / (sds * SQRT_2PI)) * result
  196. @njit(fastmath=True,parallel=True)
  197. def likelihood_obs(obs, particles, std):
  198. """Calculates likelihoods assuming Gaussian observational noise."""
  199. #obs (J,) particles (M,J)
  200. M=particles.shape[0]
  201. d=np.empty((M,))
  202. for i in prange(M):
  203. d[i] = np.sqrt((obs- particles[i])@(obs- particles[i]).T)
  204. return normals(0,d,std)
  205. #likelihood before normalisation
  206. @njit(fastmath=True)
  207. def update_Nest(obs,particles,weights,R,M):
  208. ''' returns updated weights for U and likelihood of parameter theta'''
  209. likeli_U=likelihood_obs(obs,particles,R)
  210. weights *= likeli_U
  211. weights += 1.e-300
  212. likeli_theta=(1./M)*numba_sum(weights)
  213. # avoid round-off to zero
  214. weights /= numba_sum(weights)
  215. likeli_theta+=1.e-300
  216. return weights,likeli_theta
  217. @njit(fastmath=True)
  218. def get_truncN(mean,std,A,B):
  219. '''One sample from truncated normal'''
  220. out=mean+std*npr.normal()
  221. while not ((out<=B)&(out>=A)):
  222. out=mean+std*npr.normal()
  223. return out
  224. @njit(fastmath=True)
  225. def jitter(theta,N,theta_range_sq,theta_range):
  226. '''Jitters a single parameter particle using a truncated normal kernel'''
  227. #theta_range_sq is sqrt(range(theta))
  228. eps=1./sqrt(N)
  229. u=npr.rand()
  230. if u<=(1-eps):
  231. return theta
  232. else:
  233. for i in range(len(theta)):
  234. std_i=theta_range_sq[i]/(N**0.75)
  235. theta[i]=get_truncN(theta[i],std_i,theta_range[i][0],theta_range[i][1])
  236. return theta
  237. @njit(fastmath=True)
  238. def estimate(particles,weights):
  239. w=numba_sum(weights)
  240. mean=np.sum(np.multiply(weights[:,np.newaxis],particles),axis=0)
  241. var=np.sum(np.multiply(weights[:,np.newaxis],(particles-mean)**2),axis=0)
  242. return mean/w, var/w
  243. @njit(fastmath=True)
  244. def estimate_p(particles,weights):
  245. '''Weighted empirical mean of parameters'''
  246. return particles.T@weights
  247. @njit(fastmath=True)
  248. def estimate_u(particles,weights_p,weights_u):
  249. '''Weighted empirical mean of state'''
  250. wpu=weights_p[:,np.newaxis]*weights_u
  251. return np.average(particles,weights=wpu,axis=(0,1))
  252. @njit(fastmath=True)
  253. def Neff(weights):
  254. '''Estimates the effective number of particles'''
  255. return 1. / (weights@weights.T)
  256. @njit(fastmath=True)
  257. def stratified_resample(weights):
  258. N = len(weights)
  259. # make N subdivisions, chose a random position within each one
  260. positions = (numba_random(N) + np.arange(N)) / N
  261. indexes = np.zeros(N, 'i')
  262. cumulative_sum = np.cumsum(weights)
  263. i, j = 0, 0
  264. while i < N:
  265. if positions[i] < cumulative_sum[j]:
  266. indexes[i] = j
  267. i += 1
  268. else:
  269. j += 1
  270. return indexes
  271. @njit(fastmath=True)
  272. def resample(particles, indexes):
  273. particles[:] = particles[indexes]
  274. return particles
  275. @njit(fastmath=True)
  276. def get_GP_U(M,x):
  277. '''M samples from GP prior for the state'''
  278. mx=np.zeros_like(x) #GP mean
  279. K=np.zeros((len(x),len(x)))
  280. for i in range(len(x)):
  281. for j in range(i,len(x)):
  282. k_=2*np.exp(-0.5*(x[i]-x[j])**2) #covariance function
  283. K[i][j]=k_
  284. K[j][i]=k_
  285. with objmode(out='float64[:,:]'):
  286. out = np.random.multivariate_normal(mx,K,M)
  287. return out
  288. # %%
  289. @njit(fastmath=True)
  290. def predict_U(particles,W,l,mu,to_dt,x,J,q,M,t_n,params):
  291. '''performs one prediction step for the state ensemble associated to the parameter particle params'''
  292. A,nu,f=params
  293. particles+=to_dt*(-particles+I_trav(x,t_n,A,nu,f)+(W@sigmoid_(particles,l,mu).T).T)+q*noise_2d(M,J)
  294. return particles
  295. # %%
  296. @njit(fastmath=True,parallel=True)
  297. def inner_filter(N,M,n,Y_n,w_u,w_p,Ny,x, J,G, t_n,W,to_dt,l,mu,theta_range, theta_range_Sq, particles_all, theta_parts,q,R):
  298. '''for each parameter particle, the function jitters it then conditional on the jittered particle, it performs state ensemble prediction,
  299. update and potentially resampling if the effective number of particles is below a threshold'''
  300. for i in prange(N):
  301. theta=theta_parts[i]
  302. #jitter
  303. theta_=jitter(theta,N,theta_range_Sq,theta_range)
  304. theta_parts[i]=theta_
  305. particles_all[i]=G*predict_U(particles_all[i],W,l,mu,to_dt,x,J,q,M,t_n,theta_)
  306. # print(likelihood_obs(Y_n,U_,R).max())
  307. w_u[i],w_p[i]=update_Nest(Y_n,particles_all[i],w_u[i],R,M)
  308. if Neff(w_u[i])<M/2:
  309. indexes = stratified_resample(w_u[i])
  310. particles_all[i]=resample(particles_all[i], indexes)
  311. w_u[i]=(1/M)*np.ones((M,))
  312. return particles_all,theta_parts,w_u,w_p
  313. # %%
  314. def Nested(N,M,obs,t,Ny, G,J, dt,x,W,to_dt,l,mu,theta_range, theta_range_Sq, particles_all, theta_parts,q,R):
  315. '''Loops over observations and saves estimated means and std of parameters and state
  316. parameters
  317. ----------
  318. N,M:int
  319. Numbers of parameter and state partcles
  320. Ny:int
  321. number of observations
  322. J:int
  323. size of each observation vector
  324. obs:np.ndarray
  325. Array of observations of shape (Ny+1,J)
  326. t:np.ndarray
  327. Temporal grid of shape(Ny+1,)
  328. dt,to_dt:float
  329. to_dt=dt/tau where tau is the time constant
  330. G:int or np.ndarray
  331. Observation operator
  332. x:np.ndarray
  333. Spatial grid of shape (J,)
  334. l,mu:float
  335. Sigmoid steepness and threshold
  336. theta_range, theta_range_Sq:np.ndarray
  337. Prior range of theta and its square root, shape (dim_theta,2)
  338. particles_all:np.ndarray
  339. Ensembles of state particles sampled from the prior, of shape (N,M,J)
  340. theta_parts:
  341. Ensemble of parameter particles sampled from the prior, of shape (N,dim_theta)
  342. q,R:float
  343. intensities of process and observation noises
  344. '''
  345. dim_theta=theta_range.shape[0] #number of parameters to be inferred
  346. Ess=-np.ones((Ny+1,)) #effective sample size
  347. theta_hist=np.empty((Ny+1,2,dim_theta)) #container for mean and std of parameters
  348. U_hist=np.empty((Ny+1,J)) #container for estimated mean of state
  349. w_u=(1/M)*np.ones((N,M)) #state weights
  350. w_p=(1/N)*np.ones((N,)) #parameter weights
  351. U_hist[0]=np.mean(particles_all,axis=(0,1)) #initializing the state estimated mean
  352. theta_hist[0,0]=np.mean(theta_parts,axis=0) #initializing the parameters estimated mean
  353. theta_hist[0,1]=np.std(theta_parts,axis=0) #initializing the parameters estimated std
  354. for n in range(0,Ny):
  355. Y_n=obs[n+1]
  356. t_n=t[n+1]
  357. particles_all,theta_parts,w_u,w_p=inner_filter(N,M,n,Y_n,w_u,w_p,Ny,x, J,G, t_n,W,to_dt,l,mu,theta_range, theta_range_Sq, particles_all, theta_parts,q,R)
  358. w_p /= numba_sum(w_p)
  359. w_p+=1.e-300
  360. #visualizing particle ensemble each 100 time step
  361. if n%100==1:
  362. fig,axs=plt.subplots(1,3,figsize=(12,3))
  363. axs[0].scatter(theta_parts[:,0],theta_parts[:,2],c='k',marker='.',s=0.3)
  364. axs[0].set_xlabel('A')
  365. axs[0].set_ylabel('f')
  366. axs[1].scatter(theta_parts[:,1],theta_parts[:,2],c='k',marker='.',s=0.3)
  367. axs[1].set_xlabel(r'$\nu$')
  368. axs[1].set_ylabel('f')
  369. axs[2].scatter(theta_parts[:,0],theta_parts[:,1],c='k',marker='.',s=0.3)
  370. axs[2].set_xlabel('A')
  371. axs[2].set_ylabel(r'$\nu$')
  372. plt.show()
  373. #resampling the ensembles according to parameters weights
  374. if Neff(w_p)<N/2:
  375. Ess[n+1]=Neff(w_p)
  376. indexes = stratified_resample(w_p)
  377. particles_all=resample(particles_all, indexes)
  378. theta_parts=resample(theta_parts,indexes)
  379. w_p=(1/N)*np.ones((N,))
  380. #estimation of mean/std for parameters and mean for state
  381. U_hist[n+1]=numba_mean_3(particles_all)
  382. # =np.average(particles_all,weights=w_p[:,np.newaxis]*w_u,axis=(0,1))
  383. # theta_mean=
  384. theta_hist[n+1,0]=theta_parts.T@w_p #use theta_hist[n+1,0]=numba_mean_2(theta_parts) for 1/N weights
  385. theta_hist[n+1,1]=numba_std_2(theta_parts)
  386. return theta_hist,U_hist,Ess
  387. # %% [markdown]
  388. # ##### Synthetic test
  389. # %%
  390. @njit(fastmath=True)
  391. def I_chirp(x,t,A,nu,f,ax):
  392. return A*np.cos(2*pi*(nu*x-f*t-ax*t**2))
  393. # %%
  394. L=10 #spatial domain [0,L]
  395. Mx=500
  396. Dx=L/Mx
  397. x_grid=np.arange(0,L+Dx,Dx)
  398. T=100 #final time
  399. Nt=20000
  400. Dt=T/Nt
  401. t_grid=np.arange(0,T+Dt,Dt)
  402. u0=np.sin(pi*x_grid)
  403. to_Dt=Dt/tau_ #dt/tau
  404. W0=Dx*w(x_grid[:,None],x_grid,10,4,6,1) #synaptic connections matrix
  405. W0[:,0]*=0.5 #weights for trapezium
  406. W0[:,-1]*=0.5
  407. A0,nu0,f0,ax=1,0.1,0.5,-0.005 #true parameters
  408. # %%
  409. u_hist=np.empty((Nt+1,Mx+1))
  410. u_hist[0]=np.copy(u0)
  411. u=np.copy(u0)
  412. for n in range(Nt):
  413. u+=to_Dt*(-u+W0@sigmoid_(u)+I_chirp(x_grid,t_grid[n],A0,nu0,f0,ax))
  414. u_hist[n+1,:]=u
  415. # %%
  416. plt.imshow(u_hist,aspect='auto')
  417. # %%
  418. #generate noisy observations
  419. J=30
  420. Ny= Nt//2#
  421. t= np.linspace(0,T,Ny+1)#time domain of the observations and inference
  422. x=np.linspace(0,L,J) #spatial domain of the observations and inference
  423. dt,dx=t[1],x[1]
  424. to_dt=dt/tau_
  425. Ys=np.array(list(map(lambda U: np.interp(t,t_grid,U),u_hist.T))).T #interpolation of u_hist on the temporal domain
  426. Ys=np.array(list(map(lambda U: np.interp(x,x_grid,U),Ys)))
  427. eps=0.5
  428. Ys+=eps*npr.randn(Ny+1,J) #adding noise
  429. # %%
  430. plt.imshow(Ys,aspect='auto')
  431. # %% [markdown]
  432. # ##### Run inference
  433. # %%
  434. W=dx*w(x[:,np.newaxis],x) #connection matrix used for the inference, different from W0 used to generate the observations
  435. W[:,0]*=0.5
  436. W[:,-1]*=0.5
  437. N=500#number of parameter particles
  438. M=500 #number of state particles for each parameter particle
  439. theta_range=np.array([[0,10],[0,1],[0,1]]) #range of the prior for theta
  440. theta_range_Sq=np.array([10,2,2])*np.sqrt(np.abs(theta_range[:,1]-theta_range[:,0])) #square root of the range multiplied by constants of the magnitude of each parameter range, used in jittering
  441. theta_parts=np.empty((N,len(theta_range)))
  442. for i in range(len(theta_range)):
  443. theta_parts[:, i] = npr.uniform(theta_range[i][0], theta_range[i][1], size=N)
  444. #theta_parts[:, i] = npr.normal(means[i], std, size=N) can be used to generate gaussian priors istead
  445. particles_all=np.empty((N,M,J))
  446. for i in range(N):
  447. particles_all[i]=get_GP_U(M,x)
  448. # %%
  449. q=.1
  450. R=.5
  451. G=1 #no observation matrix, change this to Tukey window if running for LFP data
  452. ps,us,ess=Nested(N,M,Ys,t,5, G,J, dt,x,W,to_dt,lambda_,mu,theta_range, theta_range_Sq, particles_all, theta_parts,q,R)
  453. # %%
  454. mm=ps1[:,0]
  455. std_2=2*ps1[:,1]
  456. v0=[A0,nu0,f0]
  457. v1=[0,0,ax]
  458. labels_params=['A',r'$\nu$','f']
  459. for i in range(3):
  460. fig=plt.figure(figsize=(4,3))
  461. plt.plot(t,mm[:,i])
  462. plt.plot(t,v0[i]+v1[i]*t[:-1],'r-')
  463. plt.fill_between(x=t,y1=mm[:,i]+std_2[:,i],y2=mm[:,i]-std_2[:,i],color='skyblue')
  464. plt.ylabel(labels_params[i],fontsize=10,rotation=0,labelpad=8)
  465. plt.xticks(np.arange(min(t), max(t)+1, 20))
  466. plt.xlabel('Time (s)')
  467. # %% [markdown]
  468. # ##### Postprocessing
  469. # %%
  470. def get_stats(theta_runs):
  471. '''calculates the combined empirical mean, std and variances from multiple runs'''
  472. #theta_runs has shape (N_runs, time,2,dim_theta), where the third dimension contains the mean and std of each run
  473. means = theta_runs[:,:,0,:] # (N_runs, T)
  474. stds = theta_runs[:,:,1,:] # (N_runs, T)
  475. mu_combined = means.mean(axis=0) # (T,)
  476. var_within = (stds**2).mean(axis=0) # (T,)
  477. var_between = ((means - mu_combined)**2).mean(axis=0) # (T,)
  478. std_combined = np.sqrt(var_within + var_between)
  479. return mu_combined, var_within,var_between,std_combined
  480. # %%
  481. #Figures
  482. # %%
  483. # %%

NPF.ipynb, under CC-BY-SA-4.0 · at the source

Overview

Authors: Daniele Avitabile1,2, Gabriel J Lord3, Khadija Meddouni3
ORCID iDs: Khadija Meddouni
  1. Amsterdam Center for Dynamics and Computation, VU Amsterdam, Amsterdam, The Netherlands
  2. Inria Math Neuro Team, Inria Branch at the University of Montpellier, Montpellier, France
  3. Department of Mathematics, IMAPP, Radboud University, Nijmegen, The Netherlands
Journal: Journal of mathematical biology, volume 93, issue 4, article 52
Dates: received 1 December 2025; accepted 28 July 2026; published online 3 October 2026; in print 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1007/s00285-026-02451-w · PMID 42828681 · PMCID PMC13634030 · OpenAlex W7114809393
Open access: hybrid, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: extracellular electrophysiology (units, LFP) (modality), mouse (organism), computational (subfield)
Keywords: Wilson–Cowan–Amari model, Bayesian inference, Particle filters, Local field potential, Parameter estimation
MeSH: Models, Neurological*, Animals, Bayes Theorem, Cerebral Cortex, Computer Simulation, Local Field Potential Measurement, Mathematical Concepts, Mice, Neurons, Sleep (* major topic)
Topic: Neural dynamics and brain function (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Citations: not cited yet (Europe PMC); 48 references in the paper

Abstract

The study of cortical dynamics during different states such as decision making, sleep and movement, is an important topic in Neuroscience. Modelling efforts aim to relate the neural rhythms present in cortical recordings to the underlying dynamics responsible for their emergence. We present an effort to capture certain features of the neural activity from the cortex of a mouse during natural sleep, obtained through local field potential measurements. Our approach relies on using a discretized Wilson–Cowan Amari neural field model for neural activity, along with a data assimilation method that allows the Bayesian joint estimation of the state and parameters. We demonstrate the feasibility of our approach on synthetic measurements before applying it to a dataset available in literature. Our findings suggest the potential of our approach to characterize the parameters of the external forcing in the neural activity model, while simultaneously inferring a state that aligns with the observed signal.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repository

Its files are read in the Code ↔ Paper reader above, with 5 matches between paragraphs and lines of code.

Zenodo 21795156

License: CC-BY-SA-4.0
State: the link answers, verified on 6 October 2026
Evidence: files inventoried
Languages: Jupyter (1)
Size: 1 file, 1 script
Software Heritage: not checked
Found in: “Code availability”
Holds: 1 notebook
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Matplotlib (1 file), Numba (1 file), NumPy (1 file), scikit-image (1 file), SciPy (1 file)
Availability: 1 check, the latest on 6 October 2026: the link answers (HTTP 200)
  • 6 October 2026: the link answers (HTTP 200)
1 file

Code availability

A repository with codes is available at https://doi.org/10.5281/zenodo.21795156.

Reproduced under the paper's license (CC BY), from the paper cited above.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 1 script, each with its path and the digest of its content;
  • 5 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data availability

Imaging data used in this work have been deposited in the Donders Repository https://doi.org/10.34973/2w2s-tg07.

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 6 October 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 3 authors, 5 keywords, 10 MeSH terms, 30 references.

Cite

This paper

Avitabile, D., Lord, G. J., & Meddouni, K. (2026). State and parameter estimation for a neural model of local field potentials. Journal of mathematical biology, 93(4), 52. https://doi.org/10.1007/s00285-026-02451-w

BibTeX

@article{avitabile2026state,
author = {Avitabile, Daniele and Lord, Gabriel J and Meddouni, Khadija},
title = {{State and parameter estimation for a neural model of local field potentials}},
journal = {Journal of mathematical biology},
year = {2026},
month = oct,
volume = {93},
number = {4},
pages = {52},
publisher = {Springer Science+Business Media},
issn = {0303-6812},
doi = {10.1007/s00285-026-02451-w},
url = {https://doi.org/10.1007/s00285-026-02451-w},
pmid = {42828681},
pmcid = {PMC13634030}
}

RIS

TY - JOUR
AU - Avitabile, Daniele
AU - Lord, Gabriel J
AU - Meddouni, Khadija
TI - State and parameter estimation for a neural model of local field potentials
T2 - Journal of mathematical biology
J2 - J Math Biol
PY - 2026
DA - 2026/10/03
VL - 93
IS - 4
SP - 52
SN - 0303-6812
PB - Springer Science+Business Media
DO - 10.1007/s00285-026-02451-w
UR - https://doi.org/10.1007/s00285-026-02451-w
LA - en
ER -

CSL-JSON

{
"id": "10.1007/s00285-026-02451-w",
"type": "article-journal",
"title": "State and parameter estimation for a neural model of local field potentials",
"container-title": "Journal of mathematical biology",
"author": [
{
"family": "Avitabile",
"given": "Daniele"
},
{
"family": "Lord",
"given": "Gabriel J"
},
{
"family": "Meddouni",
"given": "Khadija"
}
],
"container-title-short": "J Math Biol",
"volume": "93",
"issue": "4",
"page": "52",
"DOI": "10.1007/s00285-026-02451-w",
"PMID": "42828681",
"PMCID": "PMC13634030",
"ISSN": "0303-6812",
"publisher": "Springer Science+Business Media",
"URL": "https://doi.org/10.1007/s00285-026-02451-w",
"language": "en",
"issued": {
"date-parts": [
[
2026,
10,
3
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1371/journal.pcbi.1012911 [code]
Virtual epilepsy patient cohort: Generation and evaluation.
Journal: PLoS computational biology
In common: Numba, SciPy, Matplotlib, 1 other tool, 4 references
[2] doi:10.3390/biomimetics11040224
Resonance-Dependent Pattern Dynamics in a Neural Field for Spatial Coding.
Journal: Biomimetics (Basel, Switzerland)
In common: computational, 5 references
[3] doi:10.3389/fnins.2023.1141884 [code]
An <i>in-silico</i> framework for modeling optimal control of neural systems.
Journal: Frontiers in neuroscience
In common: scikit-image, SciPy, Matplotlib, 1 other tool, computational, 2 references
[4] doi:10.1371/journal.pcbi.1013463 [code]
A multi-frequency whole-brain neural mass model with homeostatic feedback inhibition.
Journal: PLoS computational biology
In common: Numba, scikit-image, SciPy, 2 other tools, computational, 1 reference
[5] doi:10.1038/s42003-024-06083-y [code]
Rhythmicity of neuronal oscillations delineates their cortical and spectral architecture.
Journal: Communications biology
In common: Numba, scikit-image, SciPy, 2 other tools, 1 reference
[6] doi:10.1038/s41467-024-48341-x [code]
Self-organization of modular activity in immature cortical networks.
Journal: Nature communications
In common: scikit-image, SciPy, Matplotlib, 1 other tool, 2 references
[7] doi:10.1038/s42003-023-04580-0 [code]
Simulations approaching data: cortical slow waves in inferred models of the whole hemisphere of mouse.
Journal: Communications biology
In common: scikit-image, SciPy, Matplotlib, 1 other tool, computational, mouse, 1 reference
[8] doi:10.7554/elife.87055 [code]
Firing rate adaptation affords place cell theta sweeps, phase precession, and procession.
Journal: eLife
In common: SciPy, Matplotlib, NumPy, extracellular electrophysiology (units, LFP), 2 references
[9] doi:10.1371/journal.pcbi.1010547 [code]
Multiple bumps can enhance robustness to noise in continuous attractor networks.
Journal: PLoS computational biology
In common: SciPy, Matplotlib, NumPy, computational, 2 references
[10] doi:10.1038/s41467-026-74466-2 [code]
Neuromorphic hierarchical modular reservoirs.
Journal: Nature communications
In common: Numba, SciPy, Matplotlib, 1 other tool, computational, 1 reference

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.1007/s00285-026-02451-w.svg)](https://openscicode.org/badge/doi/10.1007/s00285-026-02451-w)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1007/s00285-026-02451-w.svg
   :target: https://openscicode.org/badge/doi/10.1007/s00285-026-02451-w
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1007/s00285-026-02451-w"><img src="https://openscicode.org/badge/doi/10.1007/s00285-026-02451-w.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.