Debian Codegraph @

examples/advanced/modelfitting_sbi.py

raw
1 """
2 Model fitting with simulation-based inference
3 ---------------------------------------------
4
5 In this example, a HH-type model is used to demonstrate simulation-based
6 inference with the sbi toolbox (https://www.mackelab.org/sbi/). It is based
7 on a fake current-clamp recording generated from the same model that we use
8 in the inference process. Two of the parameters (the maximum sodium and
9 potassium conductances) are considered parameters of the model.
10
11 For more details about this approach, see the references below.
12
13 To run this example, you need to install the sbi package, e.g. with::
14
15 pip install sbi
16
17 References:
18
19 * https://www.mackelab.org/sbi
20 * Tejero-Cantero et al., (2020). sbi: A toolkit for simulation-based inference.
21 Journal of Open Source Software, 5(52), 2505, https://doi.org/10.21105/joss.02505
22 """
23 import matplotlib.pyplot as plt
24
25 from brian2 import *
26 import sbi.utils
27 import sbi.analysis
28 import sbi.inference
29 import torch # PyTorch
30
31 defaultclock.dt = 0.05*ms
32
33 def simulate(params, I=1*nA, t_on=50*ms, t_total=350*ms):
34 """
35 Simulates the HH-model with Brian2 for parameter sets in params and the
36 given input current (injection of I between t_on and t_total-t_on).
37
38 Returns a dictionary {'t': time steps, 'v': voltage,
39 'I_inj': current, 'spike_count': spike count}.
40 """
41 assert t_total > 2*t_on
42 t_off = t_total - t_on
43
44 params = np.atleast_2d(params)
45 # fixed parameters
46 gleak = 10*nS
47 Eleak = -70*mV
48 VT = -60.0*mV
49 C = 200*pF
50 ENa = 53*mV
51 EK = -107*mV
52
53 # The conductance-based model
54 eqs = '''
55 dVm/dt = -(gNa*m**3*h*(Vm - ENa) + gK*n**4*(Vm - EK) + gleak*(Vm - Eleak) - I_inj) / C : volt
56 I_inj = int(t >= t_on and t < t_off)*I : amp (shared)
57 dm/dt = alpham*(1-m) - betam*m : 1
58 dn/dt = alphan*(1-n) - betan*n : 1
59 dh/dt = alphah*(1-h) - betah*h : 1
60
61 alpham = (-0.32/mV) * (Vm - VT - 13.*mV) / (exp((-(Vm - VT - 13.*mV))/(4.*mV)) - 1)/ms : Hz
62 betam = (0.28/mV) * (Vm - VT - 40.*mV) / (exp((Vm - VT - 40.*mV)/(5.*mV)) - 1)/ms : Hz
63
64 alphah = 0.128 * exp(-(Vm - VT - 17.*mV) / (18.*mV))/ms : Hz
65 betah = 4/(1 + exp((-(Vm - VT - 40.*mV)) / (5.*mV)))/ms : Hz
66
67 alphan = (-0.032/mV) * (Vm - VT - 15.*mV) / (exp((-(Vm - VT - 15.*mV)) / (5.*mV)) - 1)/ms : Hz
68 betan = 0.5*exp(-(Vm - VT - 10.*mV) / (40.*mV))/ms : Hz
69 # The parameters to fit
70 gNa : siemens (constant)
71 gK : siemens (constant)
72 '''
73 neurons = NeuronGroup(params.shape[0], eqs, threshold='m>0.5', refractory='m>0.5',
74 method='exponential_euler', name='neurons')
75 Vm_mon = StateMonitor(neurons, 'Vm', record=True, name='Vm_mon')
76 spike_mon = SpikeMonitor(neurons, record=False, name='spike_mon') #record=False → do not record times
77 neurons.gNa_ = params[:, 0]*uS
78 neurons.gK = params[:, 1]*uS
79
80 neurons.Vm = 'Eleak'
81 neurons.m = '1/(1 + betam/alpham)' # Would be the solution when dm/dt = 0
82 neurons.h = '1/(1 + betah/alphah)' # Would be the solution when dh/dt = 0
83 neurons.n = '1/(1 + betan/alphan)' # Would be the solution when dn/dt = 0
84
85 run(t_total)
86 # For convenient plotting, reconstruct the current
87 I_inj = ((Vm_mon.t >= t_on) & (Vm_mon.t < t_off))*I
88 return dict(v=Vm_mon.Vm,
89 t=Vm_mon.t,
90 I_inj=I_inj,
91 spike_count=spike_mon.count)
92
93
94 def calculate_summary_statistics(x):
95 """Calculate summary statistics for results in x"""
96 I_inj = x["I_inj"]
97 v = x["v"]/mV
98
99 spike_count = x["spike_count"]
100 # Mean and standard deviation during stimulation
101 v_active = v[:, I_inj > 0*nA]
102 mean_active = np.mean(v_active, axis=1)
103 std_active = np.std(v_active, axis=1)
104 # Height of action potential peaks
105 max_v = np.max(v_active, axis=1)
106
107 # concatenation of summary statistics
108 sum_stats = np.vstack((spike_count, mean_active, std_active, max_v))
109
110 return sum_stats.T
111
112
113 def simulation_wrapper(params):
114 """
115 Returns summary statistics from conductance values in `params`.
116 Summarizes the output of the simulation and converts it to `torch.Tensor`.
117 """
118 obs = simulate(params)
119 summstats = torch.as_tensor(calculate_summary_statistics(obs))
120 return summstats.to(torch.float32)
121
122
123 if __name__ == '__main__':
124 # Define prior distribution over parameters
125 prior_min = [.5, 1e-4] # (gNa, gK) in µS
126 prior_max = [80.,15.]
127 prior = sbi.utils.torchutils.BoxUniform(low=torch.as_tensor(prior_min),
128 high=torch.as_tensor(prior_max))
129
130 # Simulate samples from the prior distribution
131 theta = prior.sample((10_000,))
132 print('Simulating samples from prior simulation... ', end='')
133 stats = simulation_wrapper(theta.numpy())
134 print('done.')
135
136 # Train inference network
137 density_estimator_build_fun = sbi.utils.posterior_nn(model='mdn')
138 inference = sbi.inference.SNPE(prior,
139 density_estimator=density_estimator_build_fun)
140 print('Training inference network... ')
141 inference.append_simulations(theta, stats).train()
142 posterior = inference.build_posterior()
143
144 # true parameters for real ground truth data
145 true_params = np.array([[32., 1.]])
146 true_data = simulate(true_params)
147 t = true_data['t']
148 I_inj = true_data['I_inj']
149 v = true_data['v']
150 xo = calculate_summary_statistics(true_data)
151 print("The true summary statistics are: ", xo)
152
153 # Plot estimated posterior distribution
154 samples = posterior.sample((1000,), x=xo, show_progress_bars=False)
155 labels_params = [r'$\overline{g}_{Na}$', r'$\overline{g}_{K}$']
156 sbi.analysis.pairplot(samples,
157 limits=[[.5, 80], [1e-4, 15.]],
158 ticks=[[.5, 80], [1e-4, 15.]],
159 figsize=(4, 4),
160 points=true_params, labels=labels_params,
161 points_offdiag={'markersize': 6},
162 points_colors=['r'])
163 plt.tight_layout()
164
165 # Draw a single sample from the posterior and convert to numpy for plotting.
166 posterior_sample = posterior.sample((1,), x=xo,
167 show_progress_bars=False).numpy()
168 x = simulate(posterior_sample)
169
170 # plot observation and sample
171 fig, ax = plt.subplots(figsize=(8, 4))
172 ax.plot(t/ms, v[0, :]/mV, lw=2, label='observation')
173 ax.plot(t/ms, x['v'][0, :]/mV, '--', lw=2, label='posterior sample')
174 ax.legend()
175 ax.set(xlabel='time (ms)', ylabel='voltage (mV)')
176 plt.show()