Skip to content

EventArray

idea is to have abscissa and ordinate, and to use aliasing to have n_series, _series_subset, series_ids, (or trial_ids), and so on.

What is the genericized class? EventArray? eventseries, eventcollection

when event <==> spike, abscissa <==> data, eventseries <==> eventarray eventseries_id <==> series_id, eventseries_type <==> series, then we have a EventArray. (n_events, n_spikes)

series ==> series (series, trial, DIO, ...)

event rate (smooth; ds, sigma) series_id eventarray shift ISI PSTH

BaseEventArray

Bases: ABC

Base class for EventArray and BinnedEventArray.

NOTE: This class can't really be instantiated, almost like a pseudo abstract class. In particular, during initialization it might fail because it checks the n_series of its derived classes to validate input to series_ids and series_labels. If NoneTypes are used, then you may actually succeed in creating an instance of this class, but it will be pretty useless.

This docstring only applies to this base class, as subclasses may have different behavior. Therefore read the particular subclass' docstring for the most accurate information.

Parameters:

Name Type Description Default
fs

Sampling rate / frequency (Hz).

None
series_ids list of int

Unit IDs

None
series_labels list of str

Labels corresponding to series. Default casts series_ids to str.

None
series_tags optional

Tags correponding to series. NOTE: Currently we do not do any input validation so these can be any type. We also don't use these for anything yet.

None
label str

Information pertaining to the source of the event series. Default is None.

None
empty bool

Whether to create an empty class instance (no data). Default is False

False
abscissa optional

Object for the abscissa (x-axis) coordinate

None
ordinate optional

Object for the ordinate (y-axis) coordinate

None
kwargs optional

Other keyword arguments. NOTE: Currently we do not do anything with these.

{}

Attributes:

Name Type Description
n_series int

Number of series in event series.

issempty bool

Whether the class instance is empty (no data)

series_ids list of int

Unit IDs

series_labels list of str

Labels corresponding to series. Default casts series_ids to str.

series_tags

Tags corresponding to series. NOTE: Currently we do not do any input validation so these can be any type. We also don't use these for anything yet.

n_intervals int

The number of underlying intervals.

support IntervalArray

The support of the EventArray.

fs float

Sampling frequency (Hz).

label str or None

Information pertaining to the source of the event series.

Source code in nelpy/core/_eventarray.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
class BaseEventArray(ABC):
    """Base class for EventArray and BinnedEventArray.

    NOTE: This class can't really be instantiated, almost like a pseudo
    abstract class. In particular, during initialization it might fail
    because it checks the n_series of its derived classes to validate
    input to series_ids and series_labels. If NoneTypes are used, then you
    may actually succeed in creating an instance of this class, but it
    will be pretty useless.

    This docstring only applies to this base class, as subclasses may have
    different behavior. Therefore read the particular subclass' docstring
    for the most accurate information.

    Parameters
    ----------
    fs: float, optional
        Sampling rate / frequency (Hz).
    series_ids : list of int, optional
        Unit IDs
    series_labels : list of str, optional
        Labels corresponding to series. Default casts series_ids to str.
    series_tags : optional
        Tags correponding to series.
        NOTE: Currently we do not do any input validation so these can
        be any type. We also don't use these for anything yet.
    label : str, optional
        Information pertaining to the source of the event series.
        Default is None.
    empty : bool, optional
        Whether to create an empty class instance (no data).
        Default is False
    abscissa : optional
        Object for the abscissa (x-axis) coordinate
    ordinate : optional
        Object for the ordinate (y-axis) coordinate
    kwargs : optional
        Other keyword arguments. NOTE: Currently we do not do anything
        with these.

    Attributes
    ----------
    n_series : int
        Number of series in event series.
    issempty : bool
        Whether the class instance is empty (no data)
    series_ids : list of int
        Unit IDs
    series_labels : list of str
        Labels corresponding to series. Default casts series_ids to str.
    series_tags :
        Tags corresponding to series.
        NOTE: Currently we do not do any input validation so these can
        be any type. We also don't use these for anything yet.
    n_intervals : int
        The number of underlying intervals.
    support : nelpy.IntervalArray
        The support of the EventArray.
    fs: float
        Sampling frequency (Hz).
    label : str or None
        Information pertaining to the source of the event series.
    """

    __aliases__ = {}

    __attributes__ = ["_fs", "_series_ids", "_series_labels", "_series_tags", "_label"]

    def __init__(
        self,
        *,
        fs=None,
        series_ids=None,
        series_labels=None,
        series_tags=None,
        label=None,
        empty=False,
        abscissa=None,
        ordinate=None,
        **kwargs,
    ):
        self.__version__ = version.__version__
        self.type_name = self.__class__.__name__
        if abscissa is None:
            abscissa = core.Abscissa()  # TODO: integrate into constructor?
        if ordinate is None:
            ordinate = core.Ordinate()  # TODO: integrate into constructor?
        self._abscissa = abscissa
        self._ordinate = ordinate

        series_label = kwargs.pop("series_label", None)
        if series_label is None:
            series_label = "series"
        self._series_label = series_label

        # if an empty object is requested, return it:
        if empty:
            for attr in self.__attributes__:
                exec("self." + attr + " = None")
            self._abscissa.support = type(self._abscissa.support)(empty=True)
            self.loc = _accessors.ItemGetterLoc(self)
            self.iloc = _accessors.ItemGetterIloc(self)
            return

        # set initial fs to None
        self._fs = None
        # then attempt to update the fs; this does input validation:
        self.fs = fs

        # WARNING! we need to ensure that self.n_series can work BEFORE
        # we can set self.series_ids or self.series_labels, since those
        # setters check that the lengths of the inputs are consistent
        # with self.n_series.

        # inherit series IDs if available, otherwise initialize to default
        if series_ids is None:
            series_ids = list(range(1, self.n_series + 1))

        series_ids = np.array(series_ids, ndmin=1)  # standardize series_ids

        # if series_labels is empty, default to series_ids
        if series_labels is None:
            series_labels = series_ids

        series_labels = np.array(series_labels, ndmin=1)  # standardize

        self.series_ids = series_ids
        self.series_labels = series_labels
        self._series_tags = series_tags  # no input validation yet
        self.label = label

        self.loc = _accessors.ItemGetterLoc(self)
        self.iloc = _accessors.ItemGetterIloc(self)

    def __renew__(self):
        """Re-attach slicers and indexers."""
        self.loc = _accessors.ItemGetterLoc(self)
        self.iloc = _accessors.ItemGetterIloc(self)

    def __repr__(self):
        address_str = " at " + str(hex(id(self)))
        return "<BaseEventArray" + address_str + ">"

    @abstractmethod
    @keyword_equivalence(this_or_that={"n_intervals": "n_epochs"})
    def partition(self, ds=None, n_intervals=None):
        """
        Returns a BaseEventArray whose support has been partitioned.

        Parameters
        ----------
        ds : float, optional
            Maximum duration (in seconds), for each interval.
        n_intervals : int, optional
            Number of intervals. If ds is None and n_intervals is None, then
            default is to use n_intervals = 100

        Returns
        -------
        out : BaseEventArray
            BaseEventArray that has been partitioned.

        Notes
        -----
        Irrespective of whether 'ds' or 'n_intervals' are used, the exact
        underlying support is propagated, and the first and last points
        of the supports are always included, even if this would cause
        n_points or ds to be violated.
        """
        return

    @abstractmethod
    def isempty(self):
        """(bool) Empty BaseEventArray."""
        return

    @abstractmethod
    def n_series(self):
        """(int) The number of series."""
        return

    @property
    def n_intervals(self):
        if self.isempty:
            return 0
        """(int) The number of underlying intervals."""
        return self._abscissa.support.n_intervals

    @property
    def series_ids(self):
        """Unit IDs contained in the BaseEventArray."""
        return self._series_ids

    @series_ids.setter
    def series_ids(self, val):
        if len(val) != self.n_series:
            raise TypeError("series_ids must be of length n_series")
        elif len(set(val)) < len(val):
            raise TypeError("duplicate series_ids are not allowed")
        else:
            try:
                # cast to int:
                series_ids = [int(id) for id in val]
            except TypeError:
                raise TypeError("series_ids must be int-like")
        self._series_ids = series_ids

    @property
    def series_labels(self):
        """Labels corresponding to series contained in the BaseEventArray."""
        if self._series_labels is None:
            logging.warning("series labels have not yet been specified")
            return self.series_ids
        return self._series_labels

    @series_labels.setter
    def series_labels(self, val):
        if len(val) != self.n_series:
            raise TypeError("labels must be of length n_series")
        else:
            try:
                # cast to str:
                labels = [str(label) for label in val]
            except TypeError:
                raise TypeError("labels must be string-like")
        self._series_labels = labels

    @property
    def series_tags(self):
        """Tags corresponding to series contained in the BaseEventArray"""
        if self._series_tags is None:
            logging.warning("series tags have not yet been specified")
        return self._series_tags

    @property
    def support(self):
        """(nelpy.IntervalArray) The support of the EventArray."""
        return self._abscissa.support

    @support.setter
    def support(self, val):
        """(nelpy.IntervalArray) The support of the EventArray."""
        # modify support
        if isinstance(val, type(self._abscissa.support)):
            self._abscissa.support = val
        elif isinstance(val, (tuple, list)):
            prev_domain = self._abscissa.domain
            self._abscissa.support = type(self._abscissa.support)([val[0], val[1]])
            self._abscissa.domain = prev_domain
        else:
            raise TypeError(
                "support must be of type {}".format(str(type(self._abscissa.support)))
            )
        # restrict data to new support
        self._restrict_to_interval(self._abscissa.support)

    @property
    def domain(self):
        """(nelpy.IntervalArray) The domain of the EventArray."""
        return self._abscissa.domain

    @domain.setter
    def domain(self, val):
        """(nelpy.IntervalArray) The domain of the EventArray."""
        # modify domain
        if isinstance(val, type(self._abscissa.support)):
            self._abscissa.domain = val
        elif isinstance(val, (tuple, list)):
            self._abscissa.domain = type(self._abscissa.support)([val[0], val[1]])
        else:
            raise TypeError(
                "support must be of type {}".format(str(type(self._abscissa.support)))
            )
        # restrict data to new support
        self._restrict_to_interval(self._abscissa.support)

    @property
    def fs(self):
        """(float) Sampling rate."""
        return self._fs

    @fs.setter
    def fs(self, val):
        """(float) Sampling rate."""
        if self._fs == val:
            return
        try:
            if val <= 0:
                raise ValueError("sampling rate must be positive")
        except TypeError:
            raise TypeError("sampling rate must be a scalar")
        self._fs = val

    @property
    def label(self):
        """Label pertaining to the source of the event series."""
        if self._label is None:
            logging.warning("label has not yet been specified")
        return self._label

    @label.setter
    def label(self, val):
        if val is not None:
            try:  # cast to str:
                label = str(val)
            except TypeError:
                raise TypeError("cannot convert label to string")
        else:
            label = val
        self._label = label

    def _series_subset(self, series_list):
        """Return a BaseEventArray restricted to a subset of series.

        Parameters
        ----------
        series_list : array-like
            Array or list of series_ids.
        """
        return self.loc[:, series_list]

    def __setattr__(self, name, value):
        # https://stackoverflow.com/questions/4017572/how-can-i-make-an-alias-to-a-non-function-member-attribute-in-a-python-class
        name = self.__aliases__.get(name, name)
        object.__setattr__(self, name, value)

    def __getattr__(self, name):
        # https://stackoverflow.com/questions/4017572/how-can-i-make-an-alias-to-a-non-function-member-attribute-in-a-python-class
        if name == "aliases":
            raise AttributeError  # http://nedbatchelder.com/blog/201010/surprising_getattr_recursion.html
        name = self.__aliases__.get(name, name)
        # return getattr(self, name) #Causes infinite recursion on non-existent attribute
        return object.__getattribute__(self, name)

domain property writable

(nelpy.IntervalArray) The domain of the EventArray.

fs property writable

(float) Sampling rate.

label property writable

Label pertaining to the source of the event series.

series_ids property writable

Unit IDs contained in the BaseEventArray.

series_labels property writable

Labels corresponding to series contained in the BaseEventArray.

series_tags property

Tags corresponding to series contained in the BaseEventArray

support property writable

(nelpy.IntervalArray) The support of the EventArray.

isempty() abstractmethod

(bool) Empty BaseEventArray.

Source code in nelpy/core/_eventarray.py
208
209
210
211
@abstractmethod
def isempty(self):
    """(bool) Empty BaseEventArray."""
    return

n_series() abstractmethod

(int) The number of series.

Source code in nelpy/core/_eventarray.py
213
214
215
216
@abstractmethod
def n_series(self):
    """(int) The number of series."""
    return

partition(ds=None, n_intervals=None) abstractmethod

Returns a BaseEventArray whose support has been partitioned.

Parameters:

Name Type Description Default
ds float

Maximum duration (in seconds), for each interval.

None
n_intervals int

Number of intervals. If ds is None and n_intervals is None, then default is to use n_intervals = 100

None

Returns:

Name Type Description
out BaseEventArray

BaseEventArray that has been partitioned.

Notes

Irrespective of whether 'ds' or 'n_intervals' are used, the exact underlying support is propagated, and the first and last points of the supports are always included, even if this would cause n_points or ds to be violated.

Source code in nelpy/core/_eventarray.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
@abstractmethod
@keyword_equivalence(this_or_that={"n_intervals": "n_epochs"})
def partition(self, ds=None, n_intervals=None):
    """
    Returns a BaseEventArray whose support has been partitioned.

    Parameters
    ----------
    ds : float, optional
        Maximum duration (in seconds), for each interval.
    n_intervals : int, optional
        Number of intervals. If ds is None and n_intervals is None, then
        default is to use n_intervals = 100

    Returns
    -------
    out : BaseEventArray
        BaseEventArray that has been partitioned.

    Notes
    -----
    Irrespective of whether 'ds' or 'n_intervals' are used, the exact
    underlying support is propagated, and the first and last points
    of the supports are always included, even if this would cause
    n_points or ds to be violated.
    """
    return

BinnedEventArray

Bases: BaseEventArray

BinnedEventArray.

Parameters:

Name Type Description Default
eventarray EventArray or RegularlySampledAnalogSignalArray

Input data.

None
ds float

The bin width, in seconds. Default is 0.0625 (62.5 ms)

None
empty bool

Whether an empty BinnedEventArray should be constructed (no data).

False
fs float

Sampling rate in Hz. If fs is passed as a parameter, then data is assumed to be in sample numbers instead of actual data.

required
kwargs optional

Additional keyword arguments to forward along to the BaseEventArray constructor.

{}

Attributes:

Name Type Description
Note Read the docstring for the BaseEventArray superclass for additional
attributes that are defined there.
isempty bool

Whether the BinnedEventArray is empty (no data).

n_series int

The number of series.

bin_centers ndarray

The bin centers, in seconds.

event_centers ndarray

The centers of each event, in seconds.

data np.array, with shape (n_series, n_bins)

Event counts in all bins.

bins ndarray

The bin edges, in seconds.

binned_support np.ndarray, with shape (n_intervals, 2)

The binned support of the BinnedEventArray (in bin IDs).

lengths ndarray

Lengths of contiguous segments, in number of bins.

eventarray EventArray

The original eventarray associated with the binned data.

n_bins int

The number of bins.

ds float

Bin width, in seconds.

n_active int

The number of active series. A series is considered active if it fired at least one event.

n_active_per_bin np.ndarray, with shape (n_bins, )

Number of active series per data bin.

n_events ndarray

The number of events in each series.

support IntervalArray

The support of the BinnedEventArray.

Source code in nelpy/core/_eventarray.py
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
class BinnedEventArray(BaseEventArray):
    """BinnedEventArray.

    Parameters
    ----------
    eventarray : nelpy.EventArray or nelpy.RegularlySampledAnalogSignalArray
        Input data.
    ds : float
        The bin width, in seconds.
        Default is 0.0625 (62.5 ms)
    empty : bool, optional
        Whether an empty BinnedEventArray should be constructed (no data).
    fs : float, optional
        Sampling rate in Hz. If fs is passed as a parameter, then data
        is assumed to be in sample numbers instead of actual data.
    kwargs : optional
        Additional keyword arguments to forward along to the BaseEventArray
        constructor.

    Attributes
    ----------
    Note : Read the docstring for the BaseEventArray superclass for additional
    attributes that are defined there.
    isempty : bool
        Whether the BinnedEventArray is empty (no data).
    n_series : int
        The number of series.
    bin_centers : np.ndarray
        The bin centers, in seconds.
    event_centers : np.ndarray
        The centers of each event, in seconds.
    data : np.array, with shape (n_series, n_bins)
        Event counts in all bins.
    bins : np.ndarray
        The bin edges, in seconds.
    binned_support : np.ndarray, with shape (n_intervals, 2)
        The binned support of the BinnedEventArray (in
        bin IDs).
    lengths : np.ndarray
        Lengths of contiguous segments, in number of bins.
    eventarray : nelpy.EventArray
        The original eventarray associated with the binned data.
    n_bins : int
        The number of bins.
    ds : float
        Bin width, in seconds.
    n_active : int
        The number of active series. A series is considered active if
        it fired at least one event.
    n_active_per_bin : np.ndarray, with shape (n_bins, )
        Number of active series per data bin.
    n_events : np.ndarray
        The number of events in each series.
    support : nelpy.IntervalArray
        The support of the BinnedEventArray.
    """

    __attributes__ = [
        "_ds",
        "_bins",
        "_data",
        "_bin_centers",
        "_binned_support",
        "_eventarray",
    ]
    __attributes__.extend(BaseEventArray.__attributes__)

    def __init__(self, eventarray=None, *, ds=None, empty=False, **kwargs):
        super().__init__(empty=True)

        # if an empty object is requested, return it:
        if empty:
            # super().__init__(empty=True)
            for attr in self.__attributes__:
                exec("self." + attr + " = None")
            self._abscissa.support = type(self._abscissa.support)(empty=True)
            self._event_centers = None
            return

        # handle casting other nelpy objects to BinnedEventArray:
        if isinstance(eventarray, core.RegularlySampledAnalogSignalArray):
            if eventarray.isempty:
                for attr in self.__attributes__:
                    exec("self." + attr + " = None")
                self._abscissa.support = type(eventarray._abscissa.support)(empty=True)
                self._event_centers = None
                return
            eventarray = eventarray.copy()  # Note: this is a deep copy
            n_empty_epochs = np.sum(eventarray.support.lengths == 0)
            if n_empty_epochs > 0:
                logging.warning(
                    "Detected {} empty epochs. Removing these in the cast object".format(
                        n_empty_epochs
                    )
                )
                eventarray.support = eventarray.support._drop_empty_intervals()
            if not eventarray.support.ismerged:
                logging.warning(
                    "Detected overlapping epochs. Merging these in the cast object"
                )
                eventarray.support = eventarray.support.merge()

            self._eventarray = None
            self._ds = 1 / eventarray.fs
            self._series_labels = eventarray._series_labels
            self._bin_centers = eventarray.abscissa_vals
            tmp = np.insert(np.cumsum(eventarray.lengths), 0, 0)
            self._binned_support = np.array((tmp[:-1], tmp[1:] - 1)).T
            self._abscissa.support = eventarray.support
            try:
                self._series_ids = (
                    np.array(eventarray.series_labels).astype(int)
                ).tolist()
            except (ValueError, TypeError):
                self._series_ids = (np.arange(eventarray.n_signals) + 1).tolist()
            self._data = eventarray._ydata_rowsig

            bins = []
            for starti, stopi in self._binned_support:
                bins_edges_in_interval = (
                    self._bin_centers[starti : stopi + 1] - self._ds / 2
                ).tolist()
                bins_edges_in_interval.append(self._bin_centers[stopi] + self._ds / 2)
                bins.extend(bins_edges_in_interval)
            self._bins = np.array(bins)
            return

        if type(eventarray).__name__ == "BinnedSpikeTrainArray":
            # old-style nelpy BinnedSpikeTrainArray object?
            try:
                self._eventarray = eventarray._spiketrainarray
                self._ds = eventarray.ds
                self._series_labels = eventarray.unit_labels
                self._bin_centers = eventarray.bin_centers
                self._binned_support = eventarray.binned_support
                try:
                    self._abscissa.support = core.EpochArray(eventarray.support.data)
                except AttributeError:
                    self._abscissa.support = core.EpochArray(eventarray.support.time)
                self._series_ids = eventarray.unit_ids
                self._data = eventarray.data
                return
            except Exception:
                pass

        if not isinstance(eventarray, EventArray):
            raise TypeError("eventarray must be a nelpy.EventArray object.")

        self._ds = None
        self._bin_centers = np.array([])
        self._event_centers = None

        logging.disable(logging.CRITICAL)
        kwargs = {
            "fs": eventarray.fs,
            "series_ids": eventarray.series_ids,
            "series_labels": eventarray.series_labels,
            "series_tags": eventarray.series_tags,
            "label": eventarray.label,
        }
        logging.disable(0)

        # initialize super so that self.fs is set:
        self._data = np.zeros((eventarray.n_series, 0))
        # the above is necessary so that super() can determine
        # self.n_series when initializing. self.data will
        # be updated later in __init__ to reflect subsequent changes
        super().__init__(**kwargs)

        if ds is None:
            logging.warning("no bin size was given, assuming 62.5 ms")
            ds = 0.0625

        self._eventarray = eventarray  # TODO: remove this if we don't need it, or decide that it's too wasteful
        self._abscissa = copy.deepcopy(eventarray._abscissa)
        self.ds = ds

        self._bin_events(eventarray=eventarray, intervalArray=eventarray.support, ds=ds)

    def __mul__(self, other):
        """Overloaded * operator"""

        if isinstance(other, numbers.Number):
            neweva = self.copy()
            neweva._data = self.data * other
            return neweva
        elif isinstance(other, np.ndarray):
            neweva = self.copy()
            neweva._data = (self.data.T * other).T
            return neweva
        else:
            raise TypeError(
                "unsupported operand type(s) for *: '{}' and '{}'".format(
                    str(type(self)), str(type(other))
                )
            )

    def __rmul__(self, other):
        """Overloaded * operator"""
        return self.__mul__(other)

    def __sub__(self, other):
        """Overloaded - operator"""
        if isinstance(other, numbers.Number):
            neweva = self.copy()
            neweva._data = self.data - other
            return neweva
        elif isinstance(other, np.ndarray):
            neweva = self.copy()
            neweva._data = (self.data.T - other).T
            return neweva
        else:
            raise TypeError(
                "unsupported operand type(s) for -: '{}' and '{}'".format(
                    str(type(self)), str(type(other))
                )
            )

    def __add__(self, other):
        """Overloaded + operator"""

        if isinstance(other, numbers.Number):
            neweva = self.copy()
            neweva._data = self.data + other
            return neweva
        elif isinstance(other, np.ndarray):
            neweva = self.copy()
            neweva._data = (self.data.T + other).T
            return neweva
        elif isinstance(other, type(self)):
            # TODO: additional checks need to be done, e.g., same series ids...
            assert self.n_series == other.n_series
            support = self._abscissa.support + other.support

            newdata = []
            for series in range(self.n_series):
                newdata.append(np.append(self.data[series], other.data[series]))

            fs = self.fs
            if self.fs != other.fs:
                fs = None
            return type(self)(newdata, support=support, fs=fs)
        else:
            raise TypeError(
                "unsupported operand type(s) for +: '{}' and '{}'".format(
                    str(type(self)), str(type(other))
                )
            )

    def __truediv__(self, other):
        """Overloaded / operator"""

        if isinstance(other, numbers.Number):
            neweva = self.copy()
            neweva._data = self.data / other
            return neweva
        elif isinstance(other, np.ndarray):
            neweva = self.copy()
            neweva._data = (self.data.T / other).T
            return neweva
        else:
            raise TypeError(
                "unsupported operand type(s) for /: '{}' and '{}'".format(
                    str(type(self)), str(type(other))
                )
            )

    def median(self, *, axis=1):
        """Returns the median of each series in BinnedEventArray."""
        try:
            medians = np.nanmedian(self.data, axis=axis).squeeze()
            if medians.size == 1:
                return medians.item()
            return medians
        except IndexError:
            raise IndexError("Empty BinnedEventArray; cannot calculate median.")

    def mean(self, *, axis=1):
        """Returns the mean of each series in BinnedEventArray."""
        try:
            means = np.nanmean(self.data, axis=axis).squeeze()
            if means.size == 1:
                return means.item()
            return means
        except IndexError:
            raise IndexError("Empty BinnedEventArray; cannot calculate mean.")

    def std(self, *, axis=1):
        """Returns the standard deviation of each series in BinnedEventArray."""
        try:
            stds = np.nanstd(self.data, axis=axis).squeeze()
            if stds.size == 1:
                return stds.item()
            return stds
        except IndexError:
            raise IndexError(
                "Empty BinnedEventArray; cannot calculate standard deviation"
            )

    def center(self, inplace=False):
        """Center data (zero mean)."""
        if inplace:
            out = self
        else:
            out = self.copy()
        out._data = (out._data.T - out.mean()).T
        return out

    def normalize(self, inplace=False):
        """Normalize data (unit standard deviation)."""
        if inplace:
            out = self
        else:
            out = self.copy()
        std = out.std()
        std[std == 0] = 1
        out._data = (out._data.T / std).T
        return out

    def standardize(self, inplace=False):
        """Standardize data (zero mean and unit std deviation)."""
        if inplace:
            out = self
        else:
            out = self.copy()
        out._data = (out._data.T - out.mean()).T
        std = out.std()
        std[std == 0] = 1
        out._data = (out._data.T / std).T

        return out

    @keyword_equivalence(this_or_that={"n_intervals": "n_epochs"})
    def partition(self, ds=None, n_intervals=None):
        """Returns a BaseEventArray whose support has been partitioned.

        Parameters
        ----------
        ds : float, optional
            Maximum duration (in seconds), for each interval.
        n_points : int, optional
            Number of intervals. If ds is None and n_intervals is None, then
            default is to use n_intervals = 100

        Returns
        -------
        out : BaseEventArray
            BaseEventArray that has been partitioned.

        Notes
        -----
        Irrespective of whether 'ds' or 'n_intervals' are used, the exact
        of the supports are always included, even if this would cause
        n_points or ds to be violated.
        """

        partitioned = type(self)(
            core.RegularlySampledAnalogSignalArray(self).partition(
                ds=ds, n_intervals=n_intervals
            )
        )
        # partitioned.loc = ItemGetter_loc(partitioned)
        # partitioned.iloc = ItemGetter_iloc(partitioned)
        return partitioned

        # raise NotImplementedError('workaround: cast to AnalogSignalArray, partition, and cast back to BinnedEventArray')

    def _copy_without_data(self):
        """Returns a copy of the BinnedEventArray, without data.
        Note: the support is left unchanged, but the binned_support is removed.
        """
        out = copy.copy(self)  # shallow copy
        out._bin_centers = None
        out._binned_support = None
        out._bins = None
        out._data = np.zeros((self.n_series, 0))
        out._eventarray = out._eventarray._copy_without_data()
        out = copy.deepcopy(
            out
        )  # just to be on the safe side, but at least now we are not copying the data!
        out.__renew__()
        return out

    def copy(self):
        """Returns a copy of the BinnedEventArray."""
        newcopy = copy.deepcopy(self)
        newcopy.__renew__()
        return newcopy

    def __repr__(self):
        address_str = " at " + str(hex(id(self)))
        if self.isempty:
            return "<empty " + self.type_name + address_str + ">"
        # Summarize labels if too many
        max_display = 5
        labels = self._series_labels
        n = len(labels)
        if n <= max_display:
            label_str = str(labels)
        else:
            label_str = f"[{', '.join(map(str, labels[:3]))}, ..., {', '.join(map(str, labels[-2:]))}]"
        ustr = f" {self.n_series} {label_str}"
        if self._abscissa.support.n_intervals > 1:
            epstr = f" ({self._abscissa.support.n_intervals} segments) in"
        else:
            epstr = " in"
        if self.n_bins == 1:
            bstr = f" {self.n_bins} bin of width {utils.PrettyDuration(self.ds)}"
            dstr = ""
        else:
            bstr = f" {self.n_bins} bins of width {utils.PrettyDuration(self.ds)}"
            dstr = f" for a total of {utils.PrettyDuration(self.n_bins * self.ds)}"
        return f"<{self.type_name}{address_str}:{ustr}{epstr}{bstr}>{dstr}"

    def __iter__(self):
        """BinnedEventArray iterator initialization."""
        # initialize the internal index to zero when used as iterator
        self._index = 0
        return self

    def __next__(self):
        """BinnedEventArray iterator advancer."""
        index = self._index

        if index > self._abscissa.support.n_intervals - 1:
            raise StopIteration

        # TODO: return self.loc[index], and make sure that __getitem__ is updated
        logging.disable(logging.CRITICAL)
        support = self._abscissa.support[index]
        bsupport = self.binned_support[[index], :]

        binnedeventarray = type(self)(empty=True)
        exclude = ["_bins", "_data", "_support", "_bin_centers", "_binned_support"]
        attrs = (x for x in self.__attributes__ if x not in exclude)
        for attr in attrs:
            exec("binnedeventarray." + attr + " = self." + attr)
        binindices = np.insert(0, 1, np.cumsum(self.lengths + 1))  # indices of bins
        binstart = binindices[index]
        binstop = binindices[index + 1]
        binnedeventarray._bins = self._bins[binstart:binstop]
        binnedeventarray._data = self._data[:, bsupport[0][0] : bsupport[0][1] + 1]
        binnedeventarray._abscissa.support = support
        binnedeventarray._bin_centers = self._bin_centers[
            bsupport[0][0] : bsupport[0][1] + 1
        ]
        binnedeventarray._binned_support = bsupport - bsupport[0, 0]
        logging.disable(0)
        self._index += 1
        binnedeventarray.__renew__()
        return binnedeventarray

    def empty(self, *, inplace=False):
        """Remove data (but not metadata) from BinnedEventArray.

        Attributes 'data', and 'support' 'binned_support' are all emptied.

        Note: n_series, series_ids, etc. are all preserved.
        """
        if not inplace:
            out = self._copy_without_data()
            out._abscissa.support = type(self._abscissa.support)(empty=True)
            return out
        out = self
        out._data = np.zeros((self.n_series, 0))
        out._abscissa.support = type(self._abscissa.support)(empty=True)
        out._binned_support = None
        out._bin_centers = None
        out._bins = None
        out._eventarray.empty(inplace=True)
        out.__renew__()
        return out

    def __getitem__(self, idx):
        """BinnedEventArray index access.

        By default, this method is bound to .loc
        """
        return self.loc[idx]

    def _restrict(self, intervalslice, seriesslice):
        # This function should be called only by an itemgetter
        # because it mutates data.
        # The itemgetter is responsible for creating copies
        # of objects

        self._restrict_to_series_subset(seriesslice)
        self._eventarray._restrict_to_series_subset(seriesslice)

        self._restrict_to_interval(intervalslice)
        self._eventarray._restrict_to_interval(intervalslice)
        return self

    def _restrict_to_series_subset(self, idx):
        # Warning: This function can mutate data

        if isinstance(idx, core.IntervalArray):
            raise IndexError(
                "Slicing is [intervals, signal]; perhaps you have the order reversed?"
            )

        # TODO: update tags
        try:
            self._data = np.atleast_2d(self.data[idx, :])
            self._series_ids = list(np.atleast_1d(np.atleast_1d(self._series_ids)[idx]))
            self._series_labels = list(
                np.atleast_1d(np.atleast_1d(self._series_labels)[idx])
            )
        except IndexError:
            raise IndexError(
                "One of more indices were out of bounds for n_series with size {}".format(
                    self.n_series
                )
            )
        except Exception:
            raise TypeError("Unsupported indexing type {}".format(type(idx)))

    def _restrict_to_interval(self, intervalslice):
        # Warning: This function can mutate data. It should only be called from
        # _restrict

        if isinstance(intervalslice, slice):
            if (
                intervalslice.start is None
                and intervalslice.stop is None
                and intervalslice.step is None
            ):
                # no restriction on interval
                return self

        newintervals = self._abscissa.support[intervalslice].merge()
        if newintervals.isempty:
            logging.warning("Index resulted in empty interval array")
            return self.empty(inplace=True)

        bcenter_inds = []
        bin_inds = []
        start = 0
        bsupport = np.zeros((newintervals.n_intervals, 2), dtype=int)
        support_intervals = np.zeros((newintervals.n_intervals, 2))

        if not self.isempty:
            for ii, interval in enumerate(newintervals.data):
                a_start = interval[0]
                a_stop = interval[1]
                frm, to = np.searchsorted(self._bins, (a_start, a_stop))
                # If bin edges equal a_stop, they should still be included
                if self._bins[to] <= a_stop:
                    bin_inds.extend(np.arange(frm, to + 1, step=1))
                else:
                    bin_inds.extend(np.arange(frm, to, step=1))
                    to -= 1
                support_intervals[ii] = [self._bins[frm], self._bins[to]]

                lind, rind = np.searchsorted(
                    self._bin_centers, (self._bins[frm], self._bins[to])
                )
                # We don't have to worry about an if-else block here unlike
                # for the bin_inds because the bin_centers can NEVER equal
                # the bins. Therefore we know every interval looks like
                # the following:
                #  first desired bin         last desired bin
                # |------------------|......|-------------------|
                #          ^                                         ^
                #          |                                         |
                #        lind                                      rind
                # Since arange is half-open, the indices we actually take
                # will be such that all bin centers fall within the desired
                # bin edges.
                bcenter_inds.extend(np.arange(lind, rind, step=1))

                bsupport[ii] = [start, start + (to - frm - 1)]
                start += to - frm

            self._bins = self._bins[bin_inds]
            self._bin_centers = self._bin_centers[bcenter_inds]
            self._data = np.atleast_2d(self._data[:, bcenter_inds])
            self._binned_support = bsupport

        self._abscissa.support = type(self._abscissa.support)(support_intervals)

    @property
    def isempty(self):
        """(bool) Empty BinnedEventArray."""
        try:
            return len(self.bin_centers) == 0
        except TypeError:
            return True  # this happens when self.bin_centers is None

    @property
    def n_series(self):
        """(int) The number of series."""
        try:
            return utils.PrettyInt(self.data.shape[0])
        except AttributeError:
            return 0

    @property
    def centers(self):
        """(np.array) The bin centers (in seconds)."""
        logging.warning("centers is deprecated. Use bin_centers instead.")
        return self.bin_centers

    @property
    def _abscissa_vals(self):
        """(np.array) The bin centers (in seconds)."""
        return self._bin_centers

    @property
    def bin_centers(self):
        """(np.array) The bin centers (in seconds)."""
        return self._bin_centers

    @property
    def event_centers(self):
        """(np.array) The centers (in seconds) of each event."""
        if self._event_centers is None:
            raise NotImplementedError("event_centers not yet implemented")
            # self._event_centers = midpoints
        return self._event_centers

    @property
    def _midpoints(self):
        """(np.array) The centers (in index space) of all events.

        Examples
        -------
        ax, img = npl.imagesc(bst.data) # data is of shape (n_series, n_bins)
        # then _midpoints correspond to the xvals at the center of
        # each event.
        ax.plot(bst.event_centers, np.repeat(1, self.n_intervals), marker='o', color='w')

        """
        if self._event_centers is None:
            midpoints = np.zeros(len(self.lengths))
            for idx, length in enumerate(self.lengths):
                midpoints[idx] = np.sum(self.lengths[:idx]) + length / 2
            self._event_centers = midpoints
        return self._event_centers

    @property
    def data(self):
        """(np.array) Event counts in all bins, with shape (n_series, n_bins)."""
        return self._data

    @property
    def bins(self):
        """(np.array) The bin edges (in seconds)."""
        return self._bins

    @property
    def binnedSupport(self):
        """(np.array) The binned support of the BinnedEventArray (in
        bin IDs) of shape (n_intervals, 2).
        """
        logging.warning("binnedSupport is deprecated. Use bined_support instead.")
        return self._binned_support

    @property
    def binned_support(self):
        """(np.array) The binned support of the BinnedEventArray (in
        bin IDs) of shape (n_intervals, 2).
        """
        return self._binned_support

    @property
    def lengths(self):
        """Lengths of contiguous segments, in number of bins."""
        if self.isempty:
            return 0
        return np.atleast_1d(
            (self.binned_support[:, 1] - self.binned_support[:, 0] + 1).squeeze()
        )

    @property
    def eventarray(self):
        """(nelpy.EventArray) The original EventArray associated with
        the binned data.
        """
        return self._eventarray

    @property
    def n_bins(self):
        """(int) The number of bins."""
        if self.isempty:
            return 0
        return utils.PrettyInt(len(self.bin_centers))

    @property
    def ds(self):
        """(float) Bin width in seconds."""
        return self._ds

    @ds.setter
    def ds(self, val):
        if self._ds is not None:
            raise AttributeError("can't set attribute")
        else:
            try:
                if val <= 0:
                    pass
            except ValueError:
                raise TypeError("bin width must be a scalar")
            if val <= 0:
                raise ValueError("bin width must be positive")
            self._ds = val

    @staticmethod
    def _get_bins_inside_interval(interval, ds):
        """(np.array) Return bin edges entirely contained inside an interval.

        Bin edges always start at interval.start, and continue for as many
        bins as would fit entirely inside the interval.

        NOTE 1: there are (n+1) bin edges associated with n bins.

        WARNING: if an interval is smaller than ds, then no bin will be
                associated with the particular interval.

        NOTE 2: nelpy uses half-open intervals [a,b), but if the bin
                width divides b-a, then the bins will cover the entire
                range. For example, if interval = [0,2) and ds = 1, then
                bins = [0,1,2], even though [0,2] is not contained in
                [0,2).

        Parameters
        ----------
        interval : IntervalArray
            IntervalArray containing a single interval with a start, and stop
        ds : float
            Time bin width, in seconds.

        Returns
        -------
        bins : array
            Bin edges in an array of shape (n+1,) where n is the number
            of bins
        centers : array
            Bin centers in an array of shape (n,) where n is the number
            of bins
        """

        if interval.length < ds:
            logging.warning("interval duration is less than bin size: ignoring...")
            return None, None

        n = int(np.floor(interval.length / ds))  # number of bins

        # linspace is better than arange for non-integral steps
        bins = np.linspace(interval.start, interval.start + n * ds, n + 1)
        centers = bins[:-1] + (ds / 2)
        return bins, centers

    def _bin_events(self, eventarray, intervalArray, ds):
        """
        Docstring goes here. TBD. For use with bins that are contained
        wholly inside the intervals.

        """
        b = []  # bin list
        c = []  # centers list
        s = []  # data list
        for nn in range(eventarray.n_series):
            s.append([])
        left_edges = []
        right_edges = []
        counter = 0
        for interval in intervalArray:
            bins, centers = self._get_bins_inside_interval(interval, ds)
            if bins is not None:
                for uu, eventarraydatas in enumerate(eventarray.data):
                    event_counts, _ = np.histogram(
                        eventarraydatas,
                        bins=bins,
                        density=False,
                        range=(interval.start, interval.stop),
                    )  # TODO: is it faster to limit range, or to cut out events?
                    s[uu].extend(event_counts.tolist())
                left_edges.append(counter)
                counter += len(centers) - 1
                right_edges.append(counter)
                counter += 1
                b.extend(bins.tolist())
                c.extend(centers.tolist())
        self._bins = np.array(b)
        self._bin_centers = np.array(c)
        self._data = np.array(s)
        le = np.array(left_edges)
        le = le[:, np.newaxis]
        re = np.array(right_edges)
        re = re[:, np.newaxis]
        self._binned_support = np.hstack((le, re))
        support_starts = self.bins[np.insert(np.cumsum(self.lengths + 1), 0, 0)[:-1]]
        support_stops = self.bins[np.insert(np.cumsum(self.lengths + 1) - 1, 0, 0)[1:]]
        supportdata = np.vstack([support_starts, support_stops]).T
        self._abscissa.support = type(self._abscissa.support)(
            supportdata
        )  # set support to TRUE bin support

    @keyword_deprecation(replace_x_with_y={"bw": "truncate"})
    def smooth(
        self, *, sigma=None, inplace=False, truncate=None, within_intervals=False
    ):
        """Smooth BinnedEventArray by convolving with a Gaussian kernel.

        Smoothing is applied in data, and the same smoothing is applied
        to each series in a BinnedEventArray.

        Smoothing is applied within each interval.

        Parameters
        ----------
        sigma : float, optional
            Standard deviation of Gaussian kernel, in seconds. Default is 0.01 (10 ms)
        truncate : float, optional
            Bandwidth outside of which the filter value will be zero. Default is 4.0
        inplace : bool
            If True the data will be replaced with the smoothed data.
            Default is False.

        Returns
        -------
        out : BinnedEventArray
            New BinnedEventArray with smoothed data.
        """

        if truncate is None:
            truncate = 4
        if sigma is None:
            sigma = 0.01  # 10 ms default

        fs = 1 / self.ds

        return utils.gaussian_filter(
            self,
            fs=fs,
            sigma=sigma,
            truncate=truncate,
            inplace=inplace,
            within_intervals=within_intervals,
        )

    @staticmethod
    def _smooth_array(arr, w=None):
        """Smooth an array by convolving a boxcar, row-wise.

        Parameters
        ----------
        w : int, optional
            Number of bins to include in boxcar window. Default is 10.

        Returns
        -------
        smoothed: array
            Smoothed array with same shape as arr.
        """

        if w is None:
            w = 10

        if w == 1:  # perform no smoothing
            return arr

        w = np.min((w, arr.shape[1]))

        smoothed = arr.astype(float)  # copy array and cast to float
        window = np.ones((w,)) / w

        # smooth per row
        for rowi, row in enumerate(smoothed):
            smoothed[rowi, :] = np.convolve(row, window, mode="same")

        if arr.shape[1] != smoothed.shape[1]:
            raise TypeError("Incompatible shape returned!")

        return smoothed

    @staticmethod
    def _rebin_array(arr, w):
        """Rebin an array of shape (n_signals, n_bins) into a
        coarser bin size.

        Parameters
        ----------
        arr : array
            Array with shape (n_signals, n_bins) to re-bin. A copy
            is returned.
        w : int
            Number of original bins to combine into each new bin.

        Returns
        -------
        out : array
            Bnned array with shape (n_signals, n_new_bins)
        bin_idx : array
            Array of shape (n_new_bins,) with the indices of the new
            binned array, relative to the original array.
        """
        cs = np.cumsum(arr, axis=1)
        binidx = np.arange(start=w, stop=cs.shape[1] + 1, step=w) - 1

        rebinned = np.hstack(
            (np.array(cs[:, w - 1], ndmin=2).T, cs[:, binidx[1:]] - cs[:, binidx[:-1]])
        )
        # bins = bins[np.insert(binidx+1, 0, 0)]
        return rebinned, binidx

    def rebin(self, w=None):
        """Rebin the BinnedEventArray into a coarser bin size.

        Parameters
        ----------
        w : int, optional
            number of bins of width bst.ds to bin into new bin of
            width bst.ds*w. Default is w=1 (no re-binning).

        Returns
        -------
        out : BinnedEventArray
            New BinnedEventArray with coarser resolution.
        """

        if w is None:
            w = 1

        if not float(w).is_integer:
            raise ValueError("w has to be an integer!")

        w = int(w)

        bst = self
        return self._rebin_binnedeventarray(bst, w=w)

    @staticmethod
    def _rebin_binnedeventarray(bst, w=None):
        """Rebin a BinnedEventArray into a coarser bin size.

        Parameters
        ----------
        bst : BinnedEventArray
            BinnedEventArray to re-bin into a coarser resolution.
        w : int, optional
            number of bins of width bst.ds to bin into new bin of
            width bst.ds*w. Default is w=1 (no re-binning).

        Returns
        -------
        out : BinnedEventArray
            New BinnedEventArray with coarser resolution.

        # FFB! TODO: if w is longer than some event size,
        # an exception will occur. Handle it! Although I may already
        # implicitly do that.
        """

        if w is None:
            w = 1

        if w == 1:
            return bst

        edges = np.insert(np.cumsum(bst.lengths), 0, 0)
        newlengths = [0]
        binedges = np.insert(np.cumsum(bst.lengths + 1), 0, 0)
        n_events = bst.support.n_intervals
        newdata = None

        for ii in range(n_events):
            data = bst.data[:, edges[ii] : edges[ii + 1]]
            bins = bst.bins[binedges[ii] : binedges[ii + 1]]

            datalen = data.shape[1]
            if w <= datalen:
                rebinned, binidx = bst._rebin_array(data, w=w)
                bins = bins[np.insert(binidx + 1, 0, 0)]

                newlengths.append(rebinned.shape[1])

                if newdata is None:
                    newdata = rebinned
                    newbins = bins
                    newcenters = bins[:-1] + np.diff(bins) / 2
                    newsupport = np.array([bins[0], bins[-1]])
                else:
                    newdata = np.hstack((newdata, rebinned))
                    newbins = np.hstack((newbins, bins))
                    newcenters = np.hstack((newcenters, bins[:-1] + np.diff(bins) / 2))
                    newsupport = np.vstack((newsupport, np.array([bins[0], bins[-1]])))
            else:
                pass

        # assemble new binned event series array:
        newedges = np.cumsum(newlengths)
        newbst = bst._copy_without_data()
        abscissa = copy.copy(bst._abscissa)
        if newdata is not None:
            newbst._data = newdata
            newbst._abscissa = abscissa
            newbst._abscissa.support = type(bst.support)(newsupport)
            newbst._bins = newbins
            newbst._bin_centers = newcenters
            newbst._ds = bst.ds * w
            newbst._binned_support = np.array((newedges[:-1], newedges[1:] - 1)).T
        else:
            logging.warning(
                "No events are long enough to contain any bins of width {}".format(
                    utils.PrettyDuration(bst.ds)
                )
            )
            newbst._data = None
            newbst._abscissa = abscissa
            newbst._abscissa.support = None
            newbst._binned_support = None
            newbst._bin_centers = None
            newbst._bins = None

        newbst.__renew__()

        return newbst

    def bst_from_indices(self, idx):
        """
        Return a BinnedEventArray from a list of indices.

        bst : BinnedEventArray
        idx : list of sample (bin) numbers with shape (n_intervals, 2) INCLUSIVE

        Examples
        --------
        idx = [[10, 20]
            [25, 50]]
        bst_from_indices(bst, idx=idx)
        """

        idx = np.atleast_2d(idx)

        newbst = self._copy_without_data()
        ds = self.ds
        bin_centers_ = []
        bins_ = []
        binned_support_ = []
        support_ = []
        all_abscissa_vals = []

        n_preceding_bins = 0

        for frm, to in idx:
            idx_array = np.arange(frm, to + 1).astype(int)
            all_abscissa_vals.append(idx_array)
            bin_centers = self.bin_centers[idx_array]
            bins = np.append(bin_centers - ds / 2, bin_centers[-1] + ds / 2)

            binned_support = [n_preceding_bins, n_preceding_bins + len(bins) - 2]
            n_preceding_bins += len(bins) - 1
            support = type(self._abscissa.support)((bins[0], bins[-1]))

            bin_centers_.append(bin_centers)
            bins_.append(bins)
            binned_support_.append(binned_support)
            support_.append(support)

        bin_centers = np.concatenate(bin_centers_)
        bins = np.concatenate(bins_)
        binned_support = np.array(binned_support_)
        support = np.sum(support_)
        all_abscissa_vals = np.concatenate(all_abscissa_vals)

        newbst._bin_centers = bin_centers
        newbst._bins = bins
        newbst._binned_support = binned_support
        newbst._abscissa.support = support
        newbst._data = newbst.data[:, all_abscissa_vals]

        newbst.__renew__()

        return newbst

    @property
    def n_active(self):
        """Number of active series.

        An active series is any series that fired at least one event.
        """
        if self.isempty:
            return 0
        return utils.PrettyInt(np.count_nonzero(self.n_events))

    @property
    def n_active_per_bin(self):
        """Number of active series per data bin with shape (n_bins,)."""
        if self.isempty:
            return 0
        # TODO: profile several alternatves. Could use data > 0, or
        # other numpy methods to get a more efficient implementation:
        return self.data.clip(max=1).sum(axis=0)

    @property
    def n_events(self):
        """(np.array) The number of events in each series."""
        if self.isempty:
            return 0
        return self.data.sum(axis=1)

    def flatten(self, *, series_id=None, series_label=None):
        """Collapse events across series.

        WARNING! series_tags are thrown away when flattening.

        Parameters
        ----------
        series_id: (int)
            (series) ID to assign to flattened event series, default is 0.
        series_label (str)
            (series) Label for event series, default is 'flattened'.
        """
        if self.n_series < 2:  # already flattened
            return self

        # default args:
        if series_id is None:
            series_id = 0
        if series_label is None:
            series_label = "flattened"

        binnedeventarray = self._copy_without_data()

        binnedeventarray._data = np.array(self.data.sum(axis=0), ndmin=2)

        binnedeventarray._bins = self.bins
        binnedeventarray._abscissa.support = self.support
        binnedeventarray._bin_centers = self.bin_centers
        binnedeventarray._binned_support = self.binned_support

        binnedeventarray._series_ids = [series_id]
        binnedeventarray._series_labels = [series_label]
        binnedeventarray._series_tags = None
        binnedeventarray.__renew__()

        return binnedeventarray

    @property
    def support(self):
        """(nelpy.IntervalArray) The support of the underlying BinnedEventArray."""
        return self._abscissa.support

    @support.setter
    def support(self, val):
        """(nelpy.IntervalArray) The support of the underlying BinnedEventArray."""
        # modify support
        if isinstance(val, type(self._abscissa.support)):
            self._abscissa.support = val
        elif isinstance(val, (tuple, list)):
            prev_domain = self._abscissa.domain
            self._abscissa.support = type(self._abscissa.support)([val[0], val[1]])
            self._abscissa.domain = prev_domain
        else:
            raise TypeError(
                "support must be of type {}".format(str(type(self._abscissa.support)))
            )
        # restrict data to new support
        self._restrict_to_interval(self._abscissa.support)

bin_centers property

(np.array) The bin centers (in seconds).

binnedSupport property

(np.array) The binned support of the BinnedEventArray (in bin IDs) of shape (n_intervals, 2).

binned_support property

(np.array) The binned support of the BinnedEventArray (in bin IDs) of shape (n_intervals, 2).

bins property

(np.array) The bin edges (in seconds).

centers property

(np.array) The bin centers (in seconds).

data property

(np.array) Event counts in all bins, with shape (n_series, n_bins).

ds property writable

(float) Bin width in seconds.

event_centers property

(np.array) The centers (in seconds) of each event.

eventarray property

(nelpy.EventArray) The original EventArray associated with the binned data.

isempty property

(bool) Empty BinnedEventArray.

lengths property

Lengths of contiguous segments, in number of bins.

n_active property

Number of active series.

An active series is any series that fired at least one event.

n_active_per_bin property

Number of active series per data bin with shape (n_bins,).

n_bins property

(int) The number of bins.

n_events property

(np.array) The number of events in each series.

n_series property

(int) The number of series.

support property writable

(nelpy.IntervalArray) The support of the underlying BinnedEventArray.

bst_from_indices(idx)

Return a BinnedEventArray from a list of indices.

bst : BinnedEventArray idx : list of sample (bin) numbers with shape (n_intervals, 2) INCLUSIVE

Examples:

idx = [[10, 20] [25, 50]] bst_from_indices(bst, idx=idx)

Source code in nelpy/core/_eventarray.py
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
def bst_from_indices(self, idx):
    """
    Return a BinnedEventArray from a list of indices.

    bst : BinnedEventArray
    idx : list of sample (bin) numbers with shape (n_intervals, 2) INCLUSIVE

    Examples
    --------
    idx = [[10, 20]
        [25, 50]]
    bst_from_indices(bst, idx=idx)
    """

    idx = np.atleast_2d(idx)

    newbst = self._copy_without_data()
    ds = self.ds
    bin_centers_ = []
    bins_ = []
    binned_support_ = []
    support_ = []
    all_abscissa_vals = []

    n_preceding_bins = 0

    for frm, to in idx:
        idx_array = np.arange(frm, to + 1).astype(int)
        all_abscissa_vals.append(idx_array)
        bin_centers = self.bin_centers[idx_array]
        bins = np.append(bin_centers - ds / 2, bin_centers[-1] + ds / 2)

        binned_support = [n_preceding_bins, n_preceding_bins + len(bins) - 2]
        n_preceding_bins += len(bins) - 1
        support = type(self._abscissa.support)((bins[0], bins[-1]))

        bin_centers_.append(bin_centers)
        bins_.append(bins)
        binned_support_.append(binned_support)
        support_.append(support)

    bin_centers = np.concatenate(bin_centers_)
    bins = np.concatenate(bins_)
    binned_support = np.array(binned_support_)
    support = np.sum(support_)
    all_abscissa_vals = np.concatenate(all_abscissa_vals)

    newbst._bin_centers = bin_centers
    newbst._bins = bins
    newbst._binned_support = binned_support
    newbst._abscissa.support = support
    newbst._data = newbst.data[:, all_abscissa_vals]

    newbst.__renew__()

    return newbst

center(inplace=False)

Center data (zero mean).

Source code in nelpy/core/_eventarray.py
1333
1334
1335
1336
1337
1338
1339
1340
def center(self, inplace=False):
    """Center data (zero mean)."""
    if inplace:
        out = self
    else:
        out = self.copy()
    out._data = (out._data.T - out.mean()).T
    return out

copy()

Returns a copy of the BinnedEventArray.

Source code in nelpy/core/_eventarray.py
1417
1418
1419
1420
1421
def copy(self):
    """Returns a copy of the BinnedEventArray."""
    newcopy = copy.deepcopy(self)
    newcopy.__renew__()
    return newcopy

empty(*, inplace=False)

Remove data (but not metadata) from BinnedEventArray.

Attributes 'data', and 'support' 'binned_support' are all emptied.

Note: n_series, series_ids, etc. are all preserved.

Source code in nelpy/core/_eventarray.py
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
def empty(self, *, inplace=False):
    """Remove data (but not metadata) from BinnedEventArray.

    Attributes 'data', and 'support' 'binned_support' are all emptied.

    Note: n_series, series_ids, etc. are all preserved.
    """
    if not inplace:
        out = self._copy_without_data()
        out._abscissa.support = type(self._abscissa.support)(empty=True)
        return out
    out = self
    out._data = np.zeros((self.n_series, 0))
    out._abscissa.support = type(self._abscissa.support)(empty=True)
    out._binned_support = None
    out._bin_centers = None
    out._bins = None
    out._eventarray.empty(inplace=True)
    out.__renew__()
    return out

flatten(*, series_id=None, series_label=None)

Collapse events across series.

WARNING! series_tags are thrown away when flattening.

Parameters:

Name Type Description Default
series_id

(series) ID to assign to flattened event series, default is 0.

None
series_label

(series) Label for event series, default is 'flattened'.

None
Source code in nelpy/core/_eventarray.py
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
def flatten(self, *, series_id=None, series_label=None):
    """Collapse events across series.

    WARNING! series_tags are thrown away when flattening.

    Parameters
    ----------
    series_id: (int)
        (series) ID to assign to flattened event series, default is 0.
    series_label (str)
        (series) Label for event series, default is 'flattened'.
    """
    if self.n_series < 2:  # already flattened
        return self

    # default args:
    if series_id is None:
        series_id = 0
    if series_label is None:
        series_label = "flattened"

    binnedeventarray = self._copy_without_data()

    binnedeventarray._data = np.array(self.data.sum(axis=0), ndmin=2)

    binnedeventarray._bins = self.bins
    binnedeventarray._abscissa.support = self.support
    binnedeventarray._bin_centers = self.bin_centers
    binnedeventarray._binned_support = self.binned_support

    binnedeventarray._series_ids = [series_id]
    binnedeventarray._series_labels = [series_label]
    binnedeventarray._series_tags = None
    binnedeventarray.__renew__()

    return binnedeventarray

mean(*, axis=1)

Returns the mean of each series in BinnedEventArray.

Source code in nelpy/core/_eventarray.py
1311
1312
1313
1314
1315
1316
1317
1318
1319
def mean(self, *, axis=1):
    """Returns the mean of each series in BinnedEventArray."""
    try:
        means = np.nanmean(self.data, axis=axis).squeeze()
        if means.size == 1:
            return means.item()
        return means
    except IndexError:
        raise IndexError("Empty BinnedEventArray; cannot calculate mean.")

median(*, axis=1)

Returns the median of each series in BinnedEventArray.

Source code in nelpy/core/_eventarray.py
1301
1302
1303
1304
1305
1306
1307
1308
1309
def median(self, *, axis=1):
    """Returns the median of each series in BinnedEventArray."""
    try:
        medians = np.nanmedian(self.data, axis=axis).squeeze()
        if medians.size == 1:
            return medians.item()
        return medians
    except IndexError:
        raise IndexError("Empty BinnedEventArray; cannot calculate median.")

normalize(inplace=False)

Normalize data (unit standard deviation).

Source code in nelpy/core/_eventarray.py
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
def normalize(self, inplace=False):
    """Normalize data (unit standard deviation)."""
    if inplace:
        out = self
    else:
        out = self.copy()
    std = out.std()
    std[std == 0] = 1
    out._data = (out._data.T / std).T
    return out

partition(ds=None, n_intervals=None)

Returns a BaseEventArray whose support has been partitioned.

Parameters:

Name Type Description Default
ds float

Maximum duration (in seconds), for each interval.

None
n_points int

Number of intervals. If ds is None and n_intervals is None, then default is to use n_intervals = 100

required

Returns:

Name Type Description
out BaseEventArray

BaseEventArray that has been partitioned.

Notes

Irrespective of whether 'ds' or 'n_intervals' are used, the exact of the supports are always included, even if this would cause n_points or ds to be violated.

Source code in nelpy/core/_eventarray.py
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
@keyword_equivalence(this_or_that={"n_intervals": "n_epochs"})
def partition(self, ds=None, n_intervals=None):
    """Returns a BaseEventArray whose support has been partitioned.

    Parameters
    ----------
    ds : float, optional
        Maximum duration (in seconds), for each interval.
    n_points : int, optional
        Number of intervals. If ds is None and n_intervals is None, then
        default is to use n_intervals = 100

    Returns
    -------
    out : BaseEventArray
        BaseEventArray that has been partitioned.

    Notes
    -----
    Irrespective of whether 'ds' or 'n_intervals' are used, the exact
    of the supports are always included, even if this would cause
    n_points or ds to be violated.
    """

    partitioned = type(self)(
        core.RegularlySampledAnalogSignalArray(self).partition(
            ds=ds, n_intervals=n_intervals
        )
    )
    # partitioned.loc = ItemGetter_loc(partitioned)
    # partitioned.iloc = ItemGetter_iloc(partitioned)
    return partitioned

rebin(w=None)

Rebin the BinnedEventArray into a coarser bin size.

Parameters:

Name Type Description Default
w int

number of bins of width bst.ds to bin into new bin of width bst.ds*w. Default is w=1 (no re-binning).

None

Returns:

Name Type Description
out BinnedEventArray

New BinnedEventArray with coarser resolution.

Source code in nelpy/core/_eventarray.py
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
def rebin(self, w=None):
    """Rebin the BinnedEventArray into a coarser bin size.

    Parameters
    ----------
    w : int, optional
        number of bins of width bst.ds to bin into new bin of
        width bst.ds*w. Default is w=1 (no re-binning).

    Returns
    -------
    out : BinnedEventArray
        New BinnedEventArray with coarser resolution.
    """

    if w is None:
        w = 1

    if not float(w).is_integer:
        raise ValueError("w has to be an integer!")

    w = int(w)

    bst = self
    return self._rebin_binnedeventarray(bst, w=w)

smooth(*, sigma=None, inplace=False, truncate=None, within_intervals=False)

Smooth BinnedEventArray by convolving with a Gaussian kernel.

Smoothing is applied in data, and the same smoothing is applied to each series in a BinnedEventArray.

Smoothing is applied within each interval.

Parameters:

Name Type Description Default
sigma float

Standard deviation of Gaussian kernel, in seconds. Default is 0.01 (10 ms)

None
truncate float

Bandwidth outside of which the filter value will be zero. Default is 4.0

None
inplace bool

If True the data will be replaced with the smoothed data. Default is False.

False

Returns:

Name Type Description
out BinnedEventArray

New BinnedEventArray with smoothed data.

Source code in nelpy/core/_eventarray.py
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
@keyword_deprecation(replace_x_with_y={"bw": "truncate"})
def smooth(
    self, *, sigma=None, inplace=False, truncate=None, within_intervals=False
):
    """Smooth BinnedEventArray by convolving with a Gaussian kernel.

    Smoothing is applied in data, and the same smoothing is applied
    to each series in a BinnedEventArray.

    Smoothing is applied within each interval.

    Parameters
    ----------
    sigma : float, optional
        Standard deviation of Gaussian kernel, in seconds. Default is 0.01 (10 ms)
    truncate : float, optional
        Bandwidth outside of which the filter value will be zero. Default is 4.0
    inplace : bool
        If True the data will be replaced with the smoothed data.
        Default is False.

    Returns
    -------
    out : BinnedEventArray
        New BinnedEventArray with smoothed data.
    """

    if truncate is None:
        truncate = 4
    if sigma is None:
        sigma = 0.01  # 10 ms default

    fs = 1 / self.ds

    return utils.gaussian_filter(
        self,
        fs=fs,
        sigma=sigma,
        truncate=truncate,
        inplace=inplace,
        within_intervals=within_intervals,
    )

standardize(inplace=False)

Standardize data (zero mean and unit std deviation).

Source code in nelpy/core/_eventarray.py
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
def standardize(self, inplace=False):
    """Standardize data (zero mean and unit std deviation)."""
    if inplace:
        out = self
    else:
        out = self.copy()
    out._data = (out._data.T - out.mean()).T
    std = out.std()
    std[std == 0] = 1
    out._data = (out._data.T / std).T

    return out

std(*, axis=1)

Returns the standard deviation of each series in BinnedEventArray.

Source code in nelpy/core/_eventarray.py
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
def std(self, *, axis=1):
    """Returns the standard deviation of each series in BinnedEventArray."""
    try:
        stds = np.nanstd(self.data, axis=axis).squeeze()
        if stds.size == 1:
            return stds.item()
        return stds
    except IndexError:
        raise IndexError(
            "Empty BinnedEventArray; cannot calculate standard deviation"
        )

BinnedSpikeTrainArray

Bases: BinnedEventArray

Binned spike train array for analyzing neural spike data.

A specialized version of BinnedEventArray designed specifically for spike train analysis. This class bins spike events into discrete time intervals and provides spike train-specific methods and properties through aliased attribute names.

Parameters:

Name Type Description Default
eventarray EventArray or RegularlySampledAnalogSignalArray

Input spike train data to be binned.

required
ds float

The bin width, in seconds. Default is 0.0625 (62.5 ms).

required
empty bool

Whether an empty BinnedSpikeTrainArray should be constructed (no data). Default is False.

required
fs float

Sampling rate in Hz. If fs is passed as a parameter, then data is assumed to be in sample numbers instead of actual time values.

required
support IntervalArray

The support (time intervals) over which the spike trains are defined.

required
unit_ids list of int

Unit IDs for each spike train. Default creates sequential IDs starting from 1.

required
unit_labels list of str

Labels corresponding to units. Default casts unit_ids to str.

required
unit_tags optional

Tags corresponding to units. Currently accepts any type.

required
label str

Information pertaining to the source of the spike train data. Default is None.

required
abscissa TemporalAbscissa

Object for the time (x-axis) coordinate. Default creates TemporalAbscissa.

required
ordinate AnalogSignalArrayOrdinate

Object for the signal (y-axis) coordinate. Default creates AnalogSignalArrayOrdinate.

required
**kwargs optional

Additional keyword arguments passed to the parent BinnedEventArray constructor.

{}

Attributes:

Name Type Description
Note Read the docstring for the BinnedEventArray parent class for additional
attributes that are defined there.
Spike train-specific attributes (aliases)
time array

Alias for data. Spike counts in all bins, with shape (n_units, n_bins).

n_epochs int

Alias for n_intervals. The number of underlying time intervals.

n_units int

Alias for n_series. The number of units (neurons).

n_spikes ndarray

Alias for n_events. The number of spikes in each unit.

unit_ids list of int

Alias for series_ids. Unit IDs contained in the spike train array.

unit_labels list of str

Alias for series_labels. Labels corresponding to units.

unit_tags

Alias for series_tags. Tags corresponding to units.

Inherited attributes
isempty bool

Whether the BinnedSpikeTrainArray is empty (no data).

bin_centers ndarray

The bin centers, in seconds.

data np.array, with shape (n_units, n_bins)

Spike counts in all bins.

bins ndarray

The bin edges, in seconds.

binned_support np.ndarray, with shape (n_intervals, 2)

The binned support of the array (in bin IDs).

lengths ndarray

Lengths of contiguous segments, in number of bins.

eventarray EventArray

The original EventArray associated with the binned spike data.

n_bins int

The number of bins.

ds float

Bin width, in seconds.

n_active int

The number of active units. A unit is considered active if it fired at least one spike.

n_active_per_bin np.ndarray, with shape (n_bins, )

Number of active units per data bin.

support IntervalArray

The support of the BinnedSpikeTrainArray.

Methods:

Name Description
All methods from BinnedEventArray are available, plus spike train-specific
aliases for method names:
reorder_units_by_ids

Alias for reorder_series_by_ids. Reorder units by their IDs.

reorder_units

Alias for reorder_series. Reorder units.

Examples:

>>> import nelpy as nel
>>> # Create a BinnedSpikeTrainArray from spike times
>>> spike_times = [np.array([0.1, 0.3, 0.7]), np.array([0.2, 0.5, 0.8])]
>>> sta = SpikeTrainArray(spike_times, unit_ids=[1, 2], fs=1000)
>>> bst = nel.BinnedSpikeTrainArray(sta, ds=0.1)
>>> print(bst.n_units)
2
>>> print(bst.n_bins)
7
>>> print(bst.time.shape)  # alias for data
(2, 7)
See Also

BinnedEventArray : Parent class for general event arrays EventArray : Unbinned event array class SpikeTrainArray : Unbinned spike train array class

Source code in nelpy/core/_eventarray.py
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
class BinnedSpikeTrainArray(BinnedEventArray):
    """Binned spike train array for analyzing neural spike data.

    A specialized version of BinnedEventArray designed specifically for spike train
    analysis. This class bins spike events into discrete time intervals and provides
    spike train-specific methods and properties through aliased attribute names.

    Parameters
    ----------
    eventarray : nelpy.EventArray or nelpy.RegularlySampledAnalogSignalArray, optional
        Input spike train data to be binned.
    ds : float, optional
        The bin width, in seconds. Default is 0.0625 (62.5 ms).
    empty : bool, optional
        Whether an empty BinnedSpikeTrainArray should be constructed (no data).
        Default is False.
    fs : float, optional
        Sampling rate in Hz. If fs is passed as a parameter, then data
        is assumed to be in sample numbers instead of actual time values.
    support : nelpy.IntervalArray, optional
        The support (time intervals) over which the spike trains are defined.
    unit_ids : list of int, optional
        Unit IDs for each spike train. Default creates sequential IDs starting from 1.
    unit_labels : list of str, optional
        Labels corresponding to units. Default casts unit_ids to str.
    unit_tags : optional
        Tags corresponding to units. Currently accepts any type.
    label : str, optional
        Information pertaining to the source of the spike train data.
        Default is None.
    abscissa : nelpy.TemporalAbscissa, optional
        Object for the time (x-axis) coordinate. Default creates TemporalAbscissa.
    ordinate : nelpy.AnalogSignalArrayOrdinate, optional
        Object for the signal (y-axis) coordinate. Default creates AnalogSignalArrayOrdinate.
    **kwargs : optional
        Additional keyword arguments passed to the parent BinnedEventArray constructor.

    Attributes
    ----------
    Note : Read the docstring for the BinnedEventArray parent class for additional
    attributes that are defined there.

    Spike train-specific attributes (aliases):
    time : np.array
        Alias for data. Spike counts in all bins, with shape (n_units, n_bins).
    n_epochs : int
        Alias for n_intervals. The number of underlying time intervals.
    n_units : int
        Alias for n_series. The number of units (neurons).
    n_spikes : np.ndarray
        Alias for n_events. The number of spikes in each unit.
    unit_ids : list of int
        Alias for series_ids. Unit IDs contained in the spike train array.
    unit_labels : list of str
        Alias for series_labels. Labels corresponding to units.
    unit_tags :
        Alias for series_tags. Tags corresponding to units.

    Inherited attributes:
    isempty : bool
        Whether the BinnedSpikeTrainArray is empty (no data).
    bin_centers : np.ndarray
        The bin centers, in seconds.
    data : np.array, with shape (n_units, n_bins)
        Spike counts in all bins.
    bins : np.ndarray
        The bin edges, in seconds.
    binned_support : np.ndarray, with shape (n_intervals, 2)
        The binned support of the array (in bin IDs).
    lengths : np.ndarray
        Lengths of contiguous segments, in number of bins.
    eventarray : nelpy.EventArray
        The original EventArray associated with the binned spike data.
    n_bins : int
        The number of bins.
    ds : float
        Bin width, in seconds.
    n_active : int
        The number of active units. A unit is considered active if
        it fired at least one spike.
    n_active_per_bin : np.ndarray, with shape (n_bins, )
        Number of active units per data bin.
    support : nelpy.IntervalArray
        The support of the BinnedSpikeTrainArray.

    Methods
    -------
    All methods from BinnedEventArray are available, plus spike train-specific
    aliases for method names:

    reorder_units_by_ids(*args, **kwargs)
        Alias for reorder_series_by_ids. Reorder units by their IDs.
    reorder_units(*args, **kwargs)
        Alias for reorder_series. Reorder units.

    Examples
    --------
    >>> import nelpy as nel
    >>> # Create a BinnedSpikeTrainArray from spike times
    >>> spike_times = [np.array([0.1, 0.3, 0.7]), np.array([0.2, 0.5, 0.8])]
    >>> sta = SpikeTrainArray(spike_times, unit_ids=[1, 2], fs=1000)
    >>> bst = nel.BinnedSpikeTrainArray(sta, ds=0.1)
    >>> print(bst.n_units)
    2
    >>> print(bst.n_bins)
    7
    >>> print(bst.time.shape)  # alias for data
    (2, 7)

    See Also
    --------
    BinnedEventArray : Parent class for general event arrays
    EventArray : Unbinned event array class
    SpikeTrainArray : Unbinned spike train array class
    """

    # specify class-specific aliases:
    __aliases__ = {
        "time": "data",
        "_time": "_data",
        "n_epochs": "n_intervals",
        "n_units": "n_series",
        "_unit_subset": "_series_subset",  # requires kw change
        # 'get_event_firing_order' : 'get_spike_firing_order'
        "reorder_units_by_ids": "reorder_series_by_ids",
        "reorder_units": "reorder_series",
        "_reorder_units_by_idx": "_reorder_series_by_idx",
        "n_spikes": "n_events",
        "unit_ids": "series_ids",
        "unit_labels": "series_labels",
        "unit_tags": "series_tags",
        "_unit_ids": "_series_ids",
        "_unit_labels": "_series_labels",
        "_unit_tags": "_series_tags",
    }

    def __init__(self, *args, **kwargs):
        # add class-specific aliases to existing aliases:
        self.__aliases__ = {**super().__aliases__, **self.__aliases__}

        support = kwargs.get("support", None)
        if support is not None:
            abscissa = kwargs.get("abscissa", core.TemporalAbscissa(support=support))
        else:
            abscissa = kwargs.get("abscissa", core.TemporalAbscissa())
        ordinate = kwargs.get("ordinate", core.AnalogSignalArrayOrdinate())

        kwargs["abscissa"] = abscissa
        kwargs["ordinate"] = ordinate

        super().__init__(*args, **kwargs)

EventArray

Bases: BaseEventArray

A multiseries eventarray with shared support.

Parameters:

Name Type Description Default
abscissa_vals array of np.array(dtype=np.float64) event datas in seconds.

Array of length n_series, each entry with shape (n_data,).

None
fs float

Sampling rate in Hz. Default is 30,000.

None
support IntervalArray

IntervalArray on which eventarrays are defined. Default is [0, last event] inclusive.

None
series_ids list of int

Unit IDs.

None
series_labels list of str

Labels corresponding to series. Default casts series_ids to str.

None
series_tags optional

Tags correponding to series. NOTE: Currently we do not do any input validation so these can be any type. We also don't use these for anything yet.

None
label str or None

Information pertaining to the source of the eventarray.

None
empty bool

Whether an empty EventArray should be constructed (no data).

False
assume_sorted boolean

Whether the abscissa values should be treated as sorted (non-decreasing) or not. Significant overhead during RSASA object creation can be removed if this is True, but note that unsorted abscissa values will mess everything up. Default is False

None
kwargs optional

Additional keyword arguments to forward along to the BaseEventArray constructor.

{}

Attributes:

Name Type Description
Note Read the docstring for the BaseEventArray superclass for additional
attributes that are defined there.
isempty bool

Whether the EventArray is empty (no data).

n_series int

The number of series.

n_active int

The number of active series. A series is considered active if it fired at least one event.

data array of np.array(dtype=np.float64) event datas in seconds.

Array of length n_series, each entry with shape (n_data,).

n_events ndarray

The number of events in each series.

issorted bool

Whether the data are sorted.

first_event float

The time of the very first event, across all series.

last_event float

The time of the very last event, across all series.

Source code in nelpy/core/_eventarray.py
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
class EventArray(BaseEventArray):
    """A multiseries eventarray with shared support.

    Parameters
    ----------
    abscissa_vals : array of np.array(dtype=np.float64) event datas in seconds.
        Array of length n_series, each entry with shape (n_data,).
    fs : float, optional
        Sampling rate in Hz. Default is 30,000.
    support : IntervalArray, optional
        IntervalArray on which eventarrays are defined.
        Default is [0, last event] inclusive.
    series_ids : list of int, optional
        Unit IDs.
    series_labels : list of str, optional
        Labels corresponding to series. Default casts series_ids to str.
    series_tags : optional
        Tags correponding to series.
        NOTE: Currently we do not do any input validation so these can
        be any type. We also don't use these for anything yet.
    label : str or None, optional
        Information pertaining to the source of the eventarray.
    empty : bool, optional
        Whether an empty EventArray should be constructed (no data).
    assume_sorted : boolean, optional
        Whether the abscissa values should be treated as sorted (non-decreasing)
        or not. Significant overhead during RSASA object creation can be removed
        if this is True, but note that unsorted abscissa values will mess
        everything up.
        Default is False
    kwargs : optional
        Additional keyword arguments to forward along to the BaseEventArray
        constructor.

    Attributes
    ----------
    Note : Read the docstring for the BaseEventArray superclass for additional
    attributes that are defined there.
    isempty : bool
        Whether the EventArray is empty (no data).
    n_series : int
        The number of series.
    n_active : int
        The number of active series. A series is considered active if
        it fired at least one event.
    data : array of np.array(dtype=np.float64) event datas in seconds.
        Array of length n_series, each entry with shape (n_data,).
    n_events : np.ndarray
        The number of events in each series.
    issorted : bool
        Whether the data are sorted.
    first_event : np.float
        The time of the very first event, across all series.
    last_event : np.float
        The time of the very last event, across all series.
    """

    __attributes__ = ["_data"]
    __attributes__.extend(BaseEventArray.__attributes__)

    def __init__(
        self,
        abscissa_vals=None,
        *,
        fs=None,
        support=None,
        series_ids=None,
        series_labels=None,
        series_tags=None,
        label=None,
        empty=False,
        assume_sorted=None,
        **kwargs,
    ):
        if assume_sorted is None:
            assume_sorted = False

        # if an empty object is requested, return it:
        if empty:
            super().__init__(empty=True)
            for attr in self.__attributes__:
                exec("self." + attr + " = None")
            self._abscissa.support = type(self._abscissa.support)(empty=True)
            return

        # set default sampling rate
        if fs is None:
            fs = 30000
            logging.warning(
                "No sampling rate was specified! Assuming default of {} Hz.".format(fs)
            )

        def is_singletons(data):
            """Returns True if data is a list of singletons (more than one)."""
            data = np.array(data, dtype=object)
            try:
                if data.shape[-1] < 2 and np.max(data.shape) > 1:
                    return True
                if max(np.array(data).shape[:-1]) > 1 and data.shape[-1] == 1:
                    return True
            except (IndexError, TypeError, ValueError):
                return False
            return False

        def is_single_series(data):
            """Returns True if data represents event datas from a single series.

            Examples
            --------
            [1, 2, 3]           : True
            [[1, 2, 3]]         : True
            [[1, 2, 3], []]     : False
            [[], [], []]        : False
            [[[[1, 2, 3]]]]     : True
            [[[[[1],[2],[3]]]]] : False
            """
            try:
                if isinstance(data[0][0], list) or isinstance(data[0][0], np.ndarray):
                    logging.info("event datas input has too many layers!")
                    try:
                        if max(np.array(data).shape[:-1]) > 1:
                            #                 singletons = True
                            return False
                    except ValueError:
                        return False
                    data = np.squeeze(data)
            except (IndexError, TypeError):
                pass
            try:
                if isinstance(data[1], list) or isinstance(data[1], np.ndarray):
                    return False
            except (IndexError, TypeError):
                pass
            return True

        def standardize_to_2d(data):
            if is_single_series(data):
                return np.array(np.squeeze(data), ndmin=2)
            if is_singletons(data):
                data = np.squeeze(data)
                n = np.max(data.shape)
                if len(data.shape) == 1:
                    m = 1
                else:
                    m = np.min(data.shape)
                data = np.reshape(data, (n, m))
            else:
                data = np.squeeze(data)
                if data.dtype == np.dtype("O"):
                    jagged = True
                else:
                    jagged = False
                if jagged:  # jagged array
                    # standardize input so that a list of lists is converted
                    # to an array of arrays:
                    data = np.array([np.asarray(st) for st in data], dtype=object)
                else:
                    data = np.array(data, ndmin=2)
            return data

        # standardize input data to 2D array
        data = standardize_to_2d(np.array(abscissa_vals, dtype=object))

        # If user said to assume the absicssa vals are sorted but they actually
        # aren't, then the mistake will get propagated down. The responsibility
        # therefore lies on the user whenever he/she uses assume_sorted=True
        # as a constructor argument
        for ii, train in enumerate(data):
            if not assume_sorted:
                # sort event series, but only if necessary
                if not utils.is_sorted(train):
                    data[ii] = np.sort(train)
            else:
                data[ii] = np.sort(train)

        kwargs["fs"] = fs
        kwargs["series_ids"] = series_ids
        kwargs["series_labels"] = series_labels
        kwargs["series_tags"] = series_tags
        kwargs["label"] = label

        self._data = data  # this is necessary so that
        # super() can determine self.n_series when initializing.

        # initialize super so that self.fs is set:
        super().__init__(**kwargs)

        # print(self.type_name, kwargs)

        # if only empty data were received AND no support, attach an
        # empty support:
        if np.sum([st.size for st in data]) == 0 and support is None:
            logging.warning("no events; cannot automatically determine support")
            support = type(self._abscissa.support)(empty=True)

        # determine eventarray support:
        if support is None:
            first_spk = np.nanmin(
                np.array([series[0] for series in data if len(series) != 0])
            )
            # BUG: if eventseries is empty np.array([]) then series[-1]
            # raises an error in the following:
            # FIX: list[-1] raises an IndexError for an empty list,
            # whereas list[-1:] returns an empty list.
            last_spk = np.nanmax(
                np.array([series[-1:] for series in data if len(series) != 0])
            )
            self.support = type(self._abscissa.support)(
                np.array([first_spk, last_spk + 1 / fs])
            )
            # in the above, there's no reason to restrict to support
        else:
            # restrict events to only those within the eventseries
            # array's support:
            self.support = support

        # TODO: if sorted, we may as well use the fast restrict here as well?
        self._restrict_to_interval(self._abscissa.support, data=data)

    @keyword_equivalence(this_or_that={"n_intervals": "n_epochs"})
    def partition(self, ds=None, n_intervals=None):
        """Returns a BaseEventArray whose support has been partitioned.

        Parameters
        ----------
        ds : float, optional
            Maximum duration (in seconds), for each interval.
        n_points : int, optional
            Number of intervals. If ds is None and n_intervals is None, then
            default is to use n_intervals = 100

        Returns
        -------
        out : BaseEventArray
            BaseEventArray that has been partitioned.

        Notes
        -----
        Irrespective of whether 'ds' or 'n_intervals' are used, the exact
        underlying support is propagated, and the first and last points
        of the supports are always included, even if this would cause
        n_points or ds to be violated.
        """

        out = self.copy()
        abscissa = copy.deepcopy(out._abscissa)
        abscissa.support = abscissa.support.partition(ds=ds, n_intervals=n_intervals)
        out._abscissa = abscissa
        out.__renew__()

        return out

    def _copy_without_data(self):
        """Return a copy of self, without event datas.
        Note: the support is left unchanged.
        """
        out = copy.copy(self)  # shallow copy
        out._data = np.array(self.n_series * [None])
        out = copy.deepcopy(
            out
        )  # just to be on the safe side, but at least now we are not copying the data!
        out.__renew__()
        return out

    def copy(self):
        """Returns a copy of the EventArray."""
        newcopy = copy.deepcopy(self)
        newcopy.__renew__()
        return newcopy

    def __iter__(self):
        """EventArray iterator initialization."""
        # initialize the internal index to zero when used as iterator
        self._index = 0
        return self

    def __next__(self):
        """EventArray iterator advancer."""
        index = self._index
        if index > self._abscissa.support.n_intervals - 1:
            raise StopIteration

        self._index += 1
        return self.loc[index]

    def __getitem__(self, idx):
        """EventArray index access.

        By default, this method is bound to EventArray.loc
        """
        return self.loc[idx]

    @property
    def isempty(self):
        """(bool) Empty EventArray."""
        try:
            return np.sum([len(st) for st in self.data]) == 0
        except TypeError:
            return True  # this happens when self.data is None

    @property
    def n_series(self):
        """(int) The number of series."""
        try:
            return utils.PrettyInt(len(self.data))
        except TypeError:
            return 0

    @property
    def n_active(self):
        """(int) The number of active series.

        A series is considered active if it fired at least one event.
        """
        if self.isempty:
            return 0
        return utils.PrettyInt(np.count_nonzero(self.n_events))

    def flatten(self, *, series_id=None, series_label=None):
        """Collapse events across series.

        WARNING! series_tags are thrown away when flattening.

        Parameters
        ----------
        series_id: (int)
            (series) ID to assign to flattened event series, default is 0.
        series_label (str)
            (series) Label for event series, default is 'flattened'.
        """
        if self.n_series < 2:  # already flattened
            return self

        # default args:
        if series_id is None:
            series_id = 0
        if series_label is None:
            series_label = "flattened"

        flattened = self._copy_without_data()
        flattened._series_ids = [series_id]
        flattened._series_labels = [series_label]
        flattened._series_tags = None

        # Efficient: concatenate all events, sort once
        all_events = np.concatenate(self.data)
        all_events.sort()
        flattened._data = np.array([all_events], ndmin=2)
        flattened.__renew__()
        return flattened

    def _restrict(self, intervalslice, seriesslice, *, subseriesslice=None):
        self._restrict_to_series_subset(seriesslice)
        self._restrict_to_interval(intervalslice)
        return self

    def _restrict_to_series_subset(self, idx):
        # Warning: This function can mutate data

        # TODO: Update tags
        try:
            self._data = self._data[idx]
            singleseries = len(self._data) == 1
            if singleseries:
                self._data = np.array(self._data[0], ndmin=2)
            self._series_ids = list(np.atleast_1d(np.atleast_1d(self._series_ids)[idx]))
            self._series_labels = list(
                np.atleast_1d(np.atleast_1d(self._series_labels)[idx])
            )
        except AttributeError:
            self._data = self._data[idx]
            singleseries = len(self._data) == 1
            if singleseries:
                self._data = np.array(self._data[0], ndmin=2)
            self._series_ids = list(np.atleast_1d(np.atleast_1d(self._series_ids)[idx]))
            self._series_labels = list(
                np.atleast_1d(np.atleast_1d(self._series_labels)[idx])
            )
        except IndexError:
            raise IndexError(
                "One of more indices were out of bounds for n_series with size {}".format(
                    self.n_series
                )
            )
        except Exception:
            raise TypeError("Unsupported indexing type {}".format(type(idx)))

        return self

    def _restrict_to_interval(self, intervalslice, *, data=None):
        """Return data restricted to an intervalarray.

        This function assumes sorted event datas, so that binary search can
        be used to quickly identify slices that should be kept in the
        restriction. It does not check every event data.

        Parameters
        ----------
        intervalarray : nelpy.IntervalArray
        """

        # Warning: this function can mutate data
        # This should be called from _restrict only. That's where
        # intervalarray is first checked against the support.
        # This function assumes that has happened already, so
        # every point in intervalarray is also in the support

        # NOTE: this used to assume multiple series for the enumeration to work

        if data is None:
            data = self._data

        if isinstance(intervalslice, slice):
            if (
                intervalslice.start is None
                and intervalslice.stop is None
                and intervalslice.step is None
            ):
                # no restriction on interval
                return self

        newintervals = self._abscissa.support[intervalslice].merge()
        if newintervals.isempty:
            logging.warning("Index resulted in empty interval array")
            return self.empty(inplace=True)

        issue_warning = False
        if not self.isempty:
            for series, evt_data in enumerate(data):
                indices = []
                for epdata in newintervals.data:
                    t_start = epdata[0]
                    t_stop = epdata[1]
                    frm, to = np.searchsorted(evt_data, (t_start, t_stop))
                    indices.append((frm, to))
                indices = np.array(indices, ndmin=2)
                if np.diff(indices).sum() < len(evt_data):
                    issue_warning = True
                singleseries = len(self._data) == 1
                if singleseries:
                    data_list = []
                    for start, stop in indices:
                        data_list.extend(evt_data[start:stop])
                    data = np.array(data_list, ndmin=2)
                else:
                    # here we have to do some annoying conversion between
                    # arrays and lists to fully support jagged array
                    # mutation
                    data_list = []
                    for start, stop in indices:
                        data_list.extend(evt_data[start:stop])
                    data_ = data.tolist()  # this creates copy
                    data_[series] = np.array(data_list)
                    data = utils.ragged_array(data_)
            self._data = data
            if issue_warning:
                logging.warning("ignoring events outside of eventarray support")

        self._abscissa.support = newintervals
        return self

    def __repr__(self):
        address_str = " at " + str(hex(id(self)))
        logging.disable(logging.CRITICAL)
        if self.isempty:
            return "<empty " + self.type_name + address_str + ">"
        if self._abscissa.support.n_intervals > 1:
            epstr = " ({} segments)".format(self._abscissa.support.n_intervals)
        else:
            epstr = ""
        if self.fs is not None:
            fsstr = " at %s Hz" % self.fs
        else:
            fsstr = ""
        if self.label is not None:
            labelstr = " from %s" % self.label
        else:
            labelstr = ""
        numstr = " %s %s" % (self.n_series, self._series_label)
        logging.disable(0)
        return "<%s%s:%s%s>%s%s" % (
            self.type_name,
            address_str,
            numstr,
            epstr,
            fsstr,
            labelstr,
        )

    def bin(self, *, ds=None):
        """Return a binned eventarray."""
        return BinnedEventArray(self, ds=ds)

    @property
    def data(self):
        """Event datas in seconds."""
        return self._data

    @property
    def n_events(self):
        """(np.array) The number of events in each series."""
        if self.isempty:
            return 0
        return np.array([len(series) for series in self.data])

    @property
    def issorted(self):
        """(bool) Sorted EventArray."""
        if self.isempty:
            return True
        return np.array([utils.is_sorted(eventarray) for eventarray in self.data]).all()

    def _reorder_series_by_idx(self, neworder, inplace=False):
        """Reorder series according to a specified order.

        neworder must be list-like, of size (n_series,)

        Return
        ------
        out : reordered EventArray
        """

        if inplace:
            out = self
        else:
            out = self.copy()

        oldorder = list(range(len(neworder)))
        for oi, ni in enumerate(neworder):
            frm = oldorder.index(ni)
            to = oi
            utils.swap_rows(out._data, frm, to)
            out._series_ids[frm], out._series_ids[to] = (
                out._series_ids[to],
                out._series_ids[frm],
            )
            out._series_labels[frm], out._series_labels[to] = (
                out._series_labels[to],
                out._series_labels[frm],
            )
            # TODO: re-build series tags (tag system not yet implemented)
            oldorder[frm], oldorder[to] = oldorder[to], oldorder[frm]

        out.__renew__()
        return out

    def reorder_series(self, neworder, *, inplace=False):
        """Reorder series according to a specified order.

        neworder must be list-like, of size (n_series,) and in terms of
        series_ids

        Return
        ------
        out : reordered EventArray
        """
        raise DeprecationWarning(
            "reorder_series has been deprecated. Use reorder_series_by_id(x/s) instead!"
        )

    def reorder_series_by_ids(self, neworder, *, inplace=False):
        """Reorder series according to a specified order.

        neworder must be list-like, of size (n_series,) and in terms of
        series_ids

        Return
        ------
        out : reordered EventArray
        """
        if inplace:
            out = self
        else:
            out = self.copy()

        neworder = [self.series_ids.index(x) for x in neworder]

        oldorder = list(range(len(neworder)))
        for oi, ni in enumerate(neworder):
            frm = oldorder.index(ni)
            to = oi
            utils.swap_rows(out._data, frm, to)
            out._series_ids[frm], out._series_ids[to] = (
                out._series_ids[to],
                out._series_ids[frm],
            )
            out._series_labels[frm], out._series_labels[to] = (
                out._series_labels[to],
                out._series_labels[frm],
            )
            # TODO: re-build series tags (tag system not yet implemented)
            oldorder[frm], oldorder[to] = oldorder[to], oldorder[frm]

        out.__renew__()
        return out

    def get_event_firing_order(self):
        """Returns a list of series_ids such that the series are ordered
        by when they first fire in the EventArray.

        Return
        ------
        firing_order : list of series_ids
        """

        first_events = [
            (ii, series[0]) for (ii, series) in enumerate(self.data) if len(series) != 0
        ]
        first_events_series_ids = np.array(self.series_ids)[
            [fs[0] for fs in first_events]
        ]
        first_events_datas = np.array([fs[1] for fs in first_events])
        sortorder = np.argsort(first_events_datas)
        first_events_series_ids = first_events_series_ids[sortorder]
        remaining_ids = list(set(self.series_ids) - set(first_events_series_ids))
        firing_order = list(first_events_series_ids)
        firing_order.extend(remaining_ids)

        return firing_order

    @property
    def first_event(self):
        """Returns the [time of the] first event across all series."""
        first = np.inf
        for series in self.data:
            if series[0] < first:
                first = series[0]
        return first

    @property
    def last_event(self):
        """Returns the [time of the] last event across all series."""
        last = -np.inf
        for series in self.data:
            if series[-1] > last:
                last = series[-1]
        return last

    def empty(self, *, inplace=False):
        """Remove data (but not metadata) from EventArray.

        Attributes 'data', and 'support' are both emptied.

        Note: n_series, series_ids, etc. are all preserved.
        """
        if not inplace:
            out = self._copy_without_data()
            out._abscissa.support = type(self._abscissa.support)(empty=True)
            return out
        out = self
        out._data = np.array(self.n_series * [None])
        out._abscissa.support = type(self._abscissa.support)(empty=True)
        out.__renew__()
        return out

data property

Event datas in seconds.

first_event property

Returns the [time of the] first event across all series.

isempty property

(bool) Empty EventArray.

issorted property

(bool) Sorted EventArray.

last_event property

Returns the [time of the] last event across all series.

n_active property

(int) The number of active series.

A series is considered active if it fired at least one event.

n_events property

(np.array) The number of events in each series.

n_series property

(int) The number of series.

bin(*, ds=None)

Return a binned eventarray.

Source code in nelpy/core/_eventarray.py
864
865
866
def bin(self, *, ds=None):
    """Return a binned eventarray."""
    return BinnedEventArray(self, ds=ds)

copy()

Returns a copy of the EventArray.

Source code in nelpy/core/_eventarray.py
639
640
641
642
643
def copy(self):
    """Returns a copy of the EventArray."""
    newcopy = copy.deepcopy(self)
    newcopy.__renew__()
    return newcopy

empty(*, inplace=False)

Remove data (but not metadata) from EventArray.

Attributes 'data', and 'support' are both emptied.

Note: n_series, series_ids, etc. are all preserved.

Source code in nelpy/core/_eventarray.py
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
def empty(self, *, inplace=False):
    """Remove data (but not metadata) from EventArray.

    Attributes 'data', and 'support' are both emptied.

    Note: n_series, series_ids, etc. are all preserved.
    """
    if not inplace:
        out = self._copy_without_data()
        out._abscissa.support = type(self._abscissa.support)(empty=True)
        return out
    out = self
    out._data = np.array(self.n_series * [None])
    out._abscissa.support = type(self._abscissa.support)(empty=True)
    out.__renew__()
    return out

flatten(*, series_id=None, series_label=None)

Collapse events across series.

WARNING! series_tags are thrown away when flattening.

Parameters:

Name Type Description Default
series_id

(series) ID to assign to flattened event series, default is 0.

None
series_label

(series) Label for event series, default is 'flattened'.

None
Source code in nelpy/core/_eventarray.py
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
def flatten(self, *, series_id=None, series_label=None):
    """Collapse events across series.

    WARNING! series_tags are thrown away when flattening.

    Parameters
    ----------
    series_id: (int)
        (series) ID to assign to flattened event series, default is 0.
    series_label (str)
        (series) Label for event series, default is 'flattened'.
    """
    if self.n_series < 2:  # already flattened
        return self

    # default args:
    if series_id is None:
        series_id = 0
    if series_label is None:
        series_label = "flattened"

    flattened = self._copy_without_data()
    flattened._series_ids = [series_id]
    flattened._series_labels = [series_label]
    flattened._series_tags = None

    # Efficient: concatenate all events, sort once
    all_events = np.concatenate(self.data)
    all_events.sort()
    flattened._data = np.array([all_events], ndmin=2)
    flattened.__renew__()
    return flattened

get_event_firing_order()

Returns a list of series_ids such that the series are ordered by when they first fire in the EventArray.

Return

firing_order : list of series_ids

Source code in nelpy/core/_eventarray.py
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def get_event_firing_order(self):
    """Returns a list of series_ids such that the series are ordered
    by when they first fire in the EventArray.

    Return
    ------
    firing_order : list of series_ids
    """

    first_events = [
        (ii, series[0]) for (ii, series) in enumerate(self.data) if len(series) != 0
    ]
    first_events_series_ids = np.array(self.series_ids)[
        [fs[0] for fs in first_events]
    ]
    first_events_datas = np.array([fs[1] for fs in first_events])
    sortorder = np.argsort(first_events_datas)
    first_events_series_ids = first_events_series_ids[sortorder]
    remaining_ids = list(set(self.series_ids) - set(first_events_series_ids))
    firing_order = list(first_events_series_ids)
    firing_order.extend(remaining_ids)

    return firing_order

partition(ds=None, n_intervals=None)

Returns a BaseEventArray whose support has been partitioned.

Parameters:

Name Type Description Default
ds float

Maximum duration (in seconds), for each interval.

None
n_points int

Number of intervals. If ds is None and n_intervals is None, then default is to use n_intervals = 100

required

Returns:

Name Type Description
out BaseEventArray

BaseEventArray that has been partitioned.

Notes

Irrespective of whether 'ds' or 'n_intervals' are used, the exact underlying support is propagated, and the first and last points of the supports are always included, even if this would cause n_points or ds to be violated.

Source code in nelpy/core/_eventarray.py
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
@keyword_equivalence(this_or_that={"n_intervals": "n_epochs"})
def partition(self, ds=None, n_intervals=None):
    """Returns a BaseEventArray whose support has been partitioned.

    Parameters
    ----------
    ds : float, optional
        Maximum duration (in seconds), for each interval.
    n_points : int, optional
        Number of intervals. If ds is None and n_intervals is None, then
        default is to use n_intervals = 100

    Returns
    -------
    out : BaseEventArray
        BaseEventArray that has been partitioned.

    Notes
    -----
    Irrespective of whether 'ds' or 'n_intervals' are used, the exact
    underlying support is propagated, and the first and last points
    of the supports are always included, even if this would cause
    n_points or ds to be violated.
    """

    out = self.copy()
    abscissa = copy.deepcopy(out._abscissa)
    abscissa.support = abscissa.support.partition(ds=ds, n_intervals=n_intervals)
    out._abscissa = abscissa
    out.__renew__()

    return out

reorder_series(neworder, *, inplace=False)

Reorder series according to a specified order.

neworder must be list-like, of size (n_series,) and in terms of series_ids

Return

out : reordered EventArray

Source code in nelpy/core/_eventarray.py
921
922
923
924
925
926
927
928
929
930
931
932
933
def reorder_series(self, neworder, *, inplace=False):
    """Reorder series according to a specified order.

    neworder must be list-like, of size (n_series,) and in terms of
    series_ids

    Return
    ------
    out : reordered EventArray
    """
    raise DeprecationWarning(
        "reorder_series has been deprecated. Use reorder_series_by_id(x/s) instead!"
    )

reorder_series_by_ids(neworder, *, inplace=False)

Reorder series according to a specified order.

neworder must be list-like, of size (n_series,) and in terms of series_ids

Return

out : reordered EventArray

Source code in nelpy/core/_eventarray.py
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
def reorder_series_by_ids(self, neworder, *, inplace=False):
    """Reorder series according to a specified order.

    neworder must be list-like, of size (n_series,) and in terms of
    series_ids

    Return
    ------
    out : reordered EventArray
    """
    if inplace:
        out = self
    else:
        out = self.copy()

    neworder = [self.series_ids.index(x) for x in neworder]

    oldorder = list(range(len(neworder)))
    for oi, ni in enumerate(neworder):
        frm = oldorder.index(ni)
        to = oi
        utils.swap_rows(out._data, frm, to)
        out._series_ids[frm], out._series_ids[to] = (
            out._series_ids[to],
            out._series_ids[frm],
        )
        out._series_labels[frm], out._series_labels[to] = (
            out._series_labels[to],
            out._series_labels[frm],
        )
        # TODO: re-build series tags (tag system not yet implemented)
        oldorder[frm], oldorder[to] = oldorder[to], oldorder[frm]

    out.__renew__()
    return out

SpikeTrainArray

Bases: EventArray

A multiseries spike train array with shared support.

SpikeTrainArray is a specialized EventArray for handling neural spike train data. It provides unit-specific aliases and methods for analyzing spike timing data across multiple recording units with a common temporal support.

Parameters:

Name Type Description Default
fs float

Sampling rate in Hz. Default is 30,000.

required
support IntervalArray

IntervalArray on which spike trains are defined. Default is [0, last spike] inclusive.

required
unit_ids list of int

Unit IDs. Alias for series_ids.

required
unit_labels list of str

Labels corresponding to units. Default casts unit_ids to str. Alias for series_labels.

required
unit_tags optional

Tags corresponding to units. Alias for series_tags. NOTE: Currently we do not do any input validation so these can be any type. We also don't use these for anything yet.

required
label str or None

Information pertaining to the source of the spike train array.

required
empty bool

Whether an empty SpikeTrainArray should be constructed (no data).

required
**kwargs optional

Additional keyword arguments forwarded to the BaseEventArray constructor.

{}

Attributes:

Name Type Description
Note Read the docstring for the BaseEventArray and EventArray superclasses
for additional attributes that are defined there.
isempty bool

Whether the SpikeTrainArray is empty (no data).

n_units int

The number of units. Alias for n_series.

n_active int

The number of active units. A unit is considered active if it fired at least one spike.

time array of np.array(dtype=np.float64)

Spike time data in seconds. Array of length n_units, each entry with shape (n_spikes,). Alias for data.

n_spikes ndarray

The number of spikes in each unit. Alias for n_events.

issorted bool

Whether the spike times are sorted.

first_spike float

The time of the very first spike, across all units.

last_spike float

The time of the very last spike, across all units.

unit_ids list of int

Unit IDs. Alias for series_ids.

unit_labels list of str

Labels corresponding to units. Alias for series_labels.

unit_tags

Tags corresponding to units. Alias for series_tags.

n_epochs int

The number of epochs/intervals. Alias for n_intervals.

support IntervalArray

The support of the SpikeTrainArray.

fs float

Sampling frequency (Hz).

label str or None

Information pertaining to the source of the spike train array.

Methods:

Name Description
bin

Return a BinnedSpikeTrainArray.

get_spike_firing_order

Returns unit_ids ordered by when they first fire.

reorder_units_by_ids

Reorder units according to specified unit_ids.

flatten

Collapse spikes across units into a single unit.

partition

Returns a SpikeTrainArray whose support has been partitioned.

copy

Returns a copy of the SpikeTrainArray.

empty

Remove data (but not metadata) from SpikeTrainArray.

Examples:

Create a SpikeTrainArray with two units:

>>> import numpy as np
>>> spike_times = [np.array([0.1, 0.3, 0.7]), np.array([0.2, 0.5, 0.8])]
>>> sta = SpikeTrainArray(spike_times, unit_ids=[1, 2], fs=1000)
>>> print(sta.n_units)
2
>>> print(sta.n_spikes)
[3 3]

Access spike times using the time alias:

>>> print(sta.time[0])  # First unit's spike times
[0.1 0.3 0.7]

Create a binned version:

>>> binned = sta.bin(ds=0.1)  # 100ms bins
Notes

SpikeTrainArray provides neuroscience-specific aliases for EventArray functionality. For example, 'units' instead of 'series', 'spikes' instead of 'events', and 'time' instead of 'data'. This makes the API more intuitive for neuroscience applications while maintaining full compatibility with the underlying EventArray infrastructure.

The class automatically handles spike time sorting and provides efficient methods for common spike train analyses. All spike times are stored in seconds and should be non-negative values within the support interval.

Source code in nelpy/core/_eventarray.py
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
class SpikeTrainArray(EventArray):
    """A multiseries spike train array with shared support.

    SpikeTrainArray is a specialized EventArray for handling neural spike train data.
    It provides unit-specific aliases and methods for analyzing spike timing data
    across multiple recording units with a common temporal support.

    Parameters
    ----------
    fs : float, optional
        Sampling rate in Hz. Default is 30,000.
    support : IntervalArray, optional
        IntervalArray on which spike trains are defined.
        Default is [0, last spike] inclusive.
    unit_ids : list of int, optional
        Unit IDs. Alias for series_ids.
    unit_labels : list of str, optional
        Labels corresponding to units. Default casts unit_ids to str.
        Alias for series_labels.
    unit_tags : optional
        Tags corresponding to units. Alias for series_tags.
        NOTE: Currently we do not do any input validation so these can
        be any type. We also don't use these for anything yet.
    label : str or None, optional
        Information pertaining to the source of the spike train array.
    empty : bool, optional
        Whether an empty SpikeTrainArray should be constructed (no data).
    **kwargs : optional
        Additional keyword arguments forwarded to the BaseEventArray
        constructor.

    Attributes
    ----------
    Note : Read the docstring for the BaseEventArray and EventArray superclasses
    for additional attributes that are defined there.

    isempty : bool
        Whether the SpikeTrainArray is empty (no data).
    n_units : int
        The number of units. Alias for n_series.
    n_active : int
        The number of active units. A unit is considered active if
        it fired at least one spike.
    time : array of np.array(dtype=np.float64)
        Spike time data in seconds. Array of length n_units, each entry with
        shape (n_spikes,). Alias for data.
    n_spikes : np.ndarray
        The number of spikes in each unit. Alias for n_events.
    issorted : bool
        Whether the spike times are sorted.
    first_spike : float
        The time of the very first spike, across all units.
    last_spike : float
        The time of the very last spike, across all units.
    unit_ids : list of int
        Unit IDs. Alias for series_ids.
    unit_labels : list of str
        Labels corresponding to units. Alias for series_labels.
    unit_tags :
        Tags corresponding to units. Alias for series_tags.
    n_epochs : int
        The number of epochs/intervals. Alias for n_intervals.
    support : IntervalArray
        The support of the SpikeTrainArray.
    fs : float
        Sampling frequency (Hz).
    label : str or None
        Information pertaining to the source of the spike train array.

    Methods
    -------
    bin(ds=None)
        Return a BinnedSpikeTrainArray.
    get_spike_firing_order()
        Returns unit_ids ordered by when they first fire.
    reorder_units_by_ids(neworder, inplace=False)
        Reorder units according to specified unit_ids.
    flatten(unit_id=None, unit_label=None)
        Collapse spikes across units into a single unit.
    partition(ds=None, n_epochs=None)
        Returns a SpikeTrainArray whose support has been partitioned.
    copy()
        Returns a copy of the SpikeTrainArray.
    empty(inplace=False)
        Remove data (but not metadata) from SpikeTrainArray.

    Examples
    --------
    Create a SpikeTrainArray with two units:

    >>> import numpy as np
    >>> spike_times = [np.array([0.1, 0.3, 0.7]), np.array([0.2, 0.5, 0.8])]
    >>> sta = SpikeTrainArray(spike_times, unit_ids=[1, 2], fs=1000)
    >>> print(sta.n_units)
    2
    >>> print(sta.n_spikes)
    [3 3]

    Access spike times using the time alias:

    >>> print(sta.time[0])  # First unit's spike times
    [0.1 0.3 0.7]

    Create a binned version:

    >>> binned = sta.bin(ds=0.1)  # 100ms bins

    Notes
    -----
    SpikeTrainArray provides neuroscience-specific aliases for EventArray
    functionality. For example, 'units' instead of 'series', 'spikes' instead
    of 'events', and 'time' instead of 'data'. This makes the API more intuitive
    for neuroscience applications while maintaining full compatibility with the
    underlying EventArray infrastructure.

    The class automatically handles spike time sorting and provides efficient
    methods for common spike train analyses. All spike times are stored in
    seconds and should be non-negative values within the support interval.
    """

    # specify class-specific aliases:
    __aliases__ = {
        "time": "data",
        "_time": "_data",
        "n_epochs": "n_intervals",
        "n_units": "n_series",
        "_unit_subset": "_series_subset",  # requires kw change
        "get_event_firing_order": "get_spike_firing_order",
        "reorder_units_by_ids": "reorder_series_by_ids",
        "reorder_units": "reorder_series",
        "_reorder_units_by_idx": "_reorder_series_by_idx",
        "n_spikes": "n_events",
        "unit_ids": "series_ids",
        "unit_labels": "series_labels",
        "unit_tags": "series_tags",
        "_unit_ids": "_series_ids",
        "_unit_labels": "_series_labels",
        "_unit_tags": "_series_tags",
        "first_spike": "first_event",
        "last_spike": "last_event",
    }

    def __init__(self, *args, **kwargs):
        # add class-specific aliases to existing aliases:
        self.__aliases__ = {**super().__aliases__, **self.__aliases__}

        series_label = kwargs.pop("series_label", None)
        if series_label is None:
            series_label = "units"
        kwargs["series_label"] = series_label

        # legacy STA constructor support for backward compatibility
        kwargs = legacySTAkwargs(**kwargs)

        support = kwargs.get("support", None)
        if support is not None:
            abscissa = kwargs.get("abscissa", core.TemporalAbscissa(support=support))
        else:
            abscissa = kwargs.get("abscissa", core.TemporalAbscissa())
        ordinate = kwargs.get("ordinate", core.AnalogSignalArrayOrdinate())

        kwargs["abscissa"] = abscissa
        kwargs["ordinate"] = ordinate

        super().__init__(*args, **kwargs)

    # @keyword_equivalence(this_or_that={'n_intervals':'n_epochs'})
    # def partition(self, ds=None, n_intervals=None, n_epochs=None):
    #     if n_intervals is None:
    #         n_intervals = n_epochs
    #     kwargs = {'ds':ds, 'n_intervals': n_intervals}
    #     return super().partition(**kwargs)

    def bin(self, *, ds=None):
        """Return a BinnedSpikeTrainArray."""
        return BinnedSpikeTrainArray(self, ds=ds)  # TODO #FIXME

bin(*, ds=None)

Return a BinnedSpikeTrainArray.

Source code in nelpy/core/_eventarray.py
2431
2432
2433
def bin(self, *, ds=None):
    """Return a BinnedSpikeTrainArray."""
    return BinnedSpikeTrainArray(self, ds=ds)  # TODO #FIXME

legacySTAkwargs(**kwargs)

Provide support for legacy SpikeTrainArray kwargs. This function is primarily intended to be a helper for the new STA constructor, not for general-purpose use.

kwarg: time <==> timestamps <==> abscissa_vals kwarg: data <==> ydata kwarg: unit_ids <==> series_ids kwarg: unit_labels <==> series_labels kwarg: unit_tags <==> series_tags

Examples:

sta = nel.SpikeTrainArray(time=..., ) sta = nel.SpikeTrainArray(timestamps=..., ) sta = nel.SpikeTrainArray(abscissa_vals=..., )

Source code in nelpy/core/_eventarray.py
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
def legacySTAkwargs(**kwargs):
    """Provide support for legacy SpikeTrainArray
    kwargs. This function is primarily intended to be
    a helper for the new STA constructor, not for
    general-purpose use.

    kwarg: time        <==> timestamps <==> abscissa_vals
    kwarg: data        <==> ydata
    kwarg: unit_ids    <==> series_ids
    kwarg: unit_labels <==> series_labels
    kwarg: unit_tags   <==> series_tags

    Examples
    --------
    sta = nel.SpikeTrainArray(time=..., )
    sta = nel.SpikeTrainArray(timestamps=..., )
    sta = nel.SpikeTrainArray(abscissa_vals=..., )
    """

    def only_one_of(*args):
        num_non_null_args = 0
        out = None
        for arg in args:
            if arg is not None:
                num_non_null_args += 1
                out = arg
        if num_non_null_args > 1:
            raise ValueError("multiple conflicting arguments received")
        return out

    # legacy STA constructor support for backward compatibility
    abscissa_vals = kwargs.pop("abscissa_vals", None)
    timestamps = kwargs.pop("timestamps", None)
    time = kwargs.pop("time", None)
    # only one of the above, otherwise raise exception
    abscissa_vals = only_one_of(abscissa_vals, timestamps, time)
    if abscissa_vals is not None:
        kwargs["abscissa_vals"] = abscissa_vals

    # Other legacy attributes
    series_ids = kwargs.pop("series_ids", None)
    unit_ids = kwargs.pop("unit_ids", None)
    series_ids = only_one_of(series_ids, unit_ids)
    kwargs["series_ids"] = series_ids

    series_labels = kwargs.pop("series_labels", None)
    unit_labels = kwargs.pop("unit_labels", None)
    series_labels = only_one_of(series_labels, unit_labels)
    kwargs["series_labels"] = series_labels

    series_tags = kwargs.pop("series_tags", None)
    unit_tags = kwargs.pop("unit_tags", None)
    series_tags = only_one_of(series_tags, unit_tags)
    kwargs["series_tags"] = series_tags

    return kwargs