Debian Codegraph @

pyspike/spike_directionality.py

raw symbols SCIP
1 # Module containing functions to compute the SPIKE directionality and the
2 # spike train order profile
3 # Copyright 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 import pyspike
10 from pyspike import DiscreteFunc
11 from functools import partial
12 from pyspike.generic import _generic_profile_multi, 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_directionality_values
19 ############################################################
20
21 def spike_directionality_values(*args, **kwargs):
22 """ Computes the spike directionality value for each spike in
23 each spike train. Returns a list containing an array of spike directionality
24 values for every given spike train.
25
26 Valid call structures::
27
28 spike_directionality_values(st1, st2) # returns the bi-variate profile
29 spike_directionality_values(st1, st2, st3) # multi-variate profile of 3
30 # spike trains
31
32 spike_trains = [st1, st2, st3, st4] # list of spike trains
33 spike_directionality_values(spike_trains) # profile of the list of spike trains
34 spike_directionality_values(spike_trains, indices=[0, 1]) # use only the spike trains
35 # given by the indices
36
37 Additonal arguments:
38 :param max_tau: Upper bound for coincidence window (default=None).
39 :param indices: list of indices defining which spike trains to use,
40 if None all given spike trains are used (default=None)
41
42 :returns: The spike directionality values :math:`D^n_i` as a list of arrays.
43 """
44 if len(args) == 1:
45 return _spike_directionality_values_impl(args[0], **kwargs)
46 else:
47 return _spike_directionality_values_impl(args, **kwargs)
48
49
50 def _spike_directionality_values_impl(spike_trains, indices=None,
51 interval=None, max_tau=None, **kwargs):
52 """ Computes the multi-variate spike directionality profile
53 of the given spike trains.
54
55 :param spike_trains: List of spike trains.
56 :type spike_trains: List of :class:`pyspike.SpikeTrain`
57 :param indices: list of indices defining which spike trains to use,
58 if None all given spike trains are used (default=None)
59 :type indices: list or None
60 :param max_tau: Maximum coincidence window size. If 0 or `None`, the
61 coincidence window has no upper bound.
62 :returns: The spike-directionality values.
63 """
64 if kwargs.get('Reconcile', True):
65 spike_trains = reconcile_spike_trains(spike_trains)
66 ## get the keywords:
67 MRTS, RI = resolve_keywords(**kwargs)
68 if isinstance(MRTS, str):
69 MRTS = default_thresh(spike_trains)
70
71 if interval is not None:
72 raise NotImplementedError("Parameter `interval` not supported.")
73 if indices is None:
74 indices = np.arange(len(spike_trains))
75 indices = np.array(indices)
76 # check validity of indices
77 assert (indices < len(spike_trains)).all() and (indices >= 0).all(), \
78 "Invalid index list."
79 # list of arrays for resulting asymmetry values
80 asymmetry_list = [np.zeros_like(spike_trains[n].spikes) for n in indices]
81 # generate a list of possible index pairs
82 pairs = [(indices[i], j) for i in range(len(indices))
83 for j in indices[i+1:]]
84
85 # cython implementation
86 try:
87 from .cython.cython_directionality import \
88 spike_directionality_profiles_cython as profile_impl
89 except ImportError:
90 pyspike.NoCythonWarn()
91
92 # use python backend
93 from .cython.directionality_python_backend import \
94 spike_directionality_profile_python as profile_impl
95
96 if max_tau is None:
97 max_tau = 0.0
98
99 for i, j in pairs:
100 d1, d2 = profile_impl(spike_trains[i].spikes, spike_trains[j].spikes,
101 spike_trains[i].t_start, spike_trains[i].t_end,
102 max_tau, MRTS)
103 asymmetry_list[i] += d1
104 asymmetry_list[j] += d2
105 for a in asymmetry_list:
106 a /= len(spike_trains)-1
107 return asymmetry_list
108
109
110 ############################################################
111 # spike_directionality
112 ############################################################
113 def spike_directionality(spike_train1, spike_train2, normalize=True,
114 interval=None, max_tau=None, **kwargs):
115 """ Computes the overall spike directionality of the first spike train with
116 respect to the second spike train.
117
118 :param spike_train1: First spike train.
119 :type spike_train1: :class:`pyspike.SpikeTrain`
120 :param spike_train2: Second spike train.
121 :type spike_train2: :class:`pyspike.SpikeTrain`
122 :param normalize: Normalize by the number of spikes (multiplicity).
123 :param max_tau: Maximum coincidence window size. If 0 or `None`, the
124 coincidence window has no upper bound.
125 :returns: The spike train order profile :math:`E(t)`.
126 """
127 if kwargs.get('Reconcile', True):
128 spike_train1, spike_train2 = reconcile_spike_trains_bi(spike_train1, spike_train2)
129 MRTS, RI = resolve_keywords(**kwargs)
130 if isinstance(MRTS, str):
131 MRTS = default_thresh([spike_train1, spike_train2])
132
133 if interval is None:
134 # distance over the whole interval is requested: use specific function
135 # for optimal performance
136 try:
137 from .cython.cython_directionality import \
138 spike_directionality_cython as spike_directionality_impl
139 if max_tau is None:
140 max_tau = 0.0
141 d = spike_directionality_impl(spike_train1.spikes,
142 spike_train2.spikes,
143 spike_train1.t_start,
144 spike_train1.t_end,
145 max_tau, MRTS)
146 c = len(spike_train1.spikes)
147 except ImportError:
148 pyspike.NoCythonWarn()
149
150 # use profile.
151 d1, x = spike_directionality_values([spike_train1, spike_train2],
152 interval=interval,
153 max_tau=max_tau,
154 MRTS=MRTS)
155 d = np.sum(d1)
156 c = len(spike_train1.spikes)
157 if normalize:
158 return 1.0*d/c
159 else:
160 return d
161 else:
162 # some specific interval is provided: not yet implemented
163 raise NotImplementedError("Parameter `interval` not supported.")
164
165
166 ############################################################
167 # spike_directionality_matrix
168 ############################################################
169 def spike_directionality_matrix(spike_trains, normalize=True, indices=None,
170 interval=None, max_tau=None, **kwargs):
171 """ Computes the spike directionality matrix for the given spike trains.
172
173 :param spike_trains: List of spike trains.
174 :type spike_trains: List of :class:`pyspike.SpikeTrain`
175 :param normalize: Normalize by the number of spikes (multiplicity).
176 :param indices: list of indices defining which spike trains to use,
177 if None all given spike trains are used (default=None)
178 :type indices: list or None
179 :param max_tau: Maximum coincidence window size. If 0 or `None`, the
180 coincidence window has no upper bound.
181 :returns: The spike-directionality values.
182 """
183 if kwargs.get('Reconcile', True):
184 spike_trains = reconcile_spike_trains(spike_trains)
185 MRTS, RI = resolve_keywords(**kwargs)
186 if isinstance(MRTS, str):
187 MRTS = default_thresh(spike_trains)
188 if indices is None:
189 indices = np.arange(len(spike_trains))
190 indices = np.array(indices)
191 # check validity of indices
192 assert (indices < len(spike_trains)).all() and (indices >= 0).all(), \
193 "Invalid index list."
194 # generate a list of possible index pairs
195 pairs = [(indices[i], j) for i in range(len(indices))
196 for j in indices[i+1:]]
197
198 distance_matrix = np.zeros((len(indices), len(indices)))
199 for i, j in pairs:
200 d = spike_directionality(spike_trains[i], spike_trains[j], normalize,
201 interval, max_tau=max_tau,
202 MRTS=MRTS, RI=RI, Reconcile=False)
203 distance_matrix[i, j] = d
204 distance_matrix[j, i] = -d
205 return distance_matrix
206
207
208 ############################################################
209 # spike_train_order_profile
210 ############################################################
211 def spike_train_order_profile(*args, **kwargs):
212 """ Computes the spike train order profile :math:`E(t)` of the given
213 spike trains. Returns the profile as a DiscreteFunction object.
214
215 Valid call structures::
216
217 spike_train_order_profile(st1, st2) # returns the bi-variate profile
218 spike_train_order_profile(st1, st2, st3) # multi-variate profile of 3
219 # spike trains
220
221 spike_trains = [st1, st2, st3, st4] # list of spike trains
222 spike_train_order_profile(spike_trains) # profile of the list of spike trains
223 spike_train_order_profile(spike_trains, indices=[0, 1]) # use only the spike trains
224 # given by the indices
225
226 Additonal arguments:
227 :param max_tau: Upper bound for coincidence window, `default=None`.
228 :param indices: list of indices defining which spike trains to use,
229 if None all given spike trains are used (default=None)
230
231 :returns: The spike train order profile :math:`E(t)`
232 :rtype: :class:`.DiscreteFunction`
233 """
234 if len(args) == 1:
235 return spike_train_order_profile_multi(args[0], **kwargs)
236 elif len(args) == 2:
237 return spike_train_order_profile_bi(args[0], args[1], **kwargs)
238 else:
239 return spike_train_order_profile_multi(args, **kwargs)
240
241
242 ############################################################
243 # spike_train_order_profile_bi
244 ############################################################
245 def spike_train_order_profile_bi(spike_train1, spike_train2,
246 max_tau=None, **kwargs):
247 """ Computes the spike train order profile P(t) of the two given
248 spike trains. Returns the profile as a DiscreteFunction object.
249
250 :param spike_train1: First spike train.
251 :type spike_train1: :class:`pyspike.SpikeTrain`
252 :param spike_train2: Second spike train.
253 :type spike_train2: :class:`pyspike.SpikeTrain`
254 :param max_tau: Maximum coincidence window size. If 0 or `None`, the
255 coincidence window has no upper bound.
256 :returns: The spike train order profile :math:`E(t)`.
257 :rtype: :class:`pyspike.function.DiscreteFunction`
258 """
259 if kwargs.get('Reconcile', True):
260 spike_train1, spike_train2 = reconcile_spike_trains_bi(spike_train1, spike_train2)
261 MRTS, RI = resolve_keywords(**kwargs)
262 if isinstance(MRTS, str):
263 MRTS = default_thresh([spike_train1, spike_train2])
264
265 # check whether the spike trains are defined for the same interval
266 assert spike_train1.t_start == spike_train2.t_start, \
267 "Given spike trains are not defined on the same interval!"
268 assert spike_train1.t_end == spike_train2.t_end, \
269 "Given spike trains are not defined on the same interval!"
270
271 # cython implementation
272 try:
273 from .cython.cython_directionality import \
274 spike_train_order_profile_cython as \
275 spike_train_order_profile_impl
276 except ImportError:
277 # raise NotImplementedError()
278 pyspike.NoCythonWarn()
279
280 # use python backend
281 from .cython.directionality_python_backend import \
282 spike_train_order_profile_python as spike_train_order_profile_impl
283
284 if max_tau is None:
285 max_tau = 0.0
286
287 times, coincidences, multiplicity \
288 = spike_train_order_profile_impl(spike_train1.spikes,
289 spike_train2.spikes,
290 spike_train1.t_start,
291 spike_train1.t_end,
292 max_tau, MRTS)
293
294 return DiscreteFunc(times, coincidences, multiplicity)
295
296
297 ############################################################
298 # spike_train_order_profile_multi
299 ############################################################
300 def spike_train_order_profile_multi(spike_trains, indices=None,
301 max_tau=None, **kwargs):
302 """ Computes the multi-variate spike train order profile for a set of
303 spike trains. For each spike in the set of spike trains, the multi-variate
304 profile is defined as the sum of asymmetry values divided by the number of
305 spike trains pairs involving the spike train of containing this spike,
306 which is the number of spike trains minus one (N-1).
307
308 :param spike_trains: list of :class:`pyspike.SpikeTrain`
309 :param indices: list of indices defining which spike trains to use,
310 if None all given spike trains are used (default=None)
311 :type indices: list or None
312 :param max_tau: Maximum coincidence window size. If 0 or `None`, the
313 coincidence window has no upper bound.
314 :returns: The multi-variate spike sync profile :math:`<S_{sync}>(t)`
315 :rtype: :class:`pyspike.function.DiscreteFunction`
316 """
317 prof_func = partial(spike_train_order_profile_bi, max_tau=max_tau)
318 average_prof, M = _generic_profile_multi(spike_trains, prof_func,
319 indices, **kwargs)
320 return average_prof
321
322
323
324 ############################################################
325 # _spike_train_order_impl
326 ############################################################
327 def _spike_train_order_impl(spike_train1, spike_train2,
328 interval=None, max_tau=None, **kwargs):
329 """ Implementation of bi-variatae spike train order value (Synfire Indicator).
330
331 :param spike_train1: First spike train.
332 :type spike_train1: :class:`pyspike.SpikeTrain`
333 :param spike_train2: Second spike train.
334 :type spike_train2: :class:`pyspike.SpikeTrain`
335 :param max_tau: Maximum coincidence window size. If 0 or `None`, the
336 coincidence window has no upper bound.
337 :returns: The spike train order value (Synfire Indicator)
338 """
339 MRTS, RI = resolve_keywords(**kwargs)
340 if isinstance(MRTS, str):
341 MRTS = default_thresh([spike_train1, spike_train2])
342 if interval is None:
343 # distance over the whole interval is requested: use specific function
344 # for optimal performance
345 try:
346 from .cython.cython_directionality import \
347 spike_train_order_cython as spike_train_order_func
348 if max_tau is None:
349 max_tau = 0.0
350 c, mp = spike_train_order_func(spike_train1.spikes,
351 spike_train2.spikes,
352 spike_train1.t_start,
353 spike_train1.t_end,
354 max_tau, MRTS)
355 except ImportError:
356 # Cython backend not available: fall back to profile averaging
357 c, mp = spike_train_order_profile(spike_train1, spike_train2,
358 max_tau=max_tau,
359 MRTS=MRTS).integral(interval)
360 return c, mp
361 else:
362 # some specific interval is provided: not yet implemented
363 raise NotImplementedError("Parameter `interval` not supported.")
364
365
366 ############################################################
367 # spike_train_order
368 ############################################################
369 def spike_train_order(*args, **kwargs):
370 """ Computes the spike train order (Synfire Indicator) of the given
371 spike trains.
372
373 Valid call structures::
374
375 spike_train_order(st1, st2, normalize=True) # normalized bi-variate
376 # spike train order
377 spike_train_order(st1, st2, st3) # multi-variate result of 3 spike trains
378
379 spike_trains = [st1, st2, st3, st4] # list of spike trains
380 spike_train_order(spike_trains) # result for the list of spike trains
381 spike_train_order(spike_trains, indices=[0, 1]) # use only the spike trains
382 # given by the indices
383
384 Additonal arguments:
385 - `max_tau` Upper bound for coincidence window, `default=None`.
386 - `normalize` Flag indicating if the reslut should be normalized by the
387 number of spikes , default=`False`
388
389
390 :returns: The spike train order value (Synfire Indicator)
391 """
392 if len(args) == 1:
393 return spike_train_order_multi(args[0], **kwargs)
394 elif len(args) == 2:
395 return spike_train_order_bi(args[0], args[1], **kwargs)
396 else:
397 return spike_train_order_multi(args, **kwargs)
398
399
400 ############################################################
401 # spike_train_order_bi
402 ############################################################
403 def spike_train_order_bi(spike_train1, spike_train2, normalize=True,
404 interval=None, max_tau=None, **kwargs):
405 """ Computes the overall spike train order value (Synfire Indicator)
406 for two spike trains.
407
408 :param spike_train1: First spike train.
409 :type spike_train1: :class:`pyspike.SpikeTrain`
410 :param spike_train2: Second spike train.
411 :type spike_train2: :class:`pyspike.SpikeTrain`
412 :param normalize: Normalize by the number of spikes (multiplicity).
413 :param max_tau: Maximum coincidence window size. If 0 or `None`, the
414 coincidence window has no upper bound.
415 :returns: The spike train order value (Synfire Indicator)
416 """
417 c, mp = _spike_train_order_impl(spike_train1, spike_train2, interval, max_tau, **kwargs)
418 if normalize:
419 return 1.0*c/mp
420 else:
421 return c
422
423 ############################################################
424 # spike_train_order_multi
425 ############################################################
426 def spike_train_order_multi(spike_trains, indices=None, normalize=True,
427 interval=None, max_tau=None, **kwargs):
428 """ Computes the overall spike train order value (Synfire Indicator)
429 for many spike trains.
430
431 :param spike_trains: list of :class:`.SpikeTrain`
432 :param indices: list of indices defining which spike trains to use,
433 if None all given spike trains are used (default=None)
434 :param normalize: Normalize by the number of spike (multiplicity).
435 :param interval: averaging interval given as a pair of floats, if None
436 the average over the whole function is computed.
437 :type interval: Pair of floats or None.
438 :param max_tau: Maximum coincidence window size. If 0 or `None`, the
439 coincidence window has no upper bound.
440 :returns: Spike train order values (Synfire Indicator) F for the given spike trains.
441 :rtype: double
442 """
443 MRTS, RI = resolve_keywords(**kwargs)
444 if isinstance(MRTS, str):
445 MRTS = default_thresh(spike_trains)
446 if indices is None:
447 indices = np.arange(len(spike_trains))
448 indices = np.array(indices)
449 # check validity of indices
450 assert (indices < len(spike_trains)).all() and (indices >= 0).all(), \
451 "Invalid index list."
452 # generate a list of possible index pairs
453 pairs = [(indices[i], j) for i in range(len(indices))
454 for j in indices[i+1:]]
455
456 e_total = 0.0
457 m_total = 0.0
458 for (i, j) in pairs:
459 e, m = _spike_train_order_impl(spike_trains[i], spike_trains[j],
460 interval, max_tau, MRTS=MRTS, RI=RI)
461 e_total += e
462 m_total += m
463
464 if m == 0.0:
465 return 1.0
466 else:
467 return e_total/m_total
468
469
470
471 ############################################################
472 # optimal_spike_train_sorting_from_matrix
473 ############################################################
474 def _optimal_spike_train_sorting_from_matrix(D, full_output=False):
475 """ Finds the best sorting via simulated annealing.
476 Returns the optimal permutation p and A value.
477 Not for direct use, call :func:`.optimal_spike_train_sorting` instead.
478
479 :param D: The directionality (Spike-ORDER) matrix.
480 :param full_output: If true, then function will additionally return the
481 number of performed iterations (default=False)
482 :return: (p, F) - tuple with the optimal permutation and synfire indicator.
483 if `full_output=True` , (p, F, iter) is returned.
484 """
485 N = len(D)
486 A = np.sum(np.triu(D, 0))
487
488 p = np.arange(N)
489
490 T_start = 2*np.max(D) # starting temperature
491 T_end = 1E-5 * T_start # final temperature
492 alpha = 0.9 # cooling factor
493
494 try:
495 from .cython.cython_simulated_annealing import sim_ann_cython as sim_ann
496 except ImportError:
497 raise NotImplementedError("PySpike with Cython required for computing spike train"
498 " sorting!")
499
500 p, A, total_iter = sim_ann(D, T_start, T_end, alpha)
501
502 if full_output:
503 return p, A, total_iter
504 else:
505 return p, A
506
507
508 ############################################################
509 # optimal_spike_train_sorting
510 ############################################################
511 def optimal_spike_train_sorting(spike_trains, indices=None, interval=None,
512 max_tau=None, full_output=False, **kwargs):
513 """ Finds the best sorting of the given spike trains by computing the spike
514 directionality matrix and optimize the order using simulated annealing.
515 For a detailed description of the algorithm see:
516 `http://iopscience.iop.org/article/10.1088/1367-2630/aa68c3/meta`
517
518 :param spike_trains: list of :class:`.SpikeTrain`
519 :param indices: list of indices defining which spike trains to use,
520 if None all given spike trains are used (default=None)
521 :type indices: list or None
522 :param interval: time interval filter given as a pair of floats, if None
523 the full spike trains are used (default=None).
524 :type interval: Pair of floats or None.
525 :param max_tau: Maximum coincidence window size. If 0 or `None`, the
526 coincidence window has no upper bound (default=None).
527 :param full_output: If true, then function will additionally return the
528 number of performed iterations (default=False)
529 :return: (p, F) - tuple with the optimal permutation and synfire indicator.
530 if `full_output=True` , (p, F, iter) is returned.
531 """
532 D = spike_directionality_matrix(spike_trains, normalize=False,
533 indices=indices, interval=interval,
534 max_tau=max_tau, **kwargs)
535 return _optimal_spike_train_sorting_from_matrix(D, full_output)
536
537 ############################################################
538 # permutate_matrix
539 ############################################################
540 def permutate_matrix(D, p):
541 """ Helper function that applies the permutation p to the columns and rows
542 of matrix D. Return the permutated matrix :math:`D'[n,m] = D[p[n], p[m]]`.
543
544 :param D: The matrix.
545 :param d: The permutation.
546 :return: The permuated matrix D', ie :math:`D'[n,m] = D[p[n], p[m]]`
547 """
548 N = len(D)
549 D_p = np.empty_like(D)
550 for n in range(N):
551 for m in range(N):
552 D_p[n, m] = D[p[n], p[m]]
553 return D_p