Debian Codegraph @

pyspike/DiscreteFunc.py

raw symbols SCIP
1 # Class representing discrete functions.
2 # Copyright 2014-2015, Mario Mulansky <[email protected]>
3 # Distributed under the BSD License
4
5 from __future__ import absolute_import, print_function
6
7 import numpy as np
8 import collections.abc
9 import pyspike
10
11
12 ##############################################################
13 # DiscreteFunc
14 ##############################################################
15 class DiscreteFunc(object):
16 """ A class representing values defined on a discrete set of points.
17 """
18
19 def __init__(self, x, y, multiplicity):
20 """ Constructs the discrete function.
21
22 :param x: array of length N defining the points at which the values are
23 defined.
24 :param y: array of length N degining the values at the points x.
25 :param multiplicity: array of length N defining the multiplicity of the
26 values.
27 """
28 # convert parameters to arrays, also ensures copying
29 self.x = np.array(x)
30 self.y = np.array(y)
31 self.mp = np.array(multiplicity)
32
33 def copy(self):
34 """ Returns a copy of itself
35
36 :rtype: :class:`DiscreteFunc`
37 """
38 return DiscreteFunc(self.x, self.y, self.mp)
39
40 def almost_equal(self, other, decimal=14):
41 """ Checks if the function is equal to another function up to `decimal`
42 precision.
43
44 :param other: another :class:`DiscreteFunc`
45 :returns: True if the two functions are equal up to `decimal` decimals,
46 False otherwise
47 :rtype: bool
48 """
49 eps = 10.0**(-decimal)
50 return np.allclose(self.x, other.x, atol=eps, rtol=0.0) and \
51 np.allclose(self.y, other.y, atol=eps, rtol=0.0) and \
52 np.allclose(self.mp, other.mp, atol=eps, rtol=0.0)
53
54 def get_plottable_data(self, averaging_window_size=0):
55 """ Returns two arrays containing x- and y-coordinates for plotting
56 the interval sequence. The optional parameter `averaging_window_size`
57 determines the size of an averaging window to smoothen the profile. If
58 this value is 0, no averaging is performed.
59
60 :param averaging_window_size: size of the averaging window, default=0.
61 :returns: (x_plot, y_plot) containing plottable data
62 :rtype: pair of np.array
63
64 Example::
65
66 x, y = f.get_plottable_data()
67 plt.plot(x, y, '-o', label="Discrete function")
68 """
69
70 if averaging_window_size > 0:
71 # for the averaged profile we have to take the multiplicity into
72 # account. values with higher multiplicity should be consider as if
73 # they appeared several times. Hence we can not know how many
74 # entries we have to consider to the left and right. Rather, we
75 # will iterate until some wanted multiplicity is reached.
76
77 # the first value in self.mp contains the number of averaged
78 # profiles without any possible extra multiplicities
79 # (by implementation)
80 expected_mp = (averaging_window_size+1) * int(self.mp[0])
81 y_plot = np.zeros_like(self.y)
82 # compute the values in a loop, could be done in cython if required
83 for i in range(len(y_plot)):
84
85 if self.mp[i] >= expected_mp:
86 # the current value contains already all the wanted
87 # multiplicity
88 y_plot[i] = self.y[i]/self.mp[i]
89 continue
90
91 # first look to the right
92 y = self.y[i]
93 mp_r = self.mp[i]
94 j = i+1
95 while j < len(y_plot):
96 if mp_r+self.mp[j] < expected_mp:
97 # if we still dont reach the required multiplicity
98 # we take the whole value
99 y += self.y[j]
100 mp_r += self.mp[j]
101 else:
102 # otherwise, just some fraction
103 y += self.y[j] * (expected_mp - mp_r)/self.mp[j]
104 mp_r += (expected_mp - mp_r)
105 break
106 j += 1
107
108 # same story to the left
109 mp_l = self.mp[i]
110 j = i-1
111 while j >= 0:
112 if mp_l+self.mp[j] < expected_mp:
113 y += self.y[j]
114 mp_l += self.mp[j]
115 else:
116 y += self.y[j] * (expected_mp - mp_l)/self.mp[j]
117 mp_l += (expected_mp - mp_l)
118 break
119 j -= 1
120 y_plot[i] = y/(mp_l+mp_r-self.mp[i])
121 return 1.0*self.x, y_plot
122
123 else: # k = 0
124
125 return 1.0*self.x, 1.0*self.y/self.mp
126
127 def integral(self, interval=None):
128 """ Returns the integral over the given interval. For the discrete
129 function, this amounts to two values: the sum over all values and the
130 sum over all multiplicities.
131
132 :param interval: integration interval given as a pair of floats, or a
133 sequence of pairs in case of multiple intervals, if
134 None the integral over the whole function is computed.
135 :type interval: Pair, sequence of pairs, or None.
136 :returns: the summed values and the summed multiplicity
137 :rtype: pair of float
138 """
139
140 value = 0.0
141 multiplicity = 0.0
142
143 def get_indices(ival):
144 """ Retuns the indeces surrounding the given interval"""
145 start_ind = np.searchsorted(self.x, ival[0], side='right')
146 end_ind = np.searchsorted(self.x, ival[1], side='left')
147 assert start_ind > 0 and end_ind < len(self.x), \
148 "Invalid averaging interval"
149 return start_ind, end_ind
150
151 if interval is None:
152 # no interval given, integrate over the whole spike train
153 # don't count the first value, which is zero by definition
154 value = 1.0 * np.sum(self.y[1:-1])
155 multiplicity = np.sum(self.mp[1:-1])
156 else:
157 # check if interval is as sequence
158 assert isinstance(interval, collections.abc.Sequence), \
159 "Invalid value for `interval`. None, Sequence or Tuple \
160 expected."
161 # check if interval is a sequence of intervals
162 if not isinstance(interval[0], collections.abc.Sequence):
163 # find the indices corresponding to the interval
164 start_ind, end_ind = get_indices(interval)
165 value = np.sum(self.y[start_ind:end_ind])
166 multiplicity = np.sum(self.mp[start_ind:end_ind])
167 else:
168 for ival in interval:
169 # find the indices corresponding to the interval
170 start_ind, end_ind = get_indices(ival)
171 value += np.sum(self.y[start_ind:end_ind])
172 multiplicity += np.sum(self.mp[start_ind:end_ind])
173 return (value, multiplicity)
174
175 def avrg(self, interval=None, normalize=True):
176 """ Computes the average of the interval sequence:
177 :math:`a = 1/N \\sum f_n` where N is the number of intervals.
178
179 :param interval: averaging interval given as a pair of floats, a
180 sequence of pairs for averaging multiple intervals, or
181 None, if None the average over the whole function is
182 computed.
183 :type interval: Pair, sequence of pairs, or None.
184 :returns: the average a.
185 :rtype: float
186 """
187 val, mp = self.integral(interval)
188 if normalize:
189 if mp > 0:
190 return val/mp
191 else:
192 return 1.0
193 else:
194 return val
195
196 def add(self, f):
197 """ Adds another `DiscreteFunc` function to this function.
198 Note: only functions defined on the same interval can be summed.
199
200 :param f: :class:`DiscreteFunc` function to be added.
201 :rtype: None
202 """
203 assert self.x[0] == f.x[0], "The functions have different intervals"
204 assert self.x[-1] == f.x[-1], "The functions have different intervals"
205
206 # cython version
207 try:
208 from .cython.cython_add import add_discrete_function_cython as \
209 add_discrete_function_impl
210 except ImportError:
211 pyspike.NoCythonWarn()
212
213 # use python backend
214 from .cython.python_backend import add_discrete_function_python as \
215 add_discrete_function_impl
216
217 self.x, self.y, self.mp = \
218 add_discrete_function_impl(self.x, self.y, self.mp,
219 f.x, f.y, f.mp)
220
221 def mul_scalar(self, fac):
222 """ Multiplies the function with a scalar value
223
224 :param fac: Value to multiply
225 :type fac: double
226 :rtype: None
227 """
228 self.y *= fac
229
230
231 def average_profile(profiles):
232 """ Computes the average profile from the given ISI- or SPIKE-profiles.
233
234 :param profiles: list of :class:`PieceWiseConstFunc` or
235 :class:`PieceWiseLinFunc` representing ISI- or
236 SPIKE-profiles to be averaged.
237 :returns: the averages profile :math:`<S_{isi}>` or :math:`<S_{spike}>`.
238 :rtype: :class:`PieceWiseConstFunc` or :class:`PieceWiseLinFunc`
239 """
240 assert len(profiles) > 1
241
242 avrg_profile = profiles[0].copy()
243 for i in range(1, len(profiles)):
244 avrg_profile.add(profiles[i])
245 avrg_profile.mul_scalar(1.0/len(profiles)) # normalize
246
247 return avrg_profile