Debian Codegraph @

pyspike/spikes.py

raw symbols SCIP
1 # Module containing several function to load and transform spike trains
2 # Copyright 2014, Mario Mulansky <[email protected]>
3 # Distributed under the BSD License
4
5 import numpy as np
6 from pyspike import SpikeTrain
7
8
9 ############################################################
10 # spike_train_from_string
11 ############################################################
12 def spike_train_from_string(s, edges, sep=' ', is_sorted=False):
13 """ Converts a string of times into a :class:`.SpikeTrain`.
14
15 :param s: the string with (ordered) spike times.
16 :param edges: interval defining the edges of the spike train.
17 Given as a pair of floats (T0, T1) or a single float T1,
18 where T0=0 is assumed.
19 :param sep: The separator between the time numbers, default=' '.
20 :param is_sorted: if True, the spike times are not sorted after loading,
21 if False, spike times are sorted with `np.sort`
22 :returns: :class:`.SpikeTrain`
23 """
24 return SpikeTrain(np.fromstring(s, sep=sep), edges, is_sorted)
25
26
27 ############################################################
28 # load_spike_trains_from_txt
29 ############################################################
30 def load_spike_trains_from_txt(file_name, edges,
31 separator=' ', comment='#', is_sorted=False,
32 ignore_empty_lines=True):
33 """ Loads a number of spike trains from a text file. Each line of the text
34 file should contain one spike train as a sequence of spike times separated
35 by `separator`. Empty lines as well as lines starting with `comment` are
36 neglected. The `edges` represents the start and the end of the
37 spike trains.
38
39 :param file_name: The name of the text file.
40 :param edges: A pair (T_start, T_end) of values representing the
41 start and end time of the spike train measurement
42 or a single value representing the end time, the
43 T_start is then assuemd as 0.
44 :param separator: The character used to seprate the values in the text file
45 :param comment: Lines starting with this character are ignored.
46 :param sort: If true, the spike times are order via `np.sort`, default=True
47 :returns: list of :class:`.SpikeTrain`
48 """
49 spike_trains = []
50 with open(file_name, 'r') as spike_file:
51 for line in spike_file:
52 if not line.startswith(comment): # ignore comments
53 if len(line) > 1:
54 # ignore empty lines
55 spike_train = spike_train_from_string(line, edges,
56 separator, is_sorted)
57 spike_trains.append(spike_train)
58 elif not(ignore_empty_lines):
59 # add empty spike train
60 spike_trains.append(SpikeTrain([], edges))
61 return spike_trains
62
63
64 def import_spike_trains_from_time_series(file_name, start_time, time_bin,
65 separator=None, comment='#'):
66 """ Imports spike trains from time series consisting of 0 and 1 denoting
67 the absence or presence of a spike. Each line in the data file represents
68 one spike train.
69
70 :param file_name: The name of the data file containing the time series.
71 :param edges: A pair (T_start, T_end) of values representing the
72 start and end time of the spike train measurement
73 or a single value representing the end time, the
74 T_start is then assuemd as 0.
75 :param separator: The character used to seprate the values in the text file
76 :param comment: Lines starting with this character are ignored.
77
78 """
79 data = np.loadtxt(file_name, comments=comment, delimiter=separator)
80 time_points = start_time + time_bin + np.arange(len(data[0, :]))*time_bin
81 spike_trains = []
82 for time_series in data:
83 spike_trains.append(SpikeTrain(time_points[time_series > 0],
84 edges=[start_time,
85 time_points[-1]]))
86 return spike_trains
87
88
89 ############################################################
90 # save_spike_trains_to_txt
91 ############################################################
92 def save_spike_trains_to_txt(spike_trains, file_name,
93 separator=' ', precision=8):
94 """ Saves the given spike trains into a file with the given file name.
95 Each spike train will be stored in one line in the text file with the times
96 separated by `separator`.
97
98 :param spike_trains: List of :class:`.SpikeTrain` objects
99 :param file_name: The name of the text file.
100 """
101 # format string to print the spike times with given precision
102 format_str = "{0:.%de}" % precision
103 with open(file_name, 'w') as spike_file:
104 for st in spike_trains:
105 s = separator.join(map(format_str.format, st.spikes))
106 spike_file.write(s+'\n')
107
108
109 ############################################################
110 # merge_spike_trains
111 ############################################################
112 def merge_spike_trains(spike_trains):
113 """ Merges a number of spike trains into a single spike train.
114
115 :param spike_trains: list of :class:`.SpikeTrain`
116 :returns: spike train with the merged spike times
117 """
118 # concatenating and sorting with numpy is fast, it also means we can handle
119 # empty spike trains
120 merged_spikes = np.concatenate([st.spikes for st in spike_trains])
121 merged_spikes.sort()
122 return SpikeTrain(merged_spikes, [spike_trains[0].t_start,
123 spike_trains[0].t_end])
124
125
126 ############################################################
127 # generate_poisson_spikes
128 ############################################################
129 def generate_poisson_spikes(rate, interval):
130 """ Generates a Poisson spike train with the given rate in the given time
131 interval
132
133 :param rate: The rate of the spike trains
134 :param interval: A pair (T_start, T_end) of values representing the
135 start and end time of the spike train measurement or
136 a single value representing the end time, the T_start
137 is then assuemd as 0. Auxiliary spikes will be added
138 to the spike train at the beginning and end of this
139 interval, if they are not yet present.
140 :type interval: pair of doubles or double
141 :returns: Poisson spike train as a :class:`.SpikeTrain`
142 """
143 try:
144 T_start = interval[0]
145 T_end = interval[1]
146 except:
147 T_start = 0
148 T_end = interval
149 # roughly how many spikes are required to fill the interval
150 N = max(1, int(1.2 * rate * (T_end-T_start)))
151 N_append = max(1, int(0.1 * rate * (T_end-T_start)))
152 intervals = np.random.exponential(1.0/rate, N)
153 # make sure we have enough spikes
154 while T_start + sum(intervals) < T_end:
155 # print T_start + sum(intervals)
156 intervals = np.append(intervals,
157 np.random.exponential(1.0/rate, N_append))
158 spikes = T_start + np.cumsum(intervals)
159 spikes = spikes[spikes < T_end]
160 return SpikeTrain(spikes, interval)
161
162 def reconcile_spike_trains(spike_trains):
163 """ make sure that Spike trains meet PySpike rules
164 In: spike_trains - a list of SpikeTrain objects
165 Out: spike_trains - same list with some fixes:
166 1) t_start and t_end are the same for every train
167 2) The spike times are sorted
168 3) No duplicate times in any train
169 4) spike times outside of t_start,t_end removed
170 """
171 ## handle sorting and uniqueness first (np.unique() does a sort)
172 spike_trains = [SpikeTrain(np.unique(s.spikes),
173 [s.t_start, s.t_end],
174 is_sorted=True) for s in spike_trains]
175
176 ## find global start and end times
177 Starts = [s.t_start for s in spike_trains]
178 tStart = min(Starts)
179
180 Ends = [s.t_end for s in spike_trains]
181 tEnd = max(Ends)
182
183 ## remove spike times outside of the bounds
184 Eps = 1e-6 #beware precision change
185 for s in spike_trains:
186 s.spikes = [t for t in s.spikes if t > tStart-Eps and t < tEnd+Eps]
187
188 ## Apply start and end times to every train
189 return [SpikeTrain(s.spikes, [tStart, tEnd], is_sorted=True) for s in spike_trains]
190
191 def reconcile_spike_trains_bi(spike_train1, spike_train2):
192 """ fix up a pair of spike trains"""
193 trains_in = [spike_train1, spike_train2]
194 trains_out = reconcile_spike_trains(trains_in)
195 return trains_out[0], trains_out[1]