| 1 |
# Class representing piece-wise linear 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 |
# PieceWiseLinFunc |
| 14 |
############################################################## |
| 15 |
class PieceWiseLinFunc: |
| 16 |
""" A class representing a piece-wise linear function. """ |
| 17 |
|
| 18 |
def __init__(self, x, y1, y2): |
| 19 |
""" Constructs the piece-wise linear function. |
| 20 |
|
| 21 |
:param x: array of length N+1 defining the edges of the intervals of |
| 22 |
the pwc function. |
| 23 |
:param y1: array of length N defining the function values at the left |
| 24 |
of the intervals. |
| 25 |
:param y2: array of length N defining the function values at the right |
| 26 |
of the intervals. |
| 27 |
""" |
| 28 |
# convert to array, which also ensures copying |
| 29 |
self.x = np.array(x) |
| 30 |
self.y1 = np.array(y1) |
| 31 |
self.y2 = np.array(y2) |
| 32 |
|
| 33 |
def __call__(self, t): |
| 34 |
""" Returns the function value for the given time t. If t is a list of |
| 35 |
times, the corresponding list of values is returned. |
| 36 |
|
| 37 |
:param: time t, or list of times |
| 38 |
:returns: function value(s) at that time(s). |
| 39 |
""" |
| 40 |
def intermediate_value(x0, x1, y0, y1, x): |
| 41 |
""" computes the intermediate value of a linear function """ |
| 42 |
return y0 + (y1-y0)*(x-x0)/(x1-x0) |
| 43 |
|
| 44 |
assert np.all(t >= self.x[0]) and np.all(t <= self.x[-1]), \ |
| 45 |
"Invalid time: " + str(t) |
| 46 |
|
| 47 |
ind = np.searchsorted(self.x, t, side='right') |
| 48 |
|
| 49 |
if isinstance(t, collections.abc.Sequence): |
| 50 |
# t is a sequence of values |
| 51 |
# correct the cases t == x[0], t == x[-1] |
| 52 |
ind[ind == 0] = 1 |
| 53 |
ind[ind == len(self.x)] = len(self.x)-1 |
| 54 |
value = intermediate_value(self.x[ind-1], |
| 55 |
self.x[ind], |
| 56 |
self.y1[ind-1], |
| 57 |
self.y2[ind-1], |
| 58 |
t) |
| 59 |
# correct the values at exact spike times: there the value should |
| 60 |
# be the at half of the step |
| 61 |
# obtain the 'left' side indices for t |
| 62 |
ind_l = np.searchsorted(self.x, t, side='left') |
| 63 |
# if left and right side indices differ, the time t has to appear |
| 64 |
# in self.x |
| 65 |
ind_at_spike = np.logical_and(np.logical_and(ind != ind_l, |
| 66 |
ind > 1), |
| 67 |
ind < len(self.x)) |
| 68 |
# get the corresponding indices for the resulting value array |
| 69 |
val_ind = np.arange(len(ind))[ind_at_spike] |
| 70 |
# and for the values in self.x, y1, y2 |
| 71 |
xy_ind = ind[ind_at_spike] |
| 72 |
# the values are defined as the average of the left and right limit |
| 73 |
value[val_ind] = 0.5 * (self.y1[xy_ind-1] + self.y2[xy_ind-2]) |
| 74 |
return value |
| 75 |
else: # t is a single value |
| 76 |
# specific check for interval edges |
| 77 |
if t == self.x[0]: |
| 78 |
return self.y1[0] |
| 79 |
if t == self.x[-1]: |
| 80 |
return self.y2[-1] |
| 81 |
# check if we are on any other exact spike time |
| 82 |
if sum(self.x == t) > 0: |
| 83 |
# use the middle of the left and right Spike value |
| 84 |
return 0.5 * (self.y1[ind-1] + self.y2[ind-2]) |
| 85 |
return intermediate_value(self.x[ind-1], |
| 86 |
self.x[ind], |
| 87 |
self.y1[ind-1], |
| 88 |
self.y2[ind-1], |
| 89 |
t) |
| 90 |
|
| 91 |
def copy(self): |
| 92 |
""" Returns a copy of itself |
| 93 |
|
| 94 |
:rtype: :class:`PieceWiseLinFunc` |
| 95 |
""" |
| 96 |
return PieceWiseLinFunc(self.x, self.y1, self.y2) |
| 97 |
|
| 98 |
def almost_equal(self, other, decimal=14): |
| 99 |
""" Checks if the function is equal to another function up to `decimal` |
| 100 |
precision. |
| 101 |
|
| 102 |
:param other: another :class:`PieceWiseLinFunc` |
| 103 |
:returns: True if the two functions are equal up to `decimal` decimals, |
| 104 |
False otherwise |
| 105 |
:rtype: bool |
| 106 |
""" |
| 107 |
eps = 10.0**(-decimal) |
| 108 |
return np.allclose(self.x, other.x, atol=eps, rtol=0.0) and \ |
| 109 |
np.allclose(self.y1, other.y1, atol=eps, rtol=0.0) and \ |
| 110 |
np.allclose(self.y2, other.y2, atol=eps, rtol=0.0) |
| 111 |
|
| 112 |
def get_plottable_data(self): |
| 113 |
""" Returns two arrays containing x- and y-coordinates for immeditate |
| 114 |
plotting of the piece-wise function. |
| 115 |
|
| 116 |
:returns: (x_plot, y_plot) containing plottable data |
| 117 |
:rtype: pair of np.array |
| 118 |
|
| 119 |
Example:: |
| 120 |
|
| 121 |
x, y = f.get_plottable_data() |
| 122 |
plt.plot(x, y, '-o', label="Piece-wise const function") |
| 123 |
""" |
| 124 |
x_plot = np.empty(2*len(self.x)-2) |
| 125 |
x_plot[0] = self.x[0] |
| 126 |
x_plot[1::2] = self.x[1:] |
| 127 |
x_plot[2::2] = self.x[1:-1] |
| 128 |
y_plot = np.empty_like(x_plot) |
| 129 |
y_plot[0::2] = self.y1 |
| 130 |
y_plot[1::2] = self.y2 |
| 131 |
return x_plot, y_plot |
| 132 |
|
| 133 |
def integral(self, interval=None): |
| 134 |
""" Returns the integral over the given interval. |
| 135 |
|
| 136 |
:param interval: integration interval given as a pair of floats, if |
| 137 |
None the integral over the whole function is computed. |
| 138 |
:type interval: Pair of floats or None. |
| 139 |
:returns: the integral |
| 140 |
:rtype: float |
| 141 |
""" |
| 142 |
|
| 143 |
def intermediate_value(x0, x1, y0, y1, x): |
| 144 |
""" computes the intermediate value of a linear function """ |
| 145 |
return y0 + (y1-y0)*(x-x0)/(x1-x0) |
| 146 |
|
| 147 |
if interval is None: |
| 148 |
# no interval given, integrate over the whole spike train |
| 149 |
return np.sum((self.x[1:]-self.x[:-1]) * 0.5*(self.y1+self.y2)) |
| 150 |
|
| 151 |
# find the indices corresponding to the interval |
| 152 |
start_ind = np.searchsorted(self.x, interval[0], side='right') |
| 153 |
end_ind = np.searchsorted(self.x, interval[1], side='left')-1 |
| 154 |
assert start_ind > 0 and end_ind < len(self.x), \ |
| 155 |
"Invalid averaging interval" |
| 156 |
if start_ind > end_ind: |
| 157 |
print(start_ind, end_ind, self.x[start_ind]) |
| 158 |
# contribution from between two closest edges |
| 159 |
y_x0 = intermediate_value(self.x[start_ind-1], |
| 160 |
self.x[start_ind], |
| 161 |
self.y1[start_ind-1], |
| 162 |
self.y2[start_ind-1], |
| 163 |
interval[0]) |
| 164 |
y_x1 = intermediate_value(self.x[start_ind-1], |
| 165 |
self.x[start_ind], |
| 166 |
self.y1[start_ind-1], |
| 167 |
self.y2[start_ind-1], |
| 168 |
interval[1]) |
| 169 |
print(y_x0, y_x1, interval[1] - interval[0]) |
| 170 |
integral = (y_x0 + y_x1) * 0.5 * (interval[1] - interval[0]) |
| 171 |
print(integral) |
| 172 |
else: |
| 173 |
# first the contribution from between the indices |
| 174 |
integral = np.sum((self.x[start_ind+1:end_ind+1] - |
| 175 |
self.x[start_ind:end_ind]) * |
| 176 |
0.5*(self.y1[start_ind:end_ind] + |
| 177 |
self.y2[start_ind:end_ind])) |
| 178 |
# correction from start to first index |
| 179 |
integral += (self.x[start_ind]-interval[0]) * 0.5 * \ |
| 180 |
(self.y2[start_ind-1] + |
| 181 |
intermediate_value(self.x[start_ind-1], |
| 182 |
self.x[start_ind], |
| 183 |
self.y1[start_ind-1], |
| 184 |
self.y2[start_ind-1], |
| 185 |
interval[0])) |
| 186 |
# correction from last index to end |
| 187 |
integral += (interval[1]-self.x[end_ind]) * 0.5 * \ |
| 188 |
(self.y1[end_ind] + |
| 189 |
intermediate_value(self.x[end_ind], self.x[end_ind+1], |
| 190 |
self.y1[end_ind], self.y2[end_ind], |
| 191 |
interval[1] |
| 192 |
)) |
| 193 |
return integral |
| 194 |
|
| 195 |
def avrg(self, interval=None): |
| 196 |
""" Computes the average of the piece-wise linear function: |
| 197 |
:math:`a = 1/T \int_0^T f(x) dx` where T is the interval length. |
| 198 |
|
| 199 |
:param interval: averaging interval given as a pair of floats, a |
| 200 |
sequence of pairs for averaging multiple intervals, or |
| 201 |
None, if None the average over the whole function is |
| 202 |
computed. |
| 203 |
:type interval: Pair, sequence of pairs, or None. |
| 204 |
:returns: the average a. |
| 205 |
:rtype: float |
| 206 |
|
| 207 |
""" |
| 208 |
|
| 209 |
if interval is None: |
| 210 |
# no interval given, average over the whole spike train |
| 211 |
return self.integral() / (self.x[-1]-self.x[0]) |
| 212 |
|
| 213 |
# check if interval is as sequence |
| 214 |
assert isinstance(interval, collections.abc.Sequence), \ |
| 215 |
"Invalid value for `interval`. None, Sequence or Tuple expected." |
| 216 |
# check if interval is a sequence of intervals |
| 217 |
if not isinstance(interval[0], collections.abc.Sequence): |
| 218 |
# just one interval |
| 219 |
a = self.integral(interval) / (interval[1]-interval[0]) |
| 220 |
else: |
| 221 |
# several intervals |
| 222 |
a = 0.0 |
| 223 |
int_length = 0.0 |
| 224 |
for ival in interval: |
| 225 |
a += self.integral(ival) |
| 226 |
int_length += ival[1] - ival[0] |
| 227 |
a /= int_length |
| 228 |
return a |
| 229 |
|
| 230 |
def add(self, f): |
| 231 |
""" Adds another PieceWiseLin function to this function. |
| 232 |
Note: only functions defined on the same interval can be summed. |
| 233 |
|
| 234 |
:param f: :class:`PieceWiseLinFunc` function to be added. |
| 235 |
:rtype: None |
| 236 |
""" |
| 237 |
assert self.x[0] == f.x[0], "The functions have different intervals" |
| 238 |
assert self.x[-1] == f.x[-1], "The functions have different intervals" |
| 239 |
|
| 240 |
# python implementation |
| 241 |
# from .python_backend import add_piece_wise_lin_python |
| 242 |
# self.x, self.y1, self.y2 = add_piece_wise_lin_python( |
| 243 |
# self.x, self.y1, self.y2, f.x, f.y1, f.y2) |
| 244 |
|
| 245 |
# cython version |
| 246 |
try: |
| 247 |
from .cython.cython_add import add_piece_wise_lin_cython as \ |
| 248 |
add_piece_wise_lin_impl |
| 249 |
except ImportError: |
| 250 |
pyspike.NoCythonWarn() |
| 251 |
|
| 252 |
# use python backend |
| 253 |
from .cython.python_backend import add_piece_wise_lin_python as \ |
| 254 |
add_piece_wise_lin_impl |
| 255 |
|
| 256 |
self.x, self.y1, self.y2 = add_piece_wise_lin_impl( |
| 257 |
self.x, self.y1, self.y2, f.x, f.y1, f.y2) |
| 258 |
|
| 259 |
def mul_scalar(self, fac): |
| 260 |
""" Multiplies the function with a scalar value |
| 261 |
|
| 262 |
:param fac: Value to multiply |
| 263 |
:type fac: double |
| 264 |
:rtype: None |
| 265 |
""" |
| 266 |
self.y1 *= fac |
| 267 |
self.y2 *= fac |