Debian Codegraph @

pyspike/spike_sync.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 # Module containing several functions to compute SPIKE-Synchronization profiles
2 # and distances
3 # Copyright 2014-2015, Mario Mulansky <[email protected]>
4 # Distributed under the BSD License
5
6 from __future__ import absolute_import
7
8 import numpy as np
9 from functools import partial
10 import pyspike
11 from pyspike import DiscreteFunc, SpikeTrain
12 from pyspike.generic import _generic_profile_multi, _generic_distance_matrix, resolve_keywords
13 from pyspike.isi_lengths import default_thresh
14 from pyspike.spikes import reconcile_spike_trains, reconcile_spike_trains_bi
15
16
17 ############################################################
18 # spike_sync_profile
19 ############################################################
20 def spike_sync_profile(*args, **kwargs):
21 """ Computes the spike-synchronization profile S_sync(t) of the given
22 spike trains. Returns the profile as a DiscreteFunction object. In the
23 bivariate case, he S_sync values are either 1 or 0, indicating the presence
24 or absence of a coincidence. For multi-variate cases, each spike in the set
25 of spike trains, the profile is defined as the number of coincidences
26 divided by the number of spike trains pairs involving the spike train of
27 containing this spike, which is the number of spike trains minus one (N-1).
28
29 Valid call structures::
30
31 spike_sync_profile(st1, st2) # returns the bi-variate profile
32 spike_sync_profile(st1, st2, st3) # multi-variate profile of 3 sts
33
34 sts = [st1, st2, st3, st4] # list of spike trains
35 spike_sync_profile(sts) # profile of the list of spike trains
36 spike_sync_profile(sts, indices=[0, 1]) # use only the spike trains
37 # given by the indices
38
39 In the multivariate case, the profile is defined as the number of
40 coincidences for each spike in the set of spike trains divided by the
41 number of spike trains pairs involving the spike train of containing this
42 spike, which is the number of spike trains minus one (N-1).
43
44 :returns: The spike-sync profile :math:`S_{sync}(t)`.
45 :rtype: :class:`pyspike.function.DiscreteFunction`
46 """
47 if len(args) == 1:
48 return spike_sync_profile_multi(args[0], **kwargs)
49 elif len(args) == 2:
50 return spike_sync_profile_bi(args[0], args[1], **kwargs)
51 else:
52 return spike_sync_profile_multi(args, **kwargs)
53
54
55 ############################################################
56 # spike_sync_profile_bi
57 ############################################################
58 def spike_sync_profile_bi(spike_train1, spike_train2, max_tau=None, **kwargs):
59 """ Specific function to compute a bivariate SPIKE-Sync-profile. This is a
60 deprecated function and should not be called directly. Use
61 :func:`.spike_sync_profile` to compute SPIKE-Sync-profiles.
62
63 :param spike_train1: First spike train.
64 :type spike_train1: :class:`pyspike.SpikeTrain`
65 :param spike_train2: Second spike train.
66 :type spike_train2: :class:`pyspike.SpikeTrain`
67 :param max_tau: Maximum coincidence window size. If 0 or `None`, the
68 coincidence window has no upper bound.
69 :returns: The spike-sync profile :math:`S_{sync}(t)`.
70 :rtype: :class:`pyspike.function.DiscreteFunction`
71
72 """
73 if kwargs.get('Reconcile', True):
74 spike_train1, spike_train2 = reconcile_spike_trains_bi(spike_train1, spike_train2)
75
76 MRTS, RI = resolve_keywords(**kwargs)
77 if isinstance(MRTS, str):
78 MRTS = default_thresh([spike_train1, spike_train2])
79
80 # cython implementation
81 try:
82 from .cython.cython_profiles import coincidence_profile_cython \
83 as coincidence_profile_impl
84 except ImportError:
85 pyspike.NoCythonWarn()
86
87 # use python backend
88 from .cython.python_backend import coincidence_python \
89 as coincidence_profile_impl
90
91 if max_tau is None:
92 max_tau = 0.0
93
94 times, coincidences, multiplicity \
95 = coincidence_profile_impl(spike_train1.spikes, spike_train2.spikes,
96 spike_train1.t_start, spike_train1.t_end,
97 max_tau, MRTS)
98
99 return DiscreteFunc(times, coincidences, multiplicity)
100
101
102 ############################################################
103 # spike_sync_profile_multi
104 ############################################################
105 def spike_sync_profile_multi(spike_trains, indices=None, max_tau=None, **kwargs):
106 """ Specific function to compute a multivariate SPIKE-Sync-profile.
107 This is a deprecated function and should not be called directly. Use
108 :func:`.spike_sync_profile` to compute SPIKE-Sync-profiles.
109
110 :param spike_trains: list of :class:`pyspike.SpikeTrain`
111 :param indices: list of indices defining which spike trains to use,
112 if None all given spike trains are used (default=None)
113 :type indices: list or None
114 :param max_tau: Maximum coincidence window size. If 0 or `None`, the
115 coincidence window has no upper bound.
116 :returns: The multi-variate spike sync profile :math:`<S_{sync}>(t)`
117 :rtype: :class:`pyspike.function.DiscreteFunction`
118
119 """
120 prof_func = partial(spike_sync_profile_bi, max_tau=max_tau)
121 average_prof, M = _generic_profile_multi(spike_trains, prof_func,
122 indices, **kwargs)
123 # average_dist.mul_scalar(1.0/M) # no normalization here!
124 return average_prof
125
126
127 ############################################################
128 # _spike_sync_values
129 ############################################################
130 def _spike_sync_values(spike_train1, spike_train2, interval, max_tau, **kwargs):
131 """" Internal function. Computes the summed coincidences and multiplicity
132 for spike synchronization of the two given spike trains.
133
134 Do not call this function directly, use `spike_sync` or `spike_sync_multi`
135 instead.
136 """
137 MRTS, RI = resolve_keywords(**kwargs)
138 if isinstance(MRTS, str):
139 MRTS = default_thresh([spike_train1, spike_train2])
140 if interval is None:
141 # distance over the whole interval is requested: use specific function
142 # for optimal performance
143 try:
144 from .cython.cython_distances import coincidence_value_cython \
145 as coincidence_value_impl
146 if max_tau is None:
147 max_tau = 0.0
148 c, mp = coincidence_value_impl(spike_train1.spikes,
149 spike_train2.spikes,
150 spike_train1.t_start,
151 spike_train1.t_end,
152 max_tau, MRTS)
153 return c, mp
154 except ImportError:
155 # Cython backend not available: fall back to profile averaging
156 return spike_sync_profile_bi(spike_train1, spike_train2,
157 max_tau, **kwargs).integral(interval)
158 else:
159 # some specific interval is provided: use profile
160 return spike_sync_profile_bi(spike_train1, spike_train2,
161 max_tau, **kwargs).integral(interval)
162
163
164 ############################################################
165 # spike_sync
166 ############################################################
167 def spike_sync(*args, **kwargs):
•168 r""" Computes the spike synchronization value of the given spike
169 trains. The spike synchronization value is the computed as the total number
170 of coincidences divided by the total number of spikes:
171
172 .. math:: SYNC = \sum_n C_n / N.
173
174
175 Valid call structures::
176
177 spike_sync(st1, st2) # returns the bi-variate spike synchronization
178 spike_sync(st1, st2, st3) # multi-variate result for 3 spike trains
179
180 spike_trains = [st1, st2, st3, st4] # list of spike trains
181 spike_sync(spike_trains) # spike-sync of the list of spike trains
182 spike_sync(spike_trains, indices=[0, 1]) # use only the spike trains
183 # given by the indices
184
185 The multivariate SPIKE-Sync is again defined as the overall ratio of all
186 coincidence values divided by the total number of spikes.
187
188 :returns: The spike synchronization value.
189 :rtype: `double`
190 """
191
192 if len(args) == 1:
193 return spike_sync_multi(args[0], **kwargs)
194 elif len(args) == 2:
195 return spike_sync_bi(args[0], args[1], **kwargs)
196 else:
197 return spike_sync_multi(args, **kwargs)
198
199
200 ############################################################
201 # spike_sync_bi
202 ############################################################
203 def spike_sync_bi(spike_train1, spike_train2, interval=None, max_tau=None, **kwargs):
204 """ Specific function to compute a bivariate SPIKE-Sync value.
205 This is a deprecated function and should not be called directly. Use
206 :func:`.spike_sync` to compute SPIKE-Sync values.
207
208 :param spike_train1: First spike train.
209 :type spike_train1: :class:`pyspike.SpikeTrain`
210 :param spike_train2: Second spike train.
211 :type spike_train2: :class:`pyspike.SpikeTrain`
212 :param interval: averaging interval given as a pair of floats (T0, T1),
213 if `None` the average over the whole function is computed.
214 :type interval: Pair of floats or None.
215 :param max_tau: Maximum coincidence window size. If 0 or `None`, the
216 coincidence window has no upper bound.
217 :returns: The spike synchronization value.
218 :rtype: `double`
219
220 """
221 if kwargs.get('Reconcile', True):
222 spike_train1, spike_train2 = reconcile_spike_trains_bi(spike_train1, spike_train2)
223 kwargs['Reconcile'] = False
224 c, mp = _spike_sync_values(spike_train1, spike_train2, interval, max_tau, **kwargs)
225 if mp == 0:
226 return 1.0
227 else:
228 return 1.0*c/mp
229
230
231 ############################################################
232 # spike_sync_multi
233 ############################################################
234 def spike_sync_multi(spike_trains, indices=None, interval=None, max_tau=None, **kwargs):
235 """ Specific function to compute a multivariate SPIKE-Sync value.
236 This is a deprecated function and should not be called directly. Use
237 :func:`.spike_sync` to compute SPIKE-Sync values.
238
239 :param spike_trains: list of :class:`pyspike.SpikeTrain`
240 :param indices: list of indices defining which spike trains to use,
241 if None all given spike trains are used (default=None)
242 :type indices: list or None
243 :param interval: averaging interval given as a pair of floats, if None
244 the average over the whole function is computed.
245 :type interval: Pair of floats or None.
246 :param max_tau: Maximum coincidence window size. If 0 or `None`, the
247 coincidence window has no upper bound.
248 :returns: The multi-variate spike synchronization value SYNC.
249 :rtype: double
250
251 """
252 if kwargs.get('Reconcile', True):
253 spike_trains = reconcile_spike_trains(spike_trains)
254 kwargs['Reconcile'] = False
255 MRTS, RI = resolve_keywords(**kwargs)
256 if isinstance(MRTS, str):
257 kwargs['MRTS'] = default_thresh(spike_trains)
258
259 if indices is None:
260 indices = np.arange(len(spike_trains))
261 indices = np.array(indices)
262 # check validity of indices
263 assert (indices < len(spike_trains)).all() and (indices >= 0).all(), \
264 "Invalid index list."
265 # generate a list of possible index pairs
266 pairs = [(indices[i], j) for i in range(len(indices))
267 for j in indices[i+1:]]
268
269 coincidence = 0.0
270 mp = 0.0
271 for (i, j) in pairs:
272 c, m = _spike_sync_values(spike_trains[i], spike_trains[j],
273 interval, max_tau,
274 **kwargs)
275 coincidence += c
276 mp += m
277
278 if mp == 0.0:
279 return 1.0
280 else:
281 return coincidence/mp
282
283
284 ############################################################
285 # spike_sync_matrix
286 ############################################################
287 def spike_sync_matrix(spike_trains, indices=None, interval=None, max_tau=None, **kwargs):
288 """ Computes the overall spike-synchronization value of all pairs of
289 spike-trains.
290
291 :param spike_trains: list of :class:`pyspike.SpikeTrain`
292 :param indices: list of indices defining which spike trains to use,
293 if None all given spike trains are used (default=None)
294 :type indices: list or None
295 :param interval: averaging interval given as a pair of floats, if None
296 the average over the whole function is computed.
297 :type interval: Pair of floats or None.
298 :param max_tau: Maximum coincidence window size. If 0 or `None`, the
299 coincidence window has no upper bound.
300 :returns: 2D array with the pair wise time spike synchronization values
301 :math:`SYNC_{ij}`
302 :rtype: np.array
303
304 """
305 dist_func = partial(spike_sync_bi, max_tau=max_tau)
306 ShouldBeSync = _generic_distance_matrix(spike_trains, dist_func,
307 indices, interval, **kwargs)
308 # These elements are not really distances, but spike-sync values
309 # The diagonal needs to reflect that:
310 for i in range(ShouldBeSync.shape[0]):
311 ShouldBeSync[i][i] = 1.0
312 return ShouldBeSync
313
314
315 ############################################################
316 # filter_by_spike_sync
317 ############################################################
318 def filter_by_spike_sync(spike_trains, threshold, indices=None, max_tau=None,
319 return_removed_spikes=False, **kwargs):
320 """ Removes the spikes with a multi-variate spike_sync value below
321 threshold.
322 """
323 if kwargs.get('Reconcile', True):
324 spike_trains = reconcile_spike_trains(spike_trains)
325 MRTS, RI = resolve_keywords(**kwargs)
326 if isinstance(MRTS, str):
327 MRTS = default_thresh(spike_trains)
328 N = len(spike_trains)
329 filtered_spike_trains = []
330 removed_spike_trains = []
331
332 # cython implementation
333 try:
334 from .cython.cython_profiles import coincidence_single_profile_cython \
335 as coincidence_impl
336 except ImportError:
337 pyspike.NoCythonWarn()
338
339 # use python backend
340 from .cython.python_backend import coincidence_single_python \
341 as coincidence_impl
342
343 if max_tau is None:
344 max_tau = 0.0
345
346 for i, st in enumerate(spike_trains):
347 coincidences = np.zeros_like(st)
348 for j in range(N):
349 if i == j:
350 continue
351 coincidences += coincidence_impl(st.spikes, spike_trains[j].spikes,
352 st.t_start, st.t_end, max_tau, MRTS)
353 filtered_spikes = st[coincidences > threshold*(N-1)]
354 filtered_spike_trains.append(SpikeTrain(filtered_spikes,
355 [st.t_start, st.t_end]))
356 if return_removed_spikes:
357 removed_spikes = st[coincidences <= threshold*(N-1)]
358 removed_spike_trains.append(SpikeTrain(removed_spikes,
359 [st.t_start, st.t_end]))
360 if return_removed_spikes:
361 return [filtered_spike_trains, removed_spike_trains]
362 else:
363 return filtered_spike_trains